Skip to content
quarry Artifact [250df2fdcf]
Login

Artifact [250df2fdcf]

Artifact 250df2fdcf4422e91df058dee5ecddffa867e908c4516f1a8b351971427f0604:


package web

import (
	"io"
	"net/http"
	"net/http/httptest"
	"net/url"
	"path/filepath"
	"regexp"
	"strings"
	"testing"

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

func runnerCodeServer(t *testing.T) *httptest.Server {
	t.Helper()
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	eng := &mintRecorder{}
	r := ops.NewRegistry()
	if err := api.RegisterAll(r, api.Deps{Version: "v", WorkerTokens: eng, RunnerCodes: db,
		Repos: api.NewRepos(map[string]*api.Repo{"alpha": {Chat: "alpha", Index: landingIndex(t, false)}})}); err != nil {
		t.Fatal(err)
	}
	srv := httptest.NewServer(HandlerWith(r, nil, nil, []Option{
		WithSessions(fakeSessions{user: "dan", roles: map[string]ops.Auth{"alpha": ops.Admin}}),
		WithCaps(stubCaps{letters: "a8i"}),
		WithEngine(eng),
	}))
	t.Cleanup(srv.Close)
	return srv
}

func postRunnerCode(t *testing.T, srv *httptest.Server, datastar bool) (*http.Response, string) {
	t.Helper()
	req, _ := http.NewRequest("POST", srv.URL+"/r/alpha/settings/runner-code", strings.NewReader(url.Values{}.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	if datastar {
		req.Header.Set("Datastar-Request", "true")
	}
	req.AddCookie(&http.Cookie{Name: sessionCookie, Value: "good"})
	client := srv.Client()
	client.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
	resp, err := client.Do(req)
	if err != nil {
		t.Fatal(err)
	}
	defer resp.Body.Close()
	b, _ := io.ReadAll(resp.Body)
	return resp, string(b)
}

// "Add a runner" answers in place, with the whole command and a live
// code, and no redirect carries the code.
func TestAddARunnerAnswersInPlaceWithTheCommand(t *testing.T) {
	srv := runnerCodeServer(t)
	page := asDan(t, srv, "/r/alpha/settings")
	if !strings.Contains(page, `data-hook="add-runner"`) || !strings.Contains(page, `data-hook="add-runner-button"`) {
		t.Errorf("FAIL: settings has no add-a-runner control")
	}
	if strings.Contains(page, "data-on-click") || !regexp.MustCompile(`@post\((?:'|')/r/alpha/settings/runner-code`).MatchString(strings.ReplaceAll(page, `\/`, `/`)) {
		t.Errorf("FAIL: the button is not a Datastar post to the code route")
	}
	command := regexp.MustCompile(`data-hook="runner-install-command">sudo quarry-runner install (https?://[^/]+/r/alpha) --code (qri_[0-9a-f]+)<`)
	for _, datastar := range []bool{true, false} {
		resp, body := postRunnerCode(t, srv, datastar)
		if resp.StatusCode != http.StatusOK || resp.Header.Get("Location") != "" {
			t.Errorf("FAIL: datastar=%v answered %d with Location %q, want an in-place 200", datastar, resp.StatusCode, resp.Header.Get("Location"))
		}
		if !command.MatchString(body) {
			t.Errorf("FAIL: datastar=%v: no install command with a code in the answer", datastar)
		}
		if resp.Header.Get("Cache-Control") != "no-store" {
			t.Errorf("FAIL: datastar=%v: an answer carrying a code may be stored", datastar)
		}
	}
	if strings.Contains(asDan(t, srv, "/r/alpha/settings"), "qri_") {
		t.Errorf("FAIL: a later visit to settings shows a code")
	}
	if !t.Failed() {
		t.Log("ok")
	}
}