refactor: testing from the beginning. a journey in 150k lines of tests to none

This commit is contained in:
sam committed 2026-10-03 21:16:25 +10:00
1 parent ba37e37e53
commit ff424b70ac
651 files changed
-146443

No files matched your search

-177
View File
@@ -1,177 +0,0 @@
package taskstate
import (
"slices"
"testing"
)
// The rules must be the same wherever an operator acts. These cases are the
// contract both the dashboard and chat are held to; a divergence between them
// is what this package exists to prevent.
func TestActionRules(t *testing.T) {
tests := []struct {
status string
approve, retry, decline bool
terminal bool
actions []Action
}{
{status: Queued, decline: true, actions: []Action{ActionCancel, ActionReject}},
{status: Running, decline: true, actions: []Action{ActionStop, ActionReject}},
{status: WaitingHuman, approve: true, decline: true, actions: []Action{ActionApprove, ActionReject, ActionRereview}},
{status: PROpen, decline: true, actions: []Action{ActionOpenPR, ActionOpenIssue, ActionReject}},
{status: Parked, retry: true, decline: true, actions: []Action{ActionRetry, ActionAbandon, ActionReject}},
{status: Merged, terminal: true, actions: []Action{ActionArchive}},
{status: Rejected, terminal: true, actions: []Action{ActionArchive}},
{status: Dead, terminal: true, actions: []Action{ActionArchive}},
{status: Declined, terminal: true, actions: []Action{ActionArchive}},
{status: Completed, terminal: true, actions: []Action{ActionArchive}},
}
for _, tc := range tests {
t.Run(tc.status, func(t *testing.T) {
if got := CheckApprove(tc.status) == nil; got != tc.approve {
t.Errorf("CheckApprove allowed = %v, want %v", got, tc.approve)
}
if got := CheckRetry(tc.status) == nil; got != tc.retry {
t.Errorf("CheckRetry allowed = %v, want %v", got, tc.retry)
}
if got := CheckDecline(tc.status) == nil; got != tc.decline {
t.Errorf("CheckDecline allowed = %v, want %v", got, tc.decline)
}
if got := Terminal(tc.status); got != tc.terminal {
t.Errorf("Terminal = %v, want %v", got, tc.terminal)
}
if got := Actions(tc.status); !slices.Equal(got, tc.actions) {
t.Errorf("Actions = %v, want %v", got, tc.actions)
}
for _, action := range tc.actions {
if err := CheckAction(tc.status, action); err != nil {
t.Errorf("CheckAction(%q) = %v", action, err)
}
}
})
}
}
// An unknown status must not be silently actionable: a typo or a status from
// a newer version should refuse rather than approve.
func TestUnknownStatusIsNotApprovable(t *testing.T) {
const unknown = "quantum_superposition"
if err := CheckApprove(unknown); err == nil {
t.Error("CheckApprove allowed an unknown status")
}
if err := CheckRetry(unknown); err == nil {
t.Error("CheckRetry allowed an unknown status")
}
if err := CheckDecline(unknown); err == nil {
t.Error("CheckDecline allowed an unknown status")
}
}
// Rejected and Declined must stay distinct. Collapsing them would lose the
// difference between "the forge closed the PR" and "a human said no", which
// is the drift this package was created to end.
func TestRejectedAndDeclinedAreDistinct(t *testing.T) {
if Rejected == Declined {
t.Fatal("Rejected and Declined are the same string")
}
if !Terminal(Rejected) || !Terminal(Declined) {
t.Error("both must be terminal")
}
}
// The presentation catalog must cover every status and action the lifecycle
// exposes, so the frontend can render anything the rules allow without holding
// its own copy of the vocabulary.
func TestPresentationCatalog(t *testing.T) {
allowedKinds := map[string]bool{"idle": true, "info": true, "ok": true, "warn": true, "danger": true}
statuses := Statuses()
if len(statuses) == 0 {
t.Fatal("Statuses() returned no entries")
}
seen := map[string]bool{}
for _, meta := range statuses {
if meta.ID == "" || meta.Label == "" || !allowedKinds[meta.Kind] {
t.Errorf("status %q: id=%q label=%q kind=%q", meta.ID, meta.ID, meta.Label, meta.Kind)
}
if seen[meta.ID] {
t.Errorf("duplicate status id %q", meta.ID)
}
seen[meta.ID] = true
if meta.NeedsYou && meta.Kind == "idle" {
t.Errorf("status %q is marked needs_you but has idle severity", meta.ID)
}
}
// Every lifecycle status must have presentation metadata.
for _, status := range []string{Queued, Running, WaitingHuman, PROpen, Merged, Parked, Dead, Rejected, Declined, Completed} {
if !seen[status] {
t.Errorf("status %q missing from Statuses()", status)
}
}
actions := ActionCatalog()
if len(actions) == 0 {
t.Fatal("ActionCatalog() returned no entries")
}
actionSeen := map[string]bool{}
for _, meta := range actions {
if meta.ID == "" || meta.Label == "" {
t.Errorf("action %q: id=%q label=%q", meta.ID, meta.ID, meta.Label)
}
if actionSeen[meta.ID] {
t.Errorf("duplicate action id %q", meta.ID)
}
actionSeen[meta.ID] = true
// link actions navigate; the rest must carry a button kind.
if meta.Kind != "link" && meta.Kind != "primary" && meta.Kind != "quiet" && meta.Kind != "danger" {
t.Errorf("action %q has unknown kind %q", meta.ID, meta.Kind)
}
}
// Every action the lifecycle table can emit must be describable, otherwise
// the frontend has no way to present it.
byID := func(status string) map[Action]bool {
out := map[Action]bool{}
for _, a := range Actions(status) {
out[a] = true
}
return out
}
for _, status := range []string{Queued, Running, WaitingHuman, PROpen, Parked, Merged, Rejected, Dead, Declined, Completed} {
for a := range byID(status) {
if !actionSeen[string(a)] {
t.Errorf("action %q from status %q has no ActionCatalog entry", a, status)
}
}
}
}
func TestActionsReturnsIndependentSlices(t *testing.T) {
first := Actions(WaitingHuman)
first[0] = ActionArchive
if got := Actions(WaitingHuman); !slices.Equal(got, []Action{ActionApprove, ActionReject, ActionRereview}) {
t.Fatalf("mutating returned actions changed lifecycle table: %v", got)
}
}
func TestNormalizeParkClass(t *testing.T) {
tests := []struct {
name string
input string
want ParkClass
}{
{name: "empty defaults to needs_human", input: "", want: ParkNeedsHuman},
{name: "a known class passes through", input: ParkTransient, want: ParkTransient},
{name: "terminal passes through", input: ParkTerminal, want: ParkTerminal},
{name: "an unknown class falls back to needs_human", input: "urgent", want: ParkNeedsHuman},
{name: "case differences are not classes", input: "TRANSIENT", want: ParkNeedsHuman},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := NormalizeParkClass(tt.input); got != tt.want {
t.Errorf("NormalizeParkClass(%q) = %q, want %q", tt.input, got, tt.want)
}
})
}
}
@@ -1,133 +0,0 @@
package taskstatetest
import (
"context"
"slices"
"testing"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// The routes the fixtures ask for, written out rather than derived from the
// table: a route that changed shape -- a longer way round, or through a status
// whose transition writes something else -- would otherwise be invisible.
func TestPathIsTheShortLegalRoute(t *testing.T) {
tests := []struct {
name, from, target string
want []string
}{
{name: "already there", from: taskstate.Queued, target: taskstate.Queued},
{name: "claim", from: taskstate.Queued, target: taskstate.Running, want: []string{taskstate.Running}},
{name: "await approval", from: taskstate.Queued, target: taskstate.WaitingHuman, want: []string{taskstate.Running, taskstate.WaitingHuman}},
{name: "park", from: taskstate.Queued, target: taskstate.Parked, want: []string{taskstate.Running, taskstate.Parked}},
{name: "spend the retries", from: taskstate.Queued, target: taskstate.Dead, want: []string{taskstate.Running, taskstate.Parked, taskstate.Dead}},
{name: "merge", from: taskstate.Queued, target: taskstate.Merged, want: []string{taskstate.Running, taskstate.PROpen, taskstate.Merged}},
{name: "rejected pull request", from: taskstate.Queued, target: taskstate.Rejected, want: []string{taskstate.Running, taskstate.PROpen, taskstate.Rejected}},
{name: "finish with no pull request", from: taskstate.Queued, target: taskstate.Completed, want: []string{taskstate.Running, taskstate.Completed}},
{name: "refuse the work", from: taskstate.Queued, target: taskstate.Declined, want: []string{taskstate.Declined}},
{name: "merge a running task", from: taskstate.Running, target: taskstate.Merged, want: []string{taskstate.PROpen, taskstate.Merged}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := Path(tt.from, tt.target)
if err != nil {
t.Fatalf("Path(%s, %s) error = %v", tt.from, tt.target, err)
}
if !slices.Equal(got, tt.want) {
t.Errorf("Path(%s, %s) = %v, want %v", tt.from, tt.target, got, tt.want)
}
})
}
}
// Every route is walkable. A route through a pair the table refuses is exactly
// what this package exists to prevent, so it is checked here rather than
// discovered later at the store.
func TestRoutesOnlyTakeLegalEdges(t *testing.T) {
for _, from := range statusIDs() {
for _, want := range statusIDs() {
got, err := Path(from, want)
if err != nil {
continue
}
at := from
for _, to := range got {
if !taskstate.CanTransition(at, to) {
t.Errorf("route %s -> %s takes %s -> %s, which the table refuses", from, want, at, to)
}
at = to
}
if at != want {
t.Errorf("route %s -> %s ends at %s", from, want, at)
}
}
}
}
// Nothing follows a terminal status, so no fixture can seed out of one: it
// would have to have been written there illegitimately in the first place.
func TestTerminalStatusIsNotAStartingPoint(t *testing.T) {
for _, from := range statusIDs() {
if !taskstate.Terminal(from) {
continue
}
for _, want := range statusIDs() {
if want == from {
continue
}
got, err := Path(from, want)
if err == nil {
t.Errorf("Path(%s, %s) = %v, want an error", from, want, got)
}
}
}
}
func TestUnknownStatusIsNeverARoute(t *testing.T) {
const unknown = "half_written"
if got, err := Path(unknown, taskstate.Running); err == nil {
t.Errorf("Path(%s, running) = %v, want an error", unknown, got)
}
if got, err := Path(taskstate.Queued, unknown); err == nil {
t.Errorf("Path(queued, %s) = %v, want an error", unknown, got)
}
if got, err := Path(unknown, unknown); err == nil {
t.Errorf("Path(%s, %s) = %v, want an error", unknown, unknown, got)
}
}
// Seed applies the route edge by edge, in order, carrying the fixture's own
// reason: a park seeded this way keeps the reason the fixture passed, which is
// what the retry path reads back as the previous failure.
func TestSeedWalksTheRouteThroughTheStore(t *testing.T) {
st := &recorder{}
Seed(t.Context(), t, st, 7, taskstate.Queued, taskstate.Merged, "fixture reason")
want := []edge{
{from: taskstate.Queued, to: taskstate.Running, detail: "fixture reason"},
{from: taskstate.Running, to: taskstate.PROpen, detail: "fixture reason"},
{from: taskstate.PROpen, to: taskstate.Merged, detail: "fixture reason"},
}
if !slices.Equal(st.edges, want) {
t.Errorf("Seed wrote %v, want %v", st.edges, want)
}
}
// A task already in the wanted status is left untouched rather than written to
// itself: a guarded transition from running to running matches no row.
func TestSeedOfTheSameStatusWritesNothing(t *testing.T) {
st := &recorder{}
Seed(t.Context(), t, st, 7, taskstate.Completed, taskstate.Completed, "")
if len(st.edges) != 0 {
t.Errorf("Seed wrote %v, want no writes", st.edges)
}
}
type edge struct{ from, to, detail string }
type recorder struct{ edges []edge }
func (r *recorder) Transition(_ context.Context, _ int64, from, to, detail string) error {
r.edges = append(r.edges, edge{from: from, to: to, detail: detail})
return nil
}
-276
View File
@@ -1,276 +0,0 @@
package taskstate
import (
"slices"
"testing"
)
// The legal pairs are written out here rather than read from the map under
// test. A table-driven test that derived its expectation from the table would
// hold for any table, including an empty one.
var legalExecutionTransitions = []struct{ from, to string }{
{Queued, Running},
{Queued, Declined},
{Running, Queued},
{Running, WaitingHuman},
{Running, PROpen},
{Running, Completed},
{Running, Parked},
{Running, Declined},
{WaitingHuman, Queued},
{WaitingHuman, Declined},
{Parked, Queued},
{Parked, Dead},
{Parked, Declined},
{PROpen, Merged},
{PROpen, Rejected},
{PROpen, Queued},
{PROpen, Declined},
}
var legalStepTransitions = []struct{ from, to StepStatus }{
{StepPending, StepRunning},
{StepPending, StepCancelled},
{StepRunning, StepSucceeded},
{StepRunning, StepFailed},
{StepRunning, StepCancelled},
{StepRunning, StepInterrupted},
}
func statusIDs() []string {
ids := make([]string, 0, len(Statuses()))
for _, meta := range Statuses() {
ids = append(ids, meta.ID)
}
return ids
}
func execPair(from, to string) string { return from + " -> " + to }
// The whole cross product, not a sample: every pair the vocabulary can
// express is checked against the legal set, so an edge nobody meant to add
// fails here rather than at the store.
func TestExecutionTransitionTableIsExactlyThePRDTable(t *testing.T) {
known := statusIDs()
legal := map[string]bool{}
for _, p := range legalExecutionTransitions {
if !slices.Contains(known, p.from) || !slices.Contains(known, p.to) {
t.Fatalf("legal pair %s names a status the catalog does not present", execPair(p.from, p.to))
}
if legal[execPair(p.from, p.to)] {
t.Fatalf("duplicate legal pair %s", execPair(p.from, p.to))
}
legal[execPair(p.from, p.to)] = true
}
for _, from := range known {
for _, to := range known {
want := legal[execPair(from, to)]
if got := CanTransition(from, to); got != want {
t.Errorf("CanTransition(%s) = %v, want %v", execPair(from, to), got, want)
}
}
}
}
// The PRD names one write the store accepts today and the table must refuse:
// a queued task cannot be born merged. It is the pair a table that only
// checked "is this a known status" would still let through.
func TestQueuedCannotReachMerged(t *testing.T) {
if CanTransition(Queued, Merged) {
t.Error("CanTransition(queued, merged) = true; the transition tables section names this pair as illegal")
}
}
// The other pair written before the table existed, by every fixture that
// needed a finished task: a merge is observed on an open pull request, never
// straight from running. Named here so the next fixture that reaches for it is
// a failure in the table's own test rather than a surprise at the store.
func TestRunningCannotReachMerged(t *testing.T) {
if CanTransition(Running, Merged) {
t.Error("CanTransition(running, merged) = true; a merge is only observed on an open pull request")
}
}
// An unknown status must be illegal in both positions. A status written by a
// newer version, or a typo, must not be able to start or end a transition.
func TestUnknownStatusIsNeverATransition(t *testing.T) {
const unknown = "quantum_superposition"
for _, status := range statusIDs() {
if CanTransition(unknown, status) {
t.Errorf("CanTransition(%s -> %s) = true", unknown, status)
}
if CanTransition(status, unknown) {
t.Errorf("CanTransition(%s -> %s) = true", status, unknown)
}
}
if CanTransition(unknown, unknown) {
t.Errorf("CanTransition(%s -> %s) = true", unknown, unknown)
}
if CanStepTransition(StepStatus(unknown), StepPending) {
t.Errorf("CanStepTransition(%s -> %s) = true", unknown, StepPending)
}
if CanStepTransition(StepRunning, StepStatus(unknown)) {
t.Errorf("CanStepTransition(%s -> %s) = true", StepRunning, unknown)
}
}
// Rows must cover the vocabulary, and only the vocabulary. A status added to
// the presentation catalog without a row would be unroutable -- no writer
// could move a task into or out of it -- and the failure would surface as a
// task stuck in a state, long after the edit.
func TestTransitionRowsCoverTheStatusVocabulary(t *testing.T) {
known := map[string]bool{}
for _, id := range statusIDs() {
known[id] = true
if _, ok := executionTransitions[id]; !ok {
t.Errorf("status %q has no row in executionTransitions", id)
}
}
for from := range executionTransitions {
if !known[from] {
t.Errorf("executionTransitions has a row for %q, which the catalog does not present", from)
}
for _, to := range executionTransitions[from] {
if !known[to] {
t.Errorf("executionTransitions row %q names %q, which the catalog does not present", from, to)
}
}
}
}
// A terminal status has no way out and a live one must have at least one way
// forward: a live status with no edges strands every task that reaches it.
func TestTerminalAndRoutableRowsAgree(t *testing.T) {
for _, id := range statusIDs() {
if got, want := len(executionTransitions[id]) == 0, Terminal(id); got != want {
t.Errorf("status %q: row is empty = %v, Terminal = %v", id, got, want)
}
}
for _, status := range stepVocabulary() {
if got, want := len(stepTransitions[status]) == 0, StepTerminal(status); got != want {
t.Errorf("step %q: row is empty = %v, StepTerminal = %v", status, got, want)
}
}
}
func stepVocabulary() []StepStatus {
return []StepStatus{StepPending, StepRunning, StepSucceeded, StepFailed, StepCancelled, StepInterrupted}
}
func TestStepTransitionTableIsExactlyThePRDTable(t *testing.T) {
known := stepVocabulary()
legal := map[StepStatus]bool{}
for _, p := range legalStepTransitions {
if !slices.Contains(known, p.from) || !slices.Contains(known, p.to) {
t.Fatalf("legal pair %s -> %s names a step status not in the vocabulary", p.from, p.to)
}
legal[p.from+"->"+p.to] = true
}
for _, from := range known {
for _, to := range known {
want := legal[from+"->"+to]
if got := CanStepTransition(from, to); got != want {
t.Errorf("CanStepTransition(%s -> %s) = %v, want %v", from, to, got, want)
}
}
}
}
func TestStepTransitionRowsCoverTheStepVocabulary(t *testing.T) {
known := map[StepStatus]bool{}
for _, status := range stepVocabulary() {
known[status] = true
if _, ok := stepTransitions[status]; !ok {
t.Errorf("step status %q has no row in stepTransitions", status)
}
}
for from := range stepTransitions {
if !known[from] {
t.Errorf("stepTransitions has a row for unknown step status %q", from)
}
for _, to := range stepTransitions[from] {
if !known[to] {
t.Errorf("stepTransitions row %q names unknown step status %q", from, to)
}
}
}
}
// Two ways for a step to stop early, and they must not be confused:
// cancelled is someone asking, interrupted is the process dying.
func TestStepTerminal(t *testing.T) {
terminals := []StepStatus{StepSucceeded, StepFailed, StepCancelled, StepInterrupted}
for _, status := range stepVocabulary() {
want := slices.Contains(terminals, status)
if got := StepTerminal(status); got != want {
t.Errorf("StepTerminal(%s) = %v, want %v", status, got, want)
}
}
if StepTerminal(StepStatus("half_written")) {
t.Error("StepTerminal(unknown) = true")
}
}
// The step vocabulary is separate and stays out of the execution catalog: a
// step status listed in Statuses() would show the dashboard a task status no
// task can have.
func TestStepVocabularyStaysOutOfTheExecutionCatalog(t *testing.T) {
ids := statusIDs()
for _, status := range stepVocabulary() {
if string(status) == Running {
// The two vocabularies deliberately share this word.
continue
}
if slices.Contains(ids, string(status)) {
t.Errorf("step status %q is presented as an execution status", status)
}
}
}
// A step may only enter running while its execution is running, and never
// under a parent that is already terminal: a finished parent's children were
// cancelled or interrupted when it finished.
func TestCheckStepStart(t *testing.T) {
tests := []struct {
name string
execution string
parentTerminal bool
wantErr bool
}{
{name: "running execution, live parent", execution: Running},
{name: "running execution, terminal parent", execution: Running, parentTerminal: true, wantErr: true},
{name: "queued execution", execution: Queued, wantErr: true},
{name: "execution waiting on a human", execution: WaitingHuman, wantErr: true},
{name: "execution parked", execution: Parked, wantErr: true},
{name: "execution with a pull request open", execution: PROpen, wantErr: true},
{name: "terminal execution", execution: Merged, wantErr: true},
{name: "unknown execution", execution: "quantum_superposition", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := CheckStepStart(tt.execution, tt.parentTerminal)
if got := err != nil; got != tt.wantErr {
t.Errorf("CheckStepStart(%q, %v) error = %v, want error = %v", tt.execution, tt.parentTerminal, err, tt.wantErr)
}
})
}
for _, id := range statusIDs() {
if err := CheckStepStart(id, false); (err != nil) != (id != Running) {
t.Errorf("CheckStepStart(%q, false) = %v, want error exactly when %q is not running", id, err, id)
}
}
}
func TestOfferedActionsAreLegalTransitions(t *testing.T) {
for status := range executionTransitions {
for _, action := range Actions(status) {
to, moves := ActionTarget(action)
if moves && !CanTransition(status, to) {
t.Errorf("%s offers %s, but %s -> %s is not in the transition table", status, action, status, to)
}
}
}
}