返回 last30days-skill
run_test.go
根目录 / mcp / internal / engine / run_test.go
1 package engine
2
3 import (
4 "context"
5 "errors"
6 "os"
7 "path/filepath"
8 "runtime"
9 "strconv"
10 "strings"
11 "testing"
12 "time"
13 )
14
15 // makeStubPython writes a shell script that simulates python3 and returns
16 // its absolute path. The script honors a small env-driven protocol so each
17 // test can shape its output:
18 //
19 // STUB_STDOUT - text printed to stdout
20 // STUB_STDERR - text printed to stderr
21 // STUB_EXIT_CODE - integer exit code (default 0)
22 // STUB_SLEEP_SECS - sleep before exiting (for timeout tests)
23 // STUB_ECHO_ENV - name of an env var; the stub prints "<NAME>=<VALUE>"
24 // STUB_ECHO_ARG - integer index; the stub prints "ARG<i>=<args[i]>"
25 // STUB_ECHO_ARGS - when set (any value), the stub prints its full argv
26 // after the script path, one argument per line, so tests
27 // can assert the exact argv the engine receives
28 //
29 // The stub ignores its first argument (the script path), matching how a
30 // real python3 invocation treats `python3 last30days.py ...`.
31 func makeStubPython(t *testing.T) string {
32 t.Helper()
33 if runtime.GOOS == "windows" {
34 t.Skip("stub-python tests rely on POSIX shell")
35 }
36 dir := t.TempDir()
37 path := filepath.Join(dir, "python3-stub.sh")
38 script := `#!/usr/bin/env bash
39 if [ -n "${STUB_SLEEP_SECS:-}" ]; then sleep "$STUB_SLEEP_SECS"; fi
40 if [ -n "${STUB_STDOUT:-}" ]; then printf "%s" "$STUB_STDOUT"; fi
41 if [ -n "${STUB_STDERR:-}" ]; then printf "%s" "$STUB_STDERR" >&2; fi
42 if [ -n "${STUB_ECHO_ENV:-}" ]; then echo "${STUB_ECHO_ENV}=${!STUB_ECHO_ENV:-<unset>}"; fi
43 if [ -n "${STUB_ECHO_ARG:-}" ]; then echo "ARG${STUB_ECHO_ARG}=${!STUB_ECHO_ARG:-<unset>}"; fi
44 if [ -n "${STUB_ECHO_ARGS:-}" ]; then shift; printf "%s\n" "$@"; fi
45 exit "${STUB_EXIT_CODE:-0}"
46 `
47 if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
48 t.Fatalf("write stub: %v", err)
49 }
50 return path
51 }
52
53 // stageCache materializes a fake CacheDir with a no-op last30days.py so
54 // the existence check in Run passes. The stub python3 ignores the script
55 // contents, so the file just has to exist.
56 func stageCache(t *testing.T) string {
57 t.Helper()
58 dir := t.TempDir()
59 if err := os.WriteFile(filepath.Join(dir, "last30days.py"), []byte("# stub\n"), 0o644); err != nil {
60 t.Fatalf("stage cache: %v", err)
61 }
62 return dir
63 }
64
65 func TestRunHappyPath(t *testing.T) {
66 stub := makeStubPython(t)
67 cache := stageCache(t)
68 t.Setenv("STUB_STDOUT", "synthesis output\n")
69
70 res, err := Run(context.Background(), RunOptions{
71 PythonPath: stub,
72 CacheDir: cache,
73 Args: []string{"my topic", "--emit=compact"},
74 })
75 if err != nil {
76 t.Fatalf("Run: %v", err)
77 }
78 if string(res.Stdout) != "synthesis output\n" {
79 t.Fatalf("stdout = %q, want %q", res.Stdout, "synthesis output\n")
80 }
81 if res.ExitCode != 0 {
82 t.Fatalf("ExitCode = %d, want 0", res.ExitCode)
83 }
84 if res.TimedOut {
85 t.Fatal("TimedOut = true, want false")
86 }
87 }
88
89 // TestRunForwardsExactArgv pins the full argv the engine subprocess
90 // receives: options first, explicit empty --save-dir on decline, `--`
91 // separator, then the positional topic. The default-deny
92 // --no-browser-cookies flag rides along in this shape too.
93 func TestRunForwardsExactArgv(t *testing.T) {
94 stub := makeStubPython(t)
95 cache := stageCache(t)
96 t.Setenv("STUB_ECHO_ARGS", "1")
97
98 want := []string{"--emit=compact", "--no-browser-cookies", "--save-dir", "", "--", "--mock"}
99 res, err := Run(context.Background(), RunOptions{
100 PythonPath: stub,
101 CacheDir: cache,
102 Args: want,
103 })
104 if err != nil {
105 t.Fatalf("Run: %v", err)
106 }
107 got := strings.Split(strings.TrimSuffix(string(res.Stdout), "\n"), "\n")
108 if strings.Join(got, "\x00") != strings.Join(want, "\x00") {
109 t.Fatalf("engine argv = %#v, want %#v", got, want)
110 }
111 }
112
113 func TestRunForwardsEnv(t *testing.T) {
114 stub := makeStubPython(t)
115 cache := stageCache(t)
116 t.Setenv("OPENAI_API_KEY", "sk-test-value")
117 t.Setenv("STUB_ECHO_ENV", "OPENAI_API_KEY")
118
119 res, err := Run(context.Background(), RunOptions{
120 PythonPath: stub,
121 CacheDir: cache,
122 })
123 if err != nil {
124 t.Fatalf("Run: %v", err)
125 }
126 if got := strings.TrimSpace(string(res.Stdout)); got != "OPENAI_API_KEY=sk-test-value" {
127 t.Fatalf("stdout = %q, want OPENAI_API_KEY=sk-test-value", got)
128 }
129 }
130
131 func TestRunSetsPythonPath(t *testing.T) {
132 stub := makeStubPython(t)
133 cache := stageCache(t)
134 t.Setenv("STUB_ECHO_ENV", "PYTHONPATH")
135
136 res, err := Run(context.Background(), RunOptions{
137 PythonPath: stub,
138 CacheDir: cache,
139 })
140 if err != nil {
141 t.Fatalf("Run: %v", err)
142 }
143 want := "PYTHONPATH=" + cache
144 if got := strings.TrimSpace(string(res.Stdout)); got != want {
145 t.Fatalf("stdout = %q, want %q", got, want)
146 }
147 }
148
149 // TestRunDropsPreExistingPythonPath guards the buildEnv dedup: when the
150 // parent already sets PYTHONPATH (common on dev machines and CI runners
151 // that touch Python), the child must NOT see two PYTHONPATH= entries.
152 // POSIX getenv returns the first match, so a duplicate from os.Environ
153 // would shadow our cache-dir entry and break `from lib import ...`.
154 func TestRunDropsPreExistingPythonPath(t *testing.T) {
155 stub := makeStubPython(t)
156 cache := stageCache(t)
157 t.Setenv("PYTHONPATH", "/users-stale-pythonpath")
158 t.Setenv("STUB_ECHO_ENV", "PYTHONPATH")
159
160 res, err := Run(context.Background(), RunOptions{
161 PythonPath: stub,
162 CacheDir: cache,
163 })
164 if err != nil {
165 t.Fatalf("Run: %v", err)
166 }
167 got := strings.TrimSpace(string(res.Stdout))
168 want := "PYTHONPATH=" + cache
169 if got != want {
170 t.Fatalf("stdout = %q, want %q (stale parent value leaked through)", got, want)
171 }
172 }
173
174 func TestBuildEnvDropsAllPreExistingPythonPath(t *testing.T) {
175 // Direct unit test on buildEnv to catch the case where the parent has
176 // PYTHONPATH set: the returned slice must contain exactly one
177 // PYTHONPATH= entry, and it must be ours.
178 t.Setenv("PYTHONPATH", "/parent/one")
179 cache := "/cache/dir"
180 out := buildEnv(cache, []string{"EXTRA=1"})
181
182 var pythonPaths []string
183 for _, kv := range out {
184 if strings.HasPrefix(kv, "PYTHONPATH=") {
185 pythonPaths = append(pythonPaths, kv)
186 }
187 }
188 if len(pythonPaths) != 1 {
189 t.Fatalf("got %d PYTHONPATH entries, want 1: %v", len(pythonPaths), pythonPaths)
190 }
191 if pythonPaths[0] != "PYTHONPATH="+cache {
192 t.Fatalf("PYTHONPATH = %q, want %q", pythonPaths[0], "PYTHONPATH="+cache)
193 }
194 // Confirm ExtraEnv still rides along.
195 found := false
196 for _, kv := range out {
197 if kv == "EXTRA=1" {
198 found = true
199 break
200 }
201 }
202 if !found {
203 t.Fatal("EXTRA=1 missing from buildEnv output")
204 }
205 }
206
207 func TestBuildEnvDeduplicatesOverriddenExtraEnvKeys(t *testing.T) {
208 t.Setenv("LAST30DAYS_X_BACKEND", "${user_config.last30days_x_backend}")
209 out := buildEnv("/cache/dir", []string{"LAST30DAYS_X_BACKEND=xapi"})
210
211 var matches []string
212 for _, kv := range out {
213 if strings.HasPrefix(kv, "LAST30DAYS_X_BACKEND=") {
214 matches = append(matches, kv)
215 }
216 }
217 if len(matches) != 1 || matches[0] != "LAST30DAYS_X_BACKEND=xapi" {
218 t.Fatalf("LAST30DAYS_X_BACKEND entries = %#v, want single override LAST30DAYS_X_BACKEND=xapi", matches)
219 }
220 }
221
222 func TestRunSurfacesExitCode(t *testing.T) {
223 stub := makeStubPython(t)
224 cache := stageCache(t)
225 t.Setenv("STUB_STDERR", "engine boom\n")
226 t.Setenv("STUB_EXIT_CODE", "2")
227
228 res, err := Run(context.Background(), RunOptions{
229 PythonPath: stub,
230 CacheDir: cache,
231 })
232 if err == nil {
233 t.Fatal("expected error for non-zero exit")
234 }
235 if res == nil {
236 t.Fatal("res is nil; want populated result alongside error")
237 }
238 if res.ExitCode != 2 {
239 t.Fatalf("ExitCode = %d, want 2", res.ExitCode)
240 }
241 if !strings.Contains(string(res.Stderr), "engine boom") {
242 t.Fatalf("stderr did not surface engine output: %q", res.Stderr)
243 }
244 }
245
246 func TestRunTimesOut(t *testing.T) {
247 stub := makeStubPython(t)
248 cache := stageCache(t)
249 t.Setenv("STUB_SLEEP_SECS", "3")
250
251 res, err := Run(context.Background(), RunOptions{
252 PythonPath: stub,
253 CacheDir: cache,
254 Timeout: 200 * time.Millisecond,
255 })
256 if err == nil {
257 t.Fatal("expected timeout error")
258 }
259 if !res.TimedOut {
260 t.Fatal("TimedOut = false, want true")
261 }
262 if !strings.Contains(err.Error(), "timeout") {
263 t.Fatalf("error %q lacks 'timeout' marker", err)
264 }
265 if !errors.Is(err, context.DeadlineExceeded) {
266 t.Fatalf("Run error = %v, want context.DeadlineExceeded", err)
267 }
268 }
269
270 func TestRunCanceledBeforeStart(t *testing.T) {
271 for _, wantErr := range []error{context.Canceled, context.DeadlineExceeded} {
272 t.Run(wantErr.Error(), func(t *testing.T) {
273 expired := wantErr == context.DeadlineExceeded
274 ctx, cancel := context.WithCancel(context.Background())
275 if expired {
276 cancel()
277 ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
278 }
279 cancel()
280 cache := stageCache(t)
281 // A missing executable exposes an attempted start even when a
282 // valid child would be killed before it could write output.
283 res, err := Run(ctx, RunOptions{
284 PythonPath: filepath.Join(cache, "must-not-start"),
285 CacheDir: cache,
286 })
287 if !errors.Is(err, wantErr) {
288 t.Errorf("Run error = %v, want %v", err, wantErr)
289 }
290 if res == nil {
291 t.Fatal("Run result is nil; want a canceled result")
292 }
293 if res.TimedOut != expired || res.ExitCode != -1 || len(res.Stdout) != 0 {
294 t.Errorf("Run result = %+v, want no started subprocess and TimedOut=%v", res, expired)
295 }
296 })
297 }
298 }
299
300 func TestResolvePythonHonorsEnvOverride(t *testing.T) {
301 executable := fakePython(t, t.TempDir(), "selected-python", "3.12")
302 t.Setenv(PythonEnvOverride, executable)
303 t.Setenv("PATH", "")
304
305 got, err := resolvePython("")
306 if err != nil {
307 t.Fatalf("resolvePython: %v", err)
308 }
309 gotInfo, err := os.Stat(got)
310 if err != nil {
311 t.Fatalf("stat resolved path %q: %v", got, err)
312 }
313 wantInfo, err := os.Stat(executable)
314 if err != nil {
315 t.Fatalf("stat override path %q: %v", executable, err)
316 }
317 if !os.SameFile(gotInfo, wantInfo) {
318 t.Fatalf("resolvePython = %q, want executable %q", got, executable)
319 }
320 }
321
322 func TestResolvePythonRejectsInvalidEnvOverride(t *testing.T) {
323 t.Run("missing path", func(t *testing.T) {
324 missing := filepath.Join(t.TempDir(), "missing-python")
325 t.Setenv(PythonEnvOverride, missing)
326
327 _, err := resolvePython("")
328 if err == nil {
329 t.Fatal("expected invalid override error")
330 }
331 if !strings.Contains(err.Error(), PythonEnvOverride) || !strings.Contains(err.Error(), strconv.Quote(missing)) {
332 t.Fatalf("error %q does not identify invalid %s path %q", err, PythonEnvOverride, missing)
333 }
334 })
335
336 t.Run("empty value", func(t *testing.T) {
337 t.Setenv(PythonEnvOverride, "")
338
339 _, err := resolvePython("")
340 if err == nil {
341 t.Fatal("expected empty override error")
342 }
343 if !strings.Contains(err.Error(), PythonEnvOverride) || !strings.Contains(err.Error(), "set but empty") {
344 t.Fatalf("error %q does not clearly identify the empty override", err)
345 }
346 })
347 }
348
349 func TestResolvePythonDefaultsToPython3Lookup(t *testing.T) {
350 dir := t.TempDir()
351 candidate := fakePython(t, dir, DefaultPythonBinary, "3.12")
352 t.Setenv(PythonEnvOverride, "temporarily-set-for-cleanup")
353 if err := os.Unsetenv(PythonEnvOverride); err != nil {
354 t.Fatalf("unset %s: %v", PythonEnvOverride, err)
355 }
356 t.Setenv("PATH", dir)
357
358 got, err := resolvePython("")
359 if err != nil {
360 t.Fatalf("resolvePython: %v", err)
361 }
362 gotInfo, err := os.Stat(got)
363 if err != nil {
364 t.Fatalf("stat resolved path %q: %v", got, err)
365 }
366 wantInfo, err := os.Stat(candidate)
367 if err != nil {
368 t.Fatalf("stat default stub %q: %v", candidate, err)
369 }
370 if !os.SameFile(gotInfo, wantInfo) {
371 t.Fatalf("resolvePython = %q, want python3 lookup result %q", got, candidate)
372 }
373 }
374
375 func TestRunMissingPython(t *testing.T) {
376 unsetPythonOverride(t)
377 cache := stageCache(t)
378 // Empty PATH guarantees the lookup fails. PythonPath stays unset so Run
379 // falls through to exec.LookPath.
380 t.Setenv(PythonEnvOverride, "temporarily-set-for-cleanup")
381 if err := os.Unsetenv(PythonEnvOverride); err != nil {
382 t.Fatalf("unset %s: %v", PythonEnvOverride, err)
383 }
384 t.Setenv("PATH", "")
385
386 _, err := Run(context.Background(), RunOptions{CacheDir: cache})
387 if err == nil {
388 t.Fatal("expected lookup failure with empty PATH")
389 }
390 if !strings.Contains(err.Error(), DefaultPythonBinary) {
391 t.Fatalf("error %q does not mention %s", err, DefaultPythonBinary)
392 }
393 if !strings.Contains(err.Error(), PythonInstallURL) {
394 t.Fatalf("error %q does not include install URL", err)
395 }
396 }
397
398 func TestResolvePythonRejectsRelativePATH(t *testing.T) {
399 unsetPythonOverride(t)
400 if runtime.GOOS == "windows" {
401 t.Skip("POSIX executable fixture")
402 }
403 t.Chdir(t.TempDir())
404 if err := os.WriteFile(DefaultPythonBinary, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil {
405 t.Fatal(err)
406 }
407 t.Setenv("PATH", ".")
408 // Exercise our own guard even when Go's ErrDot protection is disabled.
409 t.Setenv("GODEBUG", "execerrdot=0")
410 if path, err := resolvePython(""); err == nil || path != "" {
411 t.Fatalf("resolvePython accepted relative executable: path=%q err=%v", path, err)
412 }
413 }
414
415 func TestResolvePythonAcceptsAbsolutePATH(t *testing.T) {
416 unsetPythonOverride(t)
417 if runtime.GOOS == "windows" {
418 t.Skip("POSIX executable fixture")
419 }
420 dir := t.TempDir()
421 want := filepath.Join(dir, DefaultPythonBinary)
422 if err := os.WriteFile(want, []byte("#!/bin/sh\nprintf '3.12\\n'\n"), 0o755); err != nil {
423 t.Fatal(err)
424 }
425 t.Setenv("PATH", dir)
426 if path, err := resolvePython(""); err != nil || path != want {
427 t.Fatalf("resolvePython = %q, %v; want %q", path, err, want)
428 }
429 }
430
431 func TestResolvePythonPreservesExplicitOverride(t *testing.T) {
432 t.Setenv("PATH", "")
433 want := filepath.Join("explicit", "python")
434 if path, err := resolvePython(want); err != nil || path != want {
435 t.Fatalf("resolvePython = %q, %v; want trusted override %q", path, err, want)
436 }
437 }
438
439 func TestRunMissingScript(t *testing.T) {
440 stub := makeStubPython(t)
441 // CacheDir exists but contains no last30days.py.
442 cache := t.TempDir()
443
444 _, err := Run(context.Background(), RunOptions{
445 PythonPath: stub,
446 CacheDir: cache,
447 })
448 if err == nil {
449 t.Fatal("expected error when last30days.py missing")
450 }
451 if !strings.Contains(err.Error(), "last30days.py") {
452 t.Fatalf("error %q does not name missing script", err)
453 }
454 }
455
456 func TestRunRejectsEmptyCacheDir(t *testing.T) {
457 stub := makeStubPython(t)
458 _, err := Run(context.Background(), RunOptions{PythonPath: stub})
459 if err == nil {
460 t.Fatal("expected error for empty CacheDir")
461 }
462 if !errors.Is(err, err) || !strings.Contains(err.Error(), "CacheDir") {
463 t.Fatalf("error %q does not name CacheDir", err)
464 }
465 }
466
467 func TestResolveTimeoutHonorsEnv(t *testing.T) {
468 t.Setenv(TimeoutEnvOverride, "750ms")
469 if got := resolveTimeout(0); got != 750*time.Millisecond {
470 t.Fatalf("resolveTimeout = %v, want 750ms", got)
471 }
472 t.Setenv(TimeoutEnvOverride, "garbage")
473 if got := resolveTimeout(0); got != DefaultTimeout {
474 t.Fatalf("garbage value: got %v, want default %v", got, DefaultTimeout)
475 }
476 if got := resolveTimeout(time.Minute); got != time.Minute {
477 t.Fatalf("explicit value not honored: got %v", got)
478 }
479 }
480
481 func TestResolveTimeoutBareIntegerSeconds(t *testing.T) {
482 t.Setenv(TimeoutEnvOverride, "300")
483 if got := resolveTimeout(0); got != 300*time.Second {
484 t.Fatalf("bare integer 300: got %v, want 5m0s", got)
485 }
486 t.Setenv(TimeoutEnvOverride, "1")
487 if got := resolveTimeout(0); got != 1*time.Second {
488 t.Fatalf("bare integer 1: got %v, want 1s", got)
489 }
490 t.Setenv(TimeoutEnvOverride, "0")
491 if got := resolveTimeout(0); got != DefaultTimeout {
492 t.Fatalf("bare integer 0: got %v, want default %v", got, DefaultTimeout)
493 }
494 t.Setenv(TimeoutEnvOverride, "-1")
495 if got := resolveTimeout(0); got != DefaultTimeout {
496 t.Fatalf("bare integer -1: got %v, want default %v", got, DefaultTimeout)
497 }
498 }
499
499 lines GO