gunk-dev/the-valley

harness_test.go

source68d12192bbd3main's published tip history
22.4 KiB
1//go:build e2e
2
3package e2e
4
5import (
6 "bytes"
7 "encoding/json"
8 "fmt"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "testing"
14 "time"
15
16 "the-valley/flow/internal/run"
17)
18
19// Harness is a fully isolated environment for driving the real klaus binary.
20//
21// Isolation guarantees (so tests never touch the developer's real tmux server
22// or ~/.klaus state):
23// - tmux: a private server on a per-test unix socket (Sock). klaus' own tmux
24// calls are pointed at it via the $TMUX env var; the test's control-plane
25// queries use `tmux -S <Sock>`.
26// - state: HOME is a per-test temp dir, so all ~/.klaus/sessions state lands
27// under Home.
28// - externals: a per-test bin dir (BinDir) is prepended to PATH and holds the
29// klaus binary plus fake `claude`/`gh` stubs. git and tmux stay real.
30//
31// A unique socket name + temp HOME per test keeps tests parallel-safe.
32type Harness struct {
33 t *testing.T
34
35 Home string // temp HOME ($HOME for all klaus invocations)
36 BinDir string // dir prepended to PATH; holds klaus + stubs
37 E2EDir string // scratch dir for stub coordination/log files
38 RepoDir string // sandbox repo working tree (CWD for klaus)
39 OriginDir string // bare "origin" remote backing RepoDir
40
41 Sock string // tmux server socket path (isolated server)
42 ServerPID string // isolated tmux server pid (for the $TMUX value)
43 InitialPane string // the session's first pane id (klaus splits from here)
44
45 SessionID string // KLAUS_SESSION_ID for all invocations
46 shellWrap string // path to the no-profile shell wrapper for tmux panes
47}
48
49// RunResult is the outcome of a klaus invocation.
50type RunResult struct {
51 Stdout string
52 Stderr string
53 ExitCode int
54}
55
56// NewHarness builds nothing (the binary is built once in TestMain) but wires up
57// a complete isolated environment: temp HOME, a bin dir with the klaus binary
58// and fake claude/gh stubs, a sandbox git repo with a bare origin, and an
59// isolated tmux server. It registers cleanup to kill the tmux server; temp dirs
60// are removed automatically by t.TempDir.
61func NewHarness(t *testing.T) *Harness {
62 t.Helper()
63
64 if klausBinary == "" {
65 t.Fatal("klaus binary not built (TestMain did not run)")
66 }
67
68 root := t.TempDir()
69 h := &Harness{
70 t: t,
71 Home: filepath.Join(root, "home"),
72 BinDir: filepath.Join(root, "bin"),
73 E2EDir: filepath.Join(root, "e2e"),
74 RepoDir: filepath.Join(root, "repo"),
75 OriginDir: filepath.Join(root, "origin.git"),
76 Sock: filepath.Join(root, "tmux.sock"),
77 SessionID: "session-e2e-" + filepath.Base(root),
78 }
79
80 for _, d := range []string{h.Home, h.BinDir, h.E2EDir} {
81 if err := os.MkdirAll(d, 0o755); err != nil {
82 t.Fatalf("mkdir %s: %v", d, err)
83 }
84 }
85
86 h.installKlausBinary()
87 h.installDefaultStubs()
88 h.setupGitConfig()
89 h.setupSandboxRepo()
90 h.writeRepoConfig()
91 h.startTmuxServer()
92
93 return h
94}
95
96// installKlausBinary copies the prebuilt klaus binary into BinDir as "klaus"
97// so the pane pipeline (which runs `klaus _format-stream`/`klaus _finalize`)
98// resolves it from PATH.
99func (h *Harness) installKlausBinary() {
100 h.t.Helper()
101 data, err := os.ReadFile(klausBinary)
102 if err != nil {
103 h.t.Fatalf("reading klaus binary: %v", err)
104 }
105 dst := filepath.Join(h.BinDir, "klaus")
106 if err := os.WriteFile(dst, data, 0o755); err != nil {
107 h.t.Fatalf("installing klaus binary: %v", err)
108 }
109}
110
111// WriteStub writes an executable script into BinDir, shadowing any real binary
112// of the same name for klaus invocations in this harness. A script that starts
113// with "#!/usr/bin/env bash" runs under the bash on PATH, named by its path:
114// the nix build sandbox the e2e check runs in has no /usr/bin/env.
115func (h *Harness) WriteStub(name, script string) {
116 h.t.Helper()
117 if rest, ok := strings.CutPrefix(script, "#!/usr/bin/env bash\n"); ok {
118 script = "#!" + mustBash(h.t) + "\n" + rest
119 }
120 p := filepath.Join(h.BinDir, name)
121 if err := os.WriteFile(p, []byte(script), 0o755); err != nil {
122 h.t.Fatalf("writing stub %s: %v", name, err)
123 }
124}
125
126// installDefaultStubs writes the fake claude and gh binaries. The claude stub
127// blocks until released (see ReleaseClaude) so tests can deterministically
128// observe the live pane before _finalize tears it down. Tests may override
129// either stub with WriteStub before launching.
130func (h *Harness) installDefaultStubs() {
131 h.t.Helper()
132 h.WriteDefaultClaudeOutput(defaultClaudeOutput)
133 h.WriteStub("claude", h.claudeStubScript())
134 h.WriteStub("gh", h.ghStubScript())
135}
136
137// defaultClaudeOutput is the stream-json the fake agent emits. It contains a PR
138// URL (matched by hidden.go's prURLExtractRegex), which _finalize records for
139// a run whose origin is on GitHub (UseGitHubOrigin), and a result event
140// carrying cost/duration/session_id so _finalize can populate run state.
141const defaultClaudeOutput = `{"type":"system","subtype":"init","model":"claude-e2e"}
142{"type":"assistant","message":{"content":[{"type":"text","text":"Opened PR: https://github.com/acme/widget/pull/4242"}]}}
143{"type":"result","subtype":"success","total_cost_usd":0.1234,"duration_ms":4242,"session_id":"11111111-2222-4333-8444-555555555555"}
144`
145
146// WriteDefaultClaudeOutput sets the JSONL the fake claude prints once released.
147func (h *Harness) WriteDefaultClaudeOutput(jsonl string) {
148 h.t.Helper()
149 if err := os.WriteFile(filepath.Join(h.E2EDir, "claude.output.jsonl"), []byte(jsonl), 0o644); err != nil {
150 h.t.Fatalf("writing claude output: %v", err)
151 }
152}
153
154func (h *Harness) claudeStubScript() string {
155 // Records argv, stdin (unless it is the pane's tty) + cwd, signals start,
156 // blocks until a release file appears (max ~60s), then emits the canned
157 // stream-json. Paths are baked in so the stub is independent of the pane's
158 // environment.
159 return fmt.Sprintf(`#!/usr/bin/env bash
160dir=%q
161{ for a in "$@"; do printf '%%s\n' "$a"; done; } > "$dir/claude.argv"
162[ -t 0 ] || cat > "$dir/claude.stdin"
163printf '%%s' "$PWD" > "$dir/claude.cwd"
164: > "$dir/claude.started"
165for _ in {1..600}; do
166 [ -f "$dir/claude.release" ] && break
167 sleep 0.1
168done
169cat "$dir/claude.output.jsonl"
170`, h.E2EDir)
171}
172
173func (h *Harness) ghStubScript() string {
174 // Logs every invocation so tests can prove how (or whether) gh was called,
175 // and returns benign output. The launch path avoids gh entirely (pr_reviewer
176 // is configured), so this is mostly a safety net against hitting real gh.
177 return fmt.Sprintf(`#!/usr/bin/env bash
178dir=%q
179{ printf 'gh'; for a in "$@"; do printf ' %%q' "$a"; done; printf '\n'; } >> "$dir/gh.argv"
180exit 0
181`, h.E2EDir)
182}
183
184// ReleaseClaude unblocks the fake claude so the pane pipeline proceeds to
185// _format-stream and _finalize.
186func (h *Harness) ReleaseClaude() {
187 h.t.Helper()
188 if err := os.WriteFile(filepath.Join(h.E2EDir, "claude.release"), nil, 0o644); err != nil {
189 h.t.Fatalf("releasing claude: %v", err)
190 }
191}
192
193// WaitForClaudeStart blocks until the fake claude has started running in the
194// pane (or the timeout elapses).
195func (h *Harness) WaitForClaudeStart(timeout time.Duration) {
196 h.t.Helper()
197 started := filepath.Join(h.E2EDir, "claude.started")
198 deadline := time.Now().Add(timeout)
199 for time.Now().Before(deadline) {
200 if _, err := os.Stat(started); err == nil {
201 return
202 }
203 time.Sleep(50 * time.Millisecond)
204 }
205 h.t.Fatalf("fake claude did not start within %s", timeout)
206}
207
208// ClaudeArgv returns the argv the fake claude was invoked with (one entry per
209// line as recorded), or "" if it has not run yet.
210func (h *Harness) ClaudeArgv() string {
211 b, _ := os.ReadFile(filepath.Join(h.E2EDir, "claude.argv"))
212 return string(b)
213}
214
215// ClaudeStdin returns what the fake claude read on stdin — the prompt, for
216// backends that take it there — or "" if stdin was the pane's tty.
217func (h *Harness) ClaudeStdin() string {
218 b, _ := os.ReadFile(filepath.Join(h.E2EDir, "claude.stdin"))
219 return string(b)
220}
221
222// WorkerSystemPrompt returns the system prompt file the fake claude was given
223// with --append-system-prompt-file, failing the test if there is none.
224func (h *Harness) WorkerSystemPrompt() string {
225 h.t.Helper()
226 argv := strings.Split(h.ClaudeArgv(), "\n")
227 for i, a := range argv {
228 if a == "--append-system-prompt-file" && i+1 < len(argv) {
229 data, err := os.ReadFile(argv[i+1])
230 if err != nil {
231 h.t.Fatalf("reading system prompt file: %v", err)
232 }
233 return string(data)
234 }
235 }
236 h.t.Fatalf("claude got no --append-system-prompt-file:\n%s", h.ClaudeArgv())
237 return ""
238}
239
240// GHArgv returns the logged gh invocations (one per line), or "" if gh was
241// never called.
242func (h *Harness) GHArgv() string {
243 b, _ := os.ReadFile(filepath.Join(h.E2EDir, "gh.argv"))
244 return string(b)
245}
246
247// setupGitConfig writes a global gitconfig under the temp HOME so git has a
248// committer identity (needed by data-ref commits) without touching the real
249// user config.
250func (h *Harness) setupGitConfig() {
251 h.t.Helper()
252 cfg := "[user]\n\tname = klaus-e2e\n\temail = klaus-e2e@example.com\n[init]\n\tdefaultBranch = main\n[protocol \"file\"]\n\tallow = always\n[safe]\n\tdirectory = *\n"
253 if err := os.WriteFile(filepath.Join(h.Home, ".gitconfig"), []byte(cfg), 0o644); err != nil {
254 h.t.Fatalf("writing gitconfig: %v", err)
255 }
256}
257
258// setupSandboxRepo creates a bare origin and a working clone with one commit on
259// main, pushed to origin. klaus' worktree/branch/push operations run against
260// these real repos with no network.
261func (h *Harness) setupSandboxRepo() {
262 h.t.Helper()
263 h.git("", "init", "-q", "--bare", "-b", "main", h.OriginDir)
264 h.git("", "init", "-q", "-b", "main", h.RepoDir)
265 if err := os.WriteFile(filepath.Join(h.RepoDir, "README.md"), []byte("# widget\n"), 0o644); err != nil {
266 h.t.Fatalf("seeding repo: %v", err)
267 }
268 h.git(h.RepoDir, "add", "-A")
269 h.git(h.RepoDir, "commit", "-qm", "init")
270 h.git(h.RepoDir, "remote", "add", "origin", h.OriginDir)
271 h.git(h.RepoDir, "push", "-q", "origin", "main")
272}
273
274// writeRepoConfig writes .klaus/config.json pointing WorktreeBase at the temp
275// root and setting pr_reviewer (so launch's prompt render does not shell out to
276// gh). It is committed so worktrees see the same config.
277func (h *Harness) writeRepoConfig() {
278 h.t.Helper()
279 cfgDir := filepath.Join(h.RepoDir, ".klaus")
280 if err := os.MkdirAll(cfgDir, 0o755); err != nil {
281 h.t.Fatalf("mkdir .klaus: %v", err)
282 }
283 cfg := map[string]any{
284 "worktree_base": filepath.Join(filepath.Dir(h.RepoDir), "worktrees"),
285 "default_budget": "5.00",
286 "default_branch": "main",
287 "data_ref": "refs/klaus/data",
288 "pr_reviewer": "acme-bot",
289 }
290 data, _ := json.MarshalIndent(cfg, "", " ")
291 if err := os.WriteFile(filepath.Join(cfgDir, "config.json"), append(data, '\n'), 0o644); err != nil {
292 h.t.Fatalf("writing repo config: %v", err)
293 }
294 h.git(h.RepoDir, "add", "-A")
295 h.git(h.RepoDir, "commit", "-qm", "add klaus config")
296 h.git(h.RepoDir, "push", "-q", "origin", "main")
297}
298
299// UseGitHubOrigin points the sandbox repo's origin at git@github.com:acme/widget.git,
300// so launch treats it as a GitHub repo that gets the PR workflow. An ssh stub
301// serves that URL from the local bare origin, so fetches still work offline.
302func (h *Harness) UseGitHubOrigin() {
303 h.t.Helper()
304 // git runs `ssh [opts] git@github.com "git-upload-pack 'acme/widget.git'"`;
305 // run that service against the local bare origin instead.
306 h.WriteStub("ssh", fmt.Sprintf(`#!/usr/bin/env bash
307service="${@: -1}"
308exec "${service%%%% *}" %q
309`, h.OriginDir))
310 h.git(h.RepoDir, "remote", "set-url", "origin", "git@github.com:acme/widget.git")
311}
312
313// AmendRepoConfig merges the given keys into the sandbox repo's
314// .klaus/config.json. No commit is needed: klaus loads config from the host
315// repo's working tree.
316func (h *Harness) AmendRepoConfig(extra map[string]any) {
317 h.t.Helper()
318 path := filepath.Join(h.RepoDir, ".klaus", "config.json")
319 data, err := os.ReadFile(path)
320 if err != nil {
321 h.t.Fatalf("reading repo config: %v", err)
322 }
323 var cfg map[string]any
324 if err := json.Unmarshal(data, &cfg); err != nil {
325 h.t.Fatalf("parsing repo config: %v", err)
326 }
327 for k, v := range extra {
328 cfg[k] = v
329 }
330 out, err := json.MarshalIndent(cfg, "", " ")
331 if err != nil {
332 h.t.Fatalf("marshaling repo config: %v", err)
333 }
334 if err := os.WriteFile(path, append(out, '\n'), 0o644); err != nil {
335 h.t.Fatalf("writing repo config: %v", err)
336 }
337}
338
339// startTmuxServer launches an isolated tmux server on h.Sock and points its
340// panes at a no-profile shell wrapper so they inherit BinDir-first PATH and the
341// temp HOME (the user's login shell would otherwise reset PATH via the Nix
342// profile). Registers cleanup to kill the server.
343func (h *Harness) startTmuxServer() {
344 h.t.Helper()
345
346 // A wrapper shell that forces a deterministic PATH/HOME and refuses to
347 // source the user's profile. tmux runs pane commands via the default-shell;
348 // without this, a login shell would reset PATH and our stubs/binary would
349 // not be found. It also keeps every pane off the real tmux server: a
350 // process that drops $TMUX finds only this test's TMUX_TMPDIR, and no
351 // KLAUS_TMUX_SOCKET inherited from a klaus worker running the suite.
352 h.shellWrap = filepath.Join(filepath.Dir(h.BinDir), "shellwrap")
353 tmuxTmp := filepath.Join(filepath.Dir(h.BinDir), "tmuxtmp")
354 if err := os.Mkdir(tmuxTmp, 0o700); err != nil {
355 h.t.Fatalf("mkdir %s: %v", tmuxTmp, err)
356 }
357 wrap := fmt.Sprintf("#!/bin/sh\nexport HOME=%q\nexport PATH=%q\nexport TMUX_TMPDIR=%q\nunset KLAUS_TMUX_SOCKET\nexec %q --noprofile --norc \"$@\"\n",
358 h.Home, h.BinDir+":"+os.Getenv("PATH"), tmuxTmp, mustBash(h.t))
359 if err := os.WriteFile(h.shellWrap, []byte(wrap), 0o755); err != nil {
360 h.t.Fatalf("writing shell wrapper: %v", err)
361 }
362
363 // Start the server and set the global default-shell *before* creating the
364 // session, so even the session's initial pane uses the no-profile wrapper
365 // rather than the system default shell (which could source login profiles).
366 // h.tmux passes -f /dev/null, so the server starts ignoring any
367 // user/system tmux.conf for full isolation. exit-empty must be turned off
368 // in the same command that starts the server, otherwise the freshly started
369 // (session-less) server exits before we can set default-shell.
370 h.tmux("start-server", ";", "set-option", "-g", "exit-empty", "off")
371 h.tmux("set-option", "-g", "default-shell", h.shellWrap)
372 h.tmux("new-session", "-d", "-s", "main", "-x", "200", "-y", "50")
373 h.t.Cleanup(func() {
374 _ = exec.Command("tmux", "-S", h.Sock, "-f", "/dev/null", "kill-server").Run()
375 })
376
377 h.ServerPID = strings.TrimSpace(h.tmux("display-message", "-p", "#{pid}"))
378 panes := h.ListPanes()
379 if len(panes) == 0 {
380 h.t.Fatal("isolated tmux server has no panes")
381 }
382 h.InitialPane = panes[0]
383}
384
385// env returns the environment for a klaus invocation: isolated HOME, BinDir-first
386// PATH, the session id, and $TMUX/$TMUX_PANE pointing at the isolated server.
387func (h *Harness) env() []string {
388 return []string{
389 "HOME=" + h.Home,
390 "PATH=" + h.BinDir + ":" + os.Getenv("PATH"),
391 "KLAUS_SESSION_ID=" + h.SessionID,
392 "TMUX=" + h.Sock + "," + h.ServerPID + ",0",
393 "TMUX_PANE=" + h.InitialPane,
394 "TERM=xterm",
395 }
396}
397
398// RunKlaus runs the real klaus binary with the isolated environment, with CWD
399// set to the sandbox repo. It returns stdout/stderr/exit and never fails the
400// test on a non-zero exit (callers assert as needed).
401func (h *Harness) RunKlaus(args ...string) RunResult {
402 h.t.Helper()
403 return h.RunKlausIn(h.RepoDir, args...)
404}
405
406// RunKlausIn is RunKlaus with an explicit working directory, for commands that
407// must behave correctly outside a git checkout (E2EDir is not a repo).
408func (h *Harness) RunKlausIn(dir string, args ...string) RunResult {
409 h.t.Helper()
410 cmd := exec.Command(klausBinary, args...)
411 cmd.Dir = dir
412 cmd.Env = h.env()
413 var stdout, stderr bytes.Buffer
414 cmd.Stdout = &stdout
415 cmd.Stderr = &stderr
416 err := cmd.Run()
417 res := RunResult{Stdout: stdout.String(), Stderr: stderr.String()}
418 if ee, ok := err.(*exec.ExitError); ok {
419 res.ExitCode = ee.ExitCode()
420 } else if err != nil {
421 h.t.Fatalf("running klaus %v: %v", args, err)
422 }
423 return res
424}
425
426// RegisterProject registers a local checkout in the temp HOME's project
427// registry via the real `klaus project add`, so commands that resolve a repo
428// through the registry (merge, for one) can find it.
429func (h *Harness) RegisterProject(ref, path string) {
430 h.t.Helper()
431 res := h.RunKlaus("project", "add", ref, "--path", path, "--description", "e2e sandbox")
432 if res.ExitCode != 0 {
433 h.t.Fatalf("registering project %s: exit %d\n%s%s", ref, res.ExitCode, res.Stdout, res.Stderr)
434 }
435}
436
437// tmux runs a control-plane tmux command against the isolated server and
438// returns trimmed stdout, failing the test on error.
439func (h *Harness) tmux(args ...string) string {
440 h.t.Helper()
441 full := append([]string{"-S", h.Sock, "-f", "/dev/null"}, args...)
442 out, err := exec.Command("tmux", full...).CombinedOutput()
443 if err != nil {
444 h.t.Fatalf("tmux %v: %v: %s", args, err, out)
445 }
446 return string(out)
447}
448
449// ListPanes returns all pane ids on the isolated server.
450func (h *Harness) ListPanes() []string {
451 h.t.Helper()
452 out := h.tmux("list-panes", "-a", "-F", "#{pane_id}")
453 var panes []string
454 for _, line := range strings.Split(out, "\n") {
455 if s := strings.TrimSpace(line); s != "" {
456 panes = append(panes, s)
457 }
458 }
459 return panes
460}
461
462// PaneExists reports whether the given pane id is alive on the isolated server.
463func (h *Harness) PaneExists(paneID string) bool {
464 for _, p := range h.ListPanes() {
465 if p == paneID {
466 return true
467 }
468 }
469 return false
470}
471
472// AgentsSession is the detached tmux session klaus puts agent panes in.
473func (h *Harness) AgentsSession() string {
474 return "klaus-agents-" + h.SessionID
475}
476
477// SessionExists reports whether a tmux session with this exact name exists on
478// the isolated server.
479func (h *Harness) SessionExists(name string) bool {
480 h.t.Helper()
481 err := exec.Command("tmux", "-S", h.Sock, "-f", "/dev/null", "has-session", "-t", "="+name).Run()
482 return err == nil
483}
484
485// SessionPanes returns the pane ids belonging to the named session.
486func (h *Harness) SessionPanes(name string) []string {
487 h.t.Helper()
488 if !h.SessionExists(name) {
489 return nil
490 }
491 out := h.tmux("list-panes", "-s", "-t", "="+name, "-F", "#{pane_id}")
492 var panes []string
493 for _, line := range strings.Split(out, "\n") {
494 if s := strings.TrimSpace(line); s != "" {
495 panes = append(panes, s)
496 }
497 }
498 return panes
499}
500
501// WindowPanes returns the pane ids in the window containing the given pane.
502func (h *Harness) WindowPanes(paneID string) []string {
503 h.t.Helper()
504 out := h.tmux("list-panes", "-t", paneID, "-F", "#{pane_id}")
505 var panes []string
506 for _, line := range strings.Split(out, "\n") {
507 if s := strings.TrimSpace(line); s != "" {
508 panes = append(panes, s)
509 }
510 }
511 return panes
512}
513
514// PaneTitle returns the title of the given pane.
515func (h *Harness) PaneTitle(paneID string) string {
516 h.t.Helper()
517 return strings.TrimSpace(h.tmux("display-message", "-p", "-t", paneID, "#{pane_title}"))
518}
519
520// RunsDir is the directory holding this session's run-state JSON files.
521func (h *Harness) RunsDir() string {
522 return filepath.Join(h.Home, ".klaus", "sessions", h.SessionID, "runs")
523}
524
525// RunIDs returns the run ids (state file basenames) currently on disk.
526func (h *Harness) RunIDs() []string {
527 entries, err := os.ReadDir(h.RunsDir())
528 if err != nil {
529 return nil
530 }
531 var ids []string
532 for _, e := range entries {
533 if name := e.Name(); strings.HasSuffix(name, ".json") {
534 ids = append(ids, strings.TrimSuffix(name, ".json"))
535 }
536 }
537 return ids
538}
539
540// ReadState reads and decodes a run's state JSON from the isolated HOME.
541func (h *Harness) ReadState(runID string) (*run.State, error) {
542 data, err := os.ReadFile(filepath.Join(h.RunsDir(), runID+".json"))
543 if err != nil {
544 return nil, err
545 }
546 var st run.State
547 if err := json.Unmarshal(data, &st); err != nil {
548 return nil, err
549 }
550 return &st, nil
551}
552
553// WaitForState polls a run's state until pred is satisfied or the timeout
554// elapses, returning the final state. It fails the test on timeout.
555func (h *Harness) WaitForState(runID string, pred func(*run.State) bool, timeout time.Duration) *run.State {
556 h.t.Helper()
557 deadline := time.Now().Add(timeout)
558 var last *run.State
559 for time.Now().Before(deadline) {
560 st, err := h.ReadState(runID)
561 if err == nil {
562 last = st
563 if pred(st) {
564 return st
565 }
566 }
567 time.Sleep(100 * time.Millisecond)
568 }
569 h.t.Fatalf("state predicate not satisfied for %s within %s (last: %+v)", runID, timeout, last)
570 return last
571}
572
573// SeedState writes a run-state JSON directly into the session store, for tests
574// that exercise read paths (e.g. status) without launching an agent.
575func (h *Harness) SeedState(st *run.State) {
576 h.t.Helper()
577 if err := os.MkdirAll(h.RunsDir(), 0o755); err != nil {
578 h.t.Fatalf("mkdir runs: %v", err)
579 }
580 data, err := json.MarshalIndent(st, "", " ")
581 if err != nil {
582 h.t.Fatalf("marshal state: %v", err)
583 }
584 if err := os.WriteFile(filepath.Join(h.RunsDir(), st.ID+".json"), data, 0o644); err != nil {
585 h.t.Fatalf("writing seeded state: %v", err)
586 }
587}
588
589func (h *Harness) git(dir string, args ...string) {
590 h.t.Helper()
591 h.GitOutput(dir, args...)
592}
593
594// GitOutput runs real git in dir with the harness's git config and returns
595// its trimmed stdout, failing the test if git fails.
596func (h *Harness) GitOutput(dir string, args ...string) string {
597 h.t.Helper()
598 cmd := exec.Command("git", args...)
599 if dir != "" {
600 cmd.Dir = dir
601 }
602 cmd.Env = append(os.Environ(), "HOME="+h.Home, "GIT_CONFIG_GLOBAL="+filepath.Join(h.Home, ".gitconfig"), "GIT_CONFIG_NOSYSTEM=1")
603 var stdout, stderr bytes.Buffer
604 cmd.Stdout, cmd.Stderr = &stdout, &stderr
605 if err := cmd.Run(); err != nil {
606 h.t.Fatalf("git %v: %v: %s%s", args, err, stdout.String(), stderr.String())
607 }
608 return strings.TrimSpace(stdout.String())
609}
610
611func mustBash(t *testing.T) string {
612 t.Helper()
613 p, err := exec.LookPath("bash")
614 if err != nil {
615 t.Fatalf("bash not found: %v", err)
616 }
617 return p
618}
619
620// ghGraphQLAnswer is a gh stub fragment that answers the dashboard's PR
621// query: each PR in states (number -> OPEN, MERGED or CLOSED) is mergeable,
622// with its checks in rollup (SUCCESS, FAILURE or PENDING).
623func ghGraphQLAnswer(states map[int]string, rollup string) string {
624 var prs []string
625 for n, state := range states {
626 prs = append(prs, fmt.Sprintf(`"pr%d": {"state": "%s", "mergeable": "MERGEABLE", "headRefOid": "h%d", "commits": {"nodes": [{"commit": {"statusCheckRollup": {"state": "%s"}}}]}}`, n, state, n, rollup))
627 }
628 body := `{"data": {"repository": {` + strings.Join(prs, ", ") + `}}}`
629 return fmt.Sprintf("if [[ \"$*\" == *graphql* ]]; then printf 'HTTP/2.0 200 OK\\r\\n\\r\\n%%s' %q; exit 0; fi\n", body)
630}
631
632// skipWithout skips t for want of a tool, or of a feature of one, unless
633// KLAUS_TEST_TOOLS=required, as the flow checks set: there it fails t, so a
634// scenario that did not run cannot pass.
635func skipWithout(t testing.TB, format string, args ...any) {
636 t.Helper()
637 if os.Getenv("KLAUS_TEST_TOOLS") == "required" {
638 t.Fatalf(format, args...)
639 }
640 t.Skipf(format, args...)
641}