package ci import ( "context" "errors" "path/filepath" "slices" "testing" "hearthforge/internal/config" "hearthforge/internal/db" ) // newRunnerDB gives a Runner backed by a fresh database holding one repo. func newRunnerDB(t *testing.T) (*Runner, *db.DB) { t.Helper() dir := t.TempDir() d, err := db.Open(filepath.Join(dir, "hearthforge.db")) if err != nil { t.Fatal(err) } t.Cleanup(func() { d.Close() }) for _, q := range []string{ `INSERT INTO repositories (id, name, is_private, created_at) VALUES (1, 'demo', 0, 'now')`, `INSERT INTO users (id, username, created_at) VALUES (1, 'admin', 'now')`, } { if _, err := d.ExecContext(context.Background(), q); err != nil { t.Fatal(err) } } return New(&config.Config{DataDir: dir, CIMaxConcurrent: 1, CIMaxHistory: 50}, d), d } func insertRun(t *testing.T, d *db.DB, status string) int64 { t.Helper() res, err := d.ExecContext(context.Background(), `INSERT INTO ci_runs (repo_id, trigger_source, commit_sha, status) VALUES (1, 'manual', 'abc', ?)`, status) if err != nil { t.Fatal(err) } id, _ := res.LastInsertId() return id } func TestRetryRunRejectsUnfinishedRun(t *testing.T) { r, d := newRunnerDB(t) for _, status := range []string{"pending", "running", "queued"} { id := insertRun(t, d, status) if err := r.RetryRun(context.Background(), id, 1); !errors.Is(err, ErrRunNotFinished) { t.Fatalf("status %s: got %v", status, err) } var got string if err := d.QueryRowContext(context.Background(), `SELECT status FROM ci_runs WHERE id = ?`, id).Scan(&got); err != nil { t.Fatal(err) } if got != status { t.Fatalf("status %s was changed to %s", status, got) } } } func TestRetryRunMissingRun(t *testing.T) { r, _ := newRunnerDB(t) if err := r.RetryRun(context.Background(), 999, 1); err == nil { t.Fatal("expected an error") } } // The terminal status list in RetryRun must match the statuses runs finish // with, otherwise no run could ever be retried. func TestRetryRunAcceptsFinishedStatuses(t *testing.T) { r, d := newRunnerDB(t) // A full concurrency slot keeps the retry in the queue, so the run does // not start and this test never talks to a container engine. r.running[-1] = &task{} for _, status := range []string{"success", "failure", "warning", "cancelled", "skipped"} { id := insertRun(t, d, status) if err := r.RetryRun(context.Background(), id, 1); err != nil { t.Fatalf("status %s: %v", status, err) } var got string if err := d.QueryRowContext(context.Background(), `SELECT status FROM ci_runs WHERE id = ?`, id).Scan(&got); err != nil { t.Fatal(err) } if got != "queued" { t.Fatalf("status %s became %s, want queued", status, got) } } } // finishSlot must not release a slot another execution owns: a retry that // restarted the same run holds its own task. func TestFinishSlotKeepsForeignTask(t *testing.T) { r, _ := newRunnerDB(t) mine, theirs := &task{}, &task{} r.running[7] = theirs r.finishSlot(7, mine) if r.running[7] != theirs { t.Fatal("finishSlot released a slot it does not own") } r.finishSlot(7, theirs) if _, ok := r.running[7]; ok { t.Fatal("finishSlot did not release its own slot") } } func TestMaskLog(t *testing.T) { secrets := []string{"abc", "abcdef"} if got := maskLog("x abcdef y", secrets, false); got != "x [MASKED] y" { t.Errorf("longest first: got %q", got) } if got := maskLog("x ab", secrets, false); got != "x ab" { t.Errorf("complete log: got %q", got) } if got := maskLog("x abcdefg ab", secrets, true); got != "x [MASKED]g " { t.Errorf("partial log: got %q", got) } if got := maskLog("x ab"+logTruncatedNotice, secrets, false); got != "x "+logTruncatedNotice { t.Errorf("truncated log: got %q", got) } } func TestRegistryIsLowercase(t *testing.T) { env, _ := buildEnvVars(1, "MyRepo", "", "git.example.com", runRow{}, &Config{}, nil, nil) if !slices.Contains(env, "CI_REGISTRY=git.example.com/myrepo") { t.Fatalf("env = %v", env) } } // A retried old run finishes last, so it must survive the prune. func TestPruneHistoryKeepsRecentlyFinished(t *testing.T) { r, d := newRunnerDB(t) r.cfg.CIMaxHistory = 2 var ids []int64 for i, finished := range []string{"2026-01-04", "2026-01-02", "2026-01-03"} { ids = append(ids, insertRun(t, d, "success")) if _, err := d.ExecContext(context.Background(), `UPDATE ci_runs SET finished_at = ? WHERE id = ?`, finished, ids[i]); err != nil { t.Fatal(err) } } r.pruneHistory(context.Background(), 1) var left []int64 rows, err := d.QueryContext(context.Background(), `SELECT id FROM ci_runs ORDER BY id`) if err != nil { t.Fatal(err) } defer rows.Close() for rows.Next() { var id int64 rows.Scan(&id) left = append(left, id) } if !slices.Equal(left, []int64{ids[0], ids[2]}) { t.Fatalf("kept %v, want %v", left, []int64{ids[0], ids[2]}) } } func TestRetryRunRejectsRunStillCleaningUp(t *testing.T) { r, d := newRunnerDB(t) id := insertRun(t, d, "cancelled") r.running[id] = &task{} if err := r.RetryRun(context.Background(), id, 1); !errors.Is(err, ErrRunNotFinished) { t.Fatalf("got %v", err) } }