package api
import (
"context"
"encoding/json"
"testing"
"craftdesign.group/quarry/internal/ops"
)
// checkin.get names the checks the check-in's branch requires and which
// of them are not green on this check-in, by the same name rule a
// landing's accept gate uses — so a deploy can ask "is this exact hash
// green for trunk" without re-implementing the rule in shell.
func TestCheckinGetNamesRequiredAndUnmetChecks(t *testing.T) {
ix := redTrunkIndex(t)
runs := runsStub{runs: []CIRun{
{RunID: "r1", Checkin: redTrunkTip, Workflow: "quarry.quarry.1", Pipeline: "ci/quarry.json", Status: "completed"},
{RunID: "r2", Checkin: redTrunkTip, Workflow: "quarry.race.1", Pipeline: "ci/race.json", Status: "failed"},
}}
get := func(d Deps) map[string]any {
t.Helper()
r := ops.NewRegistry()
if err := RegisterAll(r, d); err != nil {
t.Fatal(err)
}
got, err := r.Invoke(context.Background(), "checkin.get", checkinGetIn{Repo: "test", Hash: redTrunkTip})
if err != nil {
t.Fatal(err)
}
b, _ := json.Marshal(got)
var m map[string]any
if err := json.Unmarshal(b, &m); err != nil {
t.Fatal(err)
}
return m
}
d := Deps{Version: "v", Repos: NewRepos(map[string]*Repo{"test": {Index: ix}}), CI: runs, Checks: checksStub{required: []string{"quarry", "race"}}}
m := get(d)
req, _ := m["required"].([]any)
unmet, _ := m["unmet"].([]any)
if len(req) != 2 || req[0] != "quarry" || req[1] != "race" {
t.Fatalf("FAIL: required = %v, want [quarry race]", m["required"])
}
if len(unmet) != 1 || unmet[0] != "race" {
t.Fatalf("FAIL: unmet = %v, want [race]", m["unmet"])
}
t.Log("ok: a red required check is unmet")
runs.runs[1].Status = "completed"
d.CI = runs
m = get(d)
if u, ok := m["unmet"].([]any); !ok || len(u) != 0 {
t.Fatalf("FAIL: unmet = %#v, want an empty list", m["unmet"])
}
t.Log("ok: all green is an empty unmet list, present")
d.Checks = checksStub{}
m = get(d)
if r, ok := m["required"].([]any); !ok || len(r) != 0 {
t.Fatalf("FAIL: required = %#v, want an empty list for a branch with none", m["required"])
}
t.Log("ok: a branch with no required checks says so with an empty list")
}