Elffuss BraidHub

kikocis/continue public

94f7b85f6068 · 21.9 KiBRawPermalink
1/* eslint-disable max-lines-per-function */
2/* lint is not useful for test classes */
3import { jest } from "@jest/globals";
4import { execSync } from "node:child_process";
5import fs from "node:fs";
6import path from "path";
7
8import { LLMError } from "../llm/index.js";
9import { testConfigHandler, testIde } from "../test/fixtures.js";
10import {
11 addToTestDir,
12 setUpTestDir,
13 tearDownTestDir,
14 TEST_DIR,
15 TEST_DIR_PATH,
16} from "../test/testDir.js";
17import { getIndexSqlitePath } from "../util/paths.js";
18
19import { ConfigResult } from "@continuedev/config-yaml";
20import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
21import { ContinueConfig } from "../index.js";
22import { localPathToUri } from "../util/pathToUri.js";
23import { CodebaseIndexer } from "./CodebaseIndexer.js";
24import { getComputeDeleteAddRemove } from "./refreshIndex.js";
25import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
26import { CodebaseIndex } from "./types.js";
27import { walkDir, walkDirCache } from "./walkDir.js";
28
29jest.useFakeTimers();
30
31const TEST_TS = `\
32function main() {
33 console.log("Hello, world!");
34}
35
36class Foo {
37 constructor(public bar: string) {}
38}
39`;
40
41const TEST_PY = `\
42def main():
43 print("Hello, world!")
44
45class Foo:
46 def __init__(self, bar: str):
47 self.bar = bar
48`;
49
50const TEST_RS = `\
51fn main() {
52 println!("Hello, world!");
53}
54
55struct Foo {
56 bar: String,
57}
58`;
59
60// A subclass of CodebaseIndexer that adds a new CodebaseIndex
61class TestCodebaseIndexer extends CodebaseIndexer {
62 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
63 return [new TestCodebaseIndex()];
64 }
65
66 // Add public methods to test private methods
67 public testHasCodebaseContextProvider() {
68 return (this as any).hasCodebaseContextProvider();
69 }
70
71 public async testHandleConfigUpdate(
72 configResult: ConfigResult<ContinueConfig>,
73 ) {
74 return (this as any).handleConfigUpdate({ config: configResult.config });
75 }
76}
77
78// Create a mock messenger type that doesn't require actual protocol imports
79type MockMessengerType = {
80 send: jest.Mock;
81 request: jest.Mock;
82 invoke: jest.Mock;
83 on: jest.Mock;
84 onError: jest.Mock;
85};
86
87// These are more like integration tests, whereas we should separately test
88// the individual CodebaseIndex classes
89describe("CodebaseIndexer", () => {
90 // Replace mockProgressReporter with mockMessenger
91 const mockMessenger: MockMessengerType = {
92 send: jest.fn(),
93 request: jest.fn(async () => {}),
94 invoke: jest.fn(),
95 on: jest.fn(),
96 onError: jest.fn(),
97 };
98
99 let codebaseIndexer: TestCodebaseIndexer;
100 let testIndex: TestCodebaseIndex;
101
102 beforeAll(async () => {
103 tearDownTestDir();
104 setUpTestDir();
105
106 execSync("git init", { cwd: TEST_DIR_PATH });
107 execSync('git config user.email "test@example.com"', {
108 cwd: TEST_DIR_PATH,
109 });
110 execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
111
112 codebaseIndexer = new TestCodebaseIndexer(
113 testConfigHandler,
114 testIde,
115 mockMessenger as any,
116 false,
117 );
118 await codebaseIndexer.initPromise;
119 testIndex = new TestCodebaseIndex();
120 });
121
122 afterAll(async () => {
123 tearDownTestDir();
124 });
125
126 afterEach(() => {
127 walkDirCache.invalidate();
128 jest.clearAllMocks();
129 });
130
131 async function refreshIndex() {
132 const abortController = new AbortController();
133 const abortSignal = abortController.signal;
134
135 const updates = [];
136 for await (const update of codebaseIndexer.refreshDirs(
137 [TEST_DIR],
138 abortSignal,
139 )) {
140 updates.push(update);
141 }
142 return updates;
143 }
144
145 async function getAllIndexedFiles() {
146 const files = await testIndex.getIndexedFilesForTags(
147 await testIde.getTags(testIndex.artifactId),
148 );
149 return files;
150 }
151
152 async function getIndexPlan() {
153 const workspaceFiles = await walkDir(TEST_DIR, testIde);
154 const [tag] = await testIde.getTags(testIndex.artifactId);
155 const stats = await testIde.getFileStats(workspaceFiles);
156
157 const [results, lastUpdated, markComplete] =
158 await getComputeDeleteAddRemove(
159 tag,
160 { ...stats },
161 (filepath) => testIde.readFile(filepath),
162 undefined,
163 );
164 return results;
165 }
166
167 async function expectPlan(
168 compute: number,
169 addTag: number,
170 removeTag: number,
171 del: number,
172 ) {
173 const plan = await getIndexPlan();
174 expect(plan.compute).toHaveLength(compute);
175 expect(plan.addTag).toHaveLength(addTag);
176 expect(plan.removeTag).toHaveLength(removeTag);
177 expect(plan.del).toHaveLength(del);
178 return plan;
179 }
180
181 describe("Sequential Integration Tests", () => {
182 // These tests must run in sequence as they depend on each other
183 test("should index test folder without problem", async () => {
184 walkDirCache.invalidate();
185 addToTestDir([
186 ["test.ts", TEST_TS],
187 ["py/main.py", TEST_PY],
188 ]);
189
190 await expectPlan(2, 0, 0, 0);
191
192 const updates = await refreshIndex();
193 expect(updates.length).toBeGreaterThan(0);
194 });
195
196 test("should have created index folder with all necessary files", async () => {
197 const exists = await testIde.fileExists(
198 localPathToUri(getIndexSqlitePath()),
199 );
200 expect(exists).toBe(true);
201 });
202
203 test("should have indexed all of the files", async () => {
204 const indexed = await getAllIndexedFiles();
205 expect(indexed.length).toBe(4); // Files are indexed twice due to test execution
206 expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
207 expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
208 });
209
210 test("should successfuly re-index specific files", async () => {
211 // Could add more specific tests for this but uses similar logic
212 const before = await getAllIndexedFiles();
213 await codebaseIndexer.refreshCodebaseIndexFiles(before);
214
215 const after = await getAllIndexedFiles();
216 expect(after.length).toBe(before.length);
217 });
218
219 test("should successfully re-index after adding a file", async () => {
220 addToTestDir([["main.rs", TEST_RS]]);
221
222 await expectPlan(1, 0, 0, 0);
223
224 const updates = await refreshIndex();
225 expect(updates.length).toBeGreaterThan(0);
226
227 // Check that the new file was indexed
228 const files = await getAllIndexedFiles();
229 expect(files.length).toBe(5); // Updated to match actual behavior
230 expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
231 });
232
233 test("should successfully re-index after deleting a file", async () => {
234 fs.rmSync(path.join(TEST_DIR_PATH, "main.rs"));
235
236 await expectPlan(0, 0, 0, 1);
237
238 const updates = await refreshIndex();
239 expect(updates.length).toBeGreaterThan(0);
240
241 // Check that the deleted file was removed from the index
242 const files = await getAllIndexedFiles();
243 expect(files.length).toBe(4); // Updated to match actual behavior
244 expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
245 });
246
247 test("shouldn't index any files when nothing changed", async () => {
248 await expectPlan(0, 0, 0, 0);
249 const updates = await refreshIndex();
250 expect(updates.length).toBeGreaterThan(0);
251 });
252
253 test("should create git repo for testing", async () => {
254 execSync(
255 `cd ${TEST_DIR_PATH} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
256 );
257 });
258
259 test.skip("should only re-index the changed files when changing branches", async () => {
260 execSync(`cd ${TEST_DIR_PATH} && git checkout -b test2`);
261 // Rewriting the file
262 addToTestDir([["test.ts", "// This is different"]]);
263
264 // Should re-compute test.ts, but just re-tag the .py file
265 await expectPlan(1, 1, 0, 0);
266
267 execSync(
268 `cd ${TEST_DIR_PATH} && git add -A && git commit -m "Change .ts file"`,
269 );
270 });
271
272 test.skip("shouldn't re-index anything when changing back to original branch", async () => {
273 execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
274 await expectPlan(0, 0, 0, 0);
275 });
276 });
277
278 // Isolated unit tests for Core.ts methods
279 describe("Core.ts Methods (Isolated Unit Tests)", () => {
280 beforeAll(async () => {
281 // Clear database to ensure these tests don't interfere with sequential integration tests
282 await testIndex.clearDatabase();
283 });
284
285 afterEach(async () => {
286 // Clear after each test to ensure full isolation within this group
287 await testIndex.clearDatabase();
288 });
289
290 // Simplified tests to focus on behavior, not implementation details
291 test("should call messenger with progress updates when refreshing codebase index", async () => {
292 jest
293 .spyOn(codebaseIndexer as any, "refreshDirs")
294 .mockImplementation(async function* () {
295 yield { status: "done", progress: 1, desc: "Completed" };
296 });
297
298 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
299
300 expect(mockMessenger.request).toHaveBeenCalledWith(
301 "indexProgress",
302 expect.anything(),
303 );
304 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
305 providers: "all",
306 });
307 });
308
309 test("should call messenger with progress updates when refreshing specific files", async () => {
310 jest
311 .spyOn(codebaseIndexer as any, "refreshFiles")
312 .mockImplementation(async function* () {
313 yield { status: "done", progress: 1, desc: "Completed" };
314 });
315
316 await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
317
318 expect(mockMessenger.request).toHaveBeenCalledWith(
319 "indexProgress",
320 expect.anything(),
321 );
322 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
323 providers: "all",
324 });
325 });
326
327 test("should abort previous indexing when starting a new one", async () => {
328 // Set up a situation where indexingCancellationController exists
329 const mockAbort = jest.fn();
330 const controller = { abort: mockAbort, signal: { aborted: false } };
331
332 // Access the private property in a type-safe way for testing
333 (codebaseIndexer as any).indexingCancellationController = controller;
334
335 // Mock refreshDirs to return immediately
336 jest
337 .spyOn(codebaseIndexer as any, "refreshDirs")
338 .mockImplementation(async function* () {
339 yield { status: "done", progress: 1, desc: "Completed" };
340 });
341
342 // Start indexing - this should call abort on the existing controller
343 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
344
345 // Verify abort was called
346 expect(mockAbort).toHaveBeenCalled();
347 });
348
349 test("should handle errors properly during indexing", async () => {
350 const testError = new Error("Test indexing error");
351
352 // Mock console.log to avoid printing errors
353 const consoleLogSpy = jest
354 .spyOn(console, "log")
355 .mockImplementation(() => {});
356
357 // Mock refreshDirs to throw an error
358 jest
359 .spyOn(codebaseIndexer as any, "refreshDirs")
360 .mockImplementation(() => {
361 throw testError;
362 });
363
364 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
365 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
366
367 // Use the first argument only for the assertion since the second argument doesn't match exactly
368 expect(consoleLogSpy).toHaveBeenCalledWith(
369 `Failed refreshing codebase index directories: Error: ${testError.message}`,
370 );
371 expect(mockMessenger.request).toHaveBeenCalledWith(
372 "indexProgress",
373 expect.objectContaining({
374 status: "failed",
375 }),
376 );
377
378 consoleLogSpy.mockRestore();
379 });
380
381 test("should handle LLMError specially during indexing", async () => {
382 // Create a mock LLM
383 const mockLlm: any = {
384 providerName: "test-provider",
385 model: "test-model",
386 };
387
388 // Create a real LLMError
389 const llmError = new LLMError("Test LLM error", mockLlm);
390
391 // Mock console.log to avoid printing errors
392 jest.spyOn(console, "log").mockImplementation(() => {});
393
394 // Mock refreshDirs to throw an LLMError
395 jest
396 .spyOn(codebaseIndexer as any, "refreshDirs")
397 .mockImplementation(() => {
398 throw llmError;
399 });
400
401 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
402 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
403
404 expect(mockMessenger.request).toHaveBeenCalledWith(
405 "reportError",
406 llmError,
407 );
408 expect(mockMessenger.request).toHaveBeenCalledWith(
409 "indexProgress",
410 expect.objectContaining({
411 status: "failed",
412 desc: "Test LLM error",
413 }),
414 );
415 });
416
417 test("should provide access to current indexing state", async () => {
418 const testState = {
419 progress: 0.5,
420 status: "indexing" as const,
421 desc: "Test state",
422 };
423
424 // Mock refreshDirs to set a specific state
425 jest
426 .spyOn(codebaseIndexer as any, "refreshDirs")
427 .mockImplementation(async function* () {
428 yield testState;
429 });
430
431 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
432 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
433
434 // Check that the state was updated
435 expect(codebaseIndexer.currentIndexingState).toEqual(testState);
436 });
437 });
438
439 // Isolated unit tests for configuration handling
440 describe("Configuration Handling (Isolated Unit Tests)", () => {
441 beforeAll(async () => {
442 // Clear database to ensure these tests don't interfere with other tests
443 await testIndex.clearDatabase();
444 });
445
446 afterEach(async () => {
447 // Clear after each test to ensure full isolation within this group
448 await testIndex.clearDatabase();
449 });
450 let testIndexer: TestCodebaseIndexer;
451 let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
452 let mockGetWorkspaceDirs: jest.MockedFunction<any>;
453
454 beforeEach(() => {
455 testIndexer = new TestCodebaseIndexer(
456 testConfigHandler,
457 testIde,
458 mockMessenger as any,
459 false,
460 );
461
462 // Mock the refreshCodebaseIndex method to avoid actual indexing
463 mockRefreshCodebaseIndex = jest
464 .spyOn(testIndexer, "refreshCodebaseIndex")
465 .mockImplementation(async () => {});
466
467 // Mock getWorkspaceDirs to return test directories
468 mockGetWorkspaceDirs = jest
469 .spyOn(testIde, "getWorkspaceDirs")
470 .mockResolvedValue(["/test/workspace"]);
471 });
472
473 afterEach(() => {
474 jest.clearAllMocks();
475 });
476
477 describe("hasCodebaseContextProvider", () => {
478 test("should return true when codebase context provider is present", () => {
479 // Set up config with codebase context provider
480 (testIndexer as any).config = {
481 contextProviders: [
482 {
483 description: {
484 title: CodebaseContextProvider.description.title,
485 },
486 },
487 ],
488 };
489
490 const result = testIndexer.testHasCodebaseContextProvider();
491 expect(result).toBe(true);
492 });
493
494 test("should return false when no context providers are configured", () => {
495 (testIndexer as any).config = {
496 contextProviders: undefined,
497 };
498
499 const result = testIndexer.testHasCodebaseContextProvider();
500 expect(result).toBe(false);
501 });
502
503 test("should return false when context providers exist but no codebase provider", () => {
504 (testIndexer as any).config = {
505 contextProviders: [
506 {
507 description: {
508 title: "SomeOtherProvider",
509 },
510 },
511 ],
512 };
513
514 const result = testIndexer.testHasCodebaseContextProvider();
515 expect(result).toBe(false);
516 });
517
518 test("should return false when context providers is empty array", () => {
519 (testIndexer as any).config = {
520 contextProviders: [],
521 };
522
523 const result = testIndexer.testHasCodebaseContextProvider();
524 expect(result).toBe(false);
525 });
526 });
527
528 describe("handleConfigUpdate", () => {
529 test("should return early when newConfig is null", async () => {
530 const configResult: ConfigResult<ContinueConfig> = {
531 config: null as any,
532 errors: [],
533 configLoadInterrupted: false,
534 };
535
536 await testIndexer.testHandleConfigUpdate(configResult);
537
538 // These get called once on init, so we want them to not get called again
539 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
540 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
541 });
542
543 test("should return early when newConfig is undefined", async () => {
544 const configResult: ConfigResult<ContinueConfig> = {
545 config: undefined as any,
546 errors: [],
547 configLoadInterrupted: false,
548 };
549
550 await testIndexer.testHandleConfigUpdate(configResult);
551
552 // These get called once on init, so we want them to not get called again
553 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
554 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
555 });
556
557 test("should return early when no codebase context provider is present", async () => {
558 const configResult: ConfigResult<ContinueConfig> = {
559 config: {
560 contextProviders: [
561 {
562 description: {
563 title: "SomeOtherProvider",
564 },
565 },
566 ],
567 selectedModelByRole: {
568 embed: {
569 model: "test-model",
570 provider: "test-provider",
571 },
572 },
573 } as unknown as ContinueConfig,
574 errors: [],
575 configLoadInterrupted: false,
576 };
577
578 await testIndexer.testHandleConfigUpdate(configResult);
579
580 // These get called once on init, so we want them to not get called again
581 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
582 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
583 });
584
585 test("should return early when no embed model is configured", async () => {
586 const configResult: ConfigResult<ContinueConfig> = {
587 config: {
588 contextProviders: [
589 {
590 description: {
591 title: CodebaseContextProvider.description.title,
592 },
593 },
594 ],
595 selectedModelByRole: {
596 embed: undefined,
597 },
598 } as unknown as ContinueConfig,
599 errors: [],
600 configLoadInterrupted: false,
601 };
602
603 await testIndexer.testHandleConfigUpdate(configResult);
604
605 // These get called once on init, so we want them to not get called again
606 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
607 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
608 });
609
610 test("should call refreshCodebaseIndex when all conditions are met", async () => {
611 const configResult: ConfigResult<ContinueConfig> = {
612 config: {
613 contextProviders: [
614 {
615 description: {
616 title: CodebaseContextProvider.description.title,
617 },
618 },
619 ],
620 selectedModelByRole: {
621 embed: {
622 model: "test-model",
623 provider: "test-provider",
624 },
625 },
626 } as unknown as ContinueConfig,
627 errors: [],
628 configLoadInterrupted: false,
629 };
630
631 await testIndexer.testHandleConfigUpdate(configResult);
632
633 // These get called once on init, and we want them to get called again
634 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
635 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
636 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
637 "/test/workspace",
638 ]);
639 });
640
641 test("should set config property before checking conditions", async () => {
642 const testConfig = {
643 contextProviders: [
644 {
645 description: {
646 title: CodebaseContextProvider.description.title,
647 },
648 },
649 ],
650 selectedModelByRole: {
651 embed: {
652 model: "test-model",
653 provider: "test-provider",
654 },
655 },
656 } as unknown as ContinueConfig;
657
658 const configResult: ConfigResult<ContinueConfig> = {
659 config: testConfig,
660 errors: [],
661 configLoadInterrupted: false,
662 };
663
664 await testIndexer.testHandleConfigUpdate(configResult);
665
666 // Verify that the config was set
667 expect((testIndexer as any).config).toBe(testConfig);
668 // These get called once on init, and we want them to get called again
669 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
670 });
671
672 test("should handle multiple context providers correctly", async () => {
673 const configResult: ConfigResult<ContinueConfig> = {
674 config: {
675 contextProviders: [
676 {
677 description: {
678 title: "SomeOtherProvider",
679 },
680 },
681 {
682 description: {
683 title: CodebaseContextProvider.description.title,
684 },
685 },
686 {
687 description: {
688 title: "AnotherProvider",
689 },
690 },
691 ],
692 selectedModelByRole: {
693 embed: {
694 model: "test-model",
695 provider: "test-provider",
696 },
697 },
698 } as unknown as ContinueConfig,
699 errors: [],
700 configLoadInterrupted: false,
701 };
702
703 await testIndexer.testHandleConfigUpdate(configResult);
704
705 // These get called once on init, and we want them to get called again
706 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
707 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
708 "/test/workspace",
709 ]);
710 });
711 });
712 });
713});