package main
import (
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"testing"
"craftdesign.group/quarry/internal/api"
"craftdesign.group/quarry/internal/ci"
"craftdesign.group/quarry/internal/events"
"craftdesign.group/quarry/internal/index"
"craftdesign.group/quarry/internal/ingest"
"craftdesign.group/quarry/internal/lease"
"craftdesign.group/quarry/internal/zitcli"
)
// A RETARGETED LANDING IS TESTED AGAINST ITS NEW TARGET.
//
// The merge runs of a landing aimed at another branch tested the old
// pair. The sweep that tests an opening landing starts the new pair's
// runs, and the old pair's still-running ones stop. A pair already
// tested starts nothing.
func TestARetargetedLandingStartsItsNewPairsRuns(t *testing.T) {
if _, err := exec.LookPath("zit"); err != nil {
t.Skip("zit not on PATH")
}
dir := t.TempDir()
write := func(name, body string) {
t.Helper()
os.MkdirAll(filepath.Dir(filepath.Join(dir, name)), 0o755)
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
zitIn(t, dir, "init", ".")
write("ci/one.json", `{"name":"one","version":"1.0","steps":[]}`)
write("ci/two.json", `{"name":"two","version":"1.0","steps":[]}`)
write("f.txt", "root\n")
zitIn(t, dir, "add", "ci/one.json", "ci/two.json", "f.txt")
zitIn(t, dir, "commit", "-m", "root", "--user", "u")
write("o.txt", "other\n")
zitIn(t, dir, "add", "o.txt")
zitIn(t, dir, "commit", "-m", "other", "--branch", "other", "--user", "u")
zitIn(t, dir, "update", "trunk")
write("g.txt", "feat\n")
zitIn(t, dir, "add", "g.txt")
zitIn(t, dir, "commit", "-m", "feat", "--branch", "feat", "--user", "u")
cli := zitcli.New(dir)
id, err := cli.LandingOpen(lease.Unguarded("test"), "dan", "feat", "trunk", "land feat", "")
if err != nil {
t.Fatal(err)
}
ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(ev.Close)
ix, err := index.Open(filepath.Join(t.TempDir(), "index.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { ix.Close() })
pipe := ingest.NewPipeline(cli, ev, ix, "r", "n1")
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
var mu sync.Mutex
var started, cancelled []string
total := 0
labels := map[string]map[string]string{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
switch {
case r.URL.Path == "/workflows":
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"status":"registered"}`))
case r.URL.Path == "/runs" && r.Method == http.MethodPost:
var body struct {
Input map[string]any `json:"input"`
Labels map[string]string `json:"labels"`
}
json.NewDecoder(r.Body).Decode(&body)
total++
rid := fmt.Sprintf("r-%d", total)
started = append(started, fmt.Sprint(body.Input["checkin"]))
labels[rid] = body.Labels
w.WriteHeader(http.StatusCreated)
fmt.Fprintf(w, `{"run_id":%q}`, rid)
case r.URL.Path == "/runs":
w.Write([]byte(`[]`))
case strings.HasSuffix(r.URL.Path, "/cancel"):
cancelled = append(cancelled, strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/runs/"), "/cancel"))
case strings.HasPrefix(r.URL.Path, "/runs/"):
rid := strings.TrimPrefix(r.URL.Path, "/runs/")
json.NewEncoder(w).Encode(ci.Run{RunID: rid, Status: "running", Labels: labels[rid]})
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
rg := newTestRegistrar(t, 25)
rg.engine = ci.New(srv.URL)
rg.deps = &api.Deps{Repos: api.NewRepos(map[string]*api.Repo{"r": {Index: ix, Zit: cli}})}
tip := func(b string) string {
t.Helper()
h, err := ix.BranchTip(b)
if err != nil || h == "" {
t.Fatalf("no tip for %s: %v", b, err)
}
return h
}
step := func() (s, c []string) {
t.Helper()
if _, err := pipe.Sync(); err != nil {
t.Fatal(err)
}
rg.landingSweep("r", ix)
mu.Lock()
defer mu.Unlock()
s, c = started, cancelled
started, cancelled = nil, nil
return s, c
}
retarget := func(to string) {
t.Helper()
if _, err := cli.LandingRetarget(lease.Unguarded("test"), id, "dan", to); err != nil {
t.Fatal(err)
}
}
feat := tip("feat")
if s, _ := step(); len(s) != 2 {
t.Fatalf("FAIL: the opened landing started %v, want one run per pipeline", s)
}
if s, c := step(); len(s) != 0 || len(c) != 0 {
t.Errorf("FAIL: a quiet sweep started %v and cancelled %v", s, c)
}
retarget("other")
s, c := step()
want := ci.Pair(feat, tip("other"))
if len(s) != 2 || s[0] != want || s[1] != want {
t.Errorf("FAIL: the retarget started %v, want two runs of %s", s, want)
}
if len(c) < 2 {
t.Errorf("FAIL: the retarget cancelled %v, want the old pair's two runs", c)
}
if s, c := step(); len(s) != 0 || len(c) != 0 {
t.Errorf("FAIL: the sweep after the retarget started %v and cancelled %v", s, c)
}
retarget("trunk")
s, c = step()
if len(s) != 0 {
t.Errorf("FAIL: a retarget onto a pair already tested started %v", s)
}
if len(c) != 2 {
t.Errorf("FAIL: retargeting back cancelled %v, want the other pair's two runs", c)
}
if !t.Failed() {
t.Log("ok")
}
}