Skip to content
quarry Artifact [3c7864498f]
Login

Artifact [3c7864498f]

Artifact 3c7864498f0460f67d89679f65f0e533107e3beadf65d4eb2cc2ee327268962b:


package web

import (
	"net/http"
	"net/http/httptest"
	"net/url"
	"strings"
	"testing"

	"craftdesign.group/quarry/internal/api"
	"craftdesign.group/quarry/internal/ops"
)

// recTags is a caps plane that holds the verdict-tags setting, the way
// the production plane now does.
type recTags struct {
	stubCaps
	mode *string
}

func (r recTags) CITagsMode(string) string { return *r.mode }
func (r recTags) SetCITagsMode(_, mode string) error {
	if mode != "on" && mode != "off" {
		mode = ""
	}
	*r.mode = mode
	return nil
}

// The verdict-tags block sat unreachable in production because the real
// caps plane did not implement CITagsAdmin, so neither its rendering nor
// its POST had ever been exercised end to end. Through the handler: the
// block renders for an admin, each choice persists, and the page shows
// the stored choice back as selected.
func TestVerdictTagsSettingRendersAndPersists(t *testing.T) {
	ix := landingIndex(t, false)
	r := ops.NewRegistry()
	if err := api.RegisterAll(r, api.Deps{Version: "v",
		Repos: api.NewRepos(map[string]*api.Repo{"alpha": {Index: ix}})}); err != nil {
		t.Fatal(err)
	}
	mode := ""
	srv := httptest.NewServer(HandlerWith(r, nil, nil,
		[]Option{WithSessions(fakeSessions{user: "dan"}), WithCaps(recTags{stubCaps{letters: "a8"}, &mode})}))
	t.Cleanup(srv.Close)

	page := asDan(t, srv, "/r/alpha/settings")
	if !strings.Contains(page, `id="ci-tags"`) {
		t.Fatal("FAIL the verdict-tags block does not render for an admin")
	}
	t.Log("ok the block renders")

	for _, want := range []string{"on", "off", ""} {
		req, _ := http.NewRequest("POST", srv.URL+"/r/alpha/settings/ci-tags",
			strings.NewReader(url.Values{"mode": {want}}.Encode()))
		req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
		req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
		res, err := srv.Client().Do(req)
		if err != nil {
			t.Fatal(err)
		}
		res.Body.Close()
		if mode != want {
			t.Errorf("FAIL posting %q stored %q", want, mode)
			continue
		}
		shown := "default"
		if want != "" {
			shown = want
		}
		page = asDan(t, srv, "/r/alpha/settings")
		selected := map[string]string{"default": `value=""`, "on": `value="on"`, "off": `value="off"`}[shown]
		if !strings.Contains(page, selected+` selected`) {
			t.Errorf("FAIL after %q the page does not show %s selected", want, shown)
		} else {
			t.Logf("ok %q persists and shows back as %s", want, shown)
		}
	}
}