-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_tools_test.go
More file actions
410 lines (388 loc) · 12.3 KB
/
Copy pathcode_tools_test.go
File metadata and controls
410 lines (388 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func testCoder(t *testing.T) (*ToolCtx, string) {
t.Helper()
cfg := testCfg(t)
cfg.Coders = map[string]bool{"dev": true}
ws := t.TempDir()
cfg.Workspace = ws
return &ToolCtx{cfg: cfg, authorID: "dev"}, ws
}
func TestApplyPatchTable(t *testing.T) {
cases := []struct {
name string
initial string
ops []patchOp
want string
wantErr string
wantFile string // if non-empty, file must still equal this after failure
path string
}{
{
name: "replace unique",
initial: "alpha\nbeta\ngamma\n",
ops: []patchOp{{Op: "replace", Find: "beta", Replace: "BETA"}},
want: "patched",
wantFile: "alpha\nBETA\ngamma\n",
},
{
name: "ambiguous match refused",
initial: "foo\nbar\nfoo\n",
ops: []patchOp{{Op: "replace", Find: "foo", Replace: "FOO"}},
wantErr: "matched 2 times",
wantFile: "foo\nbar\nfoo\n",
},
{
name: "zero match refused",
initial: "only this\n",
ops: []patchOp{{Op: "replace", Find: "missing", Replace: "x"}},
wantErr: "matched 0 times",
wantFile: "only this\n",
},
{
name: "insert_after",
initial: "a\nb\n",
ops: []patchOp{{Op: "insert_after", Find: "a\n", Text: "mid\n"}},
want: "patched",
wantFile: "a\nmid\nb\n",
},
{
name: "insert_before",
initial: "a\nb\n",
ops: []patchOp{{Op: "insert_before", Find: "b\n", Text: "mid\n"}},
want: "patched",
wantFile: "a\nmid\nb\n",
},
{
name: "delete region",
initial: "keep\ndrop me\nkeep2\n",
ops: []patchOp{{Op: "delete", Find: "drop me\n"}},
want: "patched",
wantFile: "keep\nkeep2\n",
},
{
name: "multi-op success",
initial: "one\ntwo\nthree\n",
ops: []patchOp{
{Op: "replace", Find: "one", Replace: "ONE"},
{Op: "insert_after", Find: "two\n", Text: "two-and-half\n"},
},
want: "patched",
wantFile: "ONE\ntwo\ntwo-and-half\nthree\n",
},
{
name: "multi-op all-or-nothing on later failure",
initial: "one\ntwo\nthree\n",
ops: []patchOp{
{Op: "replace", Find: "one", Replace: "ONE"},
{Op: "replace", Find: "nope", Replace: "x"},
},
wantErr: "matched 0 times",
wantFile: "one\ntwo\nthree\n",
},
{
name: "path traversal refused",
initial: "safe\n",
path: "../../etc/evil",
ops: []patchOp{{Op: "replace", Find: "safe", Replace: "x"}},
wantErr: "escapes",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
coder, ws := testCoder(t)
rel := tc.path
if rel == "" {
rel = "app/sample.rb"
}
if !strings.Contains(rel, "..") {
full := filepath.Join(ws, rel)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(full, []byte(tc.initial), 0o644); err != nil {
t.Fatal(err)
}
} else {
// still seed a workspace file so we can prove it wasn't touched
_ = os.WriteFile(filepath.Join(ws, "safe.txt"), []byte(tc.initial), 0o644)
}
out := coder.applyPatch(rel, tc.ops)
if tc.wantErr != "" {
if !strings.Contains(out, tc.wantErr) {
t.Fatalf("out = %q, want error containing %q", out, tc.wantErr)
}
} else if !strings.Contains(out, tc.want) {
t.Fatalf("out = %q, want containing %q", out, tc.want)
}
if tc.wantFile != "" && !strings.Contains(rel, "..") {
got, err := os.ReadFile(filepath.Join(ws, rel))
if err != nil {
t.Fatal(err)
}
if string(got) != tc.wantFile {
t.Fatalf("file = %q, want %q", got, tc.wantFile)
}
}
if strings.Contains(rel, "..") {
if _, err := os.Stat(filepath.Join(ws, "..", "..", "etc", "evil")); err == nil {
t.Fatal("traversal wrote outside workspace")
}
}
})
}
}
func TestApplyPatchViaRun(t *testing.T) {
coder, ws := testCoder(t)
path := filepath.Join(ws, "x.txt")
if err := os.WriteFile(path, []byte("hello world\n"), 0o644); err != nil {
t.Fatal(err)
}
out := coder.Run("apply_patch", `{"path":"x.txt","ops":[{"op":"replace","find":"world","replace":"vela"}]}`)
if !strings.Contains(out, "patched") || !strings.Contains(out, "+") {
t.Fatalf("unexpected: %s", out)
}
got, _ := os.ReadFile(path)
if string(got) != "hello vela\n" {
t.Fatalf("got %q", got)
}
}
func TestSearchCodeTable(t *testing.T) {
coder, ws := testCoder(t)
write := func(rel, body string) {
t.Helper()
full := filepath.Join(ws, rel)
if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
write("app/models/user.rb", "class User\n def create\n end\nend\n")
write("app/controllers/users_controller.rb", "class UsersController\n def create\n end\nend\n")
write("README.md", "create docs here\n")
write("node_modules/pkg/index.js", "function create() {}\n")
write("vendor/bundle/gem.rb", "def create\nend\n")
write(".git/config", "create = true\n")
write("tmp/cache.txt", "create cache\n")
write("log/dev.log", "create log line\n")
write("bin/blob.dat", "create\x00binary\n")
t.Run("finds matches", func(t *testing.T) {
out := coder.searchCode(`def create`, "", "")
if !strings.Contains(out, "app/models/user.rb:2:") {
t.Fatalf("missing model hit: %s", out)
}
if !strings.Contains(out, "app/controllers/users_controller.rb:2:") {
t.Fatalf("missing controller hit: %s", out)
}
out = coder.searchCode(`create docs`, "", "")
if !strings.Contains(out, "README.md:1:") {
t.Fatalf("missing readme hit: %s", out)
}
})
t.Run("respects path filter", func(t *testing.T) {
out := coder.searchCode(`def create`, "app/models", "")
if !strings.Contains(out, "app/models/user.rb") {
t.Fatalf("expected model hit: %s", out)
}
if strings.Contains(out, "controllers") || strings.Contains(out, "README") {
t.Fatalf("path filter leaked: %s", out)
}
})
t.Run("respects glob filter", func(t *testing.T) {
out := coder.searchCode(`create`, "", "*.rb")
if !strings.Contains(out, ".rb:") {
t.Fatalf("expected rb hits: %s", out)
}
if strings.Contains(out, "README.md") {
t.Fatalf("glob should exclude md: %s", out)
}
})
t.Run("skips excluded dirs and binaries", func(t *testing.T) {
out := coder.searchCode(`create`, "", "")
for _, bad := range []string{"node_modules", "vendor/", ".git/", "tmp/", "log/", "blob.dat"} {
if strings.Contains(out, bad) {
t.Fatalf("should skip %s, got: %s", bad, out)
}
}
})
t.Run("reports truncation", func(t *testing.T) {
var body strings.Builder
for i := 0; i < maxSearchResults+10; i++ {
body.WriteString("needle line\n")
}
write("flood.txt", body.String())
out := coder.searchCode(`needle`, "flood.txt", "")
if !strings.Contains(out, "truncated") {
t.Fatalf("expected truncation note: %s", out)
}
// exactly cap lines of hits (plus maybe the note)
hits := 0
for _, line := range strings.Split(out, "\n") {
if strings.Contains(line, "flood.txt:") {
hits++
}
}
if hits != maxSearchResults {
t.Fatalf("hits = %d, want %d", hits, maxSearchResults)
}
})
t.Run("path traversal refused", func(t *testing.T) {
out := coder.searchCode(`x`, "../..", "")
if !strings.Contains(out, "escapes") {
t.Fatalf("expected escape error: %s", out)
}
})
}
func TestLineDiffCounts(t *testing.T) {
cases := []struct {
name string
before string
after string
added int
removed int
}{
{"identical", "a\nb\n", "a\nb\n", 0, 0},
{"add lines", "a\n", "a\nb\nc\n", 2, 0},
{"delete lines", "a\nb\nc\n", "a\n", 0, 2},
{"modify line", "a\nold\nc\n", "a\nnew\nc\n", 1, 1},
{"empty to content", "", "x\ny\n", 2, 0},
{"content to empty", "x\ny\n", "", 0, 2},
{"reorder", "a\nb\n", "b\na\n", 1, 1}, // LCS keeps two lines; one each side churns
{"add and delete", "keep\ngone\n", "keep\nnew\n", 1, 1},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
add, del := lineDiffCounts(tc.before, tc.after)
if add != tc.added || del != tc.removed {
t.Fatalf("got +%d -%d, want +%d -%d", add, del, tc.added, tc.removed)
}
})
}
}
func TestWriteFileDiffSummary(t *testing.T) {
coder, ws := testCoder(t)
// create
out := coder.writeWorkspaceFile("a.txt", "one\ntwo\n")
if !strings.Contains(out, "wrote a.txt") || !strings.Contains(out, "+2 -0 lines") {
t.Fatalf("create summary: %s", out)
}
// modify one line
out = coder.writeWorkspaceFile("a.txt", "one\nTWO\n")
if !strings.Contains(out, "+1 -1 lines") {
t.Fatalf("modify summary: %s", out)
}
// delete a line
out = coder.writeWorkspaceFile("a.txt", "one\n")
if !strings.Contains(out, "+0 -1 lines") {
t.Fatalf("delete summary: %s", out)
}
// apply_patch summary
if err := os.WriteFile(filepath.Join(ws, "b.txt"), []byte("x\ny\n"), 0o644); err != nil {
t.Fatal(err)
}
out = coder.applyPatch("b.txt", []patchOp{{Op: "replace", Find: "y", Replace: "Y\nZ"}})
if !strings.Contains(out, "patched b.txt") || !strings.Contains(out, "lines") {
t.Fatalf("patch summary: %s", out)
}
}
func TestApplyOpsUnit(t *testing.T) {
_, err := applyOps("aa", []patchOp{{Op: "replace", Find: "a", Replace: "b"}})
if err == nil || !strings.Contains(err.Error(), "matched 2 times") {
t.Fatalf("want ambiguous error, got %v", err)
}
_, err = applyOps("z", []patchOp{{Op: "replace", Find: "", Replace: "b"}})
if err == nil || !strings.Contains(err.Error(), "non-empty") {
t.Fatalf("want empty-find error, got %v", err)
}
}
func TestReadFileWindowRangedExact(t *testing.T) {
content := "L1\nL2\nL3\nL4\nL5\n"
out := readFileWindow(content, 2, 4, readBudgetSingle, nil)
if out != "L2\nL3\nL4" {
t.Fatalf("ranged read: %q", out)
}
}
func TestReadFileWindowOverBudgetHonest(t *testing.T) {
// 200 lines of ~80 chars → well over a tight budget.
var b strings.Builder
for i := 1; i <= 200; i++ {
b.WriteString(strings.Repeat("x", 80))
b.WriteByte('\n')
}
const budget = 500
out := readFileWindow(b.String(), 0, 0, budget, func(next int) string {
return fmt.Sprintf(`read_file path="big.rb" start_line=%d`, next)
})
if !strings.Contains(out, "[truncated:") {
t.Fatalf("expected truncation note: %s", out)
}
if !strings.Contains(out, "of 200 total") {
t.Fatalf("expected total line count: %s", out)
}
if !strings.Contains(out, `read_file path="big.rb" start_line=`) {
t.Fatalf("expected continuation call: %s", out)
}
// Body before the note must stay within budget.
body, _, _ := strings.Cut(out, "\n[truncated:")
if len(body) > budget {
t.Fatalf("body %d exceeds budget %d", len(body), budget)
}
}
func TestReadFileWindowOutOfRange(t *testing.T) {
out := readFileWindow("a\nb\n", 10, 0, readBudgetSingle, nil)
if !strings.Contains(out, "past end of file") || !strings.Contains(out, "2 lines") {
t.Fatalf("want clear OOR error, got %q", out)
}
out = readFileWindow("a\nb\n", 2, 1, readBudgetSingle, nil)
if !strings.Contains(out, "before start_line") {
t.Fatalf("want end-before-start error, got %q", out)
}
// Empty result is not OK for OOR — must be an error string.
if strings.TrimSpace(out) == "" {
t.Fatal("OOR must not return empty")
}
}
func TestReadWorkspaceFileRangedAndExisting(t *testing.T) {
coder, ws := testCoder(t)
path := filepath.Join(ws, "src.rb")
var b strings.Builder
for i := 1; i <= 20; i++ {
fmt.Fprintf(&b, "line-%d\n", i)
}
if err := os.WriteFile(path, []byte(b.String()), 0o644); err != nil {
t.Fatal(err)
}
// Existing whole-file path still works for small files.
whole := coder.readWorkspaceFile("src.rb", 0, 0)
if !strings.Contains(whole, "line-1") || !strings.Contains(whole, "line-20") {
t.Fatalf("whole read: %s", whole)
}
if strings.Contains(whole, "[truncated:") {
t.Fatalf("small file should not truncate: %s", whole)
}
got := coder.readWorkspaceFile("src.rb", 5, 7)
if got != "line-5\nline-6\nline-7" {
t.Fatalf("ranged workspace read: %q", got)
}
}
func TestReadFileWindowMultiBudgetConstant(t *testing.T) {
// Per-file multi budget is smaller than single, so 3× multi still near toolResultBudget.
if readBudgetMulti*3 > toolResultBudget {
t.Fatalf("3× multi (%d) exceeds toolResultBudget (%d)", readBudgetMulti*3, toolResultBudget)
}
if readBudgetSingle > toolResultBudget {
t.Fatalf("single (%d) exceeds toolResultBudget (%d)", readBudgetSingle, toolResultBudget)
}
// Ordinary routes-sized file (~9k) fits single budget.
if readBudgetSingle < 9000 {
t.Fatalf("single budget %d too small for ordinary source files", readBudgetSingle)
}
}