返回 last30days-skill
python_test.go
根目录 / mcp / internal / engine / python_test.go
1 package engine
2
3 import (
4 "context"
5 "errors"
6 "os"
7 "path/filepath"
8 "runtime"
9 "strings"
10 "testing"
11 "time"
12 )
13
14 func fakePython(t *testing.T, dir, name, version string) string {
15 t.Helper()
16 if runtime.GOOS == "windows" {
17 t.Skip("POSIX executable fixture")
18 }
19 path := filepath.Join(dir, name)
20 body := "#!/bin/sh\nif [ \"$1\" = '-I' ]; then printf '%s\\n' '" + version + "'; else printf 'research completed'; fi\n"
21 if err := os.WriteFile(path, []byte(body), 0755); err != nil {
22 t.Fatal(err)
23 }
24 return path
25 }
26
27 func TestPythonDiscoveryFallback(t *testing.T) {
28 for _, name := range []string{"python3", "python3.12", "python3.99", "python"} {
29 t.Run(name, func(t *testing.T) {
30 unsetPythonOverride(t)
31 first, second := t.TempDir(), t.TempDir()
32 fakePython(t, first, "python3", "3.9")
33 want := fakePython(t, second, name, "3.12")
34 t.Setenv("PATH", first+string(os.PathListSeparator)+second)
35 got, err := resolvePython("")
36 if err != nil || got != want {
37 t.Fatalf("got %q, %v; want %q", got, err, want)
38 }
39 result, err := Run(context.Background(), RunOptions{CacheDir: stageCache(t)})
40 if err != nil || string(result.Stdout) != "research completed" {
41 t.Fatalf("Run = %+v, %v", result, err)
42 }
43 })
44 }
45 }
46
47 func TestPythonDiscoveryPreservesDefault(t *testing.T) {
48 unsetPythonOverride(t)
49 dir := t.TempDir()
50 want := fakePython(t, dir, "python3", "3.12")
51 fakePython(t, dir, "python3.14", "3.14")
52 t.Setenv("PATH", dir)
53 got, err := resolvePython("")
54 if err != nil || got != want {
55 t.Fatalf("got %q, %v", got, err)
56 }
57 }
58
59 func TestPythonOverrideVerifiedWithoutFallback(t *testing.T) {
60 dir := t.TempDir()
61 fakePython(t, dir, "python3", "3.14")
62 t.Setenv("PATH", dir)
63 for _, version := range []string{"3.9", "invalid", "4.0", "3.12", "3.99"} {
64 t.Run(version, func(t *testing.T) {
65 explicit := fakePython(t, t.TempDir(), "selected-python", version)
66 t.Setenv(PythonEnvOverride, explicit)
67 got, err := resolvePython("")
68 if version == "3.12" || version == "3.99" {
69 if err != nil || got != explicit {
70 t.Fatalf("got %q, %v", got, err)
71 }
72 } else if err == nil || got != "" || !strings.Contains(err.Error(), PythonEnvOverride) {
73 t.Fatalf("invalid override fell back: %q, %v", got, err)
74 }
75 })
76 }
77 t.Setenv(PythonEnvOverride, filepath.Join(dir, "missing"))
78 if _, err := resolvePython(""); err == nil {
79 t.Fatal("missing override fell back")
80 }
81 }
82
83 func TestPythonDiscoveryExcludesRelativePathsAndConfigHelpers(t *testing.T) {
84 unsetPythonOverride(t)
85 dir := t.TempDir()
86 fakePython(t, dir, "python3-config", "3.14")
87 fakePython(t, dir, "python3.14-config", "3.14")
88 fakePython(t, dir, "python3", "3.14")
89 t.Chdir(dir)
90 t.Setenv("GODEBUG", "execerrdot=0")
91 t.Setenv("PATH", ".")
92 t.Setenv(PythonEnvOverride, "./python3")
93 if _, err := resolvePython(""); err == nil {
94 t.Fatal("accepted relative override")
95 }
96 unsetPythonOverride(t)
97 if _, err := resolvePython(""); err == nil {
98 t.Fatal("accepted relative PATH")
99 }
100 if err := os.Remove(filepath.Join(dir, "python3")); err != nil {
101 t.Fatal(err)
102 }
103 t.Setenv("PATH", dir)
104 if _, err := resolvePython(""); err == nil {
105 t.Fatal("accepted config helper")
106 }
107 }
108
109 func TestPythonProbeCancellation(t *testing.T) {
110 if runtime.GOOS == "windows" {
111 t.Skip("POSIX executable fixture")
112 }
113 path := filepath.Join(t.TempDir(), "python3")
114 if err := os.WriteFile(path, []byte("#!/bin/sh\nexec /bin/sleep 10\n"), 0755); err != nil {
115 t.Fatal(err)
116 }
117 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
118 defer cancel()
119 start := time.Now()
120 if err := checkPythonVersion(ctx, path); err == nil {
121 t.Fatal("expected timeout")
122 }
123 if time.Since(start) > time.Second {
124 t.Fatal("probe ignored cancellation")
125 }
126 }
127
128 func unsetPythonOverride(t *testing.T) {
129 t.Helper()
130 t.Setenv(PythonEnvOverride, "")
131 if err := os.Unsetenv(PythonEnvOverride); err != nil {
132 t.Fatal(err)
133 }
134 }
135
136 func TestDiscoveryFilesystemCancellation(t *testing.T) {
137 release := make(chan struct{})
138 defer close(release)
139 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
140 defer cancel()
141 start := time.Now()
142 _, err := discoveryOperation(ctx, func() (string, error) { <-release; return "", nil })
143 if err != context.DeadlineExceeded || time.Since(start) > time.Second {
144 t.Fatalf("filesystem cancellation: %v", err)
145 }
146 }
147
148 func TestDiscoveryStopsBeforeLaterDirectory(t *testing.T) {
149 unsetPythonOverride(t)
150 first, second := t.TempDir(), t.TempDir()
151 want := fakePython(t, first, "python3", "3.12")
152 t.Setenv("PATH", first+string(os.PathListSeparator)+second)
153 got, err := resolvePythonWithCandidates(context.Background(), "", func(dir string) []string {
154 if dir == second {
155 t.Error("scanned later directory after valid interpreter")
156 }
157 return pythonCandidates(dir)
158 })
159 if err != nil || got != want {
160 t.Fatalf("got %q, %v", got, err)
161 }
162 }
163 func TestDiscoveryCancelsStalledDirectory(t *testing.T) {
164 unsetPythonOverride(t)
165 t.Setenv("PATH", t.TempDir())
166 release := make(chan struct{})
167 defer close(release)
168 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
169 defer cancel()
170 start := time.Now()
171 _, err := resolvePythonWithCandidates(ctx, "", func(string) []string { <-release; return nil })
172 if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > time.Second {
173 t.Fatalf("stalled discovery ignored cancellation: %v", err)
174 }
175 }
176
177 func TestRunDiscoveryPreservesCancellation(t *testing.T) {
178 for _, wantErr := range []error{context.Canceled, context.DeadlineExceeded} {
179 t.Run(wantErr.Error(), func(t *testing.T) {
180 unsetPythonOverride(t)
181 dir := t.TempDir()
182 fakePython(t, dir, "python3", "3.12")
183 t.Setenv("PATH", dir)
184 var ctx context.Context
185 var cancel context.CancelFunc
186 if wantErr == context.DeadlineExceeded {
187 ctx, cancel = context.WithDeadline(context.Background(), time.Now().Add(-time.Second))
188 } else {
189 ctx, cancel = context.WithCancel(context.Background())
190 }
191 cancel()
192 _, err := Run(ctx, RunOptions{CacheDir: stageCache(t)})
193 if !errors.Is(err, wantErr) {
194 t.Fatalf("Run error = %v, want %v", err, wantErr)
195 }
196 })
197 }
198 }
199
200 func TestPythonCandidatesCaseInsensitiveNames(t *testing.T) {
201 dir := t.TempDir()
202 for _, name := range []string{"PYTHON.exe", "python3.12.Exe", "Python3.EXE", "python3.11.exe"} {
203 if err := os.WriteFile(filepath.Join(dir, name), nil, 0755); err != nil {
204 t.Fatal(err)
205 }
206 }
207 defer func(prev bool) { caseInsensitiveNames = prev }(caseInsensitiveNames)
208
209 caseInsensitiveNames = true
210 got := pythonCandidates(dir)
211 want := []string{
212 filepath.Join(dir, "Python3.EXE"),
213 filepath.Join(dir, "python3.12.Exe"),
214 filepath.Join(dir, "PYTHON.exe"),
215 }
216 if strings.Join(got, "|") != strings.Join(want, "|") {
217 t.Fatalf("case-insensitive candidates = %q, want %q", got, want)
218 }
219
220 caseInsensitiveNames = false
221 if got := pythonCandidates(dir); len(got) != 0 {
222 t.Fatalf("case-sensitive candidates = %q, want none", got)
223 }
224 }
225
226 func TestCheckPythonVersionRejectsOversizedStdout(t *testing.T) {
227 if runtime.GOOS == "windows" {
228 t.Skip("POSIX executable fixture")
229 }
230 path := filepath.Join(t.TempDir(), "python3")
231 // Emit a valid-looking version line followed by >64 KiB of whitespace and
232 // stderr noise so an unbounded probe would both bloat memory and falsely
233 // accept "3.12" after TrimSpace.
234 script := `#!/bin/sh
235 printf '3.12\n'
236 dd if=/dev/zero bs=4096 count=32 2>/dev/null | tr '\0' ' '
237 dd if=/dev/zero bs=4096 count=32 2>/dev/null | tr '\0' 'E' >&2
238 `
239 if err := os.WriteFile(path, []byte(script), 0o755); err != nil {
240 t.Fatal(err)
241 }
242 started := time.Now()
243 err := checkPythonVersion(context.Background(), path)
244 if time.Since(started) > 2*time.Second {
245 t.Fatalf("checkPythonVersion took %s; oversized output may have stalled", time.Since(started))
246 }
247 if err == nil || !strings.Contains(err.Error(), "exceeded") {
248 t.Fatalf("checkPythonVersion error = %v, want output limit exceeded", err)
249 }
250 }
251
251 lines GO