Elffuss BraidHub

kikocis/continue public

406467d04db9 · 14.2 KiBRawPermalink
1import * as fs from "fs";
2import * as path from "path";
3
4import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
6import { multiEditTool } from "./multiEdit.js";
7import { markFileAsRead } from "./readFile.js";
8
9// Mock the dependencies
10vi.mock("../telemetry/telemetryService.js");
11vi.mock("../telemetry/utils.js", () => ({
12 calculateLinesOfCodeDiff: vi.fn().mockReturnValue({ added: 1, removed: 0 }),
13 getLanguageFromFilePath: vi.fn().mockReturnValue("javascript"),
14}));
15vi.mock("./writeFile.js", () => ({
16 generateDiff: vi.fn().mockReturnValue("mocked diff"),
17}));
18vi.mock("fs", async () => {
19 const actual = await vi.importActual("fs");
20 return {
21 ...actual,
22 existsSync: vi.fn(),
23 readFileSync: vi.fn(),
24 writeFileSync: vi.fn(),
25 unlinkSync: vi.fn(),
26 realpathSync: vi.fn(),
27 };
28});
29
30describe("multiEditTool", () => {
31 const testFilePath = "/tmp/test-multi-edit-file.txt";
32 const originalContent = "Hello world\nThis is a test file\nGoodbye world";
33
34 beforeEach(() => {
35 vi.clearAllMocks();
36 // Mock fs functions to simulate file operations
37 vi.mocked(fs.existsSync).mockReturnValue(true);
38 vi.mocked(fs.readFileSync).mockReturnValue(originalContent);
39 vi.mocked(fs.writeFileSync).mockImplementation(() => {});
40 vi.mocked(fs.realpathSync).mockImplementation((path) => path.toString());
41 });
42
43 afterEach(() => {
44 vi.clearAllMocks();
45 });
46
47 describe("preprocess", () => {
48 it("should throw error if file has not been read", async () => {
49 const args = {
50 file_path: testFilePath,
51 edits: [
52 {
53 old_string: "Hello world",
54 new_string: "Hi there",
55 },
56 ],
57 };
58
59 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
60 `You must use the Read tool to read ${testFilePath} before editing it.`,
61 );
62 });
63
64 it("should throw error if file does not exist", async () => {
65 const nonExistentFile = "/tmp/non-existent-file.txt";
66 markFileAsRead(nonExistentFile);
67 vi.mocked(fs.existsSync).mockReturnValue(false);
68
69 const args = {
70 file_path: nonExistentFile,
71 edits: [
72 {
73 old_string: "Hello",
74 new_string: "Hi",
75 },
76 ],
77 };
78
79 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
80 `File ${nonExistentFile} does not exist`,
81 );
82 });
83
84 it("should throw error if edits array is empty", async () => {
85 markFileAsRead(testFilePath);
86
87 const args = {
88 file_path: testFilePath,
89 edits: [],
90 };
91
92 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
93 "edits array is required and must contain at least one edit",
94 );
95 });
96
97 it("should throw error if edit has missing old_string", async () => {
98 markFileAsRead(testFilePath);
99
100 const args = {
101 file_path: testFilePath,
102 edits: [
103 {
104 old_string: undefined as any,
105 new_string: "Hi there",
106 },
107 ],
108 };
109
110 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
111 "Edit 1: old_string is required",
112 );
113 });
114
115 it("should throw error if edit has missing new_string", async () => {
116 markFileAsRead(testFilePath);
117
118 const args = {
119 file_path: testFilePath,
120 edits: [
121 {
122 old_string: "Hello world",
123 new_string: undefined as any,
124 },
125 ],
126 };
127
128 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
129 "Edit 1: new_string is required",
130 );
131 });
132
133 it("should throw error if old_string and new_string are the same", async () => {
134 markFileAsRead(testFilePath);
135
136 const args = {
137 file_path: testFilePath,
138 edits: [
139 {
140 old_string: "Hello world",
141 new_string: "Hello world",
142 },
143 ],
144 };
145
146 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
147 "Edit 1: old_string and new_string must be different",
148 );
149 });
150
151 it("should throw error if old_string is not found", async () => {
152 markFileAsRead(testFilePath);
153 vi.mocked(fs.readFileSync).mockReturnValue("Different content");
154
155 const args = {
156 file_path: testFilePath,
157 edits: [
158 {
159 old_string: "Not found",
160 new_string: "Hi there",
161 },
162 ],
163 };
164
165 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
166 'Edit 1: String not found in file: "Not found"',
167 );
168 });
169
170 it("should throw error if old_string appears multiple times and replace_all is false", async () => {
171 markFileAsRead(testFilePath);
172
173 const args = {
174 file_path: testFilePath,
175 edits: [
176 {
177 old_string: "world",
178 new_string: "universe",
179 replace_all: false,
180 },
181 ],
182 };
183
184 await expect(multiEditTool.preprocess!(args)).rejects.toThrow(
185 'Edit 1: String "world" appears 2 times in the file. Either provide a more specific string with surrounding context to make it unique, or use replace_all=true to replace all occurrences.',
186 );
187 });
188
189 it("should successfully preprocess single edit", async () => {
190 markFileAsRead(testFilePath);
191
192 const args = {
193 file_path: testFilePath,
194 edits: [
195 {
196 old_string: "Hello world",
197 new_string: "Hi there",
198 },
199 ],
200 };
201
202 const result = await multiEditTool.preprocess!(args);
203
204 expect(result.args).toEqual({
205 file_path: testFilePath,
206 newContent: "Hi there\nThis is a test file\nGoodbye world",
207 originalContent: originalContent,
208 isCreatingNewFile: false,
209 editCount: 1,
210 });
211 expect(result.preview).toHaveLength(2);
212 expect(result.preview?.[0]).toEqual({
213 type: "text",
214 content: "Will apply 1 edit to modify /tmp/test-multi-edit-file.txt:",
215 });
216 expect(result.preview?.[1]).toEqual({
217 type: "diff",
218 content: "mocked diff",
219 });
220 });
221
222 it("should successfully preprocess multiple edits", async () => {
223 markFileAsRead(testFilePath);
224
225 const args = {
226 file_path: testFilePath,
227 edits: [
228 {
229 old_string: "Hello world",
230 new_string: "Hi there",
231 },
232 {
233 old_string: "Goodbye world",
234 new_string: "See you later",
235 },
236 ],
237 };
238
239 const result = await multiEditTool.preprocess!(args);
240
241 expect(result.args.newContent).toBe(
242 "Hi there\nThis is a test file\nSee you later",
243 );
244 expect(result.args.editCount).toBe(2);
245 expect(result.preview?.[0]?.content).toContain("Will apply 2 edits");
246 });
247
248 it("should successfully preprocess replace_all edit", async () => {
249 markFileAsRead(testFilePath);
250
251 const args = {
252 file_path: testFilePath,
253 edits: [
254 {
255 old_string: "world",
256 new_string: "universe",
257 replace_all: true,
258 },
259 ],
260 };
261
262 const result = await multiEditTool.preprocess!(args);
263
264 expect(result.args.newContent).toBe(
265 "Hello universe\nThis is a test file\nGoodbye universe",
266 );
267 });
268
269 it("should handle new file creation with empty old_string", async () => {
270 const newFilePath = "/tmp/new-file.txt";
271 vi.mocked(fs.existsSync).mockImplementation((path) => {
272 // Parent directory exists, but file doesn't
273 if (path === "/tmp") return true;
274 if (path === newFilePath) return false;
275 return true;
276 });
277
278 const args = {
279 file_path: newFilePath,
280 edits: [
281 {
282 old_string: "",
283 new_string: "New file content\nSecond line",
284 },
285 ],
286 };
287
288 const result = await multiEditTool.preprocess!(args);
289
290 expect(result.args.newContent).toBe("New file content\nSecond line");
291 expect(result.args.isCreatingNewFile).toBe(true);
292 expect(result.preview?.[0]?.content).toContain("create");
293 });
294
295 it("should apply edits sequentially", async () => {
296 markFileAsRead(testFilePath);
297
298 const args = {
299 file_path: testFilePath,
300 edits: [
301 {
302 old_string: "Hello world",
303 new_string: "Hi universe",
304 },
305 {
306 old_string: "Hi universe",
307 new_string: "Greetings cosmos",
308 },
309 ],
310 };
311
312 const result = await multiEditTool.preprocess!(args);
313
314 expect(result.args.newContent).toBe(
315 "Greetings cosmos\nThis is a test file\nGoodbye world",
316 );
317 });
318 });
319
320 describe("run", () => {
321 it("should successfully write file and return success message", async () => {
322 const newContent = "Hi there\nThis is a test file\nGoodbye world";
323 const args = {
324 file_path: testFilePath,
325 newContent,
326 originalContent: originalContent,
327 isCreatingNewFile: false,
328 editCount: 1,
329 };
330
331 const result = await multiEditTool.run(args);
332
333 expect(result).toBe(
334 `Successfully edited ${testFilePath} with 1 edit\nDiff:\nmocked diff`,
335 );
336 expect(fs.writeFileSync).toHaveBeenCalledWith(
337 testFilePath,
338 newContent,
339 "utf-8",
340 );
341 });
342
343 it("should return correct message for multiple edits", async () => {
344 const args = {
345 file_path: testFilePath,
346 newContent: "New content",
347 originalContent: originalContent,
348 isCreatingNewFile: false,
349 editCount: 3,
350 };
351
352 const result = await multiEditTool.run(args);
353
354 expect(result).toBe(
355 `Successfully edited ${testFilePath} with 3 edits\nDiff:\nmocked diff`,
356 );
357 });
358
359 it("should return correct message for new file creation", async () => {
360 const args = {
361 file_path: "/tmp/new-file.txt",
362 newContent: "New file content",
363 originalContent: "",
364 isCreatingNewFile: true,
365 editCount: 1,
366 };
367
368 const result = await multiEditTool.run(args);
369
370 expect(result).toBe(
371 `Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`,
372 );
373 });
374
375 it("should throw error if file write fails", async () => {
376 vi.mocked(fs.writeFileSync).mockImplementation(() => {
377 throw new Error("Write failed");
378 });
379
380 const args = {
381 file_path: testFilePath,
382 newContent: "new content",
383 originalContent: originalContent,
384 isCreatingNewFile: false,
385 editCount: 1,
386 };
387
388 await expect(multiEditTool.run(args)).rejects.toThrow(
389 `Error: failed to edit ${testFilePath}: Write failed`,
390 );
391 });
392 });
393
394 describe("relative path handling", () => {
395 it("should convert relative paths to absolute paths", async () => {
396 const relativePath = "test-file.txt";
397 const absolutePath = path.resolve(process.cwd(), relativePath);
398 markFileAsRead(absolutePath);
399
400 const args = {
401 file_path: relativePath,
402 edits: [
403 {
404 old_string: "Hello world",
405 new_string: "Hi there",
406 },
407 ],
408 };
409
410 const result = await multiEditTool.preprocess!(args);
411
412 expect(result.args.file_path).toBe(absolutePath);
413 expect(result.args.newContent).toBe(
414 "Hi there\nThis is a test file\nGoodbye world",
415 );
416 });
417
418 it("should handle relative paths with subdirectories", async () => {
419 const relativePath = "src/components/test.js";
420 const absolutePath = path.resolve(process.cwd(), relativePath);
421 markFileAsRead(absolutePath);
422
423 const args = {
424 file_path: relativePath,
425 edits: [
426 {
427 old_string: "Hello world",
428 new_string: "Hi there",
429 },
430 ],
431 };
432
433 const result = await multiEditTool.preprocess!(args);
434
435 expect(result.args.file_path).toBe(absolutePath);
436 });
437
438 it("should handle relative paths with ../ patterns", async () => {
439 const relativePath = "../test-file.txt";
440 const absolutePath = path.resolve(process.cwd(), relativePath);
441 markFileAsRead(absolutePath);
442
443 const args = {
444 file_path: relativePath,
445 edits: [
446 {
447 old_string: "Hello world",
448 new_string: "Hi there",
449 },
450 ],
451 };
452
453 const result = await multiEditTool.preprocess!(args);
454
455 expect(result.args.file_path).toBe(absolutePath);
456 });
457
458 it("should leave absolute paths unchanged", async () => {
459 const absolutePath = "/tmp/absolute-file.txt";
460 markFileAsRead(absolutePath);
461
462 const args = {
463 file_path: absolutePath,
464 edits: [
465 {
466 old_string: "Hello world",
467 new_string: "Hi there",
468 },
469 ],
470 };
471
472 const result = await multiEditTool.preprocess!(args);
473
474 expect(result.args.file_path).toBe(absolutePath);
475 });
476
477 it("should handle relative path for new file creation", async () => {
478 const relativePath = "new-file.txt";
479 const absolutePath = path.resolve(process.cwd(), relativePath);
480
481 vi.mocked(fs.existsSync).mockImplementation((path) => {
482 // Parent directory (cwd) exists, but file doesn't
483 if (path === process.cwd()) return true;
484 if (path === absolutePath) return false;
485 return true;
486 });
487
488 const args = {
489 file_path: relativePath,
490 edits: [
491 {
492 old_string: "",
493 new_string: "New file content",
494 },
495 ],
496 };
497
498 const result = await multiEditTool.preprocess!(args);
499
500 expect(result.args.file_path).toBe(absolutePath);
501 expect(result.args.newContent).toBe("New file content");
502 expect(result.args.isCreatingNewFile).toBe(true);
503 });
504 });
505
506 describe("markFileAsRead", () => {
507 it("should allow editing after marking file as read", async () => {
508 markFileAsRead(testFilePath);
509
510 const args = {
511 file_path: testFilePath,
512 edits: [
513 {
514 old_string: "Hello world",
515 new_string: "Hi there",
516 },
517 ],
518 };
519
520 const result = await multiEditTool.preprocess!(args);
521 expect(result.args.newContent).toContain("Hi there");
522 });
523 });
524});