diff --git a/.continue/prompts/core-unit-test.prompt b/.continue/prompts/core-unit-test.prompt index f04f6f48e..42ecef7bb 100644 --- a/.continue/prompts/core-unit-test.prompt +++ b/.continue/prompts/core-unit-test.prompt @@ -32,7 +32,6 @@ Jest testing setup includes Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests. IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible. -When using jest.fn, always declare the type, e.g. jest.fn<() => Promise>().mockResolvedValue("hi") Instead, generate actual mock files and data for operations Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests diff --git a/core/edit/lazy/findInAst.test.ts b/core/edit/lazy/findInAst.test.ts index e69de29bb..f9e95613b 100644 --- a/core/edit/lazy/findInAst.test.ts +++ b/core/edit/lazy/findInAst.test.ts @@ -0,0 +1,109 @@ +// Generated by continue + +import { findInAst } from "./findInAst"; +import Parser from "web-tree-sitter"; + +describe("findInAst", () => { + it("should find a node matching the criterion", () => { + const mockAst = createMockSyntaxNode("root", [ + createMockSyntaxNode("child1", []), + createMockSyntaxNode("function", [createMockSyntaxNode("child2", [])]), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + }); + + it("should return null if no node matches the criterion", () => { + const mockAst = createMockSyntaxNode("root", [ + createMockSyntaxNode("child1", []), + createMockSyntaxNode("child2", []), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).toBeNull(); + }); + + it("should find a nested node matching the criterion", () => { + const mockAst = createMockSyntaxNode("root", [ + createMockSyntaxNode("child1", [ + createMockSyntaxNode("child2", [createMockSyntaxNode("function", [])]), + ]), + createMockSyntaxNode("child3", []), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + }); + + it("should return the first node matching the criterion in depth-first traversal", () => { + const firstFunctionNode = createMockSyntaxNode("function", []); + const secondFunctionNode = createMockSyntaxNode("function", []); + const mockAst = createMockSyntaxNode("root", [ + firstFunctionNode, // First function node + createMockSyntaxNode("child1", [ + secondFunctionNode, // Second function node + ]), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + expect(JSON.stringify(result)).toBe(JSON.stringify(firstFunctionNode)); // Ensure it's the first function node + }); + + it("should return the root node if it matches the criterion", () => { + const mockAst = createMockSyntaxNode("function", [ + createMockSyntaxNode("child1", []), + createMockSyntaxNode("child2", []), + ]); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).not.toBeNull(); + expect(result!.type).toBe("function"); + expect(result).toBe(mockAst); + }); + + it("should return null when searching an empty tree", () => { + const mockAst = createMockSyntaxNode("root", []); + + const criterion = (node: Parser.SyntaxNode) => node.type === "function"; + + const result = findInAst(mockAst, criterion); + + expect(result).toBeNull(); + }); +}); + +function createMockSyntaxNode( + type: string, + children: Parser.SyntaxNode[], +): Parser.SyntaxNode { + // Define minimal properties of SyntaxNode required for the test + const node: Partial = { + type, + children, + childCount: children.length, + child: (index: number) => { + return children[index] || null; + }, + }; + return node as Parser.SyntaxNode; +} diff --git a/core/indexing/chunk/basic.test.ts b/core/indexing/chunk/basic.test.ts new file mode 100644 index 000000000..4c65f2fa8 --- /dev/null +++ b/core/indexing/chunk/basic.test.ts @@ -0,0 +1,87 @@ +// Generated by continue +// core/indexing/chunk/basic.test.ts + +import { basicChunker } from "./basic.js"; +import { countTokensAsync } from "../../llm/countTokens"; +import { ChunkWithoutID } from "../../index"; + +// jest.mock("../../llm/countTokens", () => ({ +// countTokensAsync: jest.fn(), +// })); + +describe.skip("basicChunker", () => { + beforeEach(() => { + jest.resetAllMocks(); + }); + + it("should yield no chunks for empty content", async () => { + const contents = ""; + const maxChunkSize = 10; + const chunks: ChunkWithoutID[] = []; + + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toHaveLength(0); + }); + + it("should yield a single chunk if whole content fits within the max size", async () => { + (countTokensAsync as jest.Mock).mockResolvedValue(1); + const contents = "line1\nline2\nline3"; + const maxChunkSize = 10; + const expectedChunks: ChunkWithoutID[] = [ + { content: "line1\nline2\nline3\n", startLine: 0, endLine: 2 }, + ]; + + const chunks: ChunkWithoutID[] = []; + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toEqual(expectedChunks); + }); + + it("should yield multiple chunks when content exceeds the max size", async () => { + (countTokensAsync as jest.Mock).mockImplementation(async (line: string) => { + if (line === "line3") return 5; + return 3; // Mock returning 3 tokens per line except for "line3" + }); + + const contents = "line1\nline2\nline3\nline4\nline5"; + const maxChunkSize = 8; + const expectedChunks: ChunkWithoutID[] = [ + { content: "line1\nline2\n", startLine: 0, endLine: 1 }, + { content: "line3\n", startLine: 2, endLine: 2 }, + { content: "line4\nline5\n", startLine: 3, endLine: 4 }, + ]; + + const chunks: ChunkWithoutID[] = []; + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toEqual(expectedChunks); + }); + + it("should skip lines that exceed the max chunk size", async () => { + (countTokensAsync as jest.Mock).mockImplementation(async (line: string) => { + if (line === "line3") return 15; // Making it explicitly exceed max size + return 3; + }); + + const contents = "line1\nline2\nline3\nline4\nline5"; + const maxChunkSize = 8; + const expectedChunks: ChunkWithoutID[] = [ + { content: "line1\nline2\n", startLine: 0, endLine: 1 }, + { content: "line4\nline5\n", startLine: 3, endLine: 4 }, + ]; + + const chunks: ChunkWithoutID[] = []; + for await (const chunk of basicChunker(contents, maxChunkSize)) { + chunks.push(chunk); + } + + expect(chunks).toEqual(expectedChunks); + }); +}); diff --git a/core/indexing/docs/suggestions/suggestions.test.ts b/core/indexing/docs/suggestions/suggestions.test.ts new file mode 100644 index 000000000..60b58caa6 --- /dev/null +++ b/core/indexing/docs/suggestions/suggestions.test.ts @@ -0,0 +1,283 @@ +// Generated by continue + +import { getAllSuggestedDocs } from "./index"; +import { testIde } from "../../../test/fixtures"; +import { + setUpTestDir, + tearDownTestDir, + addToTestDir, +} from "../../../test/testDir"; +import fetch, { RequestInfo } from "node-fetch"; + +jest.mock("node-fetch", undefined, { + virtual: false, +}); + +describe.skip("getAllSuggestedDocs", () => { + beforeEach(() => { + setUpTestDir(); + jest.clearAllMocks(); + }); + + afterEach(() => { + tearDownTestDir(); + jest.restoreAllMocks(); + }); + + it("should return package docs for JavaScript and Python projects", async () => { + // Set up test files + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + express: "^4.17.1", + lodash: "^4.17.21", + }, + devDependencies: { + typescript: "^4.0.0", + }, + }), + ], + ["requirements.txt", "requests==2.25.1\nflask==1.1.2"], + ]); + + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("registry.npmjs.org/express")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + homepage: "https://expressjs.com/", + name: "express", + description: "Fast, unopinionated, minimalist web framework", + license: "MIT", + }), + }) as any; + } else if (url.toString().includes("registry.npmjs.org/lodash")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + homepage: "https://lodash.com/", + name: "lodash", + description: "Lodash modular utilities.", + license: "MIT", + }), + }) as any; + } else if (url.toString().includes("pypi.org/pypi/requests/json")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + info: { + home_page: "https://docs.python-requests.org/", + name: "requests", + summary: "Python HTTP for Humans.", + license: "Apache 2.0", + }, + }), + }) as any; + } else if (url.toString().includes("pypi.org/pypi/flask/json")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + info: { + home_page: "https://palletsprojects.com/p/flask/", + name: "flask", + summary: + "A simple framework for building complex web applications.", + license: "BSD-3-Clause", + }, + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(4); + expect(results).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "express" }), + details: expect.objectContaining({ + docsLink: "https://expressjs.com/", + }), + }), + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "lodash" }), + details: expect.objectContaining({ + docsLink: "https://lodash.com/", + }), + }), + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "requests" }), + details: expect.objectContaining({ + docsLink: "https://docs.python-requests.org/", + }), + }), + expect.objectContaining({ + packageInfo: expect.objectContaining({ name: "flask" }), + details: expect.objectContaining({ + docsLink: "https://palletsprojects.com/p/flask/", + }), + }), + ]), + ); + + // Verify no errors are present + results.forEach((result) => { + expect(result.error).toBeUndefined(); + }); + }); + + it("should handle packages without documentation links", async () => { + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + "no-docs-package": "^1.0.0", + }, + }), + ], + ]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: RequestInfo | URL) => { + if (url.toString().includes("registry.npmjs.org/no-docs-package")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + name: "no-docs-package", + description: "A package without docs", + license: "MIT", + // No homepage provided + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].error).toContain( + "No documentation link found for no-docs-package", + ); + expect(results[0].details).toBeUndefined(); + }); + + it("should handle errors when fetching package details", async () => { + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + "error-package": "^1.0.0", + }, + }), + ], + ]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("registry.npmjs.org/error-package")) { + return Promise.resolve({ + ok: false, + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].error).toContain( + "Error getting package details for error-package", + ); + expect(results[0].details).toBeUndefined(); + }); + + it("should handle workspaces with no package files", async () => { + const results = await getAllSuggestedDocs(testIde); + + expect(results).toEqual([]); + }); + + it("should handle packages with GitHub documentation links", async () => { + addToTestDir([ + [ + "package.json", + JSON.stringify({ + dependencies: { + "github-docs-package": "^1.0.0", + }, + }), + ], + ]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("registry.npmjs.org/github-docs-package")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + homepage: "https://github.com/user/repo", + name: "github-docs-package", + description: "A package with GitHub docs", + license: "MIT", + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].details?.docsLink).toBe("https://github.com/user/repo"); + expect(results[0].details?.docsLinkWarning).toBe( + "Github docs not supported, find the docs site", + ); + }); + + it("should handle packages with non-docs links", async () => { + addToTestDir([["requirements.txt", "non-docs-package==1.0.0"]]); + + // Mock fetch + const mockedFetch = fetch as jest.MockedFunction; + mockedFetch.mockImplementation((url: URL | RequestInfo) => { + if (url.toString().includes("pypi.org/pypi/non-docs-package/json")) { + return Promise.resolve({ + ok: true, + json: jest.fn().mockResolvedValue({ + info: { + home_page: "https://somewebsite.com", + name: "non-docs-package", + summary: "A package with non-docs homepage", + license: "MIT", + }, + }), + }) as any; + } else { + return Promise.reject(new Error(`Unhandled URL: ${url}`)); + } + }); + + const results = await getAllSuggestedDocs(testIde); + + expect(results).toHaveLength(1); + expect(results[0].details?.docsLink).toBe("https://somewebsite.com"); + expect(results[0].details?.docsLinkWarning).toBe( + "May not be a docs site, check the URL", + ); + }); +}); diff --git a/core/jest.config.js b/core/jest.config.js index 71eaeab54..285fb2838 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -23,7 +23,8 @@ export default { collectCoverageFrom: [ "**/*.{js,ts}", // Adjust this pattern to match files you want coverage for "!**/node_modules/**", // Exclude node_modules - "!**/vendor/**", // Exclude any vendor directories if necessary + "!**/vendor/**", + // "!**/autocomplete/context/root-path-context/test/files/**", ], globalSetup: "/test/jest.global-setup.ts", setupFilesAfterEnv: ["/test/jest.setup-after-env.ts"], diff --git a/core/llm/countTokens.test.ts b/core/llm/countTokens.test.ts new file mode 100644 index 000000000..9df79cf6e --- /dev/null +++ b/core/llm/countTokens.test.ts @@ -0,0 +1,109 @@ +// Generated by continue +import { ChatMessage, MessagePart } from "../index.js"; +import { + compileChatMessages, + countTokens, + countTokensAsync, + pruneLinesFromBottom, + pruneLinesFromTop, + pruneRawPromptFromTop, + pruneStringFromBottom, + pruneStringFromTop, +} from "./countTokens.js"; + +describe.skip("countTokens", () => { + it("should count tokens for a simple string", () => { + const content = "Hello world!"; + const tokenCount = countTokens(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); + + it("should count tokens for an array of MessagePart", () => { + const content: MessagePart[] = [{ type: "text", text: "Hello world!" }]; + const tokenCount = countTokens(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); +}); + +describe("countTokensAsync", () => { + it("should count tokens asynchronously for a simple string", async () => { + const content = "Hello world!"; + const tokenCount = await countTokensAsync(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); + + it("should count tokens asynchronously for an array of MessagePart", async () => { + const content: MessagePart[] = [{ type: "text", text: "Hello world!" }]; + const tokenCount = await countTokensAsync(content, "gpt-4"); + expect(tokenCount).toBeGreaterThan(0); + }); +}); + +describe("pruneLinesFromTop", () => { + it("should prune lines from the top to fit within max tokens", () => { + const prompt = "Line 1\nLine 2\nLine 3\nLine 4"; + const pruned = pruneLinesFromTop(prompt, 5, "gpt-4"); + expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length); + }); +}); + +describe("pruneLinesFromBottom", () => { + it("should prune lines from the bottom to fit within max tokens", () => { + const prompt = "Line 1\nLine 2\nLine 3\nLine 4"; + const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4"); + expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length); + }); +}); + +describe("pruneRawPromptFromTop", () => { + it("should prune string from the top based on maxTokens", () => { + const result = pruneRawPromptFromTop("gpt-4", 5, "Hello world!", 2); + expect(result.length).toBeLessThan("Hello world!".length); + }); +}); + +describe("pruneStringFromTop", () => { + it("should prune string from the top based on maxTokens", () => { + const result = pruneStringFromTop("gpt-4", 5, "Hello world!"); + expect(result.length).toBeLessThan("Hello world!".length); + }); +}); + +describe("pruneStringFromBottom", () => { + it("should prune string from the bottom based on maxTokens", () => { + const result = pruneStringFromBottom("gpt-4", 5, "Hello world!"); + expect(result.length).toBeLessThan("Hello world!".length); + }); +}); + +describe("compileChatMessages", () => { + it("should compile and handle an empty or undefined message list", () => { + const compiled = compileChatMessages("gpt-4", undefined, 100, 50, false); + expect(compiled.length).toBe(0); + }); + + it("should compile chat messages without truncating if within context length", () => { + const msgs: ChatMessage[] = [ + { role: "user", content: "Hello world!" }, + { role: "assistant", content: "Hi there!" }, + ]; + const compiled = compileChatMessages("gpt-4", msgs, 100, 10, false); + expect(compiled.length).toBe(2); + }); + + it("should throw an error if maxTokens is close to or exceeds contextLength", () => { + expect(() => { + compileChatMessages("gpt-4", [], 100, 90, false); + }).toThrow(); + }); + + it("should filter out any empty or system messages", () => { + const msgs: ChatMessage[] = [ + { role: "system", content: "" }, + { role: "user", content: "" }, + { role: "assistant", content: "Hi there!" }, + ]; + const compiled = compileChatMessages("gpt-4", msgs, 100, 10, false); + expect(compiled.length).toBe(1); + }); +}); diff --git a/core/util/extractMinimalStackTraceInfo.test.ts b/core/util/extractMinimalStackTraceInfo.test.ts new file mode 100644 index 000000000..f8c3a682a --- /dev/null +++ b/core/util/extractMinimalStackTraceInfo.test.ts @@ -0,0 +1,83 @@ +// Generated by continue + +import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo"; + +describe("extractMinimalStackTraceInfo", () => { + it("should return an empty string when stack is not a string or an empty string", () => { + expect(extractMinimalStackTraceInfo(undefined)).toBe(""); + expect(extractMinimalStackTraceInfo(null)).toBe(""); + expect(extractMinimalStackTraceInfo(1234)).toBe(""); + expect(extractMinimalStackTraceInfo({})).toBe(""); + expect(extractMinimalStackTraceInfo([])).toBe(""); + expect(extractMinimalStackTraceInfo(true)).toBe(""); + expect(extractMinimalStackTraceInfo("")).toBe(""); + }); + + it("should extract minimal stack trace info from a valid stack trace", () => { + const stack = `Error: Something went wrong + at FunctionOne (/Users/user/project/file1.ts:10:15) + at FunctionTwo (/Users/user/project/file2.ts:20:25) + at FunctionThree (/Users/user/project/file3.ts:30:35) + at node_modules/some_module/index.js:40:45 + at FunctionFour (/Users/user/project/file4.ts:50:55) + at processTicksAndRejections (node:internal/process/task_queues:96:5) + `; + const expected = "FunctionOne, FunctionTwo, FunctionThree, FunctionFour"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); + + it("should return an empty string if no matching lines are found", () => { + const stack = `Error: Something went wrong + at node_modules/some_module/index.js:40:45 + at processTicksAndRejections (node:internal/process/task_queues:96:5) + `; + expect(extractMinimalStackTraceInfo(stack)).toBe(""); + }); + + it("should handle stack traces without 'at ' at the beginning of lines", () => { + const stack = `Error: Something went wrong + in FunctionOne (/Users/user/project/file1.ts:10:15) + in FunctionTwo (/Users/user/project/file2.ts:20:25) + `; + expect(extractMinimalStackTraceInfo(stack)).toBe(""); + }); + + it("should handle stack traces with varying whitespace", () => { + const stack = `Error: Something went wrong +at FunctionOne (/Users/user/project/file1.ts:10:15) + at FunctionTwo(/Users/user/project/file2.ts:20:25) + at FunctionThree (/Users/user/project/file3.ts:30:35) + `; + const expected = "FunctionOne, FunctionTwo(), FunctionThree"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); + + it("should correctly handle function names with spaces and special characters", () => { + const stack = `Error: Something went wrong + at Object.Function One (/Users/user/project/file1.ts:10:15) + at Module. (/Users/user/project/file2.ts:20:25) + at Function_Two (/Users/user/project/file3.ts:30:35) + `; + const expected = "Object.Function One, Module., Function_Two"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); + + it("should handle stack traces with anonymous functions", () => { + const stack = `Error: Something went wrong + at /Users/user/project/file1.ts:10:15 + at /Users/user/project/file2.ts:20:25 + at node_modules/some_module/index.js:40:45 + `; + expect(extractMinimalStackTraceInfo(stack)).toBe(""); + }); + + it("should handle lines without parentheses", () => { + const stack = `Error: Something went wrong + at FunctionOne + at FunctionTwo + at FunctionThree (/Users/user/project/file3.ts:30:35) + `; + const expected = "FunctionOne, FunctionTwo, FunctionThree"; + expect(extractMinimalStackTraceInfo(stack)).toBe(expected); + }); +}); diff --git a/core/util/extractMinimalStackTraceInfo.ts b/core/util/extractMinimalStackTraceInfo.ts index 51fcde91a..026c79aa2 100644 --- a/core/util/extractMinimalStackTraceInfo.ts +++ b/core/util/extractMinimalStackTraceInfo.ts @@ -5,12 +5,29 @@ * @returns A string containing the minimal stack trace information. */ export function extractMinimalStackTraceInfo(stack: unknown): string { - if (typeof stack !== "string") {return "";} - const lines = stack.split("\n"); + if (typeof stack !== "string") { + return ""; + } + const lines = stack + .trim() + .split("\n") + .map((line) => line.trim()); const minimalLines = lines.filter((line) => { - return line.trimStart().startsWith("at ") && !line.includes("node_modules"); + return ( + line.startsWith("at ") && + !line.includes("node_modules") && + !line.includes("node:internal") + ); }); return minimalLines - .map((line) => line.trimStart().replace("at ", "").split(" (").slice(0, 1)) + .map((line) => line.replace("at ", "").split(" (").slice(0, 1)) + .flatMap((parts) => + parts.map( + // to be safe, remove any lingering paths - anonymous function case + (part) => + part.replace(/(?:[A-Za-z]:[\\/]|[\\/])[^\n]*?:\d+:\d+/g, "").trim(), + ), + ) + .filter((part) => !!part) // remove empty string parts (anonymous functions case) .join(", "); } diff --git a/core/util/fetchFavicon.test.ts b/core/util/fetchFavicon.test.ts new file mode 100644 index 000000000..9f93dc2e2 --- /dev/null +++ b/core/util/fetchFavicon.test.ts @@ -0,0 +1,274 @@ +// Generated by continue + +import { + findFaviconPath, + getFaviconBase64, + fetchFavicon, +} from "./fetchFavicon"; + +describe("findFaviconPath", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return the favicon URL when a favicon link is present", async () => { + const mockHtml = ` + + + + + + + `; + const mockResponse = { + ok: true, + text: jest.fn().mockResolvedValue(mockHtml), + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBe("https://example.com/favicon.ico"); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should return undefined when no favicon link is present", async () => { + const mockHtml = ` + + + + + `; + const mockResponse = { + ok: true, + text: jest.fn().mockResolvedValue(mockHtml), + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should handle fetch errors gracefully and return undefined", async () => { + global.fetch = jest.fn().mockRejectedValue(new Error("Network error")); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should handle non-OK responses and return undefined", async () => { + const mockResponse = { + ok: false, + status: 404, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); + + it("should handle relative favicon URLs", async () => { + const mockHtml = ` + + + + + + + `; + const mockResponse = { + ok: true, + text: jest.fn().mockResolvedValue(mockHtml), + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const url = new URL("https://example.com"); + const faviconPath = await findFaviconPath(url); + + expect(faviconPath).toBe("https://example.com/favicon.ico"); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); +}); + +describe("getFaviconBase64", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return base64 data URI of the favicon", async () => { + const iconData = "icon data"; + const arrayBuffer = new TextEncoder().encode(iconData).buffer; + const mockResponse = { + ok: true, + arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer), + headers: { + get: jest.fn().mockReturnValue("image/png"), + }, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + global.btoa = jest + .fn() + .mockImplementation((str) => + Buffer.from(str, "binary").toString("base64"), + ); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + const expectedBase64 = Buffer.from(iconData).toString("base64"); + + expect(base64DataUri).toBe(`data:image/png;base64,${expectedBase64}`); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); + + it("should handle fetch errors gracefully and return undefined", async () => { + global.fetch = jest.fn().mockRejectedValue(new Error("Network error")); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + expect(base64DataUri).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); + + it("should handle non-OK responses and return undefined", async () => { + const mockResponse = { + ok: false, + status: 404, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + expect(base64DataUri).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); + + it("should use default mime type if content-type header is missing", async () => { + const iconData = "icon data"; + const arrayBuffer = new TextEncoder().encode(iconData).buffer; + const mockResponse = { + ok: true, + arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer), + headers: { + get: jest.fn().mockReturnValue(null), + }, + }; + + global.fetch = jest.fn().mockResolvedValue(mockResponse); + global.btoa = jest + .fn() + .mockImplementation((str) => + Buffer.from(str, "binary").toString("base64"), + ); + + const faviconUrl = "https://example.com/favicon.ico"; + const base64DataUri = await getFaviconBase64(faviconUrl); + + const expectedBase64 = Buffer.from(iconData).toString("base64"); + + expect(base64DataUri).toBe(`data:image/x-icon;base64,${expectedBase64}`); + expect(global.fetch).toHaveBeenCalledWith(faviconUrl); + }); +}); + +describe("fetchFavicon", () => { + afterEach(() => { + jest.restoreAllMocks(); + }); + + it("should return base64 data URI of the favicon when favicon is found", async () => { + const url = new URL("https://example.com"); + + // Mock fetch for homepage + const homepageHtml = ` + + + + + + + `; + const homepageResponse = { + ok: true, + text: jest.fn().mockResolvedValue(homepageHtml), + }; + + // Mock fetch for favicon + const iconData = "icon data"; + const arrayBuffer = new TextEncoder().encode(iconData).buffer; + const faviconResponse = { + ok: true, + arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer), + headers: { + get: jest.fn().mockReturnValue("image/png"), + }, + }; + + const fetchMock = jest.fn(); + fetchMock.mockResolvedValueOnce(homepageResponse); // First fetch call + fetchMock.mockResolvedValueOnce(faviconResponse); // Second fetch call + + global.fetch = fetchMock; + global.btoa = jest + .fn() + .mockImplementation((str) => + Buffer.from(str, "binary").toString("base64"), + ); + + const result = await fetchFavicon(url); + + const expectedBase64 = Buffer.from(iconData).toString("base64"); + + expect(result).toBe(`data:image/png;base64,${expectedBase64}`); + expect(global.fetch).toHaveBeenCalledTimes(2); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + expect(global.fetch).toHaveBeenCalledWith( + "https://example.com/favicon.ico", + ); + }); + + it("should return undefined when favicon is not found", async () => { + const url = new URL("https://example.com"); + + // Mock fetch for homepage + const homepageHtml = ` + + + + + `; + const homepageResponse = { + ok: true, + text: jest.fn().mockResolvedValue(homepageHtml), + }; + + const fetchMock = jest.fn(); + fetchMock.mockResolvedValueOnce(homepageResponse); // First fetch call + + global.fetch = fetchMock; + + const result = await fetchFavicon(url); + + expect(result).toBeUndefined(); + expect(global.fetch).toHaveBeenCalledTimes(1); + expect(global.fetch).toHaveBeenCalledWith("https://example.com"); + }); +}); diff --git a/core/util/generateRepoMap.test.ts b/core/util/generateRepoMap.test.ts new file mode 100644 index 000000000..d1d130d31 --- /dev/null +++ b/core/util/generateRepoMap.test.ts @@ -0,0 +1,214 @@ +// Generated by continue + +import generateRepoMap from "./generateRepoMap"; +import { testIde, testLLM } from "../test/fixtures"; +import { + setUpTestDir, + tearDownTestDir, + addToTestDir, + TEST_DIR, +} from "../test/testDir"; +import fs from "fs"; +import path from "path"; +import { getRepoMapFilePath } from "./paths"; +import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex"; + +describe.skip("generateRepoMap", () => { + beforeEach(() => { + setUpTestDir(); + }); + + afterEach(() => { + tearDownTestDir(); + jest.restoreAllMocks(); + }); + + it("should generate a repo map with signatures included", async () => { + // Arrange + // Create sample files in the test directory + addToTestDir([ + ["file1.js", "function foo() {}\nfunction bar() {}"], + ["subdir/file2.py", "def foo(): pass\ndef bar(): pass"], + ]); + + // Do not mock testIde.getWorkspaceDirs + + // Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures + jest + .spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures") + .mockImplementation(async (dirs, offset, limit) => { + // Return test data + return { + groupedByPath: { + [path.join(TEST_DIR, "file1.js")]: [ + "function foo() {}", + "function bar() {}", + ], + [path.join(TEST_DIR, "subdir/file2.py")]: [ + "def foo():", + "def bar():", + ], + }, + hasMore: false, + }; + }); + + // Set testLLM properties + testLLM.contextLength = 2048; + testLLM.countTokens = jest.fn().mockReturnValue(10); + + // Act + const repoMapContent = await generateRepoMap(testLLM, testIde, { + includeSignatures: true, + }); + + // Assert + const expectedContent = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n" + + "file1.js:\n" + + "\tfunction foo() {}\n" + + "\t...\n" + + "\tfunction bar() {}\n\n" + + "subdir/file2.py:\n" + + "\tdef foo():\n" + + "\t...\n" + + "\tdef bar():\n\n"; + + expect(repoMapContent).toBe(expectedContent); + + // Also check that the repo map file was created at the correct path + const repoMapPath = getRepoMapFilePath(); + expect(fs.existsSync(repoMapPath)).toBe(true); + + const fileContent = fs.readFileSync(repoMapPath, "utf8"); + expect(fileContent).toBe(expectedContent); + }); + + it("should generate a repo map without signatures when includeSignatures is false", async () => { + // Arrange + // Create sample files in the test directory + addToTestDir([ + ["file1.js", "function foo() {}\nfunction bar() {}"], + ["subdir/file2.py", "def foo(): pass\ndef bar(): pass"], + ]); + + // Do not mock testIde.getWorkspaceDirs + + // Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures + jest + .spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures") + .mockImplementation(async (dirs, offset, limit) => { + // Return test data + return { + groupedByPath: { + [path.join(TEST_DIR, "file1.js")]: [], + [path.join(TEST_DIR, "subdir/file2.py")]: [], + }, + hasMore: false, + }; + }); + + // Set testLLM properties + testLLM.contextLength = 2048; + testLLM.countTokens = jest.fn().mockReturnValue(10); + + // Act + const repoMapContent = await generateRepoMap(testLLM, testIde, { + includeSignatures: false, + }); + + // Assert + const expectedContent = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n" + + "file1.js\n" + + "subdir/file2.py\n"; + + expect(repoMapContent).toBe(expectedContent); + + // Also check that the repo map file was created at the correct path + const repoMapPath = getRepoMapFilePath(); + expect(fs.existsSync(repoMapPath)).toBe(true); + + const fileContent = fs.readFileSync(repoMapPath, "utf8"); + expect(fileContent).toBe(expectedContent); + }); + + it("should handle file read errors gracefully", async () => { + // Arrange + // Create sample files in the test directory + addToTestDir([ + ["file1.js", "function foo() {}\nfunction bar() {}"], + ["subdir/file2.py", "def foo(): pass\ndef bar(): pass"], + ]); + + // Do not mock testIde.getWorkspaceDirs + + // Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures + jest + .spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures") + .mockImplementation(async (dirs, offset, limit) => { + // Return test data + return { + groupedByPath: { + [path.join(TEST_DIR, "file1.js")]: ["function foo() {}"], + [path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"], + }, + hasMore: false, + }; + }); + + // Mock fs.promises.readFile to throw an error when reading file1.js + jest + .spyOn(fs.promises, "readFile") + .mockImplementation((filePath, encoding) => { + if (filePath === path.join(TEST_DIR, "file1.js")) { + return Promise.reject(new Error("File not found")); + } + return fs.promises.readFile(filePath, encoding); + }); + + // Spy on console.error + const consoleErrorSpy = jest + .spyOn(console, "error") + .mockImplementation(() => {}); + + // Set testLLM properties + testLLM.contextLength = 2048; + testLLM.countTokens = jest.fn().mockReturnValue(10); + + // Act + const repoMapContent = await generateRepoMap(testLLM, testIde, { + includeSignatures: true, + }); + + // Assert + const expectedContent = + "Below is a repository map. \n" + + "For each file in the codebase, " + + "this map contains the name of the file, and the signature for any " + + "classes, methods, or functions in the file.\n\n" + + "subdir/file2.py:\n" + + "\tdef foo():\n\n" + + "file1.js\n"; // file1.js is added in writeRemainingPaths + + expect(repoMapContent).toBe(expectedContent); + + // Also check that an error was logged + expect(consoleErrorSpy).toHaveBeenCalledWith( + expect.stringContaining( + "Failed to read file:\n" + + ` Path: ${path.join(TEST_DIR, "file1.js")}\n` + + " Error: File not found", + ), + ); + + // Clean up mock + consoleErrorSpy.mockRestore(); + }); +});