Debian Codegraph @

executor_test.go

raw
1 package clnkr
2
3 import (
4 "context"
5 "os"
6 "os/exec"
7 "path/filepath"
8 "reflect"
9 "strconv"
10 "strings"
11 "syscall"
12 "testing"
13 "time"
14 )
15
16 func envListToMap(list []string) map[string]string {
17 env := make(map[string]string, len(list))
18 for _, item := range list {
19 key, value, ok := strings.Cut(item, "=")
20 if ok {
21 env[key] = value
22 }
23 }
24 return env
25 }
26
27 func TestShellExecutor(t *testing.T) {
28 exec := &ShellExecutor{}
29 ctx := context.Background()
30
31 for _, field := range []string{"Timeout", "ProcessGroup", "ExtraEnv"} {
32 t.Run("does not expose "+field, func(t *testing.T) {
33 if _, ok := reflect.TypeOf(ShellExecutor{}).FieldByName(field); ok {
34 t.Fatalf("ShellExecutor should not expose %s", field)
35 }
36 })
37 }
38
39 t.Run("captures stdout stderr cwd and exit", func(t *testing.T) {
40 out, err := exec.Execute(ctx, `pwd && echo error >&2`, "/tmp")
41 if err != nil {
42 t.Fatalf("unexpected error: %v", err)
43 }
44 trimmed := strings.TrimSpace(out.Stdout)
45 if trimmed != "/tmp" && trimmed != "/private/tmp" {
46 t.Errorf("stdout = %q, want /tmp or /private/tmp", out.Stdout)
47 }
48 if strings.TrimSpace(out.Stderr) != "error" {
49 t.Errorf("stderr = %q, want %q", out.Stderr, "error")
50 }
51 if out.ExitCode != 0 {
52 t.Errorf("exit code = %d, want 0", out.ExitCode)
53 }
54 assertExitOutcome(t, out.Outcome, 0)
55 })
56
57 t.Run("returns exit code and stderr on failure", func(t *testing.T) {
58 out, err := exec.Execute(ctx, "echo nope >&2; exit 7", "/tmp")
59 if err == nil {
60 t.Fatal("expected error, got nil")
61 }
62 if out.ExitCode != 7 {
63 t.Errorf("exit code = %d, want 7", out.ExitCode)
64 }
65 if strings.TrimSpace(out.Stderr) != "nope" {
66 t.Errorf("stderr = %q, want %q", out.Stderr, "nope")
67 }
68 assertExitOutcome(t, out.Outcome, 7)
69 })
70
71 t.Run("records timeout outcome", func(t *testing.T) {
72 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
73 defer cancel()
74
75 out, err := exec.Execute(ctx, "sleep 1", "/tmp")
76 if err == nil {
77 t.Fatal("expected error from expired context, got nil")
78 }
79 if ctx.Err() != context.DeadlineExceeded {
80 t.Fatalf("caller context = %v, want deadline exceeded (err=%v)", ctx.Err(), err)
81 }
82 if out.Outcome.Type != CommandOutcomeTimeout {
83 t.Fatalf("outcome = %#v, want timeout", out.Outcome)
84 }
85 })
86
87 t.Run("records cancelled outcome", func(t *testing.T) {
88 ctx, cancel := context.WithCancel(context.Background())
89 cancel()
90 out, err := exec.Execute(ctx, "echo hello", "/tmp")
91 if err == nil {
92 t.Fatal("expected error from cancelled context, got nil")
93 }
94 if out.Outcome.Type != CommandOutcomeCancelled {
95 t.Fatalf("outcome = %#v, want cancelled", out.Outcome)
96 }
97 })
98
99 t.Run("records host execution error outcome", func(t *testing.T) {
100 out, err := exec.Execute(ctx, "pwd", filepath.Join(t.TempDir(), "missing"))
101 if err == nil {
102 t.Fatal("expected host execution error, got nil")
103 }
104 if out.Outcome.Type != CommandOutcomeError {
105 t.Fatalf("outcome = %#v, want error", out.Outcome)
106 }
107 if out.Outcome.Message == "" {
108 t.Fatal("outcome message is empty, want host error detail")
109 }
110 })
111
112 t.Run("context cancellation kills child processes", func(t *testing.T) {
113 dir := t.TempDir()
114 marker := filepath.Join(dir, "child-survived")
115 ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
116 defer cancel()
117
118 _, err := exec.Execute(ctx, "sh -c 'sleep 1; touch child-survived' & wait", dir)
119 if err == nil {
120 t.Fatal("expected error from expired context, got nil")
121 }
122
123 time.Sleep(1500 * time.Millisecond)
124 if _, err := os.Stat(marker); err == nil {
125 t.Fatalf("child process survived cancellation and wrote %s", marker)
126 } else if !os.IsNotExist(err) {
127 t.Fatalf("stat marker: %v", err)
128 }
129 })
130
131 t.Run("process group assigns new pgid", func(t *testing.T) {
132 parentPgid, err := syscall.Getpgid(os.Getpid())
133 if err != nil {
134 t.Fatalf("failed to get parent pgid: %v", err)
135 }
136
137 out, err := exec.Execute(ctx, "ps -o pgid= -p $$", "/tmp")
138 if err != nil {
139 if strings.Contains(out.Stderr, "Operation not permitted") {
140 t.Skip("ps is not permitted in this sandbox")
141 }
142 t.Fatalf("unexpected error: %v", err)
143 }
144 childPgid, err := strconv.Atoi(strings.TrimSpace(out.Stdout))
145 if err != nil {
146 t.Fatalf("parse child pgid %q: %v", strings.TrimSpace(out.Stdout), err)
147 }
148 if childPgid == parentPgid {
149 t.Errorf("child pgid %d should differ from parent pgid %d", childPgid, parentPgid)
150 }
151 })
152
153 t.Run("base environment controls command environment", func(t *testing.T) {
154 t.Setenv("CLNKR_PARENT_ONLY", "parent")
155 envExec := &ShellExecutor{BaseEnv: map[string]string{
156 "CLNKR_ONLY": "yes",
157 "PATH": os.Getenv("PATH"),
158 }}
159
160 out, err := envExec.Execute(
161 ctx,
162 `printf "%s,%s" "$CLNKR_ONLY" "$CLNKR_PARENT_ONLY"`,
163 "/tmp",
164 )
165 if err != nil {
166 t.Fatalf("unexpected error: %v", err)
167 }
168 if out.Stdout != "yes," {
169 t.Fatalf("stdout = %q, want %q", out.Stdout, "yes,")
170 }
171 })
172
173 t.Run("SetEnv uses a copied environment snapshot", func(t *testing.T) {
174 envExec := &ShellExecutor{}
175 base := envListToMap(os.Environ())
176 base["CLNKR_SETENV_COPY"] = "before"
177 envExec.SetEnv(base)
178 base["CLNKR_SETENV_COPY"] = "after"
179
180 out, err := envExec.Execute(ctx, `printf %s "$CLNKR_SETENV_COPY"`, "/tmp")
181 if err != nil {
182 t.Fatalf("unexpected error: %v", err)
183 }
184 if out.Stdout != "before" {
185 t.Fatalf("stdout = %q, want %q", out.Stdout, "before")
186 }
187 })
188
189 t.Run("captures post-command shell state", func(t *testing.T) {
190 out, err := exec.Execute(ctx, `export CLNKR_TEST_VAR=ok && cd /tmp && printf done`, "/")
191 if err != nil {
192 t.Fatalf("unexpected error: %v", err)
193 }
194 if out.Stdout != "done" {
195 t.Fatalf("stdout = %q, want %q", out.Stdout, "done")
196 }
197 if got := out.PostEnv["CLNKR_TEST_VAR"]; got != "ok" {
198 t.Fatalf("PostEnv[CLNKR_TEST_VAR] = %q, want ok", got)
199 }
200 assertSamePath(t, out.PostCwd, "/tmp")
201 })
202
203 t.Run("state file does not leak into environment snapshots", func(t *testing.T) {
204 envExec := &ShellExecutor{}
205 base := envListToMap(os.Environ())
206 base["BASE"] = "ok"
207 delete(base, "CLNKR_STATE_FILE")
208 envExec.SetEnv(base)
209
210 out, err := envExec.Execute(ctx, `export CLNKR_TEST_VAR=ok && printf done`, "/tmp")
211 if err != nil {
212 t.Fatalf("unexpected error: %v", err)
213 }
214 if _, ok := out.PostEnv["CLNKR_STATE_FILE"]; ok {
215 t.Fatalf("CLNKR_STATE_FILE leaked into PostEnv: %+v", out.PostEnv)
216 }
217 if got := envExec.BaseEnv["CLNKR_STATE_FILE"]; got != "" {
218 t.Fatalf("CLNKR_STATE_FILE leaked into BaseEnv: %q", got)
219 }
220 })
221
222 t.Run("captures full env snapshots across stateful commands", func(t *testing.T) {
223 envExec := &ShellExecutor{}
224 out1 := executeAndUseEnv(
225 t,
226 envExec,
227 `export CLNKR_CHAIN_ONE=one && cd /tmp && printf done`,
228 "/tmp",
229 )
230 if out1.PostEnv["CLNKR_CHAIN_ONE"] != "one" {
231 t.Fatalf("missing chain var in snapshot: %+v", out1.PostEnv)
232 }
233
234 out2 := executeAndUseEnv(
235 t,
236 envExec,
237 `export CLNKR_CHAIN_TWO=two && cd /tmp && printf done`,
238 "/tmp",
239 )
240 if out2.PostEnv["CLNKR_CHAIN_ONE"] != "one" || out2.PostEnv["CLNKR_CHAIN_TWO"] != "two" {
241 t.Fatalf("snapshot should include earlier exports: %+v", out2.PostEnv)
242 }
243
244 out3 := executeAndUseEnv(
245 t,
246 envExec,
247 `unset CLNKR_CHAIN_ONE && cd /tmp && printf done`,
248 "/tmp",
249 )
250 if _, ok := out3.PostEnv["CLNKR_CHAIN_ONE"]; ok {
251 t.Fatalf("unset variable should be removed from snapshot: %+v", out3.PostEnv)
252 }
253 if out3.PostEnv["CLNKR_CHAIN_TWO"] != "two" {
254 t.Fatalf("expected other vars to persist: %+v", out3.PostEnv)
255 }
256 if _, ok := out3.PostEnv["CLNKR_STATE_FILE"]; ok {
257 t.Fatalf("state file leaked into PostEnv: %+v", out3.PostEnv)
258 }
259
260 out4, err := envExec.Execute(
261 ctx,
262 `printf "%s,%s" "$CLNKR_CHAIN_ONE" "$CLNKR_CHAIN_TWO"`,
263 "/tmp",
264 )
265 if err != nil {
266 t.Fatalf("step 4: %v", err)
267 }
268 if out4.Stdout != ",two" {
269 t.Fatalf("stdout = %q, want %q", out4.Stdout, ",two")
270 }
271 })
272
273 t.Run("collects feedback from a clean git baseline", func(t *testing.T) {
274 repo := initGitRepo(t)
275 writeFile(t, filepath.Join(repo, "note.txt"), "before\n")
276 runGit(t, repo, "add", "note.txt")
277 runGit(t, repo, "commit", "-qm", "add note")
278
279 out, err := exec.Execute(ctx, "printf 'next\\n' > note.txt", repo)
280 if err != nil {
281 t.Fatalf("unexpected error: %v", err)
282 }
283 if got := out.Feedback.ChangedFiles; !reflect.DeepEqual(got, []string{"note.txt"}) {
284 t.Fatalf("changed files = %#v, want %#v", got, []string{"note.txt"})
285 }
286 if !strings.Contains(out.Feedback.Diff, "note.txt") ||
287 !strings.Contains(out.Feedback.Diff, "+next") {
288 t.Fatalf("diff = %q, want note.txt and +next", out.Feedback.Diff)
289 }
290 })
291
292 t.Run("omits feedback when repo was dirty before command", func(t *testing.T) {
293 repo := initGitRepo(t)
294 writeFile(t, filepath.Join(repo, "dirty.txt"), "dirty\n")
295
296 out, err := exec.Execute(ctx, "printf 'next\\n' > note.txt", repo)
297 if err != nil {
298 t.Fatalf("unexpected error: %v", err)
299 }
300 if len(out.Feedback.ChangedFiles) != 0 || out.Feedback.Diff != "" {
301 t.Fatalf("feedback = %#v, want empty", out.Feedback)
302 }
303 })
304
305 t.Run("tracks both sides of a rename", func(t *testing.T) {
306 repo := initGitRepo(t)
307 writeFile(t, filepath.Join(repo, "old.txt"), "before\n")
308 runGit(t, repo, "add", "old.txt")
309 runGit(t, repo, "commit", "-qm", "add old")
310
311 out, err := exec.Execute(ctx, "git mv old.txt new.txt", repo)
312 if err != nil {
313 t.Fatalf("unexpected error: %v", err)
314 }
315 if got := out.Feedback.ChangedFiles; !reflect.DeepEqual(
316 got,
317 []string{"new.txt", "old.txt"},
318 ) {
319 t.Fatalf("changed files = %#v, want %#v", got, []string{"new.txt", "old.txt"})
320 }
321 })
322
323 t.Run("normalizes feedback paths relative to final cwd", func(t *testing.T) {
324 repo := initGitRepo(t)
325 subdir := filepath.Join(repo, "dir", "subdir")
326
327 out, err := exec.Execute(
328 ctx,
329 "mkdir -p dir/subdir && cd dir/subdir && printf 'nested\\n' > local.txt",
330 repo,
331 )
332 if err != nil {
333 t.Fatalf("unexpected error: %v", err)
334 }
335 assertSamePath(t, out.PostCwd, subdir)
336 if got := out.Feedback.ChangedFiles; !reflect.DeepEqual(got, []string{"local.txt"}) {
337 t.Fatalf("changed files = %#v, want %#v", got, []string{"local.txt"})
338 }
339 })
340 }
341
342 func assertExitOutcome(t *testing.T, got CommandOutcome, want int) {
343 t.Helper()
344
345 if got.Type != CommandOutcomeExit || got.ExitCode == nil || *got.ExitCode != want {
346 t.Fatalf("outcome = %#v, want exit %d", got, want)
347 }
348 }
349
350 func assertSamePath(t *testing.T, got, want string) {
351 t.Helper()
352
353 gotResolved, err := filepath.EvalSymlinks(got)
354 if err != nil {
355 t.Fatalf("resolve got path %q: %v", got, err)
356 }
357 wantResolved, err := filepath.EvalSymlinks(want)
358 if err != nil {
359 t.Fatalf("resolve want path %q: %v", want, err)
360 }
361 if gotResolved != wantResolved {
362 t.Fatalf(
363 "path = %q (resolved %q), want %q (resolved %q)",
364 got,
365 gotResolved,
366 want,
367 wantResolved,
368 )
369 }
370 }
371
372 func executeAndUseEnv(t *testing.T, exec *ShellExecutor, command, dir string) CommandResult {
373 t.Helper()
374
375 out, err := exec.Execute(context.Background(), command, dir)
376 if err != nil {
377 t.Fatalf("execute %q: %v", command, err)
378 }
379 exec.SetEnv(out.PostEnv)
380 return out
381 }
382
383 func initGitRepo(t *testing.T) string {
384 t.Helper()
385
386 repo := t.TempDir()
387 runGit(t, repo, "init", "-q")
388 runGit(t, repo, "config", "user.name", "clnkr test")
389 runGit(t, repo, "config", "user.email", "[email protected]")
390 writeFile(t, filepath.Join(repo, ".gitignore"), "")
391 runGit(t, repo, "add", ".gitignore")
392 runGit(t, repo, "commit", "-qm", "init")
393 return repo
394 }
395
396 func runGit(t *testing.T, dir string, args ...string) {
397 t.Helper()
398
399 cmd := exec.Command("git", args...)
400 cmd.Dir = dir
401 out, err := cmd.CombinedOutput()
402 if err != nil {
403 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
404 }
405 }
406
407 func writeFile(t *testing.T, path, content string) {
408 t.Helper()
409
410 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
411 t.Fatalf("mkdir %s: %v", filepath.Dir(path), err)
412 }
413 if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
414 t.Fatalf("write %s: %v", path, err)
415 }
416 }