Skip to content
quarry Artifact [72dd884f3c]
Login

Artifact [72dd884f3c]

Artifact 72dd884f3cabab5f97fc04dcc63b46b36766b21e339876fef8f1713b6a2dc562:


package api

import (
	"os/exec"
	"path/filepath"
	"regexp"
	"testing"

	"craftdesign.group/quarry/internal/events"
	"craftdesign.group/quarry/internal/index"
	"craftdesign.group/quarry/internal/ingest"
	"craftdesign.group/quarry/internal/oltp"
	"craftdesign.group/quarry/internal/ops"
	"craftdesign.group/quarry/internal/zitcli"
)

// waitStub is a sweep store that remembers the waiting reason per landing.
type waitStub struct {
	rows    []oltp.AutoAccept
	waiting map[string]string
	cleared map[string]bool
	lapsed  map[string]bool
}

func (s *waitStub) AutoAccepts() ([]oltp.AutoAccept, error) { return s.rows, nil }
func (s *waitStub) ClearAutoAccept(_, landing string) error {
	s.cleared[landing] = true
	return nil
}
func (s *waitStub) LapseAutoAccept(_, landing, _ string) error {
	if s.lapsed == nil {
		s.lapsed = map[string]bool{}
	}
	s.lapsed[landing] = true
	return nil
}
func (s *waitStub) SetAutoWaiting(_, landing, reason string) { s.waiting[landing] = reason }

// armedRungs is the armed rows still live: a landing the sweep cleared
// is no longer armed.
func (s *waitStub) armed() []oltp.AutoAccept {
	var out []oltp.AutoAccept
	for _, r := range s.rows {
		if !s.cleared[r.Landing] {
			out = append(out, r)
		}
	}
	return out
}

// threeRungs is a real store with low onto trunk, mid onto low and high
// onto mid, each touching its own file.
func threeRungs(t *testing.T) (dir string, ids map[string]string, ix *index.Index, sync func() (int, error)) {
	t.Helper()
	if _, err := exec.LookPath("zit"); err != nil {
		t.Skip("zit not on PATH")
	}
	dir = t.TempDir()
	zrun(t, dir, "init", ".")
	zwrite(t, dir, "f.txt", "root\n")
	zrun(t, dir, "add", "f.txt")
	zrun(t, dir, "commit", "-m", "root", "--user", "u")
	ids = map[string]string{}
	for _, b := range []struct{ branch, from string }{{"low", "trunk"}, {"mid", "low"}, {"high", "mid"}} {
		zrun(t, dir, "update", b.from)
		zwrite(t, dir, b.branch+".txt", b.branch+"\n")
		zrun(t, dir, "add", b.branch+".txt")
		zrun(t, dir, "commit", "-m", b.branch, "--branch", b.branch, "--user", "u")
		id, err := zitcli.New(dir).LandingOpen(testToken, "dan", b.branch, b.from, "land "+b.branch, "")
		if err != nil {
			t.Fatal(err)
		}
		ids[b.branch] = id
	}
	ev, err := events.Start(filepath.Join(t.TempDir(), "nats"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(ev.Close)
	lastStoreEvents = ev
	ix, err = index.Open(filepath.Join(t.TempDir(), "index.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { ix.Close() })
	pipe := ingest.NewPipeline(zitcli.New(dir), ev, ix, "test", "n1")
	if _, err := pipe.Sync(); err != nil {
		t.Fatal(err)
	}
	return dir, ids, ix, pipe.Sync
}

func prefixDeps(t *testing.T, dir string, ix *index.Index, sync func() (int, error), ci *mergeRuns) (Deps, *oltp.DB) {
	t.Helper()
	db, err := oltp.Open(filepath.Join(t.TempDir(), "o.db"))
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() { db.Close() })
	if err := db.AddAccount("dan", "a-long-enough-password", false); err != nil {
		t.Fatal(err)
	}
	return Deps{Version: "v", ZitVersion: zitcli.MinVersion, Checks: mergeChecks{}, CI: ci, Auto: db,
		CIRunPair: func(_, _, _, _ string) error { return nil },
		Repos:     NewRepos(map[string]*Repo{"test": {Chat: "test", Index: ix, Zit: zitcli.New(dir), Sync: sync}})}, db
}

func stateOf(t *testing.T, ix *index.Index, id string) string {
	t.Helper()
	l, ok, err := ix.LandingByPrefix(id)
	if err != nil || !ok {
		t.Fatalf("no landing %s: %v", id, err)
	}
	return l.State
}

// ticket 467: every rung armed, the bottom green, the top still testing.
// The sweep lands the green prefix and says on each rung left why it
// waits; once the next rung is green the next sweep lands it.
func TestAnArmedStackLandsItsGreenPrefix(t *testing.T) {
	dir, ids, ix, sync := threeRungs(t)
	ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
	ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
	d, _ := prefixDeps(t, dir, ix, sync, ci)
	store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
	for _, b := range []string{"low", "mid", "high"} {
		store.rows = append(store.rows, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
	}

	landed := d.AutoAcceptSweep(store)
	if len(landed) != 1 || landed[0] != "test/"+ids["low"] {
		t.Errorf("FAIL: first sweep landed %v, want low alone", landed)
	}
	for b, want := range map[string]string{"low": "accepted", "mid": "open", "high": "open"} {
		if got := stateOf(t, ix, ids[b]); got != want {
			t.Errorf("FAIL: %s reads %q after the first sweep, want %q", b, got, want)
		}
	}
	for _, b := range []string{"mid", "high"} {
		if store.waiting[ids[b]] == "" {
			t.Errorf("FAIL: armed rung %s has an empty autoWaiting", b)
		}
	}
	if store.waiting[ids["mid"]] == store.waiting[ids["high"]] {
		t.Errorf("FAIL: mid and high carry the same reason %q, each should say its own", store.waiting[ids["mid"]])
	}

	// mid goes green on its merge; the arms still standing are swept again.
	// Judged on what it now sits on, trunk: no verdict against the rung
	// it was stacked on is wanted.
	ci.green(ztip(t, dir, "mid"), ztip(t, dir, "trunk"))
	store.rows = store.armed()
	landed = d.AutoAcceptSweep(store)
	if len(landed) != 1 || landed[0] != "test/"+ids["mid"] {
		t.Errorf("FAIL: second sweep landed %v, want mid alone", landed)
	}
	if got := stateOf(t, ix, ids["high"]); got != "open" {
		t.Errorf("FAIL: high reads %q after the second sweep, want open", got)
	}
	if w := store.waiting[ids["high"]]; w == "" {
		t.Errorf("FAIL: high has an empty autoWaiting after the second sweep")
	} else if regexp.MustCompile(`\b(low|mid)\b`).MatchString(w) {
		t.Errorf("FAIL: high waits on a landed rung: %q", w)
	}
	for b, w := range map[string]string{"mid": store.waiting[ids["mid"]]} {
		if regexp.MustCompile(`\blow\b`).MatchString(w) {
			t.Errorf("FAIL: %s names the landed rung low: %q", b, w)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An explicit press on the top stays whole: with a rung above the green
// bottom still testing, nothing lands.
func TestAPressedStackStillLandsAllOrNothing(t *testing.T) {
	dir, ids, ix, sync := threeRungs(t)
	ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
	ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
	d, _ := prefixDeps(t, dir, ix, sync, ci)
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["high"]})
	if err != nil {
		t.Fatal(err)
	}
	if out := got.(landingLandOut); len(out.Landed) != 0 {
		t.Errorf("FAIL: a press with a pending rung landed %v", out.Landed)
	}
	if got := stateOf(t, ix, ids["low"]); got != "open" {
		t.Errorf("FAIL: low reads %q after a press that could not land the stack, want open", got)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The listing's open count is the open landings it lists, a stack of
// three counting three.
func TestTheLandingListCountsEveryOpenLanding(t *testing.T) {
	dir, _, ix, sync := threeRungs(t)
	d, _ := prefixDeps(t, dir, ix, sync, &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}})
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	got, err := r.Invoke(as("dan", "i"), "landing.list", landingListIn{Repo: "test", State: "open"})
	if err != nil {
		t.Fatal(err)
	}
	out := got.(landingListOut)
	if out.Open != 3 || out.Count != 3 || out.Decisions != 1 {
		t.Errorf("FAIL: list reads open=%d count=%d decisions=%d, want 3, 3 and 1", out.Open, out.Count, out.Decisions)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// trunkChecks requires the check on trunk alone: a rung above the base
// targets the rung below, which requires nothing.
type trunkChecks struct{}

func (trunkChecks) RequiredChecks(_, target string) []string {
	if target == "trunk" {
		return []string{"ci"}
	}
	return nil
}

// With checks required on trunk only (every rung is held to the base's
// set), a stack green throughout lands whole in one sweep.
func TestAnArmedStackWithTrunkOnlyChecksLandsInOneSweep(t *testing.T) {
	dir, ids, ix, sync := threeRungs(t)
	ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
	ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
	ci.green(ztip(t, dir, "mid"), ztip(t, dir, "low"))
	ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
	d, _ := prefixDeps(t, dir, ix, sync, ci)
	d.Checks = trunkChecks{}
	store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
	for _, b := range []string{"low", "mid", "high"} {
		store.rows = append(store.rows, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
	}
	if landed := d.AutoAcceptSweep(store); len(landed) != 3 {
		t.Errorf("FAIL: the sweep landed %v, want all three", landed)
	}
	for _, b := range []string{"low", "mid", "high"} {
		if got := stateOf(t, ix, ids[b]); got != "accepted" {
			t.Errorf("FAIL: %s reads %q, want accepted", b, got)
		}
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// The sweep lands the base; a press on the top then lands the rest once
// they are green: the rung above the landed one is not "behind" for
// holding the merge of what landed beneath it.
func TestAPressAfterTheSweepLandedTheBaseLandsTheRest(t *testing.T) {
	dir, ids, ix, sync := threeRungs(t)
	ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
	ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
	d, _ := prefixDeps(t, dir, ix, sync, ci)
	store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
	for _, b := range []string{"low", "mid", "high"} {
		store.rows = append(store.rows, oltp.AutoAccept{Repo: "test", Landing: ids[b], Account: "dan", Tip: ztip(t, dir, b)})
	}
	if landed := d.AutoAcceptSweep(store); len(landed) != 1 {
		t.Fatalf("FAIL: the sweep landed %v, want the base alone", landed)
	}
	ci.green(ztip(t, dir, "mid"), ztip(t, dir, "trunk"))
	ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
	r := ops.NewRegistry()
	if err := RegisterAll(r, d); err != nil {
		t.Fatal(err)
	}
	got, err := r.Invoke(as("dan", "i"), "landing.land", landingLandIn{Repo: "test", ID: ids["high"]})
	if err != nil {
		t.Fatal(err)
	}
	if out := got.(landingLandOut); len(out.Landed) != 2 || out.Stopped != "" {
		t.Errorf("FAIL: the press answered %+v, want mid and high landed", out)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}

// An armed rung below the top whose tip moved since arming is lapsed and
// not carried by the top's walk; the top's arm lapses with it.
func TestAMovedArmedRungBelowTheTopIsNotLanded(t *testing.T) {
	dir, ids, ix, sync := threeRungs(t)
	ci := &mergeRuns{pairRuns: &pairRuns{runs: map[string][]CIRun{}}}
	ci.green(ztip(t, dir, "low"), ztip(t, dir, "trunk"))
	ci.green(ztip(t, dir, "mid"), ztip(t, dir, "low"))
	ci.green(ztip(t, dir, "high"), ztip(t, dir, "mid"))
	d, _ := prefixDeps(t, dir, ix, sync, ci)
	store := &waitStub{waiting: map[string]string{}, cleared: map[string]bool{}}
	store.rows = []oltp.AutoAccept{
		{Repo: "test", Landing: ids["mid"], Account: "dan", Tip: ztip(t, dir, "low")},
		{Repo: "test", Landing: ids["high"], Account: "dan", Tip: ztip(t, dir, "high")},
	}
	if landed := d.AutoAcceptSweep(store); len(landed) != 0 {
		t.Errorf("FAIL: the sweep landed %v past a moved rung", landed)
	}
	if !store.lapsed[ids["mid"]] || !store.lapsed[ids["high"]] {
		t.Errorf("FAIL: lapsed %v, want mid and high", store.lapsed)
	}
	if !t.Failed() {
		t.Log("ok")
	}
}