package api
import (
"path/filepath"
"reflect"
"testing"
"craftdesign.group/quarry/internal/oltp"
"craftdesign.group/quarry/internal/ops"
)
type branchChecks map[string][]string
func (c branchChecks) RequiredChecks(_, branch string) []string { return c[branch] }
func armStackRig(t *testing.T, checks branchChecks) *ops.Registry {
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)
}
d := Deps{Version: "v", Auto: db, Checks: checks,
Repos: NewRepos(map[string]*Repo{"test": {Chat: "test", Index: strataRetargetIndex(t)}})}
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
return r
}
func armRung(t *testing.T, r *ops.Registry, id string) landingAutoOut {
t.Helper()
out, err := r.Invoke(as("dan", "i"), "landing.auto", landingAutoIn{Repo: "test", ID: id, On: flag(true)})
if err != nil {
t.Fatalf("FAIL: arming %s: %v", id, err)
}
return out.(landingAutoOut)
}
// A rung armed on a branch with no required checks is gated on the
// checks of the stack's final target, not on its immediate target.
func TestArmingARungReadsTheStacksFinalTarget(t *testing.T) {
const mid, solo = "c1c1c1c1c1c1", "d2d2d2d2d2d2"
gated := armRung(t, armStackRig(t, branchChecks{"trunk": {"go"}}), mid)
open := armRung(t, armStackRig(t, branchChecks{}), mid)
if !reflect.DeepEqual(gated.Stack, []string{"base", "mid"}) || gated.FinalTarget != "trunk" {
t.Errorf("FAIL: stack %v final %q", gated.Stack, gated.FinalTarget)
}
if !reflect.DeepEqual(open.Stack, gated.Stack) || open.FinalTarget != "trunk" {
t.Errorf("FAIL: ungated stack %v final %q", open.Stack, open.FinalTarget)
}
if gated.Say == open.Say {
t.Errorf("FAIL: the say ignored the final target's required checks: %q", gated.Say)
}
// Checks required only on the rung's immediate target do not gate a
// stack that lands on trunk.
if wrong := armRung(t, armStackRig(t, branchChecks{"base": {"go"}}), mid); wrong.Say != open.Say {
t.Errorf("FAIL: the immediate target's checks were read: %q", wrong.Say)
}
// A landing on its own has no stack and reads its own target.
alone := armRung(t, armStackRig(t, branchChecks{"trunk": {"go"}}), solo)
if len(alone.Stack) != 0 || alone.FinalTarget != "" || !alone.Armed {
t.Errorf("FAIL: a lone landing: %+v", alone)
}
if alone.Say == armRung(t, armStackRig(t, branchChecks{}), solo).Say {
t.Error("FAIL: a lone landing ignored its target's checks")
}
if !t.Failed() {
t.Log("ok")
}
}