Elffuss BraidHub

kikocis/continue public

16439cbc6ccd · 12.0 KiBRawPermalink
1import { jest } from "@jest/globals";
2import { execSync } from "node:child_process";
3import fs from "node:fs";
4import path from "path";
5
6import { LLMError } from "../llm/index.js";
7import { testConfigHandler, testIde } from "../test/fixtures.js";
8import {
9 addToTestDir,
10 setUpTestDir,
11 tearDownTestDir,
12 TEST_DIR,
13 TEST_DIR_PATH,
14} from "../test/testDir.js";
15import { getIndexSqlitePath } from "../util/paths.js";
16
17import { localPathToUri } from "../util/pathToUri.js";
18import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
19import { getComputeDeleteAddRemove } from "./refreshIndex.js";
20import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
21import { CodebaseIndex } from "./types.js";
22import { walkDir, walkDirCache } from "./walkDir.js";
23
24jest.useFakeTimers();
25
26const TEST_TS = `\
27function main() {
28 console.log("Hello, world!");
29}
30
31class Foo {
32 constructor(public bar: string) {}
33}
34`;
35
36const TEST_PY = `\
37def main():
38 print("Hello, world!")
39
40class Foo:
41 def __init__(self, bar: str):
42 self.bar = bar
43`;
44
45const TEST_RS = `\
46fn main() {
47 println!("Hello, world!");
48}
49
50struct Foo {
51 bar: String,
52}
53`;
54
55// A subclass of CodebaseIndexer that adds a new CodebaseIndex
56class TestCodebaseIndexer extends CodebaseIndexer {
57 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
58 return [new TestCodebaseIndex()];
59 }
60}
61
62// Create a mock messenger type that doesn't require actual protocol imports
63type MockMessengerType = {
64 send: jest.Mock;
65 request: jest.Mock;
66 invoke: jest.Mock;
67 on: jest.Mock;
68 onError: jest.Mock;
69};
70
71// These are more like integration tests, whereas we should separately test
72// the individual CodebaseIndex classes
73describe("CodebaseIndexer", () => {
74 const pauseToken = new PauseToken(false);
75
76 // Replace mockProgressReporter with mockMessenger
77 const mockMessenger: MockMessengerType = {
78 send: jest.fn(),
79 request: jest.fn(async () => {}),
80 invoke: jest.fn(),
81 on: jest.fn(),
82 onError: jest.fn(),
83 };
84
85 const codebaseIndexer = new TestCodebaseIndexer(
86 testConfigHandler,
87 testIde,
88 mockMessenger as any,
89 false,
90 );
91 const testIndex = new TestCodebaseIndex();
92
93 beforeAll(async () => {
94 tearDownTestDir();
95 setUpTestDir();
96
97 execSync("git init", { cwd: TEST_DIR_PATH });
98 execSync('git config user.email "test@example.com"', {
99 cwd: TEST_DIR_PATH,
100 });
101 execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
102 });
103
104 afterAll(async () => {
105 tearDownTestDir();
106 });
107
108 afterEach(() => {
109 walkDirCache.invalidate();
110 jest.clearAllMocks();
111 });
112
113 async function refreshIndex() {
114 const abortController = new AbortController();
115 const abortSignal = abortController.signal;
116
117 const updates = [];
118 for await (const update of codebaseIndexer.refreshDirs(
119 [TEST_DIR],
120 abortSignal,
121 )) {
122 updates.push(update);
123 }
124 return updates;
125 }
126
127 async function refreshIndexFiles(files: string[]) {
128 const updates = [];
129 for await (const update of codebaseIndexer.refreshFiles(files)) {
130 updates.push(update);
131 }
132 return updates;
133 }
134
135 async function getAllIndexedFiles() {
136 const files = await testIndex.getIndexedFilesForTags(
137 await testIde.getTags(testIndex.artifactId),
138 );
139 return files;
140 }
141
142 async function getIndexPlan() {
143 const workspaceFiles = await walkDir(TEST_DIR, testIde);
144 const [tag] = await testIde.getTags(testIndex.artifactId);
145 const stats = await testIde.getFileStats(workspaceFiles);
146
147 const [results, lastUpdated, markComplete] =
148 await getComputeDeleteAddRemove(
149 tag,
150 { ...stats },
151 (filepath) => testIde.readFile(filepath),
152 undefined,
153 );
154 return results;
155 }
156
157 async function expectPlan(
158 compute: number,
159 addTag: number,
160 removeTag: number,
161 del: number,
162 ) {
163 const plan = await getIndexPlan();
164 expect(plan.compute).toHaveLength(compute);
165 expect(plan.addTag).toHaveLength(addTag);
166 expect(plan.removeTag).toHaveLength(removeTag);
167 expect(plan.del).toHaveLength(del);
168 return plan;
169 }
170
171 test("should index test folder without problem", async () => {
172 addToTestDir([
173 ["test.ts", TEST_TS],
174 ["py/main.py", TEST_PY],
175 ]);
176
177 await expectPlan(2, 0, 0, 0);
178
179 const updates = await refreshIndex();
180 expect(updates.length).toBeGreaterThan(0);
181 });
182
183 test("should have created index folder with all necessary files", async () => {
184 const exists = await testIde.fileExists(
185 localPathToUri(getIndexSqlitePath()),
186 );
187 expect(exists).toBe(true);
188 });
189
190 test("should have indexed all of the files", async () => {
191 const indexed = await getAllIndexedFiles();
192 expect(indexed.length).toBe(2);
193 expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
194 expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
195 });
196
197 test("should successfuly re-index specific files", async () => {
198 // Could add more specific tests for this but uses similar logic
199 const before = await getAllIndexedFiles();
200 await refreshIndexFiles(before);
201
202 const after = await getAllIndexedFiles();
203 expect(after.length).toBe(before.length);
204 });
205
206 test("should successfully re-index after adding a file", async () => {
207 addToTestDir([["main.rs", TEST_RS]]);
208
209 await expectPlan(1, 0, 0, 0);
210
211 const updates = await refreshIndex();
212 expect(updates.length).toBeGreaterThan(0);
213
214 // Check that the new file was indexed
215 const files = await getAllIndexedFiles();
216 expect(files.length).toBe(3);
217 expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
218 });
219
220 test("should successfully re-index after deleting a file", async () => {
221 fs.rmSync(path.join(TEST_DIR_PATH, "main.rs"));
222
223 await expectPlan(0, 0, 0, 1);
224
225 const updates = await refreshIndex();
226 expect(updates.length).toBeGreaterThan(0);
227
228 // Check that the deleted file was removed from the index
229 const files = await getAllIndexedFiles();
230 expect(files.length).toBe(2);
231 expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
232 });
233
234 test("shouldn't index any files when nothing changed", async () => {
235 await expectPlan(0, 0, 0, 0);
236 const updates = await refreshIndex();
237 expect(updates.length).toBeGreaterThan(0);
238 });
239
240 test("should create git repo for testing", async () => {
241 execSync(
242 `cd ${TEST_DIR_PATH} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
243 );
244 });
245
246 test.skip("should only re-index the changed files when changing branches", async () => {
247 execSync(`cd ${TEST_DIR_PATH} && git checkout -b test2`);
248 // Rewriting the file
249 addToTestDir([["test.ts", "// This is different"]]);
250
251 // Should re-compute test.ts, but just re-tag the .py file
252 await expectPlan(1, 1, 0, 0);
253
254 execSync(
255 `cd ${TEST_DIR_PATH} && git add -A && git commit -m "Change .ts file"`,
256 );
257 });
258
259 test.skip("shouldn't re-index anything when changing back to original branch", async () => {
260 execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
261 await expectPlan(0, 0, 0, 0);
262 });
263
264 // New tests for the methods added from Core.ts
265 describe("New methods from Core.ts", () => {
266 // Simplified tests to focus on behavior, not implementation details
267 test("should call messenger with progress updates when refreshing codebase index", async () => {
268 jest
269 .spyOn(codebaseIndexer as any, "refreshDirs")
270 .mockImplementation(async function* () {
271 yield { status: "done", progress: 1, desc: "Completed" };
272 });
273
274 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
275
276 expect(mockMessenger.request).toHaveBeenCalledWith(
277 "indexProgress",
278 expect.anything(),
279 );
280 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
281 providers: "all",
282 });
283 });
284
285 test("should call messenger with progress updates when refreshing specific files", async () => {
286 jest
287 .spyOn(codebaseIndexer as any, "refreshFiles")
288 .mockImplementation(async function* () {
289 yield { status: "done", progress: 1, desc: "Completed" };
290 });
291
292 await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
293
294 expect(mockMessenger.request).toHaveBeenCalledWith(
295 "indexProgress",
296 expect.anything(),
297 );
298 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
299 providers: "all",
300 });
301 });
302
303 test("should abort previous indexing when starting a new one", async () => {
304 // Set up a situation where indexingCancellationController exists
305 const mockAbort = jest.fn();
306 const controller = { abort: mockAbort, signal: { aborted: false } };
307
308 // Access the private property in a type-safe way for testing
309 (codebaseIndexer as any).indexingCancellationController = controller;
310
311 // Mock refreshDirs to return immediately
312 jest
313 .spyOn(codebaseIndexer as any, "refreshDirs")
314 .mockImplementation(async function* () {
315 yield { status: "done", progress: 1, desc: "Completed" };
316 });
317
318 // Start indexing - this should call abort on the existing controller
319 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
320
321 // Verify abort was called
322 expect(mockAbort).toHaveBeenCalled();
323 });
324
325 test("should handle errors properly during indexing", async () => {
326 const testError = new Error("Test indexing error");
327
328 // Mock console.log to avoid printing errors
329 const consoleLogSpy = jest
330 .spyOn(console, "log")
331 .mockImplementation(() => {});
332
333 // Mock refreshDirs to throw an error
334 jest
335 .spyOn(codebaseIndexer as any, "refreshDirs")
336 .mockImplementation(() => {
337 throw testError;
338 });
339
340 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
341 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
342
343 // Use the first argument only for the assertion since the second argument doesn't match exactly
344 expect(consoleLogSpy).toHaveBeenCalledWith(
345 `Failed refreshing codebase index directories: Error: ${testError.message}`,
346 );
347 expect(mockMessenger.request).toHaveBeenCalledWith(
348 "indexProgress",
349 expect.objectContaining({
350 status: "failed",
351 }),
352 );
353
354 consoleLogSpy.mockRestore();
355 });
356
357 test("should handle LLMError specially during indexing", async () => {
358 // Create a mock LLM
359 const mockLlm: any = {
360 providerName: "test-provider",
361 model: "test-model",
362 };
363
364 // Create a real LLMError
365 const llmError = new LLMError("Test LLM error", mockLlm);
366
367 // Mock console.log to avoid printing errors
368 jest.spyOn(console, "log").mockImplementation(() => {});
369
370 // Mock refreshDirs to throw an LLMError
371 jest
372 .spyOn(codebaseIndexer as any, "refreshDirs")
373 .mockImplementation(() => {
374 throw llmError;
375 });
376
377 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
378 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
379
380 expect(mockMessenger.request).toHaveBeenCalledWith(
381 "reportError",
382 llmError,
383 );
384 expect(mockMessenger.request).toHaveBeenCalledWith(
385 "indexProgress",
386 expect.objectContaining({
387 status: "failed",
388 desc: "Test LLM error",
389 }),
390 );
391 });
392
393 test("should provide access to current indexing state", async () => {
394 const testState = {
395 progress: 0.5,
396 status: "indexing" as const,
397 desc: "Test state",
398 };
399
400 // Mock refreshDirs to set a specific state
401 jest
402 .spyOn(codebaseIndexer as any, "refreshDirs")
403 .mockImplementation(async function* () {
404 yield testState;
405 });
406
407 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
408 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
409
410 // Check that the state was updated
411 expect(codebaseIndexer.currentIndexingState).toEqual(testState);
412 });
413 });
414});