| 1 | import { ChunkWithoutID } from "../.."; |
| 2 | |
| 3 | import { codeChunker } from "./code"; |
| 4 | |
| 5 | async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> { |
| 6 | const result: T[] = []; |
| 7 | for await (const item of generator) { |
| 8 | result.push(item); |
| 9 | } |
| 10 | return result; |
| 11 | } |
| 12 | |
| 13 | async function genToStrs( |
| 14 | generator: AsyncGenerator<ChunkWithoutID>, |
| 15 | ): Promise<string[]> { |
| 16 | return (await genToArr(generator)).map((chunk) => chunk.content); |
| 17 | } |
| 18 | |
| 19 | describe.skip("codeChunker", () => { |
| 20 | test("should return empty array if file empty", async () => { |
| 21 | const chunks = await genToStrs(codeChunker("test.ts", "", 100)); |
| 22 | expect(chunks).toEqual([]); |
| 23 | }); |
| 24 | |
| 25 | test("should include entire file if smaller than max chunk size", async () => { |
| 26 | const chunks = await genToStrs(codeChunker("test.ts", "abc", 100)); |
| 27 | expect(chunks).toEqual(["abc"]); |
| 28 | }); |
| 29 | |
| 30 | test("should capture small class and function from large python file", async () => { |
| 31 | const extraLine = "# This is a comment"; |
| 32 | const myClass = "class MyClass:\n def __init__(self):\n pass"; |
| 33 | const myFunction = 'def my_function():\n return "Hello, World!"'; |
| 34 | |
| 35 | const file = |
| 36 | Array(100).fill(extraLine).join("\n") + |
| 37 | "\n\n" + |
| 38 | myClass + |
| 39 | "\n\n" + |
| 40 | myFunction + |
| 41 | "\n\n" + |
| 42 | Array(100).fill(extraLine).join("\n"); |
| 43 | |
| 44 | const chunks = await genToStrs(codeChunker("test.py", file, 200)); |
| 45 | expect(chunks.length).toBeGreaterThan(1); |
| 46 | expect(chunks).toContain(myClass); |
| 47 | expect(chunks).toContain(myFunction); |
| 48 | }); |
| 49 | |
| 50 | test("should split large python class into methods and class with truncated methods", async () => { |
| 51 | const methodI = (i: number) => |
| 52 | ` def method${i}():\n return "Hello, ${i}!"`; |
| 53 | |
| 54 | const file = |
| 55 | "class MyClass:\n" + |
| 56 | Array(100) |
| 57 | .fill(0) |
| 58 | .map((_, i) => methodI(i + 1)) |
| 59 | .join("\n") + |
| 60 | "\n\n"; |
| 61 | |
| 62 | console.log(file); |
| 63 | |
| 64 | const chunks = await genToStrs(codeChunker("test.py", file, 200)); |
| 65 | expect(chunks.length).toBeGreaterThan(1); |
| 66 | expect( |
| 67 | chunks[0].startsWith("class MyClass:\n def method1():\n ..."), |
| 68 | ).toBe(true); |
| 69 | // The extra spaces seem to be a bug with tree-sitter-python |
| 70 | expect(chunks).toContain('def method1():\n return "Hello, 1!"'); |
| 71 | expect(chunks).toContain('def method20():\n return "Hello, 20!"'); |
| 72 | }); |
| 73 | }); |