Changesets · Branches · Tags · Compare
| Changeset | bec8bc168493f08d15ddda75984a7b7e65ae499d4b0e7adadc0f176a10c638c9 |
|---|---|
| Author | Tomasz Stefaniak <tomasz.p.stefaniak@gmail.com> · 2025-06-17 10:19 -07:00 |
| Committer | GitHub <noreply@github.com> · 2025-06-17 10:19 -07:00 |
| Parents | ac2607cb1298, 198ebda6cfd2 |
30 files changed
deleted core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +0 −56
| @@ -1,56 +0,0 @@ | ||
| 1 | -import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases"; | |
| 2 | -import { testRootPathContext } from "./testUtils"; | |
| 3 | - | |
| 4 | -const TEST_CASES = [ | |
| 5 | - ...PYTHON_TEST_CASES, | |
| 6 | - ...TYPESCRIPT_TEST_CASES, | |
| 7 | - { | |
| 8 | - nodeType: "function_definition", | |
| 9 | - fileName: "file1.php", | |
| 10 | - language: "PHP", | |
| 11 | - cursorPosition: { line: 12, character: 32 }, | |
| 12 | - definitionPositions: [ | |
| 13 | - { row: 10, column: 26 }, // Person | |
| 14 | - { row: 10, column: 44 }, // Address | |
| 15 | - ], | |
| 16 | - }, | |
| 17 | - { | |
| 18 | - nodeType: "method_declaration", | |
| 19 | - fileName: "file1.php", | |
| 20 | - language: "PHP", | |
| 21 | - cursorPosition: { line: 26, character: 35 }, | |
| 22 | - definitionPositions: [ | |
| 23 | - { row: 15, column: 29 }, // BaseClass | |
| 24 | - { row: 15, column: 55 }, // FirstInterface | |
| 25 | - { row: 15, column: 72 }, // SecondInterface | |
| 26 | - { row: 25, column: 43 }, // Person | |
| 27 | - { row: 25, column: 61 }, // Address | |
| 28 | - ], | |
| 29 | - }, | |
| 30 | - { | |
| 31 | - nodeType: "function_declaration", | |
| 32 | - fileName: "file1.go", | |
| 33 | - language: "Go", | |
| 34 | - cursorPosition: { line: 7, character: 21 }, | |
| 35 | - definitionPositions: [ | |
| 36 | - { row: 6, column: 33 }, // models.User | |
| 37 | - { row: 6, column: 50 }, // models.Address | |
| 38 | - ], | |
| 39 | - }, | |
| 40 | -]; | |
| 41 | - | |
| 42 | -describe("RootPathContextService", () => { | |
| 43 | - describe("should look for correct type definitions", () => { | |
| 44 | - test.each(TEST_CASES)( | |
| 45 | - "$language: $nodeType", | |
| 46 | - async ({ fileName, cursorPosition, definitionPositions }) => { | |
| 47 | - await testRootPathContext( | |
| 48 | - "files", | |
| 49 | - fileName, | |
| 50 | - cursorPosition, | |
| 51 | - definitionPositions, | |
| 52 | - ); | |
| 53 | - }, | |
| 54 | - ); | |
| 55 | - }); | |
| 56 | -}); |
added core/autocomplete/context/root-path-context/test/RootPathContextService.vitest.ts +57 −0
| @@ -0,0 +1,57 @@ | ||
| 1 | +import { describe, test } from "vitest"; | |
| 2 | +import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases"; | |
| 3 | +import { testRootPathContext } from "./testUtils"; | |
| 4 | + | |
| 5 | +const TEST_CASES = [ | |
| 6 | + ...PYTHON_TEST_CASES, | |
| 7 | + ...TYPESCRIPT_TEST_CASES, | |
| 8 | + { | |
| 9 | + nodeType: "function_definition", | |
| 10 | + fileName: "file1.php", | |
| 11 | + language: "PHP", | |
| 12 | + cursorPosition: { line: 12, character: 32 }, | |
| 13 | + definitionPositions: [ | |
| 14 | + { row: 10, column: 26 }, // Person | |
| 15 | + { row: 10, column: 44 }, // Address | |
| 16 | + ], | |
| 17 | + }, | |
| 18 | + { | |
| 19 | + nodeType: "method_declaration", | |
| 20 | + fileName: "file1.php", | |
| 21 | + language: "PHP", | |
| 22 | + cursorPosition: { line: 26, character: 35 }, | |
| 23 | + definitionPositions: [ | |
| 24 | + { row: 15, column: 29 }, // BaseClass | |
| 25 | + { row: 15, column: 55 }, // FirstInterface | |
| 26 | + { row: 15, column: 72 }, // SecondInterface | |
| 27 | + { row: 25, column: 43 }, // Person | |
| 28 | + { row: 25, column: 61 }, // Address | |
| 29 | + ], | |
| 30 | + }, | |
| 31 | + { | |
| 32 | + nodeType: "function_declaration", | |
| 33 | + fileName: "file1.go", | |
| 34 | + language: "Go", | |
| 35 | + cursorPosition: { line: 7, character: 21 }, | |
| 36 | + definitionPositions: [ | |
| 37 | + { row: 6, column: 33 }, // models.User | |
| 38 | + { row: 6, column: 50 }, // models.Address | |
| 39 | + ], | |
| 40 | + }, | |
| 41 | +]; | |
| 42 | + | |
| 43 | +describe("RootPathContextService", () => { | |
| 44 | + describe("should look for correct type definitions", () => { | |
| 45 | + test.each(TEST_CASES)( | |
| 46 | + "$language: $nodeType", | |
| 47 | + async ({ fileName, cursorPosition, definitionPositions }) => { | |
| 48 | + await testRootPathContext( | |
| 49 | + "files", | |
| 50 | + fileName, | |
| 51 | + cursorPosition, | |
| 52 | + definitionPositions, | |
| 53 | + ); | |
| 54 | + }, | |
| 55 | + ); | |
| 56 | + }); | |
| 57 | +}); |
modified core/autocomplete/context/root-path-context/test/testUtils.ts +3 −3
| @@ -1,6 +1,6 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | 1 | import fs from "fs"; |
| 3 | 2 | import path from "path"; |
| 3 | +import { expect, vi } from "vitest"; | |
| 4 | 4 | |
| 5 | 5 | import Parser from "web-tree-sitter"; |
| 6 | 6 | import { Position } from "../../../.."; |
| @@ -36,7 +36,7 @@ | ||
| 36 | 36 | const importDefinitionsService = new ImportDefinitionsService(ide); |
| 37 | 37 | const service = new RootPathContextService(importDefinitionsService, ide); |
| 38 | 38 | |
| 39 | - const getSnippetsMock = jest | |
| 39 | + const getSnippetsMock = vi | |
| 40 | 40 | // @ts-ignore |
| 41 | 41 | .spyOn(service, "getSnippets") |
| 42 | 42 | // @ts-ignore |
| @@ -46,7 +46,7 @@ | ||
| 46 | 46 | |
| 47 | 47 | // Copy the folder to the test directory |
| 48 | 48 | const folderPath = path.join( |
| 49 | - __dirname, | |
| 49 | + process.cwd(), | |
| 50 | 50 | "autocomplete", |
| 51 | 51 | "context", |
| 52 | 52 | "root-path-context", |
deleted core/autocomplete/filtering/streamTransforms/charStream.test.ts +0 −215
| @@ -1,215 +0,0 @@ | ||
| 1 | -import { stopAtStartOf, stopAtStopTokens } from "./charStream"; | |
| 2 | - | |
| 3 | -async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 4 | - for (const chunk of chunks) { | |
| 5 | - yield chunk; | |
| 6 | - } | |
| 7 | -} | |
| 8 | - | |
| 9 | -async function streamToString(stream: AsyncGenerator<string>): Promise<string> { | |
| 10 | - let result = ""; | |
| 11 | - for await (const chunk of stream) { | |
| 12 | - result += chunk; | |
| 13 | - } | |
| 14 | - return result; | |
| 15 | -} | |
| 16 | - | |
| 17 | -describe("stopAtStopTokens", () => { | |
| 18 | - it("should yield characters until a stop token is encountered", async () => { | |
| 19 | - const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]); | |
| 20 | - const stopTokens = ["Stop"]; | |
| 21 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 22 | - | |
| 23 | - const output = []; | |
| 24 | - for await (const char of result) { | |
| 25 | - output.push(char); | |
| 26 | - } | |
| 27 | - | |
| 28 | - expect(output.join("")).toBe("Hello world! "); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - it("should handle multiple stop tokens", async () => { | |
| 32 | - const mockStream = createMockStream([ | |
| 33 | - "This", | |
| 34 | - " is a ", | |
| 35 | - "test. END", | |
| 36 | - " of stream", | |
| 37 | - ]); | |
| 38 | - const stopTokens = ["END", "STOP", "HALT"]; | |
| 39 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 40 | - | |
| 41 | - expect(await streamToString(result)).toBe("This is a test. "); | |
| 42 | - }); | |
| 43 | - | |
| 44 | - it("should handle stop tokens split across chunks", async () => { | |
| 45 | - const mockStream = createMockStream([ | |
| 46 | - "Hello", | |
| 47 | - " wo", | |
| 48 | - "r", | |
| 49 | - "ld! ST", | |
| 50 | - "OP now", | |
| 51 | - ]); | |
| 52 | - const stopTokens = ["STOP"]; | |
| 53 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 54 | - | |
| 55 | - const output = []; | |
| 56 | - for await (const char of result) { | |
| 57 | - output.push(char); | |
| 58 | - } | |
| 59 | - | |
| 60 | - expect(output.join("")).toBe("Hello world! "); | |
| 61 | - }); | |
| 62 | - | |
| 63 | - it("should yield all characters if no stop token is encountered", async () => { | |
| 64 | - const mockStream = createMockStream([ | |
| 65 | - "This", | |
| 66 | - " is ", | |
| 67 | - "a complete", | |
| 68 | - " stream", | |
| 69 | - ]); | |
| 70 | - const stopTokens = ["END"]; | |
| 71 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 72 | - | |
| 73 | - expect(await streamToString(result)).toBe("This is a complete stream"); | |
| 74 | - }); | |
| 75 | - | |
| 76 | - it("should handle empty chunks", async () => { | |
| 77 | - const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]); | |
| 78 | - const stopTokens = ["STOP"]; | |
| 79 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 80 | - | |
| 81 | - expect(await streamToString(result)).toBe("Hello world! "); | |
| 82 | - }); | |
| 83 | - | |
| 84 | - it("should handle stop token at the beginning of the stream", async () => { | |
| 85 | - const mockStream = createMockStream(["STOP", "Hello world"]); | |
| 86 | - const stopTokens = ["STOP"]; | |
| 87 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 88 | - | |
| 89 | - const output = []; | |
| 90 | - for await (const char of result) { | |
| 91 | - output.push(char); | |
| 92 | - } | |
| 93 | - | |
| 94 | - expect(output.join("")).toBe(""); | |
| 95 | - }); | |
| 96 | - | |
| 97 | - it("should handle stop token at the end of the stream", async () => { | |
| 98 | - const mockStream = createMockStream(["Hello world", "STOP"]); | |
| 99 | - const stopTokens = ["STOP"]; | |
| 100 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 101 | - | |
| 102 | - expect(await streamToString(result)).toBe("Hello world"); | |
| 103 | - }); | |
| 104 | - | |
| 105 | - it("should handle multiple stop tokens of different lengths", async () => { | |
| 106 | - const mockStream = createMockStream([ | |
| 107 | - "This is a ", | |
| 108 | - "test with ", | |
| 109 | - "multiple STOP", | |
| 110 | - " tokens END", | |
| 111 | - ]); | |
| 112 | - const stopTokens = ["STOP", "END", "HALT"]; | |
| 113 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 114 | - | |
| 115 | - expect(await streamToString(result)).toBe("This is a test with multiple "); | |
| 116 | - }); | |
| 117 | - | |
| 118 | - it("should handle an empty stream", async () => { | |
| 119 | - const mockStream = createMockStream([]); | |
| 120 | - const stopTokens = ["STOP"]; | |
| 121 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 122 | - | |
| 123 | - expect(await streamToString(result)).toBe(""); | |
| 124 | - }); | |
| 125 | - | |
| 126 | - it("should handle an empty stop tokens array", async () => { | |
| 127 | - const mockStream = createMockStream(["Hello", " world!"]); | |
| 128 | - const stopTokens: string[] = []; | |
| 129 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 130 | - | |
| 131 | - const output = []; | |
| 132 | - for await (const char of result) { | |
| 133 | - output.push(char); | |
| 134 | - } | |
| 135 | - | |
| 136 | - expect(output.join("")).toBe("Hello world!"); | |
| 137 | - }); | |
| 138 | - | |
| 139 | - it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => { | |
| 140 | - const mockStream = createMockStream(["Hello world!STOP"]); | |
| 141 | - const stopTokens: string[] = [ | |
| 142 | - "STOP", | |
| 143 | - "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER", | |
| 144 | - ]; | |
| 145 | - const result = stopAtStopTokens(mockStream, stopTokens); | |
| 146 | - | |
| 147 | - expect(await streamToString(result)).toBe("Hello world!"); | |
| 148 | - }); | |
| 149 | -}); | |
| 150 | - | |
| 151 | -describe("stopAtStartOf", () => { | |
| 152 | - const sampleCode = ` { | |
| 153 | - method: "GET", | |
| 154 | - headers: { | |
| 155 | - "Content-Type": "application/json", | |
| 156 | - Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 157 | - }, | |
| 158 | - }, | |
| 159 | - ); | |
| 160 | - const data = await response.json(); | |
| 161 | - return data.items; | |
| 162 | - } | |
| 163 | - | |
| 164 | - async getContextItems( | |
| 165 | - query: string, | |
| 166 | - extras: ContextProviderExtras, | |
| 167 | - ): Promise<ContextItem[]> { | |
| 168 | - const response = await extras.fetch( | |
| 169 | - new URL( | |
| 170 | - \`/proxy/context/\${this.options.id}/retrieve\`, | |
| 171 | - controlPlaneEnv.CONTROL_PLANE_URL, | |
| 172 | - ), | |
| 173 | -`; | |
| 174 | - | |
| 175 | - /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input | |
| 176 | -and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */ | |
| 177 | - it("should stop if the start of the suffix is reached", async () => { | |
| 178 | - const suffix = ` | |
| 179 | - const data = await response.json(); | |
| 180 | - return data.items; | |
| 181 | -}`; | |
| 182 | - const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 183 | - const result = stopAtStartOf(mockStream, suffix); | |
| 184 | - | |
| 185 | - const resultStr = await streamToString(result); | |
| 186 | - expect(resultStr).toBe(` { | |
| 187 | - method: "GET", | |
| 188 | - headers: { | |
| 189 | - "Content-Type": "application/json", | |
| 190 | - Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 191 | - }, | |
| 192 | - }, | |
| 193 | - ); | |
| 194 | - `); | |
| 195 | - }); | |
| 196 | - it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => { | |
| 197 | - const suffix = ` | |
| 198 | - xxxconst data = await response.json(); | |
| 199 | - return data.items; | |
| 200 | -}`; | |
| 201 | - const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 202 | - const result = stopAtStartOf(mockStream, suffix); | |
| 203 | - | |
| 204 | - const resultStr = await streamToString(result); | |
| 205 | - expect(resultStr).toBe(` { | |
| 206 | - method: "GET", | |
| 207 | - headers: { | |
| 208 | - "Content-Type": "application/json", | |
| 209 | - Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 210 | - }, | |
| 211 | - }, | |
| 212 | - ); | |
| 213 | - `); | |
| 214 | - }); | |
| 215 | -}); |
added core/autocomplete/filtering/streamTransforms/charStream.vitest.ts +216 −0
| @@ -0,0 +1,216 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { stopAtStartOf, stopAtStopTokens } from "./charStream"; | |
| 3 | + | |
| 4 | +async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 5 | + for (const chunk of chunks) { | |
| 6 | + yield chunk; | |
| 7 | + } | |
| 8 | +} | |
| 9 | + | |
| 10 | +async function streamToString(stream: AsyncGenerator<string>): Promise<string> { | |
| 11 | + let result = ""; | |
| 12 | + for await (const chunk of stream) { | |
| 13 | + result += chunk; | |
| 14 | + } | |
| 15 | + return result; | |
| 16 | +} | |
| 17 | + | |
| 18 | +describe("stopAtStopTokens", () => { | |
| 19 | + it("should yield characters until a stop token is encountered", async () => { | |
| 20 | + const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]); | |
| 21 | + const stopTokens = ["Stop"]; | |
| 22 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 23 | + | |
| 24 | + const output = []; | |
| 25 | + for await (const char of result) { | |
| 26 | + output.push(char); | |
| 27 | + } | |
| 28 | + | |
| 29 | + expect(output.join("")).toBe("Hello world! "); | |
| 30 | + }); | |
| 31 | + | |
| 32 | + it("should handle multiple stop tokens", async () => { | |
| 33 | + const mockStream = createMockStream([ | |
| 34 | + "This", | |
| 35 | + " is a ", | |
| 36 | + "test. END", | |
| 37 | + " of stream", | |
| 38 | + ]); | |
| 39 | + const stopTokens = ["END", "STOP", "HALT"]; | |
| 40 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 41 | + | |
| 42 | + expect(await streamToString(result)).toBe("This is a test. "); | |
| 43 | + }); | |
| 44 | + | |
| 45 | + it("should handle stop tokens split across chunks", async () => { | |
| 46 | + const mockStream = createMockStream([ | |
| 47 | + "Hello", | |
| 48 | + " wo", | |
| 49 | + "r", | |
| 50 | + "ld! ST", | |
| 51 | + "OP now", | |
| 52 | + ]); | |
| 53 | + const stopTokens = ["STOP"]; | |
| 54 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 55 | + | |
| 56 | + const output = []; | |
| 57 | + for await (const char of result) { | |
| 58 | + output.push(char); | |
| 59 | + } | |
| 60 | + | |
| 61 | + expect(output.join("")).toBe("Hello world! "); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("should yield all characters if no stop token is encountered", async () => { | |
| 65 | + const mockStream = createMockStream([ | |
| 66 | + "This", | |
| 67 | + " is ", | |
| 68 | + "a complete", | |
| 69 | + " stream", | |
| 70 | + ]); | |
| 71 | + const stopTokens = ["END"]; | |
| 72 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 73 | + | |
| 74 | + expect(await streamToString(result)).toBe("This is a complete stream"); | |
| 75 | + }); | |
| 76 | + | |
| 77 | + it("should handle empty chunks", async () => { | |
| 78 | + const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]); | |
| 79 | + const stopTokens = ["STOP"]; | |
| 80 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 81 | + | |
| 82 | + expect(await streamToString(result)).toBe("Hello world! "); | |
| 83 | + }); | |
| 84 | + | |
| 85 | + it("should handle stop token at the beginning of the stream", async () => { | |
| 86 | + const mockStream = createMockStream(["STOP", "Hello world"]); | |
| 87 | + const stopTokens = ["STOP"]; | |
| 88 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 89 | + | |
| 90 | + const output = []; | |
| 91 | + for await (const char of result) { | |
| 92 | + output.push(char); | |
| 93 | + } | |
| 94 | + | |
| 95 | + expect(output.join("")).toBe(""); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("should handle stop token at the end of the stream", async () => { | |
| 99 | + const mockStream = createMockStream(["Hello world", "STOP"]); | |
| 100 | + const stopTokens = ["STOP"]; | |
| 101 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 102 | + | |
| 103 | + expect(await streamToString(result)).toBe("Hello world"); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should handle multiple stop tokens of different lengths", async () => { | |
| 107 | + const mockStream = createMockStream([ | |
| 108 | + "This is a ", | |
| 109 | + "test with ", | |
| 110 | + "multiple STOP", | |
| 111 | + " tokens END", | |
| 112 | + ]); | |
| 113 | + const stopTokens = ["STOP", "END", "HALT"]; | |
| 114 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 115 | + | |
| 116 | + expect(await streamToString(result)).toBe("This is a test with multiple "); | |
| 117 | + }); | |
| 118 | + | |
| 119 | + it("should handle an empty stream", async () => { | |
| 120 | + const mockStream = createMockStream([]); | |
| 121 | + const stopTokens = ["STOP"]; | |
| 122 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 123 | + | |
| 124 | + expect(await streamToString(result)).toBe(""); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should handle an empty stop tokens array", async () => { | |
| 128 | + const mockStream = createMockStream(["Hello", " world!"]); | |
| 129 | + const stopTokens: string[] = []; | |
| 130 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 131 | + | |
| 132 | + const output = []; | |
| 133 | + for await (const char of result) { | |
| 134 | + output.push(char); | |
| 135 | + } | |
| 136 | + | |
| 137 | + expect(output.join("")).toBe("Hello world!"); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => { | |
| 141 | + const mockStream = createMockStream(["Hello world!STOP"]); | |
| 142 | + const stopTokens: string[] = [ | |
| 143 | + "STOP", | |
| 144 | + "STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER", | |
| 145 | + ]; | |
| 146 | + const result = stopAtStopTokens(mockStream, stopTokens); | |
| 147 | + | |
| 148 | + expect(await streamToString(result)).toBe("Hello world!"); | |
| 149 | + }); | |
| 150 | +}); | |
| 151 | + | |
| 152 | +describe("stopAtStartOf", () => { | |
| 153 | + const sampleCode = ` { | |
| 154 | + method: "GET", | |
| 155 | + headers: { | |
| 156 | + "Content-Type": "application/json", | |
| 157 | + Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 158 | + }, | |
| 159 | + }, | |
| 160 | + ); | |
| 161 | + const data = await response.json(); | |
| 162 | + return data.items; | |
| 163 | + } | |
| 164 | + | |
| 165 | + async getContextItems( | |
| 166 | + query: string, | |
| 167 | + extras: ContextProviderExtras, | |
| 168 | + ): Promise<ContextItem[]> { | |
| 169 | + const response = await extras.fetch( | |
| 170 | + new URL( | |
| 171 | + \`/proxy/context/\${this.options.id}/retrieve\`, | |
| 172 | + controlPlaneEnv.CONTROL_PLANE_URL, | |
| 173 | + ), | |
| 174 | +`; | |
| 175 | + | |
| 176 | + /* Some LLMs, such as Codestral, repeat the suffix of the query. To test our filtering, we cut the sample code at random positions, remove a part of the input | |
| 177 | +and construct a response, containing the removed part and the suffix. The goal of the stopAtStartOf() method is to detect the start of the suffix in the response */ | |
| 178 | + it("should stop if the start of the suffix is reached", async () => { | |
| 179 | + const suffix = ` | |
| 180 | + const data = await response.json(); | |
| 181 | + return data.items; | |
| 182 | +}`; | |
| 183 | + const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 184 | + const result = stopAtStartOf(mockStream, suffix); | |
| 185 | + | |
| 186 | + const resultStr = await streamToString(result); | |
| 187 | + expect(resultStr).toBe(` { | |
| 188 | + method: "GET", | |
| 189 | + headers: { | |
| 190 | + "Content-Type": "application/json", | |
| 191 | + Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 192 | + }, | |
| 193 | + }, | |
| 194 | + ); | |
| 195 | + `); | |
| 196 | + }); | |
| 197 | + it("should stop if the start of the suffix is reached, even if the suffix has a prefix", async () => { | |
| 198 | + const suffix = ` | |
| 199 | + xxxconst data = await response.json(); | |
| 200 | + return data.items; | |
| 201 | +}`; | |
| 202 | + const mockStream = createMockStream(sampleCode.split(/(?! )/g)); | |
| 203 | + const result = stopAtStartOf(mockStream, suffix); | |
| 204 | + | |
| 205 | + const resultStr = await streamToString(result); | |
| 206 | + expect(resultStr).toBe(` { | |
| 207 | + method: "GET", | |
| 208 | + headers: { | |
| 209 | + "Content-Type": "application/json", | |
| 210 | + Authorization: \`Bearer \${this.workOsAccessToken}\`, | |
| 211 | + }, | |
| 212 | + }, | |
| 213 | + ); | |
| 214 | + `); | |
| 215 | + }); | |
| 216 | +}); |
deleted core/autocomplete/filtering/streamTransforms/lineStream.test.ts +0 −616
| @@ -1,616 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | - | |
| 3 | -import * as lineStream from "./lineStream"; | |
| 4 | - | |
| 5 | -// eslint-disable-next-line max-lines-per-function | |
| 6 | -describe("lineStream", () => { | |
| 7 | - let mockFullStop: jest.Mock; | |
| 8 | - | |
| 9 | - async function getLineGenerator(lines: any) { | |
| 10 | - return (async function* () { | |
| 11 | - for (const line of lines) { | |
| 12 | - yield line; | |
| 13 | - } | |
| 14 | - })(); | |
| 15 | - } | |
| 16 | - | |
| 17 | - async function getFilteredLines(results: any) { | |
| 18 | - const output = []; | |
| 19 | - | |
| 20 | - for await (const line of results) { | |
| 21 | - output.push(line); | |
| 22 | - } | |
| 23 | - | |
| 24 | - return output; | |
| 25 | - } | |
| 26 | - | |
| 27 | - beforeEach(() => { | |
| 28 | - mockFullStop = jest.fn(); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - describe("noTopLevelKeywordsMidline", () => { | |
| 32 | - it.todo("Need some sample inputs to properly test this"); | |
| 33 | - }); | |
| 34 | - | |
| 35 | - describe("avoidPathLine", () => { | |
| 36 | - it("should filter out path lines", async () => { | |
| 37 | - const linesGenerator = await getLineGenerator([ | |
| 38 | - "// Path: src/index.ts", | |
| 39 | - "const x = 5;", | |
| 40 | - "//", | |
| 41 | - "console.log(x);", | |
| 42 | - ]); | |
| 43 | - const result = lineStream.avoidPathLine(linesGenerator, "//"); | |
| 44 | - const filteredLines = await getFilteredLines(result); | |
| 45 | - expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); | |
| 46 | - }); | |
| 47 | - }); | |
| 48 | - | |
| 49 | - describe("avoidEmptyComments", () => { | |
| 50 | - it("should filter out empty comments", async () => { | |
| 51 | - const linesGenerator = await getLineGenerator([ | |
| 52 | - "// Path: src/index.ts", | |
| 53 | - "const x = 5;", | |
| 54 | - "//", | |
| 55 | - "console.log(x);", | |
| 56 | - ]); | |
| 57 | - const result = lineStream.avoidEmptyComments(linesGenerator, "//"); | |
| 58 | - const filteredLines = await getFilteredLines(result); | |
| 59 | - expect(filteredLines).toEqual([ | |
| 60 | - "// Path: src/index.ts", | |
| 61 | - "const x = 5;", | |
| 62 | - "console.log(x);", | |
| 63 | - ]); | |
| 64 | - }); | |
| 65 | - }); | |
| 66 | - | |
| 67 | - describe("streamWithNewLines", () => { | |
| 68 | - it("should add newlines between lines", async () => { | |
| 69 | - const linesGenerator = await getLineGenerator([ | |
| 70 | - "line1", | |
| 71 | - "line2", | |
| 72 | - "line3", | |
| 73 | - ]); | |
| 74 | - | |
| 75 | - const result = lineStream.streamWithNewLines(linesGenerator); | |
| 76 | - const filteredLines = await getFilteredLines(result); | |
| 77 | - | |
| 78 | - expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]); | |
| 79 | - }); | |
| 80 | - }); | |
| 81 | - | |
| 82 | - describe("lineIsRepeated", () => { | |
| 83 | - it("should return true for similar lines", () => { | |
| 84 | - expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe( | |
| 85 | - true, | |
| 86 | - ); | |
| 87 | - }); | |
| 88 | - | |
| 89 | - it("should return false for different lines", () => { | |
| 90 | - expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe( | |
| 91 | - false, | |
| 92 | - ); | |
| 93 | - }); | |
| 94 | - | |
| 95 | - it("should return false for short lines", () => { | |
| 96 | - expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false); | |
| 97 | - }); | |
| 98 | - }); | |
| 99 | - | |
| 100 | - describe("stopAtSimilarLine", () => { | |
| 101 | - it("should stop at the exact same line", async () => { | |
| 102 | - const lineToTest = "const x = 6"; | |
| 103 | - const linesGenerator = await getLineGenerator([ | |
| 104 | - "console.log();", | |
| 105 | - "const y = () => {};", | |
| 106 | - lineToTest, | |
| 107 | - ]); | |
| 108 | - | |
| 109 | - const result = lineStream.stopAtSimilarLine( | |
| 110 | - linesGenerator, | |
| 111 | - lineToTest, | |
| 112 | - mockFullStop, | |
| 113 | - ); | |
| 114 | - const filteredLines = await getFilteredLines(result); | |
| 115 | - | |
| 116 | - expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 117 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 118 | - }); | |
| 119 | - | |
| 120 | - it("should stop at a similar line", async () => { | |
| 121 | - const lineToTest = "const x = 6;"; | |
| 122 | - const linesGenerator = await getLineGenerator([ | |
| 123 | - "console.log();", | |
| 124 | - "const y = () => {};", | |
| 125 | - lineToTest, | |
| 126 | - ]); | |
| 127 | - | |
| 128 | - const result = lineStream.stopAtSimilarLine( | |
| 129 | - linesGenerator, | |
| 130 | - "a" + lineToTest, | |
| 131 | - mockFullStop, | |
| 132 | - ); | |
| 133 | - const filteredLines = await getFilteredLines(result); | |
| 134 | - | |
| 135 | - expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 136 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 137 | - }); | |
| 138 | - | |
| 139 | - it("should continue on bracket ending lines", async () => { | |
| 140 | - const linesGenerator = await getLineGenerator([ | |
| 141 | - " if (x > 0) {", | |
| 142 | - " console.log(x);", | |
| 143 | - " }", | |
| 144 | - ]); | |
| 145 | - | |
| 146 | - const result = lineStream.stopAtSimilarLine( | |
| 147 | - linesGenerator, | |
| 148 | - "}", | |
| 149 | - mockFullStop, | |
| 150 | - ); | |
| 151 | - const filteredLines = await getFilteredLines(result); | |
| 152 | - | |
| 153 | - expect(filteredLines).toEqual([ | |
| 154 | - " if (x > 0) {", | |
| 155 | - " console.log(x);", | |
| 156 | - " }", | |
| 157 | - ]); | |
| 158 | - expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 159 | - }); | |
| 160 | - }); | |
| 161 | - | |
| 162 | - describe("stopAtLines", () => { | |
| 163 | - it("should stop at specified lines", async () => { | |
| 164 | - const linesGenerator = await getLineGenerator([ | |
| 165 | - "const x = 5;", | |
| 166 | - "let y = 10;", | |
| 167 | - lineStream.LINES_TO_STOP_AT[0], | |
| 168 | - "const z = 15;", | |
| 169 | - ]); | |
| 170 | - | |
| 171 | - const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 172 | - const filteredLines = await getFilteredLines(result); | |
| 173 | - | |
| 174 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 175 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 176 | - }); | |
| 177 | - }); | |
| 178 | - | |
| 179 | - describe("skipPrefixes", () => { | |
| 180 | - it("should skip specified prefixes", async () => { | |
| 181 | - const linesGenerator = await getLineGenerator([ | |
| 182 | - `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`, | |
| 183 | - "let y = 10;", | |
| 184 | - ]); | |
| 185 | - | |
| 186 | - const result = lineStream.skipPrefixes(linesGenerator); | |
| 187 | - const filteredLines = await getFilteredLines(result); | |
| 188 | - | |
| 189 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 190 | - }); | |
| 191 | - }); | |
| 192 | - | |
| 193 | - describe("skipLines", () => { | |
| 194 | - it("should skip specified lines", async () => { | |
| 195 | - const linesGenerator = await getLineGenerator([ | |
| 196 | - `${lineStream.LINES_TO_SKIP[0]}const x = 5;`, | |
| 197 | - "let y = 10;", | |
| 198 | - ]); | |
| 199 | - | |
| 200 | - const result = lineStream.skipLines(linesGenerator); | |
| 201 | - const filteredLines = await getFilteredLines(result); | |
| 202 | - | |
| 203 | - expect(filteredLines).toEqual(["let y = 10;"]); | |
| 204 | - }); | |
| 205 | - }); | |
| 206 | - | |
| 207 | - describe("filterCodeBlockLines", () => { | |
| 208 | - it("should handle unfenced code", async () => { | |
| 209 | - const linesGenerator = await getLineGenerator(["const x = 5;"]); | |
| 210 | - | |
| 211 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 212 | - const filteredLines = await getFilteredLines(result); | |
| 213 | - | |
| 214 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 215 | - }); | |
| 216 | - | |
| 217 | - it("should handle unfenced code with a code block", async () => { | |
| 218 | - const linesGenerator = await getLineGenerator([ | |
| 219 | - "const x = 5;", | |
| 220 | - "```bash", | |
| 221 | - "ls -al", | |
| 222 | - "```", | |
| 223 | - ]); | |
| 224 | - | |
| 225 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 226 | - const filteredLines = await getFilteredLines(result); | |
| 227 | - | |
| 228 | - expect(filteredLines).toEqual([ | |
| 229 | - "const x = 5;", | |
| 230 | - "```bash", | |
| 231 | - "ls -al", | |
| 232 | - "```", | |
| 233 | - ]); | |
| 234 | - }); | |
| 235 | - | |
| 236 | - it("should handle unfenced code with two code blocks", async () => { | |
| 237 | - const linesGenerator = await getLineGenerator([ | |
| 238 | - "const x = 5;", | |
| 239 | - "```bash", | |
| 240 | - "ls -al", | |
| 241 | - "```", | |
| 242 | - "```bash", | |
| 243 | - "ls -al", | |
| 244 | - "```", | |
| 245 | - ]); | |
| 246 | - | |
| 247 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 248 | - const filteredLines = await getFilteredLines(result); | |
| 249 | - | |
| 250 | - expect(filteredLines).toEqual([ | |
| 251 | - "const x = 5;", | |
| 252 | - "```bash", | |
| 253 | - "ls -al", | |
| 254 | - "```", | |
| 255 | - "```bash", | |
| 256 | - "ls -al", | |
| 257 | - "```", | |
| 258 | - ]); | |
| 259 | - }); | |
| 260 | - | |
| 261 | - it("should remove lines before the first valid line", async () => { | |
| 262 | - const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); | |
| 263 | - | |
| 264 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 265 | - const filteredLines = await getFilteredLines(result); | |
| 266 | - | |
| 267 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 268 | - }); | |
| 269 | - | |
| 270 | - it("should remove outer blocks", async () => { | |
| 271 | - const linesGenerator = await getLineGenerator([ | |
| 272 | - "```ts", | |
| 273 | - "const x = 5;", | |
| 274 | - "```", | |
| 275 | - ]); | |
| 276 | - | |
| 277 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 278 | - const filteredLines = await getFilteredLines(result); | |
| 279 | - | |
| 280 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 281 | - }); | |
| 282 | - | |
| 283 | - it("should leave inner blocks intact", async () => { | |
| 284 | - const linesGenerator = await getLineGenerator([ | |
| 285 | - "```md", | |
| 286 | - "const x = 5;", | |
| 287 | - "```bash", | |
| 288 | - "ls -al", | |
| 289 | - "```", | |
| 290 | - "```", | |
| 291 | - ]); | |
| 292 | - | |
| 293 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 294 | - const filteredLines = await getFilteredLines(result); | |
| 295 | - | |
| 296 | - expect(filteredLines).toEqual([ | |
| 297 | - "const x = 5;", | |
| 298 | - "```bash", | |
| 299 | - "ls -al", | |
| 300 | - "```", | |
| 301 | - ]); | |
| 302 | - }); | |
| 303 | - | |
| 304 | - it("should handle included inner ticks", async () => { | |
| 305 | - const linesGenerator = await getLineGenerator([ | |
| 306 | - "```md", | |
| 307 | - "const x = 5;", | |
| 308 | - "```bash", | |
| 309 | - "echo ```test```", | |
| 310 | - "```", | |
| 311 | - "```", | |
| 312 | - ]); | |
| 313 | - | |
| 314 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 315 | - const filteredLines = await getFilteredLines(result); | |
| 316 | - | |
| 317 | - expect(filteredLines).toEqual([ | |
| 318 | - "const x = 5;", | |
| 319 | - "```bash", | |
| 320 | - "echo ```test```", | |
| 321 | - "```", | |
| 322 | - ]); | |
| 323 | - }); | |
| 324 | - | |
| 325 | - it("should leave single inner blocks intact but not return trailing text", async () => { | |
| 326 | - const linesGenerator = await getLineGenerator([ | |
| 327 | - "```md", | |
| 328 | - "const x = 5;", | |
| 329 | - "```bash", | |
| 330 | - "ls -al", | |
| 331 | - "```", | |
| 332 | - "```", | |
| 333 | - "trailing text", | |
| 334 | - ]); | |
| 335 | - | |
| 336 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 337 | - const filteredLines = await getFilteredLines(result); | |
| 338 | - | |
| 339 | - expect(filteredLines).toEqual([ | |
| 340 | - "const x = 5;", | |
| 341 | - "```bash", | |
| 342 | - "ls -al", | |
| 343 | - "```", | |
| 344 | - ]); | |
| 345 | - }); | |
| 346 | - | |
| 347 | - it("should leave double inner blocks intact but not return trailing text", async () => { | |
| 348 | - const linesGenerator = await getLineGenerator([ | |
| 349 | - "```md", | |
| 350 | - "const x = 5;", | |
| 351 | - "```bash", | |
| 352 | - "ls -al", | |
| 353 | - "```", | |
| 354 | - "const y = 10;", | |
| 355 | - "```sh", | |
| 356 | - "echo `hello world`", | |
| 357 | - "```", | |
| 358 | - "```", | |
| 359 | - "trailing text", | |
| 360 | - ]); | |
| 361 | - | |
| 362 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 363 | - const filteredLines = await getFilteredLines(result); | |
| 364 | - | |
| 365 | - expect(filteredLines).toEqual([ | |
| 366 | - "const x = 5;", | |
| 367 | - "```bash", | |
| 368 | - "ls -al", | |
| 369 | - "```", | |
| 370 | - "const y = 10;", | |
| 371 | - "```sh", | |
| 372 | - "echo `hello world`", | |
| 373 | - "```", | |
| 374 | - ]); | |
| 375 | - }); | |
| 376 | - | |
| 377 | - it("should leave inner blocks intact but not return trailing or leading text", async () => { | |
| 378 | - const linesGenerator = await getLineGenerator([ | |
| 379 | - "[CODE]", | |
| 380 | - "const x = 5;", | |
| 381 | - "```bash", | |
| 382 | - "ls -al", | |
| 383 | - "```", | |
| 384 | - "[/CODE]", | |
| 385 | - "trailing text", | |
| 386 | - ]); | |
| 387 | - | |
| 388 | - const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 389 | - const filteredLines = await getFilteredLines(result); | |
| 390 | - | |
| 391 | - expect(filteredLines).toEqual([ | |
| 392 | - "const x = 5;", | |
| 393 | - "```bash", | |
| 394 | - "ls -al", | |
| 395 | - "```", | |
| 396 | - ]); | |
| 397 | - }); | |
| 398 | - }); | |
| 399 | - | |
| 400 | - describe("filterEnglishLinesAtStart", () => { | |
| 401 | - it("should skip initial empty line", async () => { | |
| 402 | - const linesGenerator = await getLineGenerator([ | |
| 403 | - "", | |
| 404 | - "const x = 5;", | |
| 405 | - "let y = 10;", | |
| 406 | - ]); | |
| 407 | - | |
| 408 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 409 | - const filteredLines = await getFilteredLines(result); | |
| 410 | - | |
| 411 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 412 | - }); | |
| 413 | - | |
| 414 | - it("should filter out English first line", async () => { | |
| 415 | - const linesGenerator = await getLineGenerator([ | |
| 416 | - lineStream.ENGLISH_START_PHRASES[0], | |
| 417 | - "let y = 10;", | |
| 418 | - ]); | |
| 419 | - | |
| 420 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 421 | - const filteredLines = await getFilteredLines(result); | |
| 422 | - | |
| 423 | - expect(filteredLines).toEqual(["let y = 10;"]); | |
| 424 | - }); | |
| 425 | - | |
| 426 | - it("should not filter out non-English first line", async () => { | |
| 427 | - const linesGenerator = await getLineGenerator([ | |
| 428 | - "const x = 5;", | |
| 429 | - "let y = 10;", | |
| 430 | - ]); | |
| 431 | - | |
| 432 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 433 | - const filteredLines = await getFilteredLines(result); | |
| 434 | - | |
| 435 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 436 | - }); | |
| 437 | - | |
| 438 | - it("should filter out empty newline after first line english word", async () => { | |
| 439 | - const linesGenerator = await getLineGenerator([ | |
| 440 | - lineStream.ENGLISH_START_PHRASES[0], | |
| 441 | - "", | |
| 442 | - "const x = 5;", | |
| 443 | - ]); | |
| 444 | - | |
| 445 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 446 | - const filteredLines = await getFilteredLines(result); | |
| 447 | - | |
| 448 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 449 | - }); | |
| 450 | - | |
| 451 | - it("should filter out sentences ending in a semi-colon that are not code keywords", async () => { | |
| 452 | - const linesGenerator = await getLineGenerator([ | |
| 453 | - "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":", | |
| 454 | - "const x = 5;", | |
| 455 | - ]); | |
| 456 | - | |
| 457 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 458 | - const filteredLines = await getFilteredLines(result); | |
| 459 | - | |
| 460 | - expect(filteredLines).toEqual(["const x = 5;"]); | |
| 461 | - }); | |
| 462 | - | |
| 463 | - it("should not filter out sentences ending in a semi-colon that are code keywords", async () => { | |
| 464 | - const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":"; | |
| 465 | - | |
| 466 | - const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]); | |
| 467 | - | |
| 468 | - const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 469 | - const filteredLines = await getFilteredLines(result); | |
| 470 | - | |
| 471 | - expect(filteredLines).toEqual([keyword, "const x = 5;"]); | |
| 472 | - }); | |
| 473 | - }); | |
| 474 | - | |
| 475 | - describe("filterEnglishLinesAtEnd", () => { | |
| 476 | - it("should stop at English explanation after code block", async () => { | |
| 477 | - const linesGenerator = await getLineGenerator([ | |
| 478 | - "const x = 5;", | |
| 479 | - "```", | |
| 480 | - lineStream.ENGLISH_POST_PHRASES[0], | |
| 481 | - ]); | |
| 482 | - | |
| 483 | - const result = lineStream.filterEnglishLinesAtEnd(linesGenerator); | |
| 484 | - const filteredLines = await getFilteredLines(result); | |
| 485 | - | |
| 486 | - expect(filteredLines).toEqual(["const x = 5;", "```"]); | |
| 487 | - }); | |
| 488 | - }); | |
| 489 | - | |
| 490 | - describe("fixCodeLlamaFirstLineIndentation", () => { | |
| 491 | - it("should fix indentation of the first line", async () => { | |
| 492 | - const linesGenerator = await getLineGenerator([ | |
| 493 | - " const x = 5;", | |
| 494 | - "let y = 10;", | |
| 495 | - ]); | |
| 496 | - | |
| 497 | - const result = | |
| 498 | - lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator); | |
| 499 | - const filteredLines = await getFilteredLines(result); | |
| 500 | - | |
| 501 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 502 | - }); | |
| 503 | - }); | |
| 504 | - | |
| 505 | - describe("filterLeadingAndTrailingNewLineInsertion", () => { | |
| 506 | - it("should ignore 'useless' new first lines", async () => { | |
| 507 | - const linesGenerator = await getLineGenerator([ | |
| 508 | - { type: "new", line: lineStream.USELESS_LINES[0] }, | |
| 509 | - { type: "new", line: "const x = 5;" }, | |
| 510 | - ]); | |
| 511 | - | |
| 512 | - const result = | |
| 513 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 514 | - const filteredLines = await getFilteredLines(result); | |
| 515 | - | |
| 516 | - expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]); | |
| 517 | - }); | |
| 518 | - | |
| 519 | - it("should handle preserve newlines chars in old lines", async () => { | |
| 520 | - const linesGenerator = await getLineGenerator([ | |
| 521 | - { type: "new", line: "const x = 5;" }, | |
| 522 | - { type: "old", line: "let y = 10;" }, | |
| 523 | - { type: "old", line: "" }, | |
| 524 | - { type: "new", line: "const z = 15;" }, | |
| 525 | - ]); | |
| 526 | - | |
| 527 | - const result = | |
| 528 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 529 | - const filteredLines = await getFilteredLines(result); | |
| 530 | - | |
| 531 | - expect(filteredLines).toEqual([ | |
| 532 | - { type: "new", line: "const x = 5;" }, | |
| 533 | - { type: "old", line: "let y = 10;" }, | |
| 534 | - { type: "old", line: "" }, | |
| 535 | - { type: "new", line: "const z = 15;" }, | |
| 536 | - ]); | |
| 537 | - }); | |
| 538 | - | |
| 539 | - it("should filter leading and trailing new line insertions", async () => { | |
| 540 | - const linesGenerator = await getLineGenerator([ | |
| 541 | - { type: "new", line: "" }, | |
| 542 | - { type: "new", line: "const x = 5;" }, | |
| 543 | - { type: "new", line: "let y = 10;" }, | |
| 544 | - { type: "new", line: "" }, | |
| 545 | - ]); | |
| 546 | - | |
| 547 | - const result = | |
| 548 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 549 | - const filteredLines = await getFilteredLines(result); | |
| 550 | - | |
| 551 | - expect(filteredLines).toEqual([ | |
| 552 | - { type: "new", line: "const x = 5;" }, | |
| 553 | - { type: "new", line: "let y = 10;" }, | |
| 554 | - ]); | |
| 555 | - }); | |
| 556 | - | |
| 557 | - it("should buffer newline chars and then render them if we encounter another non-empty line", async () => { | |
| 558 | - const linesGenerator = await getLineGenerator([ | |
| 559 | - { type: "new", line: "const x = 5;" }, | |
| 560 | - { type: "new", line: "" }, | |
| 561 | - { type: "new", line: "let y = 10;" }, | |
| 562 | - ]); | |
| 563 | - | |
| 564 | - const result = | |
| 565 | - lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 566 | - const filteredLines = await getFilteredLines(result); | |
| 567 | - | |
| 568 | - expect(filteredLines).toEqual([ | |
| 569 | - { type: "new", line: "const x = 5;" }, | |
| 570 | - { type: "new", line: "" }, | |
| 571 | - { type: "new", line: "let y = 10;" }, | |
| 572 | - ]); | |
| 573 | - }); | |
| 574 | - }); | |
| 575 | - | |
| 576 | - describe("stopAtRepeatingLines", () => { | |
| 577 | - it("should handle non-repeating lines correctly", async () => { | |
| 578 | - const linesGenerator = await getLineGenerator([ | |
| 579 | - "const x = 5;", | |
| 580 | - "let y = 10;", | |
| 581 | - "const z = 15;", | |
| 582 | - ]); | |
| 583 | - | |
| 584 | - const result = lineStream.stopAtRepeatingLines( | |
| 585 | - linesGenerator, | |
| 586 | - mockFullStop, | |
| 587 | - ); | |
| 588 | - const filteredLines = await getFilteredLines(result); | |
| 589 | - | |
| 590 | - expect(filteredLines).toEqual([ | |
| 591 | - "const x = 5;", | |
| 592 | - "let y = 10;", | |
| 593 | - "const z = 15;", | |
| 594 | - ]); | |
| 595 | - }); | |
| 596 | - | |
| 597 | - it("should stop at repeating lines", async () => { | |
| 598 | - const linesGenerator = await getLineGenerator([ | |
| 599 | - "const x = 5;", | |
| 600 | - "let y = 10;", | |
| 601 | - "let y = 10;", | |
| 602 | - "let y = 10;", | |
| 603 | - "const z = 15;", | |
| 604 | - ]); | |
| 605 | - | |
| 606 | - const result = lineStream.stopAtRepeatingLines( | |
| 607 | - linesGenerator, | |
| 608 | - mockFullStop, | |
| 609 | - ); | |
| 610 | - const filteredLines = await getFilteredLines(result); | |
| 611 | - | |
| 612 | - expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 613 | - expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 614 | - }); | |
| 615 | - }); | |
| 616 | -}); |
added core/autocomplete/filtering/streamTransforms/lineStream.vitest.ts +616 −0
| @@ -0,0 +1,616 @@ | ||
| 1 | +import { beforeEach, describe, expect, it, Mock, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import * as lineStream from "./lineStream"; | |
| 4 | + | |
| 5 | +// eslint-disable-next-line max-lines-per-function | |
| 6 | +describe("lineStream", () => { | |
| 7 | + let mockFullStop: Mock; | |
| 8 | + | |
| 9 | + async function getLineGenerator(lines: any) { | |
| 10 | + return (async function* () { | |
| 11 | + for (const line of lines) { | |
| 12 | + yield line; | |
| 13 | + } | |
| 14 | + })(); | |
| 15 | + } | |
| 16 | + | |
| 17 | + async function getFilteredLines(results: any) { | |
| 18 | + const output = []; | |
| 19 | + | |
| 20 | + for await (const line of results) { | |
| 21 | + output.push(line); | |
| 22 | + } | |
| 23 | + | |
| 24 | + return output; | |
| 25 | + } | |
| 26 | + | |
| 27 | + beforeEach(() => { | |
| 28 | + mockFullStop = vi.fn(); | |
| 29 | + }); | |
| 30 | + | |
| 31 | + describe("noTopLevelKeywordsMidline", () => { | |
| 32 | + it.todo("Need some sample inputs to properly test this"); | |
| 33 | + }); | |
| 34 | + | |
| 35 | + describe("avoidPathLine", () => { | |
| 36 | + it("should filter out path lines", async () => { | |
| 37 | + const linesGenerator = await getLineGenerator([ | |
| 38 | + "// Path: src/index.ts", | |
| 39 | + "const x = 5;", | |
| 40 | + "//", | |
| 41 | + "console.log(x);", | |
| 42 | + ]); | |
| 43 | + const result = lineStream.avoidPathLine(linesGenerator, "//"); | |
| 44 | + const filteredLines = await getFilteredLines(result); | |
| 45 | + expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); | |
| 46 | + }); | |
| 47 | + }); | |
| 48 | + | |
| 49 | + describe("avoidEmptyComments", () => { | |
| 50 | + it("should filter out empty comments", async () => { | |
| 51 | + const linesGenerator = await getLineGenerator([ | |
| 52 | + "// Path: src/index.ts", | |
| 53 | + "const x = 5;", | |
| 54 | + "//", | |
| 55 | + "console.log(x);", | |
| 56 | + ]); | |
| 57 | + const result = lineStream.avoidEmptyComments(linesGenerator, "//"); | |
| 58 | + const filteredLines = await getFilteredLines(result); | |
| 59 | + expect(filteredLines).toEqual([ | |
| 60 | + "// Path: src/index.ts", | |
| 61 | + "const x = 5;", | |
| 62 | + "console.log(x);", | |
| 63 | + ]); | |
| 64 | + }); | |
| 65 | + }); | |
| 66 | + | |
| 67 | + describe("streamWithNewLines", () => { | |
| 68 | + it("should add newlines between lines", async () => { | |
| 69 | + const linesGenerator = await getLineGenerator([ | |
| 70 | + "line1", | |
| 71 | + "line2", | |
| 72 | + "line3", | |
| 73 | + ]); | |
| 74 | + | |
| 75 | + const result = lineStream.streamWithNewLines(linesGenerator); | |
| 76 | + const filteredLines = await getFilteredLines(result); | |
| 77 | + | |
| 78 | + expect(filteredLines).toEqual(["line1", "\n", "line2", "\n", "line3"]); | |
| 79 | + }); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + describe("lineIsRepeated", () => { | |
| 83 | + it("should return true for similar lines", () => { | |
| 84 | + expect(lineStream.lineIsRepeated("const x = 5;", "const x = 6;")).toBe( | |
| 85 | + true, | |
| 86 | + ); | |
| 87 | + }); | |
| 88 | + | |
| 89 | + it("should return false for different lines", () => { | |
| 90 | + expect(lineStream.lineIsRepeated("const x = 5;", "let y = 10;")).toBe( | |
| 91 | + false, | |
| 92 | + ); | |
| 93 | + }); | |
| 94 | + | |
| 95 | + it("should return false for short lines", () => { | |
| 96 | + expect(lineStream.lineIsRepeated("x=5", "x=6")).toBe(false); | |
| 97 | + }); | |
| 98 | + }); | |
| 99 | + | |
| 100 | + describe("stopAtSimilarLine", () => { | |
| 101 | + it("should stop at the exact same line", async () => { | |
| 102 | + const lineToTest = "const x = 6"; | |
| 103 | + const linesGenerator = await getLineGenerator([ | |
| 104 | + "console.log();", | |
| 105 | + "const y = () => {};", | |
| 106 | + lineToTest, | |
| 107 | + ]); | |
| 108 | + | |
| 109 | + const result = lineStream.stopAtSimilarLine( | |
| 110 | + linesGenerator, | |
| 111 | + lineToTest, | |
| 112 | + mockFullStop, | |
| 113 | + ); | |
| 114 | + const filteredLines = await getFilteredLines(result); | |
| 115 | + | |
| 116 | + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 117 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 118 | + }); | |
| 119 | + | |
| 120 | + it("should stop at a similar line", async () => { | |
| 121 | + const lineToTest = "const x = 6;"; | |
| 122 | + const linesGenerator = await getLineGenerator([ | |
| 123 | + "console.log();", | |
| 124 | + "const y = () => {};", | |
| 125 | + lineToTest, | |
| 126 | + ]); | |
| 127 | + | |
| 128 | + const result = lineStream.stopAtSimilarLine( | |
| 129 | + linesGenerator, | |
| 130 | + "a" + lineToTest, | |
| 131 | + mockFullStop, | |
| 132 | + ); | |
| 133 | + const filteredLines = await getFilteredLines(result); | |
| 134 | + | |
| 135 | + expect(filteredLines).toEqual(["console.log();", "const y = () => {};"]); | |
| 136 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 137 | + }); | |
| 138 | + | |
| 139 | + it("should continue on bracket ending lines", async () => { | |
| 140 | + const linesGenerator = await getLineGenerator([ | |
| 141 | + " if (x > 0) {", | |
| 142 | + " console.log(x);", | |
| 143 | + " }", | |
| 144 | + ]); | |
| 145 | + | |
| 146 | + const result = lineStream.stopAtSimilarLine( | |
| 147 | + linesGenerator, | |
| 148 | + "}", | |
| 149 | + mockFullStop, | |
| 150 | + ); | |
| 151 | + const filteredLines = await getFilteredLines(result); | |
| 152 | + | |
| 153 | + expect(filteredLines).toEqual([ | |
| 154 | + " if (x > 0) {", | |
| 155 | + " console.log(x);", | |
| 156 | + " }", | |
| 157 | + ]); | |
| 158 | + expect(mockFullStop).toHaveBeenCalledTimes(0); | |
| 159 | + }); | |
| 160 | + }); | |
| 161 | + | |
| 162 | + describe("stopAtLines", () => { | |
| 163 | + it("should stop at specified lines", async () => { | |
| 164 | + const linesGenerator = await getLineGenerator([ | |
| 165 | + "const x = 5;", | |
| 166 | + "let y = 10;", | |
| 167 | + lineStream.LINES_TO_STOP_AT[0], | |
| 168 | + "const z = 15;", | |
| 169 | + ]); | |
| 170 | + | |
| 171 | + const result = lineStream.stopAtLines(linesGenerator, mockFullStop); | |
| 172 | + const filteredLines = await getFilteredLines(result); | |
| 173 | + | |
| 174 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 175 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 176 | + }); | |
| 177 | + }); | |
| 178 | + | |
| 179 | + describe("skipPrefixes", () => { | |
| 180 | + it("should skip specified prefixes", async () => { | |
| 181 | + const linesGenerator = await getLineGenerator([ | |
| 182 | + `${lineStream.PREFIXES_TO_SKIP[0]}const x = 5;`, | |
| 183 | + "let y = 10;", | |
| 184 | + ]); | |
| 185 | + | |
| 186 | + const result = lineStream.skipPrefixes(linesGenerator); | |
| 187 | + const filteredLines = await getFilteredLines(result); | |
| 188 | + | |
| 189 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 190 | + }); | |
| 191 | + }); | |
| 192 | + | |
| 193 | + describe("skipLines", () => { | |
| 194 | + it("should skip specified lines", async () => { | |
| 195 | + const linesGenerator = await getLineGenerator([ | |
| 196 | + `${lineStream.LINES_TO_SKIP[0]}const x = 5;`, | |
| 197 | + "let y = 10;", | |
| 198 | + ]); | |
| 199 | + | |
| 200 | + const result = lineStream.skipLines(linesGenerator); | |
| 201 | + const filteredLines = await getFilteredLines(result); | |
| 202 | + | |
| 203 | + expect(filteredLines).toEqual(["let y = 10;"]); | |
| 204 | + }); | |
| 205 | + }); | |
| 206 | + | |
| 207 | + describe("filterCodeBlockLines", () => { | |
| 208 | + it("should handle unfenced code", async () => { | |
| 209 | + const linesGenerator = await getLineGenerator(["const x = 5;"]); | |
| 210 | + | |
| 211 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 212 | + const filteredLines = await getFilteredLines(result); | |
| 213 | + | |
| 214 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 215 | + }); | |
| 216 | + | |
| 217 | + it("should handle unfenced code with a code block", async () => { | |
| 218 | + const linesGenerator = await getLineGenerator([ | |
| 219 | + "const x = 5;", | |
| 220 | + "```bash", | |
| 221 | + "ls -al", | |
| 222 | + "```", | |
| 223 | + ]); | |
| 224 | + | |
| 225 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 226 | + const filteredLines = await getFilteredLines(result); | |
| 227 | + | |
| 228 | + expect(filteredLines).toEqual([ | |
| 229 | + "const x = 5;", | |
| 230 | + "```bash", | |
| 231 | + "ls -al", | |
| 232 | + "```", | |
| 233 | + ]); | |
| 234 | + }); | |
| 235 | + | |
| 236 | + it("should handle unfenced code with two code blocks", async () => { | |
| 237 | + const linesGenerator = await getLineGenerator([ | |
| 238 | + "const x = 5;", | |
| 239 | + "```bash", | |
| 240 | + "ls -al", | |
| 241 | + "```", | |
| 242 | + "```bash", | |
| 243 | + "ls -al", | |
| 244 | + "```", | |
| 245 | + ]); | |
| 246 | + | |
| 247 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 248 | + const filteredLines = await getFilteredLines(result); | |
| 249 | + | |
| 250 | + expect(filteredLines).toEqual([ | |
| 251 | + "const x = 5;", | |
| 252 | + "```bash", | |
| 253 | + "ls -al", | |
| 254 | + "```", | |
| 255 | + "```bash", | |
| 256 | + "ls -al", | |
| 257 | + "```", | |
| 258 | + ]); | |
| 259 | + }); | |
| 260 | + | |
| 261 | + it("should remove lines before the first valid line", async () => { | |
| 262 | + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); | |
| 263 | + | |
| 264 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 265 | + const filteredLines = await getFilteredLines(result); | |
| 266 | + | |
| 267 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 268 | + }); | |
| 269 | + | |
| 270 | + it("should remove outer blocks", async () => { | |
| 271 | + const linesGenerator = await getLineGenerator([ | |
| 272 | + "```ts", | |
| 273 | + "const x = 5;", | |
| 274 | + "```", | |
| 275 | + ]); | |
| 276 | + | |
| 277 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 278 | + const filteredLines = await getFilteredLines(result); | |
| 279 | + | |
| 280 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 281 | + }); | |
| 282 | + | |
| 283 | + it("should leave inner blocks intact", async () => { | |
| 284 | + const linesGenerator = await getLineGenerator([ | |
| 285 | + "```md", | |
| 286 | + "const x = 5;", | |
| 287 | + "```bash", | |
| 288 | + "ls -al", | |
| 289 | + "```", | |
| 290 | + "```", | |
| 291 | + ]); | |
| 292 | + | |
| 293 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 294 | + const filteredLines = await getFilteredLines(result); | |
| 295 | + | |
| 296 | + expect(filteredLines).toEqual([ | |
| 297 | + "const x = 5;", | |
| 298 | + "```bash", | |
| 299 | + "ls -al", | |
| 300 | + "```", | |
| 301 | + ]); | |
| 302 | + }); | |
| 303 | + | |
| 304 | + it("should handle included inner ticks", async () => { | |
| 305 | + const linesGenerator = await getLineGenerator([ | |
| 306 | + "```md", | |
| 307 | + "const x = 5;", | |
| 308 | + "```bash", | |
| 309 | + "echo ```test```", | |
| 310 | + "```", | |
| 311 | + "```", | |
| 312 | + ]); | |
| 313 | + | |
| 314 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 315 | + const filteredLines = await getFilteredLines(result); | |
| 316 | + | |
| 317 | + expect(filteredLines).toEqual([ | |
| 318 | + "const x = 5;", | |
| 319 | + "```bash", | |
| 320 | + "echo ```test```", | |
| 321 | + "```", | |
| 322 | + ]); | |
| 323 | + }); | |
| 324 | + | |
| 325 | + it("should leave single inner blocks intact but not return trailing text", async () => { | |
| 326 | + const linesGenerator = await getLineGenerator([ | |
| 327 | + "```md", | |
| 328 | + "const x = 5;", | |
| 329 | + "```bash", | |
| 330 | + "ls -al", | |
| 331 | + "```", | |
| 332 | + "```", | |
| 333 | + "trailing text", | |
| 334 | + ]); | |
| 335 | + | |
| 336 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 337 | + const filteredLines = await getFilteredLines(result); | |
| 338 | + | |
| 339 | + expect(filteredLines).toEqual([ | |
| 340 | + "const x = 5;", | |
| 341 | + "```bash", | |
| 342 | + "ls -al", | |
| 343 | + "```", | |
| 344 | + ]); | |
| 345 | + }); | |
| 346 | + | |
| 347 | + it("should leave double inner blocks intact but not return trailing text", async () => { | |
| 348 | + const linesGenerator = await getLineGenerator([ | |
| 349 | + "```md", | |
| 350 | + "const x = 5;", | |
| 351 | + "```bash", | |
| 352 | + "ls -al", | |
| 353 | + "```", | |
| 354 | + "const y = 10;", | |
| 355 | + "```sh", | |
| 356 | + "echo `hello world`", | |
| 357 | + "```", | |
| 358 | + "```", | |
| 359 | + "trailing text", | |
| 360 | + ]); | |
| 361 | + | |
| 362 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 363 | + const filteredLines = await getFilteredLines(result); | |
| 364 | + | |
| 365 | + expect(filteredLines).toEqual([ | |
| 366 | + "const x = 5;", | |
| 367 | + "```bash", | |
| 368 | + "ls -al", | |
| 369 | + "```", | |
| 370 | + "const y = 10;", | |
| 371 | + "```sh", | |
| 372 | + "echo `hello world`", | |
| 373 | + "```", | |
| 374 | + ]); | |
| 375 | + }); | |
| 376 | + | |
| 377 | + it("should leave inner blocks intact but not return trailing or leading text", async () => { | |
| 378 | + const linesGenerator = await getLineGenerator([ | |
| 379 | + "[CODE]", | |
| 380 | + "const x = 5;", | |
| 381 | + "```bash", | |
| 382 | + "ls -al", | |
| 383 | + "```", | |
| 384 | + "[/CODE]", | |
| 385 | + "trailing text", | |
| 386 | + ]); | |
| 387 | + | |
| 388 | + const result = lineStream.filterCodeBlockLines(linesGenerator); | |
| 389 | + const filteredLines = await getFilteredLines(result); | |
| 390 | + | |
| 391 | + expect(filteredLines).toEqual([ | |
| 392 | + "const x = 5;", | |
| 393 | + "```bash", | |
| 394 | + "ls -al", | |
| 395 | + "```", | |
| 396 | + ]); | |
| 397 | + }); | |
| 398 | + }); | |
| 399 | + | |
| 400 | + describe("filterEnglishLinesAtStart", () => { | |
| 401 | + it("should skip initial empty line", async () => { | |
| 402 | + const linesGenerator = await getLineGenerator([ | |
| 403 | + "", | |
| 404 | + "const x = 5;", | |
| 405 | + "let y = 10;", | |
| 406 | + ]); | |
| 407 | + | |
| 408 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 409 | + const filteredLines = await getFilteredLines(result); | |
| 410 | + | |
| 411 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 412 | + }); | |
| 413 | + | |
| 414 | + it("should filter out English first line", async () => { | |
| 415 | + const linesGenerator = await getLineGenerator([ | |
| 416 | + lineStream.ENGLISH_START_PHRASES[0], | |
| 417 | + "let y = 10;", | |
| 418 | + ]); | |
| 419 | + | |
| 420 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 421 | + const filteredLines = await getFilteredLines(result); | |
| 422 | + | |
| 423 | + expect(filteredLines).toEqual(["let y = 10;"]); | |
| 424 | + }); | |
| 425 | + | |
| 426 | + it("should not filter out non-English first line", async () => { | |
| 427 | + const linesGenerator = await getLineGenerator([ | |
| 428 | + "const x = 5;", | |
| 429 | + "let y = 10;", | |
| 430 | + ]); | |
| 431 | + | |
| 432 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 433 | + const filteredLines = await getFilteredLines(result); | |
| 434 | + | |
| 435 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 436 | + }); | |
| 437 | + | |
| 438 | + it("should filter out empty newline after first line english word", async () => { | |
| 439 | + const linesGenerator = await getLineGenerator([ | |
| 440 | + lineStream.ENGLISH_START_PHRASES[0], | |
| 441 | + "", | |
| 442 | + "const x = 5;", | |
| 443 | + ]); | |
| 444 | + | |
| 445 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 446 | + const filteredLines = await getFilteredLines(result); | |
| 447 | + | |
| 448 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 449 | + }); | |
| 450 | + | |
| 451 | + it("should filter out sentences ending in a semi-colon that are not code keywords", async () => { | |
| 452 | + const linesGenerator = await getLineGenerator([ | |
| 453 | + "a" + lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":", | |
| 454 | + "const x = 5;", | |
| 455 | + ]); | |
| 456 | + | |
| 457 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 458 | + const filteredLines = await getFilteredLines(result); | |
| 459 | + | |
| 460 | + expect(filteredLines).toEqual(["const x = 5;"]); | |
| 461 | + }); | |
| 462 | + | |
| 463 | + it("should not filter out sentences ending in a semi-colon that are code keywords", async () => { | |
| 464 | + const keyword = lineStream.CODE_KEYWORDS_ENDING_IN_SEMICOLON[0] + ":"; | |
| 465 | + | |
| 466 | + const linesGenerator = await getLineGenerator([keyword, "const x = 5;"]); | |
| 467 | + | |
| 468 | + const result = lineStream.filterEnglishLinesAtStart(linesGenerator); | |
| 469 | + const filteredLines = await getFilteredLines(result); | |
| 470 | + | |
| 471 | + expect(filteredLines).toEqual([keyword, "const x = 5;"]); | |
| 472 | + }); | |
| 473 | + }); | |
| 474 | + | |
| 475 | + describe("filterEnglishLinesAtEnd", () => { | |
| 476 | + it("should stop at English explanation after code block", async () => { | |
| 477 | + const linesGenerator = await getLineGenerator([ | |
| 478 | + "const x = 5;", | |
| 479 | + "```", | |
| 480 | + lineStream.ENGLISH_POST_PHRASES[0], | |
| 481 | + ]); | |
| 482 | + | |
| 483 | + const result = lineStream.filterEnglishLinesAtEnd(linesGenerator); | |
| 484 | + const filteredLines = await getFilteredLines(result); | |
| 485 | + | |
| 486 | + expect(filteredLines).toEqual(["const x = 5;", "```"]); | |
| 487 | + }); | |
| 488 | + }); | |
| 489 | + | |
| 490 | + describe("fixCodeLlamaFirstLineIndentation", () => { | |
| 491 | + it("should fix indentation of the first line", async () => { | |
| 492 | + const linesGenerator = await getLineGenerator([ | |
| 493 | + " const x = 5;", | |
| 494 | + "let y = 10;", | |
| 495 | + ]); | |
| 496 | + | |
| 497 | + const result = | |
| 498 | + lineStream.fixCodeLlamaFirstLineIndentation(linesGenerator); | |
| 499 | + const filteredLines = await getFilteredLines(result); | |
| 500 | + | |
| 501 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 502 | + }); | |
| 503 | + }); | |
| 504 | + | |
| 505 | + describe("filterLeadingAndTrailingNewLineInsertion", () => { | |
| 506 | + it("should ignore 'useless' new first lines", async () => { | |
| 507 | + const linesGenerator = await getLineGenerator([ | |
| 508 | + { type: "new", line: lineStream.USELESS_LINES[0] }, | |
| 509 | + { type: "new", line: "const x = 5;" }, | |
| 510 | + ]); | |
| 511 | + | |
| 512 | + const result = | |
| 513 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 514 | + const filteredLines = await getFilteredLines(result); | |
| 515 | + | |
| 516 | + expect(filteredLines).toEqual([{ type: "new", line: "const x = 5;" }]); | |
| 517 | + }); | |
| 518 | + | |
| 519 | + it("should handle preserve newlines chars in old lines", async () => { | |
| 520 | + const linesGenerator = await getLineGenerator([ | |
| 521 | + { type: "new", line: "const x = 5;" }, | |
| 522 | + { type: "old", line: "let y = 10;" }, | |
| 523 | + { type: "old", line: "" }, | |
| 524 | + { type: "new", line: "const z = 15;" }, | |
| 525 | + ]); | |
| 526 | + | |
| 527 | + const result = | |
| 528 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 529 | + const filteredLines = await getFilteredLines(result); | |
| 530 | + | |
| 531 | + expect(filteredLines).toEqual([ | |
| 532 | + { type: "new", line: "const x = 5;" }, | |
| 533 | + { type: "old", line: "let y = 10;" }, | |
| 534 | + { type: "old", line: "" }, | |
| 535 | + { type: "new", line: "const z = 15;" }, | |
| 536 | + ]); | |
| 537 | + }); | |
| 538 | + | |
| 539 | + it("should filter leading and trailing new line insertions", async () => { | |
| 540 | + const linesGenerator = await getLineGenerator([ | |
| 541 | + { type: "new", line: "" }, | |
| 542 | + { type: "new", line: "const x = 5;" }, | |
| 543 | + { type: "new", line: "let y = 10;" }, | |
| 544 | + { type: "new", line: "" }, | |
| 545 | + ]); | |
| 546 | + | |
| 547 | + const result = | |
| 548 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 549 | + const filteredLines = await getFilteredLines(result); | |
| 550 | + | |
| 551 | + expect(filteredLines).toEqual([ | |
| 552 | + { type: "new", line: "const x = 5;" }, | |
| 553 | + { type: "new", line: "let y = 10;" }, | |
| 554 | + ]); | |
| 555 | + }); | |
| 556 | + | |
| 557 | + it("should buffer newline chars and then render them if we encounter another non-empty line", async () => { | |
| 558 | + const linesGenerator = await getLineGenerator([ | |
| 559 | + { type: "new", line: "const x = 5;" }, | |
| 560 | + { type: "new", line: "" }, | |
| 561 | + { type: "new", line: "let y = 10;" }, | |
| 562 | + ]); | |
| 563 | + | |
| 564 | + const result = | |
| 565 | + lineStream.filterLeadingAndTrailingNewLineInsertion(linesGenerator); | |
| 566 | + const filteredLines = await getFilteredLines(result); | |
| 567 | + | |
| 568 | + expect(filteredLines).toEqual([ | |
| 569 | + { type: "new", line: "const x = 5;" }, | |
| 570 | + { type: "new", line: "" }, | |
| 571 | + { type: "new", line: "let y = 10;" }, | |
| 572 | + ]); | |
| 573 | + }); | |
| 574 | + }); | |
| 575 | + | |
| 576 | + describe("stopAtRepeatingLines", () => { | |
| 577 | + it("should handle non-repeating lines correctly", async () => { | |
| 578 | + const linesGenerator = await getLineGenerator([ | |
| 579 | + "const x = 5;", | |
| 580 | + "let y = 10;", | |
| 581 | + "const z = 15;", | |
| 582 | + ]); | |
| 583 | + | |
| 584 | + const result = lineStream.stopAtRepeatingLines( | |
| 585 | + linesGenerator, | |
| 586 | + mockFullStop, | |
| 587 | + ); | |
| 588 | + const filteredLines = await getFilteredLines(result); | |
| 589 | + | |
| 590 | + expect(filteredLines).toEqual([ | |
| 591 | + "const x = 5;", | |
| 592 | + "let y = 10;", | |
| 593 | + "const z = 15;", | |
| 594 | + ]); | |
| 595 | + }); | |
| 596 | + | |
| 597 | + it("should stop at repeating lines", async () => { | |
| 598 | + const linesGenerator = await getLineGenerator([ | |
| 599 | + "const x = 5;", | |
| 600 | + "let y = 10;", | |
| 601 | + "let y = 10;", | |
| 602 | + "let y = 10;", | |
| 603 | + "const z = 15;", | |
| 604 | + ]); | |
| 605 | + | |
| 606 | + const result = lineStream.stopAtRepeatingLines( | |
| 607 | + linesGenerator, | |
| 608 | + mockFullStop, | |
| 609 | + ); | |
| 610 | + const filteredLines = await getFilteredLines(result); | |
| 611 | + | |
| 612 | + expect(filteredLines).toEqual(["const x = 5;", "let y = 10;"]); | |
| 613 | + expect(mockFullStop).toHaveBeenCalledTimes(1); | |
| 614 | + }); | |
| 615 | + }); | |
| 616 | +}); |
deleted core/autocomplete/filtering/test/filter.test.ts +0 −48
| @@ -1,48 +0,0 @@ | ||
| 1 | -import { setUpTestDir, tearDownTestDir } from "../../../test/testDir"; | |
| 2 | - | |
| 3 | -import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; | |
| 4 | -import { | |
| 5 | - AutocompleteFileringTestInput, | |
| 6 | - testAutocompleteFiltering, | |
| 7 | -} from "./util"; | |
| 8 | - | |
| 9 | -const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { | |
| 10 | - if (tests.some((test) => test.options?.only)) { | |
| 11 | - return tests.filter((test) => test.options?.only); | |
| 12 | - } | |
| 13 | - | |
| 14 | - return tests; | |
| 15 | -}; | |
| 16 | - | |
| 17 | -describe("Autocomplete filtering tests", () => { | |
| 18 | - beforeAll(async () => { | |
| 19 | - tearDownTestDir(); | |
| 20 | - setUpTestDir(); | |
| 21 | - }); | |
| 22 | - | |
| 23 | - afterAll(async () => { | |
| 24 | - tearDownTestDir(); | |
| 25 | - }); | |
| 26 | - | |
| 27 | - beforeEach(async () => { | |
| 28 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 29 | - }); | |
| 30 | - | |
| 31 | - describe("Should return unmodified LLM output", () => { | |
| 32 | - it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( | |
| 33 | - "$description", | |
| 34 | - async (testCase) => { | |
| 35 | - await testAutocompleteFiltering(testCase); | |
| 36 | - }, | |
| 37 | - ); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - describe("Should return modified LLM output", () => { | |
| 41 | - it.each(filterTestCases(TEST_CASES_WITH_DIFF))( | |
| 42 | - "$description", | |
| 43 | - async (testCase) => { | |
| 44 | - await testAutocompleteFiltering(testCase); | |
| 45 | - }, | |
| 46 | - ); | |
| 47 | - }); | |
| 48 | -}); |
added core/autocomplete/filtering/test/filter.vitest.ts +54 −0
| @@ -0,0 +1,54 @@ | ||
| 1 | +import { afterAll, beforeAll, beforeEach, describe, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + addToTestDir, | |
| 4 | + setUpTestDir, | |
| 5 | + tearDownTestDir, | |
| 6 | +} from "../../../test/testDir"; | |
| 7 | + | |
| 8 | +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; | |
| 9 | +import { | |
| 10 | + AutocompleteFileringTestInput, | |
| 11 | + testAutocompleteFiltering, | |
| 12 | +} from "./util"; | |
| 13 | + | |
| 14 | +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { | |
| 15 | + if (tests.some((test) => test.options?.only)) { | |
| 16 | + return tests.filter((test) => test.options?.only); | |
| 17 | + } | |
| 18 | + | |
| 19 | + return tests; | |
| 20 | +}; | |
| 21 | + | |
| 22 | +describe("Autocomplete filtering tests", () => { | |
| 23 | + beforeAll(async () => { | |
| 24 | + tearDownTestDir(); | |
| 25 | + setUpTestDir(); | |
| 26 | + addToTestDir([".continueignore"]); | |
| 27 | + }); | |
| 28 | + | |
| 29 | + afterAll(async () => { | |
| 30 | + tearDownTestDir(); | |
| 31 | + }); | |
| 32 | + | |
| 33 | + beforeEach(async () => { | |
| 34 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 35 | + }); | |
| 36 | + | |
| 37 | + describe("Should return unmodified LLM output", () => { | |
| 38 | + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( | |
| 39 | + "$description", | |
| 40 | + async (testCase) => { | |
| 41 | + await testAutocompleteFiltering(testCase); | |
| 42 | + }, | |
| 43 | + ); | |
| 44 | + }); | |
| 45 | + | |
| 46 | + describe("Should return modified LLM output", () => { | |
| 47 | + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( | |
| 48 | + "$description", | |
| 49 | + async (testCase) => { | |
| 50 | + await testAutocompleteFiltering(testCase); | |
| 51 | + }, | |
| 52 | + ); | |
| 53 | + }); | |
| 54 | +}); |
modified core/autocomplete/filtering/test/util.ts +1 −0
| @@ -1,3 +1,4 @@ | ||
| 1 | +import { expect } from "vitest"; | |
| 1 | 2 | import MockLLM from "../../../llm/llms/Mock"; |
| 2 | 3 | import { testConfigHandler, testIde } from "../../../test/fixtures"; |
| 3 | 4 | import { joinPathsToUri } from "../../../util/uri"; |
deleted core/autocomplete/generation/GeneratorReuseManager.test.ts +0 −215
| @@ -1,215 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | -import { GeneratorReuseManager } from "./GeneratorReuseManager"; | |
| 3 | - | |
| 4 | -function createMockGenerator( | |
| 5 | - data: string[], | |
| 6 | - delay: number = 0, | |
| 7 | -): (abortSignal: AbortSignal) => AsyncGenerator<string> { | |
| 8 | - const mockGenerator = async function* () { | |
| 9 | - for (const chunk of data) { | |
| 10 | - yield chunk; | |
| 11 | - | |
| 12 | - if (delay > 0) { | |
| 13 | - await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 14 | - } | |
| 15 | - } | |
| 16 | - }; | |
| 17 | - const newGenerator = jest | |
| 18 | - .fn<() => AsyncGenerator<string>>() | |
| 19 | - .mockReturnValue(mockGenerator()); | |
| 20 | - | |
| 21 | - return newGenerator; | |
| 22 | -} | |
| 23 | - | |
| 24 | -describe("GeneratorReuseManager", () => { | |
| 25 | - let reuseManager: GeneratorReuseManager; | |
| 26 | - let onErrorMock: jest.Mock; | |
| 27 | - | |
| 28 | - beforeEach(() => { | |
| 29 | - onErrorMock = jest.fn(); | |
| 30 | - reuseManager = new GeneratorReuseManager(onErrorMock); | |
| 31 | - }); | |
| 32 | - | |
| 33 | - afterEach(() => { | |
| 34 | - jest.clearAllMocks(); | |
| 35 | - }); | |
| 36 | - | |
| 37 | - test("creates new generator when there is no current generator", async () => { | |
| 38 | - const data = ["hello ", "world"]; | |
| 39 | - const newGenerator = createMockGenerator(data); | |
| 40 | - | |
| 41 | - const prefix = ""; | |
| 42 | - | |
| 43 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 44 | - | |
| 45 | - const output: string[] = []; | |
| 46 | - for await (const chunk of generator) { | |
| 47 | - output.push(chunk); | |
| 48 | - } | |
| 49 | - | |
| 50 | - expect(output).toEqual(data); | |
| 51 | - expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 52 | - }); | |
| 53 | - | |
| 54 | - test("reuses generator when prefix matches pending completion", async () => { | |
| 55 | - const newGenerator = createMockGenerator(["llo ", "world"]); | |
| 56 | - | |
| 57 | - // First call with initial prefix | |
| 58 | - const prefix1 = "he"; | |
| 59 | - const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); | |
| 60 | - | |
| 61 | - const output1: string[] = []; | |
| 62 | - for await (const chunk of generator1) { | |
| 63 | - output1.push(chunk); | |
| 64 | - } | |
| 65 | - | |
| 66 | - expect(output1).toEqual(["llo ", "world"]); | |
| 67 | - | |
| 68 | - // Second call with extended prefix that matches pending completion | |
| 69 | - const prefix2 = "hello "; | |
| 70 | - const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); | |
| 71 | - | |
| 72 | - const output2: string[] = []; | |
| 73 | - for await (const chunk of generator2) { | |
| 74 | - output2.push(chunk); | |
| 75 | - } | |
| 76 | - | |
| 77 | - expect(output2).toEqual(["world"]); | |
| 78 | - | |
| 79 | - // Ensure generator was reused (newGenerator should be called only once) | |
| 80 | - expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 81 | - }); | |
| 82 | - | |
| 83 | - test("creates new generator when prefix does not match pending completion", async () => { | |
| 84 | - const data = ["goodbye ", "world"]; | |
| 85 | - const newGenerator = createMockGenerator(data); | |
| 86 | - | |
| 87 | - // Initial generator with different prefix | |
| 88 | - reuseManager.pendingGeneratorPrefix = "hello "; | |
| 89 | - reuseManager.pendingCompletion = "world"; | |
| 90 | - | |
| 91 | - const prefix = "good"; | |
| 92 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 93 | - | |
| 94 | - const output: string[] = []; | |
| 95 | - for await (const chunk of generator) { | |
| 96 | - output.push(chunk); | |
| 97 | - } | |
| 98 | - | |
| 99 | - expect(output).toEqual(data); | |
| 100 | - // Ensure a new generator was created | |
| 101 | - expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 102 | - }); | |
| 103 | - | |
| 104 | - test("handles multiline=false by stopping at newline", async () => { | |
| 105 | - const data = ["first line\n", "second line"]; | |
| 106 | - const newGenerator = createMockGenerator(data); | |
| 107 | - | |
| 108 | - const prefix = ""; | |
| 109 | - const generator = reuseManager.getGenerator(prefix, newGenerator, false); | |
| 110 | - | |
| 111 | - const output: string[] = []; | |
| 112 | - for await (const chunk of generator) { | |
| 113 | - output.push(chunk); | |
| 114 | - } | |
| 115 | - | |
| 116 | - expect(output).toEqual(["first line"]); | |
| 117 | - // Ensure it stops after the first newline | |
| 118 | - }); | |
| 119 | - | |
| 120 | - test("handles multiline=true by not stopping at newline", async () => { | |
| 121 | - const data = ["first line\n", "second line"]; | |
| 122 | - const newGenerator = createMockGenerator(data); | |
| 123 | - | |
| 124 | - const prefix = ""; | |
| 125 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 126 | - | |
| 127 | - const output: string[] = []; | |
| 128 | - for await (const chunk of generator) { | |
| 129 | - output.push(chunk); | |
| 130 | - } | |
| 131 | - | |
| 132 | - expect(output).toEqual(data); | |
| 133 | - }); | |
| 134 | - | |
| 135 | - test("cancels previous generator when creating a new one", async () => { | |
| 136 | - const data1 = ["data from generator 1", "not generated"]; | |
| 137 | - const data2 = ["data from generator 2"]; | |
| 138 | - | |
| 139 | - const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it | |
| 140 | - const newGenerator2 = createMockGenerator(data2); | |
| 141 | - | |
| 142 | - const prefix1 = "prefix1"; | |
| 143 | - const prefix2 = "prefix2"; | |
| 144 | - | |
| 145 | - // First generator | |
| 146 | - const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 147 | - const output1: string[] = []; | |
| 148 | - for await (const chunk of generator1) { | |
| 149 | - output1.push(chunk); | |
| 150 | - // Simulate the generator being canceled before completing | |
| 151 | - reuseManager.currentGenerator?.cancel(); | |
| 152 | - } | |
| 153 | - | |
| 154 | - expect(output1.length).toEqual(1); | |
| 155 | - expect(output1[0]).toEqual(data1[0]); | |
| 156 | - | |
| 157 | - // Second generator | |
| 158 | - const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 159 | - const output2: string[] = []; | |
| 160 | - for await (const chunk of generator2) { | |
| 161 | - output2.push(chunk); | |
| 162 | - } | |
| 163 | - | |
| 164 | - expect(output2).toEqual(data2); | |
| 165 | - }); | |
| 166 | - | |
| 167 | - test("calls onError when generator throws an error", async () => { | |
| 168 | - const error = new Error("Generator error"); | |
| 169 | - const mockGenerator = async function* () { | |
| 170 | - throw error; | |
| 171 | - }; | |
| 172 | - const newGenerator = jest | |
| 173 | - .fn<() => AsyncGenerator<string>>() | |
| 174 | - .mockReturnValue(mockGenerator()); | |
| 175 | - | |
| 176 | - const prefix = ""; | |
| 177 | - const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 178 | - | |
| 179 | - const output: string[] = []; | |
| 180 | - await expect(async () => { | |
| 181 | - for await (const chunk of generator) { | |
| 182 | - output.push(chunk); | |
| 183 | - } | |
| 184 | - }).not.toThrow(); // getGenerator handles errors internally | |
| 185 | - | |
| 186 | - expect(onErrorMock).toHaveBeenCalledWith(error); | |
| 187 | - expect(output).toEqual([]); | |
| 188 | - }); | |
| 189 | - | |
| 190 | - test("handles backspacing by creating new generator when prefix is shorter", async () => { | |
| 191 | - const data = ["hello world"]; | |
| 192 | - const newGenerator1 = createMockGenerator(data); | |
| 193 | - const newGenerator2 = createMockGenerator(data); | |
| 194 | - | |
| 195 | - // First prefix | |
| 196 | - const prefix1 = "hello world"; | |
| 197 | - const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 198 | - const output1: string[] = []; | |
| 199 | - for await (const chunk of generator1) { | |
| 200 | - output1.push(chunk); | |
| 201 | - } | |
| 202 | - | |
| 203 | - // Simulate backspace (prefix is shorter) | |
| 204 | - const prefix2 = "hello worl"; | |
| 205 | - const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 206 | - const output2: string[] = []; | |
| 207 | - for await (const chunk of generator2) { | |
| 208 | - output2.push(chunk); | |
| 209 | - } | |
| 210 | - | |
| 211 | - // Ensure a new generator was created | |
| 212 | - expect(newGenerator1).toHaveBeenCalledTimes(1); | |
| 213 | - expect(newGenerator2).toHaveBeenCalledTimes(1); | |
| 214 | - }); | |
| 215 | -}); |
added core/autocomplete/generation/GeneratorReuseManager.vitest.ts +223 −0
| @@ -0,0 +1,223 @@ | ||
| 1 | +import { | |
| 2 | + afterEach, | |
| 3 | + beforeEach, | |
| 4 | + describe, | |
| 5 | + expect, | |
| 6 | + Mock, | |
| 7 | + test, | |
| 8 | + vi, | |
| 9 | +} from "vitest"; | |
| 10 | +import { GeneratorReuseManager } from "./GeneratorReuseManager"; | |
| 11 | + | |
| 12 | +function createMockGenerator( | |
| 13 | + data: string[], | |
| 14 | + delay: number = 0, | |
| 15 | +): (abortSignal: AbortSignal) => AsyncGenerator<string> { | |
| 16 | + const mockGenerator = async function* () { | |
| 17 | + for (const chunk of data) { | |
| 18 | + yield chunk; | |
| 19 | + | |
| 20 | + if (delay > 0) { | |
| 21 | + await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 22 | + } | |
| 23 | + } | |
| 24 | + }; | |
| 25 | + const newGenerator = vi | |
| 26 | + .fn<() => AsyncGenerator<string>>() | |
| 27 | + .mockReturnValue(mockGenerator()); | |
| 28 | + | |
| 29 | + return newGenerator; | |
| 30 | +} | |
| 31 | + | |
| 32 | +describe("GeneratorReuseManager", () => { | |
| 33 | + let reuseManager: GeneratorReuseManager; | |
| 34 | + let onErrorMock: Mock; | |
| 35 | + | |
| 36 | + beforeEach(() => { | |
| 37 | + onErrorMock = vi.fn(); | |
| 38 | + reuseManager = new GeneratorReuseManager(onErrorMock); | |
| 39 | + }); | |
| 40 | + | |
| 41 | + afterEach(() => { | |
| 42 | + vi.clearAllMocks(); | |
| 43 | + }); | |
| 44 | + | |
| 45 | + test("creates new generator when there is no current generator", async () => { | |
| 46 | + const data = ["hello ", "world"]; | |
| 47 | + const newGenerator = createMockGenerator(data); | |
| 48 | + | |
| 49 | + const prefix = ""; | |
| 50 | + | |
| 51 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 52 | + | |
| 53 | + const output: string[] = []; | |
| 54 | + for await (const chunk of generator) { | |
| 55 | + output.push(chunk); | |
| 56 | + } | |
| 57 | + | |
| 58 | + expect(output).toEqual(data); | |
| 59 | + expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 60 | + }); | |
| 61 | + | |
| 62 | + test("reuses generator when prefix matches pending completion", async () => { | |
| 63 | + const newGenerator = createMockGenerator(["llo ", "world"]); | |
| 64 | + | |
| 65 | + // First call with initial prefix | |
| 66 | + const prefix1 = "he"; | |
| 67 | + const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true); | |
| 68 | + | |
| 69 | + const output1: string[] = []; | |
| 70 | + for await (const chunk of generator1) { | |
| 71 | + output1.push(chunk); | |
| 72 | + } | |
| 73 | + | |
| 74 | + expect(output1).toEqual(["llo ", "world"]); | |
| 75 | + | |
| 76 | + // Second call with extended prefix that matches pending completion | |
| 77 | + const prefix2 = "hello "; | |
| 78 | + const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true); | |
| 79 | + | |
| 80 | + const output2: string[] = []; | |
| 81 | + for await (const chunk of generator2) { | |
| 82 | + output2.push(chunk); | |
| 83 | + } | |
| 84 | + | |
| 85 | + expect(output2).toEqual(["world"]); | |
| 86 | + | |
| 87 | + // Ensure generator was reused (newGenerator should be called only once) | |
| 88 | + expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 89 | + }); | |
| 90 | + | |
| 91 | + test("creates new generator when prefix does not match pending completion", async () => { | |
| 92 | + const data = ["goodbye ", "world"]; | |
| 93 | + const newGenerator = createMockGenerator(data); | |
| 94 | + | |
| 95 | + // Initial generator with different prefix | |
| 96 | + reuseManager.pendingGeneratorPrefix = "hello "; | |
| 97 | + reuseManager.pendingCompletion = "world"; | |
| 98 | + | |
| 99 | + const prefix = "good"; | |
| 100 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 101 | + | |
| 102 | + const output: string[] = []; | |
| 103 | + for await (const chunk of generator) { | |
| 104 | + output.push(chunk); | |
| 105 | + } | |
| 106 | + | |
| 107 | + expect(output).toEqual(data); | |
| 108 | + // Ensure a new generator was created | |
| 109 | + expect(newGenerator).toHaveBeenCalledTimes(1); | |
| 110 | + }); | |
| 111 | + | |
| 112 | + test("handles multiline=false by stopping at newline", async () => { | |
| 113 | + const data = ["first line\n", "second line"]; | |
| 114 | + const newGenerator = createMockGenerator(data); | |
| 115 | + | |
| 116 | + const prefix = ""; | |
| 117 | + const generator = reuseManager.getGenerator(prefix, newGenerator, false); | |
| 118 | + | |
| 119 | + const output: string[] = []; | |
| 120 | + for await (const chunk of generator) { | |
| 121 | + output.push(chunk); | |
| 122 | + } | |
| 123 | + | |
| 124 | + expect(output).toEqual(["first line"]); | |
| 125 | + // Ensure it stops after the first newline | |
| 126 | + }); | |
| 127 | + | |
| 128 | + test("handles multiline=true by not stopping at newline", async () => { | |
| 129 | + const data = ["first line\n", "second line"]; | |
| 130 | + const newGenerator = createMockGenerator(data); | |
| 131 | + | |
| 132 | + const prefix = ""; | |
| 133 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 134 | + | |
| 135 | + const output: string[] = []; | |
| 136 | + for await (const chunk of generator) { | |
| 137 | + output.push(chunk); | |
| 138 | + } | |
| 139 | + | |
| 140 | + expect(output).toEqual(data); | |
| 141 | + }); | |
| 142 | + | |
| 143 | + test("cancels previous generator when creating a new one", async () => { | |
| 144 | + const data1 = ["data from generator 1", "not generated"]; | |
| 145 | + const data2 = ["data from generator 2"]; | |
| 146 | + | |
| 147 | + const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it | |
| 148 | + const newGenerator2 = createMockGenerator(data2); | |
| 149 | + | |
| 150 | + const prefix1 = "prefix1"; | |
| 151 | + const prefix2 = "prefix2"; | |
| 152 | + | |
| 153 | + // First generator | |
| 154 | + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 155 | + const output1: string[] = []; | |
| 156 | + for await (const chunk of generator1) { | |
| 157 | + output1.push(chunk); | |
| 158 | + // Simulate the generator being canceled before completing | |
| 159 | + reuseManager.currentGenerator?.cancel(); | |
| 160 | + } | |
| 161 | + | |
| 162 | + expect(output1.length).toEqual(1); | |
| 163 | + expect(output1[0]).toEqual(data1[0]); | |
| 164 | + | |
| 165 | + // Second generator | |
| 166 | + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 167 | + const output2: string[] = []; | |
| 168 | + for await (const chunk of generator2) { | |
| 169 | + output2.push(chunk); | |
| 170 | + } | |
| 171 | + | |
| 172 | + expect(output2).toEqual(data2); | |
| 173 | + }); | |
| 174 | + | |
| 175 | + test("calls onError when generator throws an error", async () => { | |
| 176 | + const error = new Error("Generator error"); | |
| 177 | + const mockGenerator = async function* () { | |
| 178 | + throw error; | |
| 179 | + }; | |
| 180 | + const newGenerator = vi | |
| 181 | + .fn<() => AsyncGenerator<string>>() | |
| 182 | + .mockReturnValue(mockGenerator()); | |
| 183 | + | |
| 184 | + const prefix = ""; | |
| 185 | + const generator = reuseManager.getGenerator(prefix, newGenerator, true); | |
| 186 | + | |
| 187 | + const output: string[] = []; | |
| 188 | + await expect(async () => { | |
| 189 | + for await (const chunk of generator) { | |
| 190 | + output.push(chunk); | |
| 191 | + } | |
| 192 | + }).not.toThrow(); // getGenerator handles errors internally | |
| 193 | + | |
| 194 | + expect(onErrorMock).toHaveBeenCalledWith(error); | |
| 195 | + expect(output).toEqual([]); | |
| 196 | + }); | |
| 197 | + | |
| 198 | + test("handles backspacing by creating new generator when prefix is shorter", async () => { | |
| 199 | + const data = ["hello world"]; | |
| 200 | + const newGenerator1 = createMockGenerator(data); | |
| 201 | + const newGenerator2 = createMockGenerator(data); | |
| 202 | + | |
| 203 | + // First prefix | |
| 204 | + const prefix1 = "hello world"; | |
| 205 | + const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true); | |
| 206 | + const output1: string[] = []; | |
| 207 | + for await (const chunk of generator1) { | |
| 208 | + output1.push(chunk); | |
| 209 | + } | |
| 210 | + | |
| 211 | + // Simulate backspace (prefix is shorter) | |
| 212 | + const prefix2 = "hello worl"; | |
| 213 | + const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true); | |
| 214 | + const output2: string[] = []; | |
| 215 | + for await (const chunk of generator2) { | |
| 216 | + output2.push(chunk); | |
| 217 | + } | |
| 218 | + | |
| 219 | + // Ensure a new generator was created | |
| 220 | + expect(newGenerator1).toHaveBeenCalledTimes(1); | |
| 221 | + expect(newGenerator2).toHaveBeenCalledTimes(1); | |
| 222 | + }); | |
| 223 | +}); |
deleted core/autocomplete/generation/ListenableGenerator.test.ts +0 −174
| @@ -1,174 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | - | |
| 3 | -import { ListenableGenerator } from "./ListenableGenerator"; | |
| 4 | - | |
| 5 | -describe("ListenableGenerator", () => { | |
| 6 | - // Helper function to create an async generator | |
| 7 | - async function* asyncGenerator<T>(values: T[], delay = 0) { | |
| 8 | - for (const value of values) { | |
| 9 | - if (delay > 0) { | |
| 10 | - await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 11 | - } | |
| 12 | - yield value; | |
| 13 | - } | |
| 14 | - } | |
| 15 | - | |
| 16 | - it("should yield values from the source generator via tee()", async () => { | |
| 17 | - const values = [1, 2, 3]; | |
| 18 | - const source = asyncGenerator(values); | |
| 19 | - const onError = jest.fn(); | |
| 20 | - | |
| 21 | - const lg = new ListenableGenerator<number>( | |
| 22 | - source, | |
| 23 | - onError, | |
| 24 | - new AbortController(), | |
| 25 | - ); | |
| 26 | - | |
| 27 | - const result: number[] = []; | |
| 28 | - for await (const value of lg.tee()) { | |
| 29 | - result.push(value); | |
| 30 | - } | |
| 31 | - | |
| 32 | - expect(result).toEqual(values); | |
| 33 | - expect(onError).not.toHaveBeenCalled(); | |
| 34 | - }); | |
| 35 | - | |
| 36 | - it("should allow listeners to receive values", async () => { | |
| 37 | - const values = [1, 2, 3]; | |
| 38 | - const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior | |
| 39 | - const onError = jest.fn(); | |
| 40 | - | |
| 41 | - const lg = new ListenableGenerator<number>( | |
| 42 | - source, | |
| 43 | - onError, | |
| 44 | - new AbortController(), | |
| 45 | - ); | |
| 46 | - | |
| 47 | - const listener = jest.fn(); | |
| 48 | - | |
| 49 | - // Add listener after some delay to simulate late subscription | |
| 50 | - setTimeout(() => { | |
| 51 | - lg.listen(listener); | |
| 52 | - }, 15); | |
| 53 | - | |
| 54 | - // Wait for generator to finish | |
| 55 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 56 | - | |
| 57 | - expect(listener).toHaveBeenCalledWith(1); | |
| 58 | - expect(listener).toHaveBeenCalledWith(2); | |
| 59 | - expect(listener).toHaveBeenCalledWith(3); | |
| 60 | - // Listener should receive null at the end | |
| 61 | - expect(listener).toHaveBeenCalledWith(null); | |
| 62 | - }); | |
| 63 | - | |
| 64 | - it("should buffer values for listeners added after some values have been yielded", async () => { | |
| 65 | - const values = [1, 2, 3]; | |
| 66 | - const source = asyncGenerator(values, 10); | |
| 67 | - const onError = jest.fn(); | |
| 68 | - | |
| 69 | - const lg = new ListenableGenerator<number>( | |
| 70 | - source, | |
| 71 | - onError, | |
| 72 | - new AbortController(), | |
| 73 | - ); | |
| 74 | - | |
| 75 | - const initialListener = jest.fn(); | |
| 76 | - | |
| 77 | - lg.listen(initialListener); | |
| 78 | - | |
| 79 | - // Wait for the first value to be yielded | |
| 80 | - await new Promise((resolve) => setTimeout(resolve, 15)); | |
| 81 | - | |
| 82 | - // Add a second listener | |
| 83 | - const newListener = jest.fn(); | |
| 84 | - lg.listen(newListener); | |
| 85 | - | |
| 86 | - // Wait for generator to finish | |
| 87 | - await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 88 | - | |
| 89 | - // Both listeners should have received all values | |
| 90 | - [initialListener, newListener].forEach((listener) => { | |
| 91 | - expect(listener).toHaveBeenCalledWith(1); | |
| 92 | - expect(listener).toHaveBeenCalledWith(2); | |
| 93 | - expect(listener).toHaveBeenCalledWith(3); | |
| 94 | - expect(listener).toHaveBeenCalledWith(null); | |
| 95 | - }); | |
| 96 | - }); | |
| 97 | - | |
| 98 | - it("should handle cancellation", async () => { | |
| 99 | - const values = [1, 2, 3, 4, 5]; | |
| 100 | - const source = asyncGenerator(values, 10); | |
| 101 | - const onError = jest.fn(); | |
| 102 | - | |
| 103 | - const lg = new ListenableGenerator<number>( | |
| 104 | - source, | |
| 105 | - onError, | |
| 106 | - new AbortController(), | |
| 107 | - ); | |
| 108 | - | |
| 109 | - const result: number[] = []; | |
| 110 | - const teeIterator = lg.tee(); | |
| 111 | - | |
| 112 | - const consume = async () => { | |
| 113 | - for await (const value of teeIterator) { | |
| 114 | - result.push(value); | |
| 115 | - if (value === 3) { | |
| 116 | - lg.cancel(); | |
| 117 | - } | |
| 118 | - } | |
| 119 | - }; | |
| 120 | - | |
| 121 | - await consume(); | |
| 122 | - | |
| 123 | - expect(result).toEqual([1, 2, 3]); | |
| 124 | - expect(lg["_isEnded"]).toBe(true); | |
| 125 | - }); | |
| 126 | - | |
| 127 | - it("should call onError when the source generator throws an error", async () => { | |
| 128 | - async function* errorGenerator() { | |
| 129 | - yield 1; | |
| 130 | - throw new Error("Test error"); | |
| 131 | - } | |
| 132 | - | |
| 133 | - const source = errorGenerator(); | |
| 134 | - const onError = jest.fn(); | |
| 135 | - | |
| 136 | - const lg = new ListenableGenerator<number>( | |
| 137 | - source, | |
| 138 | - onError, | |
| 139 | - new AbortController(), | |
| 140 | - ); | |
| 141 | - | |
| 142 | - const result: number[] = []; | |
| 143 | - for await (const value of lg.tee()) { | |
| 144 | - result.push(value); | |
| 145 | - } | |
| 146 | - | |
| 147 | - expect(result).toEqual([1]); | |
| 148 | - expect(onError).toHaveBeenCalledTimes(1); | |
| 149 | - expect(onError).toHaveBeenCalledWith(new Error("Test error")); | |
| 150 | - }); | |
| 151 | - | |
| 152 | - it("should notify listeners when the generator ends", async () => { | |
| 153 | - const values = [1, 2, 3]; | |
| 154 | - const source = asyncGenerator(values); | |
| 155 | - const onError = jest.fn(); | |
| 156 | - | |
| 157 | - const lg = new ListenableGenerator<number>( | |
| 158 | - source, | |
| 159 | - onError, | |
| 160 | - new AbortController(), | |
| 161 | - ); | |
| 162 | - | |
| 163 | - const listener = jest.fn(); | |
| 164 | - lg.listen(listener); | |
| 165 | - | |
| 166 | - // Wait for the generator to finish | |
| 167 | - await new Promise((resolve) => setTimeout(resolve, 10)); | |
| 168 | - | |
| 169 | - expect(listener).toHaveBeenCalledWith(1); | |
| 170 | - expect(listener).toHaveBeenCalledWith(2); | |
| 171 | - expect(listener).toHaveBeenCalledWith(3); | |
| 172 | - expect(listener).toHaveBeenCalledWith(null); | |
| 173 | - }); | |
| 174 | -}); |
added core/autocomplete/generation/ListenableGenerator.vitest.ts +174 −0
| @@ -0,0 +1,174 @@ | ||
| 1 | +import { describe, expect, it, vi } from "vitest"; | |
| 2 | + | |
| 3 | +import { ListenableGenerator } from "./ListenableGenerator"; | |
| 4 | + | |
| 5 | +describe("ListenableGenerator", () => { | |
| 6 | + // Helper function to create an async generator | |
| 7 | + async function* asyncGenerator<T>(values: T[], delay = 0) { | |
| 8 | + for (const value of values) { | |
| 9 | + if (delay > 0) { | |
| 10 | + await new Promise((resolve) => setTimeout(resolve, delay)); | |
| 11 | + } | |
| 12 | + yield value; | |
| 13 | + } | |
| 14 | + } | |
| 15 | + | |
| 16 | + it("should yield values from the source generator via tee()", async () => { | |
| 17 | + const values = [1, 2, 3]; | |
| 18 | + const source = asyncGenerator(values); | |
| 19 | + const onError = vi.fn(); | |
| 20 | + | |
| 21 | + const lg = new ListenableGenerator<number>( | |
| 22 | + source, | |
| 23 | + onError, | |
| 24 | + new AbortController(), | |
| 25 | + ); | |
| 26 | + | |
| 27 | + const result: number[] = []; | |
| 28 | + for await (const value of lg.tee()) { | |
| 29 | + result.push(value); | |
| 30 | + } | |
| 31 | + | |
| 32 | + expect(result).toEqual(values); | |
| 33 | + expect(onError).not.toHaveBeenCalled(); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("should allow listeners to receive values", async () => { | |
| 37 | + const values = [1, 2, 3]; | |
| 38 | + const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior | |
| 39 | + const onError = vi.fn(); | |
| 40 | + | |
| 41 | + const lg = new ListenableGenerator<number>( | |
| 42 | + source, | |
| 43 | + onError, | |
| 44 | + new AbortController(), | |
| 45 | + ); | |
| 46 | + | |
| 47 | + const listener = vi.fn(); | |
| 48 | + | |
| 49 | + // Add listener after some delay to simulate late subscription | |
| 50 | + setTimeout(() => { | |
| 51 | + lg.listen(listener); | |
| 52 | + }, 15); | |
| 53 | + | |
| 54 | + // Wait for generator to finish | |
| 55 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 56 | + | |
| 57 | + expect(listener).toHaveBeenCalledWith(1); | |
| 58 | + expect(listener).toHaveBeenCalledWith(2); | |
| 59 | + expect(listener).toHaveBeenCalledWith(3); | |
| 60 | + // Listener should receive null at the end | |
| 61 | + expect(listener).toHaveBeenCalledWith(null); | |
| 62 | + }); | |
| 63 | + | |
| 64 | + it("should buffer values for listeners added after some values have been yielded", async () => { | |
| 65 | + const values = [1, 2, 3]; | |
| 66 | + const source = asyncGenerator(values, 10); | |
| 67 | + const onError = vi.fn(); | |
| 68 | + | |
| 69 | + const lg = new ListenableGenerator<number>( | |
| 70 | + source, | |
| 71 | + onError, | |
| 72 | + new AbortController(), | |
| 73 | + ); | |
| 74 | + | |
| 75 | + const initialListener = vi.fn(); | |
| 76 | + | |
| 77 | + lg.listen(initialListener); | |
| 78 | + | |
| 79 | + // Wait for the first value to be yielded | |
| 80 | + await new Promise((resolve) => setTimeout(resolve, 15)); | |
| 81 | + | |
| 82 | + // Add a second listener | |
| 83 | + const newListener = vi.fn(); | |
| 84 | + lg.listen(newListener); | |
| 85 | + | |
| 86 | + // Wait for generator to finish | |
| 87 | + await new Promise((resolve) => setTimeout(resolve, 50)); | |
| 88 | + | |
| 89 | + // Both listeners should have received all values | |
| 90 | + [initialListener, newListener].forEach((listener) => { | |
| 91 | + expect(listener).toHaveBeenCalledWith(1); | |
| 92 | + expect(listener).toHaveBeenCalledWith(2); | |
| 93 | + expect(listener).toHaveBeenCalledWith(3); | |
| 94 | + expect(listener).toHaveBeenCalledWith(null); | |
| 95 | + }); | |
| 96 | + }); | |
| 97 | + | |
| 98 | + it("should handle cancellation", async () => { | |
| 99 | + const values = [1, 2, 3, 4, 5]; | |
| 100 | + const source = asyncGenerator(values, 10); | |
| 101 | + const onError = vi.fn(); | |
| 102 | + | |
| 103 | + const lg = new ListenableGenerator<number>( | |
| 104 | + source, | |
| 105 | + onError, | |
| 106 | + new AbortController(), | |
| 107 | + ); | |
| 108 | + | |
| 109 | + const result: number[] = []; | |
| 110 | + const teeIterator = lg.tee(); | |
| 111 | + | |
| 112 | + const consume = async () => { | |
| 113 | + for await (const value of teeIterator) { | |
| 114 | + result.push(value); | |
| 115 | + if (value === 3) { | |
| 116 | + lg.cancel(); | |
| 117 | + } | |
| 118 | + } | |
| 119 | + }; | |
| 120 | + | |
| 121 | + await consume(); | |
| 122 | + | |
| 123 | + expect(result).toEqual([1, 2, 3]); | |
| 124 | + expect(lg["_isEnded"]).toBe(true); | |
| 125 | + }); | |
| 126 | + | |
| 127 | + it("should call onError when the source generator throws an error", async () => { | |
| 128 | + async function* errorGenerator() { | |
| 129 | + yield 1; | |
| 130 | + throw new Error("Test error"); | |
| 131 | + } | |
| 132 | + | |
| 133 | + const source = errorGenerator(); | |
| 134 | + const onError = vi.fn(); | |
| 135 | + | |
| 136 | + const lg = new ListenableGenerator<number>( | |
| 137 | + source, | |
| 138 | + onError, | |
| 139 | + new AbortController(), | |
| 140 | + ); | |
| 141 | + | |
| 142 | + const result: number[] = []; | |
| 143 | + for await (const value of lg.tee()) { | |
| 144 | + result.push(value); | |
| 145 | + } | |
| 146 | + | |
| 147 | + expect(result).toEqual([1]); | |
| 148 | + expect(onError).toHaveBeenCalledTimes(1); | |
| 149 | + expect(onError).toHaveBeenCalledWith(new Error("Test error")); | |
| 150 | + }); | |
| 151 | + | |
| 152 | + it("should notify listeners when the generator ends", async () => { | |
| 153 | + const values = [1, 2, 3]; | |
| 154 | + const source = asyncGenerator(values); | |
| 155 | + const onError = vi.fn(); | |
| 156 | + | |
| 157 | + const lg = new ListenableGenerator<number>( | |
| 158 | + source, | |
| 159 | + onError, | |
| 160 | + new AbortController(), | |
| 161 | + ); | |
| 162 | + | |
| 163 | + const listener = vi.fn(); | |
| 164 | + lg.listen(listener); | |
| 165 | + | |
| 166 | + // Wait for the generator to finish | |
| 167 | + await new Promise((resolve) => setTimeout(resolve, 10)); | |
| 168 | + | |
| 169 | + expect(listener).toHaveBeenCalledWith(1); | |
| 170 | + expect(listener).toHaveBeenCalledWith(2); | |
| 171 | + expect(listener).toHaveBeenCalledWith(3); | |
| 172 | + expect(listener).toHaveBeenCalledWith(null); | |
| 173 | + }); | |
| 174 | +}); |
deleted core/autocomplete/generation/utils.test.ts +0 −138
| @@ -1,138 +0,0 @@ | ||
| 1 | -import { jest } from "@jest/globals"; | |
| 2 | -import { stopAfterMaxProcessingTime } from "./utils"; | |
| 3 | - | |
| 4 | -describe("stopAfterMaxProcessingTime", () => { | |
| 5 | - beforeEach(() => { | |
| 6 | - jest.useFakeTimers(); | |
| 7 | - }); | |
| 8 | - | |
| 9 | - afterEach(() => { | |
| 10 | - jest.useRealTimers(); | |
| 11 | - }); | |
| 12 | - | |
| 13 | - async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 14 | - for (const chunk of chunks) { | |
| 15 | - yield chunk; | |
| 16 | - } | |
| 17 | - } | |
| 18 | - | |
| 19 | - async function streamToString( | |
| 20 | - stream: AsyncGenerator<string>, | |
| 21 | - ): Promise<string> { | |
| 22 | - let result = ""; | |
| 23 | - for await (const chunk of stream) { | |
| 24 | - result += chunk; | |
| 25 | - } | |
| 26 | - return result; | |
| 27 | - } | |
| 28 | - | |
| 29 | - it("should yield all chunks when maxTimeMs is not reached", async () => { | |
| 30 | - const mockStream = createMockStream(["Hello", " world", "!"]); | |
| 31 | - const fullStop = jest.fn(); | |
| 32 | - const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 33 | - | |
| 34 | - const output = await streamToString(result); | |
| 35 | - | |
| 36 | - expect(output).toBe("Hello world!"); | |
| 37 | - expect(fullStop).not.toHaveBeenCalled(); | |
| 38 | - }); | |
| 39 | - | |
| 40 | - it.only("should stop processing after max time is reached", async () => { | |
| 41 | - // Mock implementation of Date.now | |
| 42 | - let currentTime = 0; | |
| 43 | - const originalDateNow = Date.now; | |
| 44 | - Date.now = jest.fn(() => currentTime); | |
| 45 | - | |
| 46 | - // Create a generator that we can control | |
| 47 | - async function* controlledGenerator(): AsyncGenerator<string> { | |
| 48 | - for (let i = 0; i < 100; i++) { | |
| 49 | - // After yielding 10 chunks, simulate time passing beyond our limit | |
| 50 | - if (i === 10) { | |
| 51 | - currentTime = 1000; // This exceeds our 500ms limit | |
| 52 | - } | |
| 53 | - yield `chunk-${i}`; | |
| 54 | - } | |
| 55 | - } | |
| 56 | - | |
| 57 | - const fullStop = jest.fn(); | |
| 58 | - const maxTimeMs = 500; | |
| 59 | - | |
| 60 | - const transformedGenerator = stopAfterMaxProcessingTime( | |
| 61 | - controlledGenerator(), | |
| 62 | - maxTimeMs, | |
| 63 | - fullStop, | |
| 64 | - ); | |
| 65 | - | |
| 66 | - // Consume the generator and collect outputs | |
| 67 | - const outputs: string[] = []; | |
| 68 | - for await (const chunk of transformedGenerator) { | |
| 69 | - outputs.push(chunk); | |
| 70 | - } | |
| 71 | - | |
| 72 | - // We expect: | |
| 73 | - // 1. Not all chunks were processed (less than 100) | |
| 74 | - // 2. fullStop was called | |
| 75 | - // 3. We processed at least the chunks before time was exceeded | |
| 76 | - expect(outputs.length).toBeLessThan(100); | |
| 77 | - expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks | |
| 78 | - expect(fullStop).toHaveBeenCalled(); | |
| 79 | - | |
| 80 | - // Restore Date.now | |
| 81 | - Date.now = originalDateNow; | |
| 82 | - }); | |
| 83 | - | |
| 84 | - it("should check time only periodically based on checkInterval", async () => { | |
| 85 | - const chunks = Array(100).fill("x"); | |
| 86 | - const mockStream = createMockStream(chunks); | |
| 87 | - const fullStop = jest.fn(); | |
| 88 | - | |
| 89 | - // Spy on Date.now to count how many times it's called | |
| 90 | - const dateSpy = jest.spyOn(Date, "now"); | |
| 91 | - | |
| 92 | - // Stream should complete normally (not hitting the timeout) | |
| 93 | - await streamToString( | |
| 94 | - stopAfterMaxProcessingTime(mockStream, 10000, fullStop), | |
| 95 | - ); | |
| 96 | - | |
| 97 | - // The first call is to set startTime, then once every checkInterval (10) chunks | |
| 98 | - // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls | |
| 99 | - // We use a range because implementation details might vary slightly | |
| 100 | - expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1); | |
| 101 | - expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15); | |
| 102 | - | |
| 103 | - dateSpy.mockRestore(); | |
| 104 | - }); | |
| 105 | - | |
| 106 | - it("should handle empty stream gracefully", async () => { | |
| 107 | - const mockStream = createMockStream([]); | |
| 108 | - const fullStop = jest.fn(); | |
| 109 | - const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 110 | - | |
| 111 | - const output = await streamToString(result); | |
| 112 | - | |
| 113 | - expect(output).toBe(""); | |
| 114 | - expect(fullStop).not.toHaveBeenCalled(); | |
| 115 | - }); | |
| 116 | - | |
| 117 | - it("should pass through all chunks if there's no timeout", async () => { | |
| 118 | - const chunks = Array(100).fill("test chunk"); | |
| 119 | - const mockStream = createMockStream(chunks); | |
| 120 | - const fullStop = jest.fn(); | |
| 121 | - | |
| 122 | - // Use undefined as timeout to simulate no timeout | |
| 123 | - const result = stopAfterMaxProcessingTime( | |
| 124 | - mockStream, | |
| 125 | - undefined as any, | |
| 126 | - fullStop, | |
| 127 | - ); | |
| 128 | - | |
| 129 | - // Process the stream | |
| 130 | - const processedChunks = []; | |
| 131 | - for await (const chunk of result) { | |
| 132 | - processedChunks.push(chunk); | |
| 133 | - } | |
| 134 | - | |
| 135 | - expect(processedChunks.length).toBe(chunks.length); | |
| 136 | - expect(fullStop).not.toHaveBeenCalled(); | |
| 137 | - }); | |
| 138 | -}); |
added core/autocomplete/generation/utils.vitest.ts +138 −0
| @@ -0,0 +1,138 @@ | ||
| 1 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 2 | +import { stopAfterMaxProcessingTime } from "./utils"; | |
| 3 | + | |
| 4 | +describe("stopAfterMaxProcessingTime", () => { | |
| 5 | + beforeEach(() => { | |
| 6 | + vi.useFakeTimers(); | |
| 7 | + }); | |
| 8 | + | |
| 9 | + afterEach(() => { | |
| 10 | + vi.useRealTimers(); | |
| 11 | + }); | |
| 12 | + | |
| 13 | + async function* createMockStream(chunks: string[]): AsyncGenerator<string> { | |
| 14 | + for (const chunk of chunks) { | |
| 15 | + yield chunk; | |
| 16 | + } | |
| 17 | + } | |
| 18 | + | |
| 19 | + async function streamToString( | |
| 20 | + stream: AsyncGenerator<string>, | |
| 21 | + ): Promise<string> { | |
| 22 | + let result = ""; | |
| 23 | + for await (const chunk of stream) { | |
| 24 | + result += chunk; | |
| 25 | + } | |
| 26 | + return result; | |
| 27 | + } | |
| 28 | + | |
| 29 | + it("should yield all chunks when maxTimeMs is not reached", async () => { | |
| 30 | + const mockStream = createMockStream(["Hello", " world", "!"]); | |
| 31 | + const fullStop = vi.fn(); | |
| 32 | + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 33 | + | |
| 34 | + const output = await streamToString(result); | |
| 35 | + | |
| 36 | + expect(output).toBe("Hello world!"); | |
| 37 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 38 | + }); | |
| 39 | + | |
| 40 | + it("should stop processing after max time is reached", async () => { | |
| 41 | + // Mock implementation of Date.now | |
| 42 | + let currentTime = 0; | |
| 43 | + const originalDateNow = Date.now; | |
| 44 | + Date.now = vi.fn(() => currentTime); | |
| 45 | + | |
| 46 | + // Create a generator that we can control | |
| 47 | + async function* controlledGenerator(): AsyncGenerator<string> { | |
| 48 | + for (let i = 0; i < 100; i++) { | |
| 49 | + // After yielding 10 chunks, simulate time passing beyond our limit | |
| 50 | + if (i === 10) { | |
| 51 | + currentTime = 1000; // This exceeds our 500ms limit | |
| 52 | + } | |
| 53 | + yield `chunk-${i}`; | |
| 54 | + } | |
| 55 | + } | |
| 56 | + | |
| 57 | + const fullStop = vi.fn(); | |
| 58 | + const maxTimeMs = 500; | |
| 59 | + | |
| 60 | + const transformedGenerator = stopAfterMaxProcessingTime( | |
| 61 | + controlledGenerator(), | |
| 62 | + maxTimeMs, | |
| 63 | + fullStop, | |
| 64 | + ); | |
| 65 | + | |
| 66 | + // Consume the generator and collect outputs | |
| 67 | + const outputs: string[] = []; | |
| 68 | + for await (const chunk of transformedGenerator) { | |
| 69 | + outputs.push(chunk); | |
| 70 | + } | |
| 71 | + | |
| 72 | + // We expect: | |
| 73 | + // 1. Not all chunks were processed (less than 100) | |
| 74 | + // 2. fullStop was called | |
| 75 | + // 3. We processed at least the chunks before time was exceeded | |
| 76 | + expect(outputs.length).toBeLessThan(100); | |
| 77 | + expect(outputs.length).toBeGreaterThanOrEqual(10); // We should get at least the first 10 chunks | |
| 78 | + expect(fullStop).toHaveBeenCalled(); | |
| 79 | + | |
| 80 | + // Restore Date.now | |
| 81 | + Date.now = originalDateNow; | |
| 82 | + }); | |
| 83 | + | |
| 84 | + it("should check time only periodically based on checkInterval", async () => { | |
| 85 | + const chunks = Array(100).fill("x"); | |
| 86 | + const mockStream = createMockStream(chunks); | |
| 87 | + const fullStop = vi.fn(); | |
| 88 | + | |
| 89 | + // Spy on Date.now to count how many times it's called | |
| 90 | + const dateSpy = vi.spyOn(Date, "now"); | |
| 91 | + | |
| 92 | + // Stream should complete normally (not hitting the timeout) | |
| 93 | + await streamToString( | |
| 94 | + stopAfterMaxProcessingTime(mockStream, 10000, fullStop), | |
| 95 | + ); | |
| 96 | + | |
| 97 | + // The first call is to set startTime, then once every checkInterval (10) chunks | |
| 98 | + // So for 100 chunks, we expect startTime + ~10 checks = ~11 calls | |
| 99 | + // We use a range because implementation details might vary slightly | |
| 100 | + expect(dateSpy.mock.calls.length).toBeGreaterThanOrEqual(1); | |
| 101 | + expect(dateSpy.mock.calls.length).toBeLessThanOrEqual(15); | |
| 102 | + | |
| 103 | + dateSpy.mockRestore(); | |
| 104 | + }); | |
| 105 | + | |
| 106 | + it("should handle empty stream gracefully", async () => { | |
| 107 | + const mockStream = createMockStream([]); | |
| 108 | + const fullStop = vi.fn(); | |
| 109 | + const result = stopAfterMaxProcessingTime(mockStream, 1000, fullStop); | |
| 110 | + | |
| 111 | + const output = await streamToString(result); | |
| 112 | + | |
| 113 | + expect(output).toBe(""); | |
| 114 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 115 | + }); | |
| 116 | + | |
| 117 | + it("should pass through all chunks if there's no timeout", async () => { | |
| 118 | + const chunks = Array(100).fill("test chunk"); | |
| 119 | + const mockStream = createMockStream(chunks); | |
| 120 | + const fullStop = vi.fn(); | |
| 121 | + | |
| 122 | + // Use undefined as timeout to simulate no timeout | |
| 123 | + const result = stopAfterMaxProcessingTime( | |
| 124 | + mockStream, | |
| 125 | + undefined as any, | |
| 126 | + fullStop, | |
| 127 | + ); | |
| 128 | + | |
| 129 | + // Process the stream | |
| 130 | + const processedChunks = []; | |
| 131 | + for await (const chunk of result) { | |
| 132 | + processedChunks.push(chunk); | |
| 133 | + } | |
| 134 | + | |
| 135 | + expect(processedChunks.length).toBe(chunks.length); | |
| 136 | + expect(fullStop).not.toHaveBeenCalled(); | |
| 137 | + }); | |
| 138 | +}); |
deleted core/autocomplete/snippets/gitDiffCache.test.ts +0 −84
| @@ -1,84 +0,0 @@ | ||
| 1 | -import { GitDiffCache } from "./gitDiffCache"; | |
| 2 | - | |
| 3 | -beforeEach(() => { | |
| 4 | - // Add this line to GitDiffCache class to make instance accessible | |
| 5 | - (GitDiffCache as any).instance = null; | |
| 6 | -}); | |
| 7 | - | |
| 8 | -test("GitDiffCache returns cached results within cache time", async () => { | |
| 9 | - const mockDiff = ["file1.ts", "file2.ts"]; | |
| 10 | - const getDiffFn = jest.fn().mockResolvedValue(mockDiff); | |
| 11 | - const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache | |
| 12 | - | |
| 13 | - const result1 = await cache.get(); | |
| 14 | - const result2 = await cache.get(); | |
| 15 | - | |
| 16 | - expect(result1).toEqual(mockDiff); | |
| 17 | - expect(result2).toEqual(mockDiff); | |
| 18 | - expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 19 | -}); | |
| 20 | - | |
| 21 | -test("GitDiffCache refreshes cache after expiration", async () => { | |
| 22 | - const mockDiff = ["file1.ts"]; | |
| 23 | - const getDiffFn = jest.fn().mockResolvedValue(mockDiff); | |
| 24 | - const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache | |
| 25 | - | |
| 26 | - const result1 = await cache.get(); | |
| 27 | - await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire | |
| 28 | - const result2 = await cache.get(); | |
| 29 | - | |
| 30 | - expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 31 | -}); | |
| 32 | - | |
| 33 | -test("GitDiffCache returns empty array on error", async () => { | |
| 34 | - const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error")); | |
| 35 | - const cache = GitDiffCache.getInstance(getDiffFn); | |
| 36 | - | |
| 37 | - const result = await cache.get(); | |
| 38 | - expect(result).toEqual([]); | |
| 39 | -}); | |
| 40 | - | |
| 41 | -test("GitDiffCache reuses pending request", async () => { | |
| 42 | - const mockDiff = ["file1.ts"]; | |
| 43 | - let resolvePromise: (value: string[]) => void; | |
| 44 | - const getDiffFn = jest.fn().mockImplementation(() => { | |
| 45 | - return new Promise((resolve) => { | |
| 46 | - resolvePromise = resolve; | |
| 47 | - }); | |
| 48 | - }); | |
| 49 | - | |
| 50 | - const cache = GitDiffCache.getInstance(getDiffFn); | |
| 51 | - | |
| 52 | - const promise1 = cache.get(); | |
| 53 | - const promise2 = cache.get(); | |
| 54 | - | |
| 55 | - resolvePromise!(mockDiff); | |
| 56 | - | |
| 57 | - const [result1, result2] = await Promise.all([promise1, promise2]); | |
| 58 | - | |
| 59 | - expect(result1).toEqual(mockDiff); | |
| 60 | - expect(result2).toEqual(mockDiff); | |
| 61 | - expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 62 | -}); | |
| 63 | - | |
| 64 | -test("GitDiffCache invalidate clears cache", async () => { | |
| 65 | - const mockDiff = ["file1.ts"]; | |
| 66 | - const getDiffFn = jest.fn().mockResolvedValue(mockDiff); | |
| 67 | - const cache = GitDiffCache.getInstance(getDiffFn); | |
| 68 | - | |
| 69 | - await cache.get(); | |
| 70 | - cache.invalidate(); | |
| 71 | - await cache.get(); | |
| 72 | - | |
| 73 | - expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 74 | -}); | |
| 75 | - | |
| 76 | -test("GitDiffCache maintains singleton instance", () => { | |
| 77 | - const getDiffFn1 = jest.fn(); | |
| 78 | - const getDiffFn2 = jest.fn(); | |
| 79 | - | |
| 80 | - const instance1 = GitDiffCache.getInstance(getDiffFn1); | |
| 81 | - const instance2 = GitDiffCache.getInstance(getDiffFn2); | |
| 82 | - | |
| 83 | - expect(instance1).toBe(instance2); | |
| 84 | -}); |
added core/autocomplete/snippets/gitDiffCache.vitest.ts +85 −0
| @@ -0,0 +1,85 @@ | ||
| 1 | +import { beforeEach, expect, test, vi } from "vitest"; | |
| 2 | +import { GitDiffCache } from "./gitDiffCache"; | |
| 3 | + | |
| 4 | +beforeEach(() => { | |
| 5 | + // Add this line to GitDiffCache class to make instance accessible | |
| 6 | + (GitDiffCache as any).instance = null; | |
| 7 | +}); | |
| 8 | + | |
| 9 | +test("GitDiffCache returns cached results within cache time", async () => { | |
| 10 | + const mockDiff = ["file1.ts", "file2.ts"]; | |
| 11 | + const getDiffFn = vi.fn().mockResolvedValue(mockDiff); | |
| 12 | + const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache | |
| 13 | + | |
| 14 | + const result1 = await cache.get(); | |
| 15 | + const result2 = await cache.get(); | |
| 16 | + | |
| 17 | + expect(result1).toEqual(mockDiff); | |
| 18 | + expect(result2).toEqual(mockDiff); | |
| 19 | + expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 20 | +}); | |
| 21 | + | |
| 22 | +test("GitDiffCache refreshes cache after expiration", async () => { | |
| 23 | + const mockDiff = ["file1.ts"]; | |
| 24 | + const getDiffFn = vi.fn().mockResolvedValue(mockDiff); | |
| 25 | + const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache | |
| 26 | + | |
| 27 | + const result1 = await cache.get(); | |
| 28 | + await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire | |
| 29 | + const result2 = await cache.get(); | |
| 30 | + | |
| 31 | + expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 32 | +}); | |
| 33 | + | |
| 34 | +test("GitDiffCache returns empty array on error", async () => { | |
| 35 | + const getDiffFn = vi.fn().mockRejectedValue(new Error("Git error")); | |
| 36 | + const cache = GitDiffCache.getInstance(getDiffFn); | |
| 37 | + | |
| 38 | + const result = await cache.get(); | |
| 39 | + expect(result).toEqual([]); | |
| 40 | +}); | |
| 41 | + | |
| 42 | +test("GitDiffCache reuses pending request", async () => { | |
| 43 | + const mockDiff = ["file1.ts"]; | |
| 44 | + let resolvePromise: (value: string[]) => void; | |
| 45 | + const getDiffFn = vi.fn().mockImplementation(() => { | |
| 46 | + return new Promise((resolve) => { | |
| 47 | + resolvePromise = resolve; | |
| 48 | + }); | |
| 49 | + }); | |
| 50 | + | |
| 51 | + const cache = GitDiffCache.getInstance(getDiffFn); | |
| 52 | + | |
| 53 | + const promise1 = cache.get(); | |
| 54 | + const promise2 = cache.get(); | |
| 55 | + | |
| 56 | + resolvePromise!(mockDiff); | |
| 57 | + | |
| 58 | + const [result1, result2] = await Promise.all([promise1, promise2]); | |
| 59 | + | |
| 60 | + expect(result1).toEqual(mockDiff); | |
| 61 | + expect(result2).toEqual(mockDiff); | |
| 62 | + expect(getDiffFn).toHaveBeenCalledTimes(1); | |
| 63 | +}); | |
| 64 | + | |
| 65 | +test("GitDiffCache invalidate clears cache", async () => { | |
| 66 | + const mockDiff = ["file1.ts"]; | |
| 67 | + const getDiffFn = vi.fn().mockResolvedValue(mockDiff); | |
| 68 | + const cache = GitDiffCache.getInstance(getDiffFn); | |
| 69 | + | |
| 70 | + await cache.get(); | |
| 71 | + cache.invalidate(); | |
| 72 | + await cache.get(); | |
| 73 | + | |
| 74 | + expect(getDiffFn).toHaveBeenCalledTimes(2); | |
| 75 | +}); | |
| 76 | + | |
| 77 | +test("GitDiffCache maintains singleton instance", () => { | |
| 78 | + const getDiffFn1 = vi.fn(); | |
| 79 | + const getDiffFn2 = vi.fn(); | |
| 80 | + | |
| 81 | + const instance1 = GitDiffCache.getInstance(getDiffFn1); | |
| 82 | + const instance2 = GitDiffCache.getInstance(getDiffFn2); | |
| 83 | + | |
| 84 | + expect(instance1).toBe(instance2); | |
| 85 | +}); |
deleted core/autocomplete/templating/__tests__/formatOpenedFilesContext.test.ts +0 −434
| @@ -1,434 +0,0 @@ | ||
| 1 | -/** | |
| 2 | - * Comprehensive tests for formatOpenedFilesContext.ts | |
| 3 | - * | |
| 4 | - */ | |
| 5 | - | |
| 6 | -import { | |
| 7 | - AutocompleteCodeSnippet, | |
| 8 | - AutocompleteDiffSnippet, | |
| 9 | - AutocompleteSnippetType, | |
| 10 | -} from "../../snippets/types"; | |
| 11 | -import { HelperVars } from "../../util/HelperVars"; | |
| 12 | -import { formatOpenedFilesContext } from "../formatOpenedFilesContext"; | |
| 13 | - | |
| 14 | -// Import the now-exported internal functions | |
| 15 | -import { | |
| 16 | - getRecencyAndSizeScore, | |
| 17 | - rankByScore, | |
| 18 | - setLogStats, | |
| 19 | - trimSnippetForContext, | |
| 20 | -} from "../formatOpenedFilesContext"; | |
| 21 | - | |
| 22 | -describe("formatOpenedFilesContext main function tests", () => { | |
| 23 | - const mockHelper = { | |
| 24 | - modelName: "test-model", | |
| 25 | - } as HelperVars; | |
| 26 | - | |
| 27 | - const TOKEN_BUFFER = 50; | |
| 28 | - | |
| 29 | - // Create sample code snippets with various sizes | |
| 30 | - const createCodeSnippet = ( | |
| 31 | - filepath: string, | |
| 32 | - content: string, | |
| 33 | - ): AutocompleteCodeSnippet => ({ | |
| 34 | - type: AutocompleteSnippetType.Code, | |
| 35 | - filepath, | |
| 36 | - content, | |
| 37 | - }); | |
| 38 | - | |
| 39 | - const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({ | |
| 40 | - type: AutocompleteSnippetType.Diff, | |
| 41 | - content, | |
| 42 | - }); | |
| 43 | - | |
| 44 | - test("should return empty array when no snippets are provided", () => { | |
| 45 | - const result = formatOpenedFilesContext( | |
| 46 | - [], | |
| 47 | - 1000, | |
| 48 | - mockHelper, | |
| 49 | - [], | |
| 50 | - TOKEN_BUFFER, | |
| 51 | - ); | |
| 52 | - expect(result).toEqual([]); | |
| 53 | - }); | |
| 54 | - | |
| 55 | - test("should handle zero remaining token count", () => { | |
| 56 | - const snippets = [ | |
| 57 | - createCodeSnippet("file1.ts", "content of file 1"), | |
| 58 | - createCodeSnippet("file2.ts", "content of file 2"), | |
| 59 | - ]; | |
| 60 | - | |
| 61 | - const result = formatOpenedFilesContext( | |
| 62 | - snippets, | |
| 63 | - 0, | |
| 64 | - mockHelper, | |
| 65 | - [], | |
| 66 | - TOKEN_BUFFER, | |
| 67 | - ); | |
| 68 | - | |
| 69 | - expect(result).toEqual([]); | |
| 70 | - }); | |
| 71 | - | |
| 72 | - test("should handle snippets with empty content", () => { | |
| 73 | - const emptySnippets = [ | |
| 74 | - createCodeSnippet("empty1.ts", ""), | |
| 75 | - createCodeSnippet("empty2.ts", ""), | |
| 76 | - ]; | |
| 77 | - | |
| 78 | - const result = formatOpenedFilesContext( | |
| 79 | - emptySnippets, | |
| 80 | - 1000, | |
| 81 | - mockHelper, | |
| 82 | - [], | |
| 83 | - TOKEN_BUFFER, | |
| 84 | - ); | |
| 85 | - | |
| 86 | - expect(result.length).toBe(emptySnippets.length); | |
| 87 | - }); | |
| 88 | - | |
| 89 | - test("should return all snippets when they all fit within token limit", () => { | |
| 90 | - const smallSnippets = [ | |
| 91 | - createCodeSnippet("small1.ts", "a"), | |
| 92 | - createCodeSnippet("small2.ts", "b"), | |
| 93 | - createCodeSnippet("small3.ts", "c"), | |
| 94 | - ]; | |
| 95 | - | |
| 96 | - const result = formatOpenedFilesContext( | |
| 97 | - smallSnippets, | |
| 98 | - 1000, | |
| 99 | - mockHelper, | |
| 100 | - [], | |
| 101 | - TOKEN_BUFFER, | |
| 102 | - ); | |
| 103 | - | |
| 104 | - expect(result.length).toBe(smallSnippets.length); | |
| 105 | - }); | |
| 106 | - | |
| 107 | - test("should handle limited token count", () => { | |
| 108 | - const snippets = Array(10) | |
| 109 | - .fill(0) | |
| 110 | - .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 111 | - | |
| 112 | - const result = formatOpenedFilesContext( | |
| 113 | - snippets, | |
| 114 | - 1, // Extremely small token count | |
| 115 | - mockHelper, | |
| 116 | - [], | |
| 117 | - TOKEN_BUFFER, | |
| 118 | - ); | |
| 119 | - | |
| 120 | - expect(Array.isArray(result)).toBe(true); | |
| 121 | - }); | |
| 122 | - | |
| 123 | - test("should accept valid inputs with adequate token count", () => { | |
| 124 | - const snippets = [ | |
| 125 | - createCodeSnippet("file1.ts", "Some content here"), | |
| 126 | - createCodeSnippet("file2.ts", "More content here"), | |
| 127 | - ]; | |
| 128 | - | |
| 129 | - const result = formatOpenedFilesContext( | |
| 130 | - snippets, | |
| 131 | - 1000, | |
| 132 | - mockHelper, | |
| 133 | - [], | |
| 134 | - TOKEN_BUFFER, | |
| 135 | - ); | |
| 136 | - | |
| 137 | - expect(result.length).toBeGreaterThan(0); | |
| 138 | - }); | |
| 139 | - | |
| 140 | - test("should handle already added snippets parameter", () => { | |
| 141 | - const snippets = [ | |
| 142 | - createCodeSnippet("file1.ts", "content of file 1"), | |
| 143 | - createCodeSnippet("file2.ts", "content of file 2"), | |
| 144 | - ]; | |
| 145 | - | |
| 146 | - const alreadyAddedSnippets = [createDiffSnippet("diff content")]; | |
| 147 | - | |
| 148 | - const result = formatOpenedFilesContext( | |
| 149 | - snippets, | |
| 150 | - 1000, | |
| 151 | - mockHelper, | |
| 152 | - alreadyAddedSnippets, | |
| 153 | - TOKEN_BUFFER, | |
| 154 | - ); | |
| 155 | - | |
| 156 | - expect(result.length).toBe(snippets.length); | |
| 157 | - }); | |
| 158 | - | |
| 159 | - test("should handle large snippets by trimming them", () => { | |
| 160 | - const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000)); | |
| 161 | - | |
| 162 | - const result = formatOpenedFilesContext( | |
| 163 | - [largeSnippet], | |
| 164 | - 200, | |
| 165 | - mockHelper, | |
| 166 | - [], | |
| 167 | - TOKEN_BUFFER, | |
| 168 | - ); | |
| 169 | - | |
| 170 | - expect(result.length).toBe(1); | |
| 171 | - expect(result[0].filepath).toBe(largeSnippet.filepath); | |
| 172 | - expect(result[0].content.length).toBeLessThan(largeSnippet.content.length); | |
| 173 | - }); | |
| 174 | - | |
| 175 | - test("should prioritize more recent snippets when not all fit", () => { | |
| 176 | - const snippets = [ | |
| 177 | - createCodeSnippet("recent1.ts", "a".repeat(10)), | |
| 178 | - createCodeSnippet("recent2.ts", "b".repeat(10000)), | |
| 179 | - createCodeSnippet("recent3.ts", "c".repeat(10000)), | |
| 180 | - ]; | |
| 181 | - | |
| 182 | - const result = formatOpenedFilesContext( | |
| 183 | - snippets, | |
| 184 | - 200, | |
| 185 | - mockHelper, | |
| 186 | - [], | |
| 187 | - TOKEN_BUFFER, | |
| 188 | - ); | |
| 189 | - | |
| 190 | - expect(result.length).toBeGreaterThan(0); | |
| 191 | - expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true); | |
| 192 | - }); | |
| 193 | - | |
| 194 | - test("should handle a mix of large and small snippets effectively", () => { | |
| 195 | - const mixedSnippets = [ | |
| 196 | - createCodeSnippet("small1.ts", "a".repeat(10)), | |
| 197 | - createCodeSnippet("large1.ts", "b".repeat(5000)), | |
| 198 | - createCodeSnippet("small2.ts", "c".repeat(10)), | |
| 199 | - createCodeSnippet("large2.ts", "d".repeat(5000)), | |
| 200 | - ]; | |
| 201 | - | |
| 202 | - const result = formatOpenedFilesContext( | |
| 203 | - mixedSnippets, | |
| 204 | - 500, | |
| 205 | - mockHelper, | |
| 206 | - [], | |
| 207 | - TOKEN_BUFFER, | |
| 208 | - ); | |
| 209 | - | |
| 210 | - expect(result.length).toBeGreaterThan(0); | |
| 211 | - expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true); | |
| 212 | - }); | |
| 213 | - | |
| 214 | - test("should respect minimum token threshold when trimming", () => { | |
| 215 | - const largeSnippets = [ | |
| 216 | - createCodeSnippet("large1.ts", "a".repeat(5000)), | |
| 217 | - createCodeSnippet("large2.ts", "b".repeat(5000)), | |
| 218 | - ]; | |
| 219 | - | |
| 220 | - const result = formatOpenedFilesContext( | |
| 221 | - largeSnippets, | |
| 222 | - 150, | |
| 223 | - mockHelper, | |
| 224 | - [], | |
| 225 | - TOKEN_BUFFER, | |
| 226 | - ); | |
| 227 | - | |
| 228 | - expect(result.length).toBeLessThanOrEqual(1); | |
| 229 | - | |
| 230 | - if (result.length > 0) { | |
| 231 | - expect(result[0].content.length).toBeLessThan( | |
| 232 | - largeSnippets[0].content.length, | |
| 233 | - ); | |
| 234 | - } | |
| 235 | - }); | |
| 236 | -}); | |
| 237 | - | |
| 238 | -// Tests for rankByScore function | |
| 239 | -describe("rankByScore function", () => { | |
| 240 | - const createCodeSnippet = ( | |
| 241 | - filepath: string, | |
| 242 | - content: string, | |
| 243 | - ): AutocompleteCodeSnippet => ({ | |
| 244 | - type: AutocompleteSnippetType.Code, | |
| 245 | - filepath, | |
| 246 | - content, | |
| 247 | - }); | |
| 248 | - | |
| 249 | - test("should return empty array when given empty array", () => { | |
| 250 | - const result = rankByScore([]); | |
| 251 | - expect(result).toEqual([]); | |
| 252 | - }); | |
| 253 | - | |
| 254 | - test("should rank snippets by score", () => { | |
| 255 | - // Initialize logMin and logMax by calling setLogStats first | |
| 256 | - const snippets = [ | |
| 257 | - createCodeSnippet("file1.ts", "a".repeat(10)), | |
| 258 | - createCodeSnippet("file2.ts", "b".repeat(1000)), | |
| 259 | - createCodeSnippet("file3.ts", "c".repeat(100)), | |
| 260 | - ]; | |
| 261 | - setLogStats(snippets); | |
| 262 | - | |
| 263 | - const result = rankByScore(snippets); | |
| 264 | - | |
| 265 | - expect(Array.isArray(result)).toBe(true); | |
| 266 | - expect(result.length).toBeGreaterThan(0); | |
| 267 | - | |
| 268 | - // The snippets should be ranked in some order, which may not match input order | |
| 269 | - expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual( | |
| 270 | - snippets.map((s) => s.filepath), | |
| 271 | - ); | |
| 272 | - }); | |
| 273 | - | |
| 274 | - test("should limit the number of ranked snippets to defaultNumFilesUsed", () => { | |
| 275 | - // Create more snippets than the default limit | |
| 276 | - const manySnippets = Array(10) | |
| 277 | - .fill(0) | |
| 278 | - .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 279 | - setLogStats(manySnippets); | |
| 280 | - | |
| 281 | - const result = rankByScore(manySnippets); | |
| 282 | - | |
| 283 | - // The function should limit the number of snippets (defaultNumFilesUsed is 5) | |
| 284 | - expect(result.length).toBeLessThanOrEqual(5); | |
| 285 | - }); | |
| 286 | -}); | |
| 287 | - | |
| 288 | -// Tests for getRecencyAndSizeScore function | |
| 289 | -describe("getRecencyAndSizeScore function", () => { | |
| 290 | - const createCodeSnippet = ( | |
| 291 | - filepath: string, | |
| 292 | - content: string, | |
| 293 | - ): AutocompleteCodeSnippet => ({ | |
| 294 | - type: AutocompleteSnippetType.Code, | |
| 295 | - filepath, | |
| 296 | - content, | |
| 297 | - }); | |
| 298 | - | |
| 299 | - test("recency score should decrease with higher index", () => { | |
| 300 | - // Initialize log stats first | |
| 301 | - const snippets = [ | |
| 302 | - createCodeSnippet("file1.ts", "a".repeat(100)), | |
| 303 | - createCodeSnippet("file2.ts", "b".repeat(100)), | |
| 304 | - ]; | |
| 305 | - setLogStats(snippets); | |
| 306 | - | |
| 307 | - // Test that score decreases with increasing index | |
| 308 | - const score0 = getRecencyAndSizeScore(0, snippets[0]); | |
| 309 | - const score1 = getRecencyAndSizeScore(1, snippets[0]); | |
| 310 | - const score2 = getRecencyAndSizeScore(2, snippets[0]); | |
| 311 | - | |
| 312 | - expect(score0).toBeGreaterThan(score1); | |
| 313 | - expect(score1).toBeGreaterThan(score2); | |
| 314 | - }); | |
| 315 | - | |
| 316 | - test("size score should be higher for smaller snippets", () => { | |
| 317 | - // Initialize log stats first | |
| 318 | - const snippets = [ | |
| 319 | - createCodeSnippet("small.ts", "a".repeat(50)), | |
| 320 | - createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 321 | - createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 322 | - ]; | |
| 323 | - setLogStats(snippets); | |
| 324 | - | |
| 325 | - // Test with same recency index but different sizes | |
| 326 | - const smallScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 327 | - const mediumScore = getRecencyAndSizeScore(0, snippets[1]); | |
| 328 | - const largeScore = getRecencyAndSizeScore(0, snippets[2]); | |
| 329 | - | |
| 330 | - // Scores should reflect preference for smaller snippets | |
| 331 | - expect(smallScore).toBeGreaterThanOrEqual(mediumScore); | |
| 332 | - expect(mediumScore).toBeGreaterThanOrEqual(largeScore); | |
| 333 | - }); | |
| 334 | - | |
| 335 | - test("recency and size both affect the score with recency having more weight", () => { | |
| 336 | - // Initialize log stats first | |
| 337 | - const snippets = [ | |
| 338 | - createCodeSnippet("recent_large.ts", "a".repeat(1000)), | |
| 339 | - createCodeSnippet("old_small.ts", "b".repeat(50)), | |
| 340 | - ]; | |
| 341 | - setLogStats(snippets); | |
| 342 | - | |
| 343 | - // Test that recency and size both contribute to the score | |
| 344 | - const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 345 | - const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]); | |
| 346 | - | |
| 347 | - // We're not making a direct comparison, just verifying the scoring mechanism works | |
| 348 | - expect(recentLargeScore).toBeGreaterThan(0); | |
| 349 | - expect(oldSmallScore).toBeGreaterThan(0); | |
| 350 | - expect(oldSmallScore).toBeLessThan(1); | |
| 351 | - }); | |
| 352 | -}); | |
| 353 | - | |
| 354 | -// Tests for setLogStats function | |
| 355 | -describe("setLogStats function", () => { | |
| 356 | - const createCodeSnippet = ( | |
| 357 | - filepath: string, | |
| 358 | - content: string, | |
| 359 | - ): AutocompleteCodeSnippet => ({ | |
| 360 | - type: AutocompleteSnippetType.Code, | |
| 361 | - filepath, | |
| 362 | - content, | |
| 363 | - }); | |
| 364 | - | |
| 365 | - test("should set logMin and logMax based on snippet sizes", () => { | |
| 366 | - const snippets = [ | |
| 367 | - createCodeSnippet("small.ts", "a".repeat(50)), | |
| 368 | - createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 369 | - createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 370 | - ]; | |
| 371 | - | |
| 372 | - // We can't directly test logMin and logMax as they're private | |
| 373 | - // but we can verify that the function runs without errors | |
| 374 | - expect(() => setLogStats(snippets)).not.toThrow(); | |
| 375 | - }); | |
| 376 | - | |
| 377 | - test("should handle empty snippets", () => { | |
| 378 | - const emptySnippets = [ | |
| 379 | - createCodeSnippet("empty1.ts", ""), | |
| 380 | - createCodeSnippet("empty2.ts", ""), | |
| 381 | - ]; | |
| 382 | - | |
| 383 | - expect(() => setLogStats(emptySnippets)).not.toThrow(); | |
| 384 | - }); | |
| 385 | - | |
| 386 | - test("should handle single snippet", () => { | |
| 387 | - const singleSnippet = [createCodeSnippet("single.ts", "content")]; | |
| 388 | - | |
| 389 | - expect(() => setLogStats(singleSnippet)).not.toThrow(); | |
| 390 | - }); | |
| 391 | -}); | |
| 392 | - | |
| 393 | -// Tests for trimSnippetForContext function | |
| 394 | -describe("trimSnippetForContext function", () => { | |
| 395 | - const createCodeSnippet = ( | |
| 396 | - filepath: string, | |
| 397 | - content: string, | |
| 398 | - ): AutocompleteCodeSnippet => ({ | |
| 399 | - type: AutocompleteSnippetType.Code, | |
| 400 | - filepath, | |
| 401 | - content, | |
| 402 | - }); | |
| 403 | - | |
| 404 | - test("should return original snippet if it fits within token limit", () => { | |
| 405 | - const snippet = createCodeSnippet("small.ts", "small content"); | |
| 406 | - const modelName = "test-model"; | |
| 407 | - const maxTokens = 1000; // Large enough to fit the snippet | |
| 408 | - | |
| 409 | - const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 410 | - | |
| 411 | - // Should return the original snippet with its token count | |
| 412 | - expect(result.newSnippet).toEqual(snippet); | |
| 413 | - expect(typeof result.newTokens).toBe("number"); | |
| 414 | - expect(result.newTokens).toBeGreaterThan(0); | |
| 415 | - }); | |
| 416 | - | |
| 417 | - test("should trim snippet content if it exceeds token limit", () => { | |
| 418 | - const snippet = createCodeSnippet("large.ts", "a".repeat(1000)); | |
| 419 | - const modelName = "test-model"; | |
| 420 | - const maxTokens = 10; // Small enough to require trimming | |
| 421 | - | |
| 422 | - const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 423 | - | |
| 424 | - // Should return a trimmed snippet | |
| 425 | - expect(result.newSnippet.filepath).toBe(snippet.filepath); | |
| 426 | - expect(result.newSnippet.type).toBe(snippet.type); | |
| 427 | - expect(result.newSnippet.content.length).toBeLessThanOrEqual( | |
| 428 | - snippet.content.length, | |
| 429 | - ); | |
| 430 | - | |
| 431 | - // Token count should be less than or equal to maxTokens | |
| 432 | - expect(result.newTokens).toBeLessThanOrEqual(maxTokens); | |
| 433 | - }); | |
| 434 | -}); |
added core/autocomplete/templating/__tests__/formatOpenedFilesContext.vitest.ts +435 −0
| @@ -0,0 +1,435 @@ | ||
| 1 | +/** | |
| 2 | + * Comprehensive tests for formatOpenedFilesContext.ts | |
| 3 | + * | |
| 4 | + */ | |
| 5 | + | |
| 6 | +import { describe, expect, test } from "vitest"; | |
| 7 | +import { | |
| 8 | + AutocompleteCodeSnippet, | |
| 9 | + AutocompleteDiffSnippet, | |
| 10 | + AutocompleteSnippetType, | |
| 11 | +} from "../../snippets/types"; | |
| 12 | +import { HelperVars } from "../../util/HelperVars"; | |
| 13 | +import { formatOpenedFilesContext } from "../formatOpenedFilesContext"; | |
| 14 | + | |
| 15 | +// Import the now-exported internal functions | |
| 16 | +import { | |
| 17 | + getRecencyAndSizeScore, | |
| 18 | + rankByScore, | |
| 19 | + setLogStats, | |
| 20 | + trimSnippetForContext, | |
| 21 | +} from "../formatOpenedFilesContext"; | |
| 22 | + | |
| 23 | +describe("formatOpenedFilesContext main function tests", () => { | |
| 24 | + const mockHelper = { | |
| 25 | + modelName: "test-model", | |
| 26 | + } as HelperVars; | |
| 27 | + | |
| 28 | + const TOKEN_BUFFER = 50; | |
| 29 | + | |
| 30 | + // Create sample code snippets with various sizes | |
| 31 | + const createCodeSnippet = ( | |
| 32 | + filepath: string, | |
| 33 | + content: string, | |
| 34 | + ): AutocompleteCodeSnippet => ({ | |
| 35 | + type: AutocompleteSnippetType.Code, | |
| 36 | + filepath, | |
| 37 | + content, | |
| 38 | + }); | |
| 39 | + | |
| 40 | + const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({ | |
| 41 | + type: AutocompleteSnippetType.Diff, | |
| 42 | + content, | |
| 43 | + }); | |
| 44 | + | |
| 45 | + test("should return empty array when no snippets are provided", () => { | |
| 46 | + const result = formatOpenedFilesContext( | |
| 47 | + [], | |
| 48 | + 1000, | |
| 49 | + mockHelper, | |
| 50 | + [], | |
| 51 | + TOKEN_BUFFER, | |
| 52 | + ); | |
| 53 | + expect(result).toEqual([]); | |
| 54 | + }); | |
| 55 | + | |
| 56 | + test("should handle zero remaining token count", () => { | |
| 57 | + const snippets = [ | |
| 58 | + createCodeSnippet("file1.ts", "content of file 1"), | |
| 59 | + createCodeSnippet("file2.ts", "content of file 2"), | |
| 60 | + ]; | |
| 61 | + | |
| 62 | + const result = formatOpenedFilesContext( | |
| 63 | + snippets, | |
| 64 | + 0, | |
| 65 | + mockHelper, | |
| 66 | + [], | |
| 67 | + TOKEN_BUFFER, | |
| 68 | + ); | |
| 69 | + | |
| 70 | + expect(result).toEqual([]); | |
| 71 | + }); | |
| 72 | + | |
| 73 | + test("should handle snippets with empty content", () => { | |
| 74 | + const emptySnippets = [ | |
| 75 | + createCodeSnippet("empty1.ts", ""), | |
| 76 | + createCodeSnippet("empty2.ts", ""), | |
| 77 | + ]; | |
| 78 | + | |
| 79 | + const result = formatOpenedFilesContext( | |
| 80 | + emptySnippets, | |
| 81 | + 1000, | |
| 82 | + mockHelper, | |
| 83 | + [], | |
| 84 | + TOKEN_BUFFER, | |
| 85 | + ); | |
| 86 | + | |
| 87 | + expect(result.length).toBe(emptySnippets.length); | |
| 88 | + }); | |
| 89 | + | |
| 90 | + test("should return all snippets when they all fit within token limit", () => { | |
| 91 | + const smallSnippets = [ | |
| 92 | + createCodeSnippet("small1.ts", "a"), | |
| 93 | + createCodeSnippet("small2.ts", "b"), | |
| 94 | + createCodeSnippet("small3.ts", "c"), | |
| 95 | + ]; | |
| 96 | + | |
| 97 | + const result = formatOpenedFilesContext( | |
| 98 | + smallSnippets, | |
| 99 | + 1000, | |
| 100 | + mockHelper, | |
| 101 | + [], | |
| 102 | + TOKEN_BUFFER, | |
| 103 | + ); | |
| 104 | + | |
| 105 | + expect(result.length).toBe(smallSnippets.length); | |
| 106 | + }); | |
| 107 | + | |
| 108 | + test("should handle limited token count", () => { | |
| 109 | + const snippets = Array(10) | |
| 110 | + .fill(0) | |
| 111 | + .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 112 | + | |
| 113 | + const result = formatOpenedFilesContext( | |
| 114 | + snippets, | |
| 115 | + 1, // Extremely small token count | |
| 116 | + mockHelper, | |
| 117 | + [], | |
| 118 | + TOKEN_BUFFER, | |
| 119 | + ); | |
| 120 | + | |
| 121 | + expect(Array.isArray(result)).toBe(true); | |
| 122 | + }); | |
| 123 | + | |
| 124 | + test("should accept valid inputs with adequate token count", () => { | |
| 125 | + const snippets = [ | |
| 126 | + createCodeSnippet("file1.ts", "Some content here"), | |
| 127 | + createCodeSnippet("file2.ts", "More content here"), | |
| 128 | + ]; | |
| 129 | + | |
| 130 | + const result = formatOpenedFilesContext( | |
| 131 | + snippets, | |
| 132 | + 1000, | |
| 133 | + mockHelper, | |
| 134 | + [], | |
| 135 | + TOKEN_BUFFER, | |
| 136 | + ); | |
| 137 | + | |
| 138 | + expect(result.length).toBeGreaterThan(0); | |
| 139 | + }); | |
| 140 | + | |
| 141 | + test("should handle already added snippets parameter", () => { | |
| 142 | + const snippets = [ | |
| 143 | + createCodeSnippet("file1.ts", "content of file 1"), | |
| 144 | + createCodeSnippet("file2.ts", "content of file 2"), | |
| 145 | + ]; | |
| 146 | + | |
| 147 | + const alreadyAddedSnippets = [createDiffSnippet("diff content")]; | |
| 148 | + | |
| 149 | + const result = formatOpenedFilesContext( | |
| 150 | + snippets, | |
| 151 | + 1000, | |
| 152 | + mockHelper, | |
| 153 | + alreadyAddedSnippets, | |
| 154 | + TOKEN_BUFFER, | |
| 155 | + ); | |
| 156 | + | |
| 157 | + expect(result.length).toBe(snippets.length); | |
| 158 | + }); | |
| 159 | + | |
| 160 | + test("should handle large snippets by trimming them", () => { | |
| 161 | + const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000)); | |
| 162 | + | |
| 163 | + const result = formatOpenedFilesContext( | |
| 164 | + [largeSnippet], | |
| 165 | + 200, | |
| 166 | + mockHelper, | |
| 167 | + [], | |
| 168 | + TOKEN_BUFFER, | |
| 169 | + ); | |
| 170 | + | |
| 171 | + expect(result.length).toBe(1); | |
| 172 | + expect(result[0].filepath).toBe(largeSnippet.filepath); | |
| 173 | + expect(result[0].content.length).toBeLessThan(largeSnippet.content.length); | |
| 174 | + }); | |
| 175 | + | |
| 176 | + test("should prioritize more recent snippets when not all fit", () => { | |
| 177 | + const snippets = [ | |
| 178 | + createCodeSnippet("recent1.ts", "a".repeat(10)), | |
| 179 | + createCodeSnippet("recent2.ts", "b".repeat(10000)), | |
| 180 | + createCodeSnippet("recent3.ts", "c".repeat(10000)), | |
| 181 | + ]; | |
| 182 | + | |
| 183 | + const result = formatOpenedFilesContext( | |
| 184 | + snippets, | |
| 185 | + 200, | |
| 186 | + mockHelper, | |
| 187 | + [], | |
| 188 | + TOKEN_BUFFER, | |
| 189 | + ); | |
| 190 | + | |
| 191 | + expect(result.length).toBeGreaterThan(0); | |
| 192 | + expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true); | |
| 193 | + }); | |
| 194 | + | |
| 195 | + test("should handle a mix of large and small snippets effectively", () => { | |
| 196 | + const mixedSnippets = [ | |
| 197 | + createCodeSnippet("small1.ts", "a".repeat(10)), | |
| 198 | + createCodeSnippet("large1.ts", "b".repeat(5000)), | |
| 199 | + createCodeSnippet("small2.ts", "c".repeat(10)), | |
| 200 | + createCodeSnippet("large2.ts", "d".repeat(5000)), | |
| 201 | + ]; | |
| 202 | + | |
| 203 | + const result = formatOpenedFilesContext( | |
| 204 | + mixedSnippets, | |
| 205 | + 500, | |
| 206 | + mockHelper, | |
| 207 | + [], | |
| 208 | + TOKEN_BUFFER, | |
| 209 | + ); | |
| 210 | + | |
| 211 | + expect(result.length).toBeGreaterThan(0); | |
| 212 | + expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true); | |
| 213 | + }); | |
| 214 | + | |
| 215 | + test("should respect minimum token threshold when trimming", () => { | |
| 216 | + const largeSnippets = [ | |
| 217 | + createCodeSnippet("large1.ts", "a".repeat(5000)), | |
| 218 | + createCodeSnippet("large2.ts", "b".repeat(5000)), | |
| 219 | + ]; | |
| 220 | + | |
| 221 | + const result = formatOpenedFilesContext( | |
| 222 | + largeSnippets, | |
| 223 | + 150, | |
| 224 | + mockHelper, | |
| 225 | + [], | |
| 226 | + TOKEN_BUFFER, | |
| 227 | + ); | |
| 228 | + | |
| 229 | + expect(result.length).toBeLessThanOrEqual(1); | |
| 230 | + | |
| 231 | + if (result.length > 0) { | |
| 232 | + expect(result[0].content.length).toBeLessThan( | |
| 233 | + largeSnippets[0].content.length, | |
| 234 | + ); | |
| 235 | + } | |
| 236 | + }); | |
| 237 | +}); | |
| 238 | + | |
| 239 | +// Tests for rankByScore function | |
| 240 | +describe("rankByScore function", () => { | |
| 241 | + const createCodeSnippet = ( | |
| 242 | + filepath: string, | |
| 243 | + content: string, | |
| 244 | + ): AutocompleteCodeSnippet => ({ | |
| 245 | + type: AutocompleteSnippetType.Code, | |
| 246 | + filepath, | |
| 247 | + content, | |
| 248 | + }); | |
| 249 | + | |
| 250 | + test("should return empty array when given empty array", () => { | |
| 251 | + const result = rankByScore([]); | |
| 252 | + expect(result).toEqual([]); | |
| 253 | + }); | |
| 254 | + | |
| 255 | + test("should rank snippets by score", () => { | |
| 256 | + // Initialize logMin and logMax by calling setLogStats first | |
| 257 | + const snippets = [ | |
| 258 | + createCodeSnippet("file1.ts", "a".repeat(10)), | |
| 259 | + createCodeSnippet("file2.ts", "b".repeat(1000)), | |
| 260 | + createCodeSnippet("file3.ts", "c".repeat(100)), | |
| 261 | + ]; | |
| 262 | + setLogStats(snippets); | |
| 263 | + | |
| 264 | + const result = rankByScore(snippets); | |
| 265 | + | |
| 266 | + expect(Array.isArray(result)).toBe(true); | |
| 267 | + expect(result.length).toBeGreaterThan(0); | |
| 268 | + | |
| 269 | + // The snippets should be ranked in some order, which may not match input order | |
| 270 | + expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual( | |
| 271 | + snippets.map((s) => s.filepath), | |
| 272 | + ); | |
| 273 | + }); | |
| 274 | + | |
| 275 | + test("should limit the number of ranked snippets to defaultNumFilesUsed", () => { | |
| 276 | + // Create more snippets than the default limit | |
| 277 | + const manySnippets = Array(10) | |
| 278 | + .fill(0) | |
| 279 | + .map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`)); | |
| 280 | + setLogStats(manySnippets); | |
| 281 | + | |
| 282 | + const result = rankByScore(manySnippets); | |
| 283 | + | |
| 284 | + // The function should limit the number of snippets (defaultNumFilesUsed is 5) | |
| 285 | + expect(result.length).toBeLessThanOrEqual(5); | |
| 286 | + }); | |
| 287 | +}); | |
| 288 | + | |
| 289 | +// Tests for getRecencyAndSizeScore function | |
| 290 | +describe("getRecencyAndSizeScore function", () => { | |
| 291 | + const createCodeSnippet = ( | |
| 292 | + filepath: string, | |
| 293 | + content: string, | |
| 294 | + ): AutocompleteCodeSnippet => ({ | |
| 295 | + type: AutocompleteSnippetType.Code, | |
| 296 | + filepath, | |
| 297 | + content, | |
| 298 | + }); | |
| 299 | + | |
| 300 | + test("recency score should decrease with higher index", () => { | |
| 301 | + // Initialize log stats first | |
| 302 | + const snippets = [ | |
| 303 | + createCodeSnippet("file1.ts", "a".repeat(100)), | |
| 304 | + createCodeSnippet("file2.ts", "b".repeat(100)), | |
| 305 | + ]; | |
| 306 | + setLogStats(snippets); | |
| 307 | + | |
| 308 | + // Test that score decreases with increasing index | |
| 309 | + const score0 = getRecencyAndSizeScore(0, snippets[0]); | |
| 310 | + const score1 = getRecencyAndSizeScore(1, snippets[0]); | |
| 311 | + const score2 = getRecencyAndSizeScore(2, snippets[0]); | |
| 312 | + | |
| 313 | + expect(score0).toBeGreaterThan(score1); | |
| 314 | + expect(score1).toBeGreaterThan(score2); | |
| 315 | + }); | |
| 316 | + | |
| 317 | + test("size score should be higher for smaller snippets", () => { | |
| 318 | + // Initialize log stats first | |
| 319 | + const snippets = [ | |
| 320 | + createCodeSnippet("small.ts", "a".repeat(50)), | |
| 321 | + createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 322 | + createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 323 | + ]; | |
| 324 | + setLogStats(snippets); | |
| 325 | + | |
| 326 | + // Test with same recency index but different sizes | |
| 327 | + const smallScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 328 | + const mediumScore = getRecencyAndSizeScore(0, snippets[1]); | |
| 329 | + const largeScore = getRecencyAndSizeScore(0, snippets[2]); | |
| 330 | + | |
| 331 | + // Scores should reflect preference for smaller snippets | |
| 332 | + expect(smallScore).toBeGreaterThanOrEqual(mediumScore); | |
| 333 | + expect(mediumScore).toBeGreaterThanOrEqual(largeScore); | |
| 334 | + }); | |
| 335 | + | |
| 336 | + test("recency and size both affect the score with recency having more weight", () => { | |
| 337 | + // Initialize log stats first | |
| 338 | + const snippets = [ | |
| 339 | + createCodeSnippet("recent_large.ts", "a".repeat(1000)), | |
| 340 | + createCodeSnippet("old_small.ts", "b".repeat(50)), | |
| 341 | + ]; | |
| 342 | + setLogStats(snippets); | |
| 343 | + | |
| 344 | + // Test that recency and size both contribute to the score | |
| 345 | + const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]); | |
| 346 | + const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]); | |
| 347 | + | |
| 348 | + // We're not making a direct comparison, just verifying the scoring mechanism works | |
| 349 | + expect(recentLargeScore).toBeGreaterThan(0); | |
| 350 | + expect(oldSmallScore).toBeGreaterThan(0); | |
| 351 | + expect(oldSmallScore).toBeLessThan(1); | |
| 352 | + }); | |
| 353 | +}); | |
| 354 | + | |
| 355 | +// Tests for setLogStats function | |
| 356 | +describe("setLogStats function", () => { | |
| 357 | + const createCodeSnippet = ( | |
| 358 | + filepath: string, | |
| 359 | + content: string, | |
| 360 | + ): AutocompleteCodeSnippet => ({ | |
| 361 | + type: AutocompleteSnippetType.Code, | |
| 362 | + filepath, | |
| 363 | + content, | |
| 364 | + }); | |
| 365 | + | |
| 366 | + test("should set logMin and logMax based on snippet sizes", () => { | |
| 367 | + const snippets = [ | |
| 368 | + createCodeSnippet("small.ts", "a".repeat(50)), | |
| 369 | + createCodeSnippet("medium.ts", "b".repeat(200)), | |
| 370 | + createCodeSnippet("large.ts", "c".repeat(1000)), | |
| 371 | + ]; | |
| 372 | + | |
| 373 | + // We can't directly test logMin and logMax as they're private | |
| 374 | + // but we can verify that the function runs without errors | |
| 375 | + expect(() => setLogStats(snippets)).not.toThrow(); | |
| 376 | + }); | |
| 377 | + | |
| 378 | + test("should handle empty snippets", () => { | |
| 379 | + const emptySnippets = [ | |
| 380 | + createCodeSnippet("empty1.ts", ""), | |
| 381 | + createCodeSnippet("empty2.ts", ""), | |
| 382 | + ]; | |
| 383 | + | |
| 384 | + expect(() => setLogStats(emptySnippets)).not.toThrow(); | |
| 385 | + }); | |
| 386 | + | |
| 387 | + test("should handle single snippet", () => { | |
| 388 | + const singleSnippet = [createCodeSnippet("single.ts", "content")]; | |
| 389 | + | |
| 390 | + expect(() => setLogStats(singleSnippet)).not.toThrow(); | |
| 391 | + }); | |
| 392 | +}); | |
| 393 | + | |
| 394 | +// Tests for trimSnippetForContext function | |
| 395 | +describe("trimSnippetForContext function", () => { | |
| 396 | + const createCodeSnippet = ( | |
| 397 | + filepath: string, | |
| 398 | + content: string, | |
| 399 | + ): AutocompleteCodeSnippet => ({ | |
| 400 | + type: AutocompleteSnippetType.Code, | |
| 401 | + filepath, | |
| 402 | + content, | |
| 403 | + }); | |
| 404 | + | |
| 405 | + test("should return original snippet if it fits within token limit", () => { | |
| 406 | + const snippet = createCodeSnippet("small.ts", "small content"); | |
| 407 | + const modelName = "test-model"; | |
| 408 | + const maxTokens = 1000; // Large enough to fit the snippet | |
| 409 | + | |
| 410 | + const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 411 | + | |
| 412 | + // Should return the original snippet with its token count | |
| 413 | + expect(result.newSnippet).toEqual(snippet); | |
| 414 | + expect(typeof result.newTokens).toBe("number"); | |
| 415 | + expect(result.newTokens).toBeGreaterThan(0); | |
| 416 | + }); | |
| 417 | + | |
| 418 | + test("should trim snippet content if it exceeds token limit", () => { | |
| 419 | + const snippet = createCodeSnippet("large.ts", "a".repeat(1000)); | |
| 420 | + const modelName = "test-model"; | |
| 421 | + const maxTokens = 10; // Small enough to require trimming | |
| 422 | + | |
| 423 | + const result = trimSnippetForContext(snippet, maxTokens, modelName); | |
| 424 | + | |
| 425 | + // Should return a trimmed snippet | |
| 426 | + expect(result.newSnippet.filepath).toBe(snippet.filepath); | |
| 427 | + expect(result.newSnippet.type).toBe(snippet.type); | |
| 428 | + expect(result.newSnippet.content.length).toBeLessThanOrEqual( | |
| 429 | + snippet.content.length, | |
| 430 | + ); | |
| 431 | + | |
| 432 | + // Token count should be less than or equal to maxTokens | |
| 433 | + expect(result.newTokens).toBeLessThanOrEqual(maxTokens); | |
| 434 | + }); | |
| 435 | +}); |
deleted core/autocomplete/util/completionTestUtils.test.ts +0 −65
| @@ -1,65 +0,0 @@ | ||
| 1 | -import { | |
| 2 | - processTestCase, | |
| 3 | - type CompletionTestCase, | |
| 4 | -} from "./completionTestUtils"; | |
| 5 | - | |
| 6 | -describe("processTestCase utility", () => { | |
| 7 | - it("processes simple console.log completion", () => { | |
| 8 | - const testCase: CompletionTestCase = { | |
| 9 | - original: "console.log(|cur||till|)", | |
| 10 | - completion: '"foo,", bar', | |
| 11 | - }; | |
| 12 | - | |
| 13 | - expect(processTestCase(testCase)).toEqual({ | |
| 14 | - input: { | |
| 15 | - lastLineOfCompletionText: '"foo,", bar', | |
| 16 | - currentText: ")", | |
| 17 | - cursorPosition: "console.log(".length, | |
| 18 | - }, | |
| 19 | - expectedResult: { | |
| 20 | - completionText: '"foo,", bar', | |
| 21 | - }, | |
| 22 | - }); | |
| 23 | - }); | |
| 24 | - | |
| 25 | - it("processes simple console.log completion with overwriting", () => { | |
| 26 | - const testCase: CompletionTestCase = { | |
| 27 | - original: "console.log(|cur|)|till|", | |
| 28 | - completion: '"foo,", bar);', | |
| 29 | - }; | |
| 30 | - | |
| 31 | - expect(processTestCase(testCase)).toEqual({ | |
| 32 | - input: { | |
| 33 | - lastLineOfCompletionText: '"foo,", bar);', | |
| 34 | - currentText: ")", | |
| 35 | - cursorPosition: "console.log(".length, | |
| 36 | - }, | |
| 37 | - expectedResult: { | |
| 38 | - completionText: '"foo,", bar);', | |
| 39 | - range: { | |
| 40 | - start: "console.log(".length, | |
| 41 | - end: "console.log()".length, | |
| 42 | - }, | |
| 43 | - }, | |
| 44 | - }); | |
| 45 | - }); | |
| 46 | - | |
| 47 | - it("partially applying completion", () => { | |
| 48 | - const testCase: CompletionTestCase = { | |
| 49 | - original: '|cur||till|fetch("https://example.com");', | |
| 50 | - completion: 'await fetch("https://example.com");', | |
| 51 | - appliedCompletion: "await ", | |
| 52 | - }; | |
| 53 | - | |
| 54 | - expect(processTestCase(testCase)).toEqual({ | |
| 55 | - input: { | |
| 56 | - lastLineOfCompletionText: 'await fetch("https://example.com");', | |
| 57 | - currentText: 'fetch("https://example.com");', | |
| 58 | - cursorPosition: 0, | |
| 59 | - }, | |
| 60 | - expectedResult: { | |
| 61 | - completionText: "await ", | |
| 62 | - }, | |
| 63 | - }); | |
| 64 | - }); | |
| 65 | -}); |
added core/autocomplete/util/completionTestUtils.vitest.ts +66 −0
| @@ -0,0 +1,66 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { | |
| 3 | + processTestCase, | |
| 4 | + type CompletionTestCase, | |
| 5 | +} from "./completionTestUtils"; | |
| 6 | + | |
| 7 | +describe("processTestCase utility", () => { | |
| 8 | + it("processes simple console.log completion", () => { | |
| 9 | + const testCase: CompletionTestCase = { | |
| 10 | + original: "console.log(|cur||till|)", | |
| 11 | + completion: '"foo,", bar', | |
| 12 | + }; | |
| 13 | + | |
| 14 | + expect(processTestCase(testCase)).toEqual({ | |
| 15 | + input: { | |
| 16 | + lastLineOfCompletionText: '"foo,", bar', | |
| 17 | + currentText: ")", | |
| 18 | + cursorPosition: "console.log(".length, | |
| 19 | + }, | |
| 20 | + expectedResult: { | |
| 21 | + completionText: '"foo,", bar', | |
| 22 | + }, | |
| 23 | + }); | |
| 24 | + }); | |
| 25 | + | |
| 26 | + it("processes simple console.log completion with overwriting", () => { | |
| 27 | + const testCase: CompletionTestCase = { | |
| 28 | + original: "console.log(|cur|)|till|", | |
| 29 | + completion: '"foo,", bar);', | |
| 30 | + }; | |
| 31 | + | |
| 32 | + expect(processTestCase(testCase)).toEqual({ | |
| 33 | + input: { | |
| 34 | + lastLineOfCompletionText: '"foo,", bar);', | |
| 35 | + currentText: ")", | |
| 36 | + cursorPosition: "console.log(".length, | |
| 37 | + }, | |
| 38 | + expectedResult: { | |
| 39 | + completionText: '"foo,", bar);', | |
| 40 | + range: { | |
| 41 | + start: "console.log(".length, | |
| 42 | + end: "console.log()".length, | |
| 43 | + }, | |
| 44 | + }, | |
| 45 | + }); | |
| 46 | + }); | |
| 47 | + | |
| 48 | + it("partially applying completion", () => { | |
| 49 | + const testCase: CompletionTestCase = { | |
| 50 | + original: '|cur||till|fetch("https://example.com");', | |
| 51 | + completion: 'await fetch("https://example.com");', | |
| 52 | + appliedCompletion: "await ", | |
| 53 | + }; | |
| 54 | + | |
| 55 | + expect(processTestCase(testCase)).toEqual({ | |
| 56 | + input: { | |
| 57 | + lastLineOfCompletionText: 'await fetch("https://example.com");', | |
| 58 | + currentText: 'fetch("https://example.com");', | |
| 59 | + cursorPosition: 0, | |
| 60 | + }, | |
| 61 | + expectedResult: { | |
| 62 | + completionText: "await ", | |
| 63 | + }, | |
| 64 | + }); | |
| 65 | + }); | |
| 66 | +}); |
deleted core/autocomplete/util/processSingleLineCompletion.test.ts +0 −95
| @@ -1,95 +0,0 @@ | ||
| 1 | -import { processTestCase } from "./completionTestUtils"; | |
| 2 | -import { processSingleLineCompletion } from "./processSingleLineCompletion"; | |
| 3 | - | |
| 4 | -describe("processSingleLineCompletion", () => { | |
| 5 | - it("should handle simple end of line completion", () => { | |
| 6 | - const testCase = processTestCase({ | |
| 7 | - original: "console.log(|cur|", | |
| 8 | - completion: '"Hello, world!")', | |
| 9 | - }); | |
| 10 | - | |
| 11 | - const result = processSingleLineCompletion( | |
| 12 | - testCase.input.lastLineOfCompletionText, | |
| 13 | - testCase.input.currentText, | |
| 14 | - testCase.input.cursorPosition, | |
| 15 | - ); | |
| 16 | - | |
| 17 | - expect(result).toEqual(testCase.expectedResult); | |
| 18 | - }); | |
| 19 | - | |
| 20 | - it("should handle midline insert repeating the end of line", () => { | |
| 21 | - const testCase = processTestCase({ | |
| 22 | - original: "console.log(|cur|);|till|", | |
| 23 | - completion: '"Hello, world!");', | |
| 24 | - }); | |
| 25 | - | |
| 26 | - const result = processSingleLineCompletion( | |
| 27 | - testCase.input.lastLineOfCompletionText, | |
| 28 | - testCase.input.currentText, | |
| 29 | - testCase.input.cursorPosition, | |
| 30 | - ); | |
| 31 | - | |
| 32 | - expect(result).toEqual(testCase.expectedResult); | |
| 33 | - }); | |
| 34 | - | |
| 35 | - it("should handle midline insert repeating the end of line plus adding a semicolon", () => { | |
| 36 | - const testCase = processTestCase({ | |
| 37 | - original: "console.log(|cur|)|till|", | |
| 38 | - completion: '"Hello, world!");', | |
| 39 | - }); | |
| 40 | - | |
| 41 | - const result = processSingleLineCompletion( | |
| 42 | - testCase.input.lastLineOfCompletionText, | |
| 43 | - testCase.input.currentText, | |
| 44 | - testCase.input.cursorPosition, | |
| 45 | - ); | |
| 46 | - | |
| 47 | - expect(result).toEqual(testCase.expectedResult); | |
| 48 | - }); | |
| 49 | - | |
| 50 | - it("should handle simple midline insert", () => { | |
| 51 | - const testCase = processTestCase({ | |
| 52 | - original: "console.log(|cur|)", | |
| 53 | - completion: '"Hello, world!"', | |
| 54 | - }); | |
| 55 | - | |
| 56 | - const result = processSingleLineCompletion( | |
| 57 | - testCase.input.lastLineOfCompletionText, | |
| 58 | - testCase.input.currentText, | |
| 59 | - testCase.input.cursorPosition, | |
| 60 | - ); | |
| 61 | - | |
| 62 | - expect(result).toEqual(testCase.expectedResult); | |
| 63 | - }); | |
| 64 | - | |
| 65 | - it("should handle complex dif with addition in the beginning", () => { | |
| 66 | - const testCase = processTestCase({ | |
| 67 | - original: 'console.log(|cur||till|, "param1", )', // TODO | |
| 68 | - completion: '"Hello world!", "param1", param1);', | |
| 69 | - appliedCompletion: '"Hello world!"', | |
| 70 | - }); | |
| 71 | - | |
| 72 | - const result = processSingleLineCompletion( | |
| 73 | - testCase.input.lastLineOfCompletionText, | |
| 74 | - testCase.input.currentText, | |
| 75 | - testCase.input.cursorPosition, | |
| 76 | - ); | |
| 77 | - | |
| 78 | - expect(result).toEqual(testCase.expectedResult); | |
| 79 | - }); | |
| 80 | - | |
| 81 | - it("should handle simple insertion even with random equality", () => { | |
| 82 | - const testCase = processTestCase({ | |
| 83 | - original: 'print(f"Foobar length: |cur||till|")', | |
| 84 | - completion: "{len(foobar)}", | |
| 85 | - }); | |
| 86 | - | |
| 87 | - const result = processSingleLineCompletion( | |
| 88 | - testCase.input.lastLineOfCompletionText, | |
| 89 | - testCase.input.currentText, | |
| 90 | - testCase.input.cursorPosition, | |
| 91 | - ); | |
| 92 | - | |
| 93 | - expect(result).toEqual(testCase.expectedResult); | |
| 94 | - }); | |
| 95 | -}); |
added core/autocomplete/util/processSingleLineCompletion.vitest.ts +96 −0
| @@ -0,0 +1,96 @@ | ||
| 1 | +import { describe, expect, it } from "vitest"; | |
| 2 | +import { processTestCase } from "./completionTestUtils"; | |
| 3 | +import { processSingleLineCompletion } from "./processSingleLineCompletion"; | |
| 4 | + | |
| 5 | +describe("processSingleLineCompletion", () => { | |
| 6 | + it("should handle simple end of line completion", () => { | |
| 7 | + const testCase = processTestCase({ | |
| 8 | + original: "console.log(|cur|", | |
| 9 | + completion: '"Hello, world!")', | |
| 10 | + }); | |
| 11 | + | |
| 12 | + const result = processSingleLineCompletion( | |
| 13 | + testCase.input.lastLineOfCompletionText, | |
| 14 | + testCase.input.currentText, | |
| 15 | + testCase.input.cursorPosition, | |
| 16 | + ); | |
| 17 | + | |
| 18 | + expect(result).toEqual(testCase.expectedResult); | |
| 19 | + }); | |
| 20 | + | |
| 21 | + it("should handle midline insert repeating the end of line", () => { | |
| 22 | + const testCase = processTestCase({ | |
| 23 | + original: "console.log(|cur|);|till|", | |
| 24 | + completion: '"Hello, world!");', | |
| 25 | + }); | |
| 26 | + | |
| 27 | + const result = processSingleLineCompletion( | |
| 28 | + testCase.input.lastLineOfCompletionText, | |
| 29 | + testCase.input.currentText, | |
| 30 | + testCase.input.cursorPosition, | |
| 31 | + ); | |
| 32 | + | |
| 33 | + expect(result).toEqual(testCase.expectedResult); | |
| 34 | + }); | |
| 35 | + | |
| 36 | + it("should handle midline insert repeating the end of line plus adding a semicolon", () => { | |
| 37 | + const testCase = processTestCase({ | |
| 38 | + original: "console.log(|cur|)|till|", | |
| 39 | + completion: '"Hello, world!");', | |
| 40 | + }); | |
| 41 | + | |
| 42 | + const result = processSingleLineCompletion( | |
| 43 | + testCase.input.lastLineOfCompletionText, | |
| 44 | + testCase.input.currentText, | |
| 45 | + testCase.input.cursorPosition, | |
| 46 | + ); | |
| 47 | + | |
| 48 | + expect(result).toEqual(testCase.expectedResult); | |
| 49 | + }); | |
| 50 | + | |
| 51 | + it("should handle simple midline insert", () => { | |
| 52 | + const testCase = processTestCase({ | |
| 53 | + original: "console.log(|cur|)", | |
| 54 | + completion: '"Hello, world!"', | |
| 55 | + }); | |
| 56 | + | |
| 57 | + const result = processSingleLineCompletion( | |
| 58 | + testCase.input.lastLineOfCompletionText, | |
| 59 | + testCase.input.currentText, | |
| 60 | + testCase.input.cursorPosition, | |
| 61 | + ); | |
| 62 | + | |
| 63 | + expect(result).toEqual(testCase.expectedResult); | |
| 64 | + }); | |
| 65 | + | |
| 66 | + it("should handle complex dif with addition in the beginning", () => { | |
| 67 | + const testCase = processTestCase({ | |
| 68 | + original: 'console.log(|cur||till|, "param1", )', // TODO | |
| 69 | + completion: '"Hello world!", "param1", param1);', | |
| 70 | + appliedCompletion: '"Hello world!"', | |
| 71 | + }); | |
| 72 | + | |
| 73 | + const result = processSingleLineCompletion( | |
| 74 | + testCase.input.lastLineOfCompletionText, | |
| 75 | + testCase.input.currentText, | |
| 76 | + testCase.input.cursorPosition, | |
| 77 | + ); | |
| 78 | + | |
| 79 | + expect(result).toEqual(testCase.expectedResult); | |
| 80 | + }); | |
| 81 | + | |
| 82 | + it("should handle simple insertion even with random equality", () => { | |
| 83 | + const testCase = processTestCase({ | |
| 84 | + original: 'print(f"Foobar length: |cur||till|")', | |
| 85 | + completion: "{len(foobar)}", | |
| 86 | + }); | |
| 87 | + | |
| 88 | + const result = processSingleLineCompletion( | |
| 89 | + testCase.input.lastLineOfCompletionText, | |
| 90 | + testCase.input.currentText, | |
| 91 | + testCase.input.cursorPosition, | |
| 92 | + ); | |
| 93 | + | |
| 94 | + expect(result).toEqual(testCase.expectedResult); | |
| 95 | + }); | |
| 96 | +}); |
modified core/config/yaml/LocalPlatformClient.vitest.ts +0 −1
| @@ -123,7 +123,6 @@ | ||
| 123 | 123 | expect( |
| 124 | 124 | (resolvedFQSNs[0] as SecretResult & { value: unknown })?.value, |
| 125 | 125 | ).toBe(secretValue); |
| 126 | - console.log("debug1 resolved fqsn", resolvedFQSNs); | |
| 127 | 126 | }); |
| 128 | 127 | }); |
| 129 | 128 |
modified core/jest.config.js +1 −3
| @@ -29,7 +29,5 @@ | ||
| 29 | 29 | globalSetup: "<rootDir>/test/jest.global-setup.ts", |
| 30 | 30 | setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.js"], |
| 31 | 31 | maxWorkers: 1, // equivalent to CLI --runInBand |
| 32 | - modulePathIgnorePatterns: [ | |
| 33 | - "<rootDir>/config/yaml/LocalPlatformClient.test.ts", | |
| 34 | - ], | |
| 32 | + testMatch: ["**/*.test.ts"], | |
| 35 | 33 | }; |
added core/test/vitest.global-setup.ts +11 −0
| @@ -0,0 +1,11 @@ | ||
| 1 | +import fs from "fs"; | |
| 2 | +import path from "path"; | |
| 3 | + | |
| 4 | +// Sets up the GLOBAL directory for testing - equivalent to ~/.continue | |
| 5 | +// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths | |
| 6 | +export default async function () { | |
| 7 | + process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); | |
| 8 | + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { | |
| 9 | + fs.rmdirSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true }); | |
| 10 | + } | |
| 11 | +} |
added core/test/vitest.setup.ts +16 −0
| @@ -0,0 +1,16 @@ | ||
| 1 | +import { TextDecoder, TextEncoder } from "util"; | |
| 2 | + | |
| 3 | +import fetch, { Request, Response } from "node-fetch"; | |
| 4 | +import { beforeAll } from "vitest"; | |
| 5 | + | |
| 6 | +beforeAll(() => { | |
| 7 | + // @ts-ignore | |
| 8 | + globalThis.fetch = fetch; | |
| 9 | + // @ts-ignore | |
| 10 | + globalThis.Request = Request; | |
| 11 | + // @ts-ignore | |
| 12 | + globalThis.Response = Response; | |
| 13 | + globalThis.TextEncoder = TextEncoder; | |
| 14 | + // @ts-ignore | |
| 15 | + globalThis.TextDecoder = TextDecoder; | |
| 16 | +}); |
modified core/util/treeSitter.ts +2 −2
| @@ -181,7 +181,7 @@ | ||
| 181 | 181 | } |
| 182 | 182 | |
| 183 | 183 | const sourcePath = path.join( |
| 184 | - __dirname, | |
| 184 | + process.env.NODE_ENV === "test" ? process.cwd() : __dirname, | |
| 185 | 185 | "..", |
| 186 | 186 | ...(process.env.NODE_ENV === "test" |
| 187 | 187 | ? ["extensions", "vscode", "tree-sitter"] |
| @@ -201,7 +201,7 @@ | ||
| 201 | 201 | fileExtension: string, |
| 202 | 202 | ): Promise<Language> { |
| 203 | 203 | const wasmPath = path.join( |
| 204 | - __dirname, | |
| 204 | + process.env.NODE_ENV === "test" ? process.cwd() : __dirname, | |
| 205 | 205 | ...(process.env.NODE_ENV === "test" |
| 206 | 206 | ? ["node_modules", "tree-sitter-wasms", "out"] |
| 207 | 207 | : ["tree-sitter-wasms"]), |
modified core/vitest.config.ts +7 −0
| @@ -2,6 +2,13 @@ | ||
| 2 | 2 | |
| 3 | 3 | export default defineConfig({ |
| 4 | 4 | test: { |
| 5 | + testTransformMode: { | |
| 6 | + web: ["/.[jt]s?$/"], | |
| 7 | + ssr: ["/.[jt]s?$/"], | |
| 8 | + }, | |
| 9 | + globalSetup: "./test/vitest.global-setup.ts", | |
| 10 | + setupFiles: "./test/vitest.setup.ts", | |
| 11 | + fileParallelism: false, | |
| 5 | 12 | include: ["**/*.vitest.ts"], |
| 6 | 13 | }, |
| 7 | 14 | }); |