Merge pull request #2963 from continuedev/nate/autocomplete-generation-tests

ListenableGenerator.test.ts
This commit is contained in:
Tomasz Stefaniak 2024-11-18 11:28:37 -08:00 • committed by GitHub
commit 5936ae77ab
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 640 additions and 74 deletions

View file

@ -1,3 +1,13 @@
export const BRACKETS: { [key: string]: string } = {
"(": ")",
"{": "}",
"[": "]",
};
export const BRACKETS_REVERSE: { [key: string]: string } = {
")": "(",
"}": "{",
"]": "[",
};
/**
* We follow the policy of only completing bracket pairs that we started
* But sometimes we started the pair in a previous autocomplete suggestion
@ -6,30 +16,18 @@ export class BracketMatchingService {
private openingBracketsFromLastCompletion: string[] = [];
private lastCompletionFile: string | undefined = undefined;
static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" };
static BRACKETS_REVERSE: { [key: string]: string } = {
")": "(",
"}": "{",
"]": "[",
};
handleAcceptedCompletion(completion: string, filepath: string) {
this.openingBracketsFromLastCompletion = [];
const stack: string[] = [];
for (let i = 0; i < completion.length; i++) {
const char = completion[i];
if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) {
if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
} else if (
Object.values(BracketMatchingService.BRACKETS).includes(char)
) {
} else if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (
stack.length === 0 ||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
) {
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
break;
}
}
@ -63,17 +61,12 @@ export class BracketMatchingService {
(prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? "");
for (let i = 0; i < currentLine.length; i++) {
const char = currentLine[i];
if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) {
if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
} else if (
Object.values(BracketMatchingService.BRACKETS).includes(char)
) {
} else if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (
stack.length === 0 ||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
) {
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
break;
}
}
@ -87,7 +80,7 @@ export class BracketMatchingService {
if (suffix[i] === " ") {
continue;
}
const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]];
const openBracket = BRACKETS_REVERSE[suffix[i]];
if (!openBracket) {
break;
}
@ -115,19 +108,14 @@ export class BracketMatchingService {
const allLines = all.split("\n");
for (let i = 0; i < chunk.length; i++) {
const char = chunk[i];
if (Object.values(BracketMatchingService.BRACKETS).includes(char)) {
if (Object.values(BRACKETS).includes(char)) {
// It's a closing bracket
if (
stack.length === 0 ||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
) {
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
// If the stack is empty or the top of the stack doesn't match the current closing bracket
yield chunk.slice(0, i);
return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream
}
} else if (
Object.keys(BracketMatchingService.BRACKETS).includes(char)
) {
} else if (Object.keys(BRACKETS).includes(char)) {
// It's an opening bracket
stack.push(char);
}

View file

@ -6,6 +6,7 @@ import { stopAtStopTokens } from "./charStream";
import {
avoidEmptyComments,
avoidPathLine,
noDoubleNewlineAfterClosingBracket,
showWhateverWeHaveAtXMs,
skipPrefixes,
stopAtLines,
@ -47,6 +48,7 @@ export class StreamTransformPipeline {
);
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
lineGenerator = skipPrefixes(lineGenerator);
lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator);
for (const lineFilter of helper.lang.lineFilters ?? []) {
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });

View file

@ -2,6 +2,7 @@ import { distance } from "fastest-levenshtein";
import { DiffLine } from "../../..";
import { LineStream } from "../../../diff/util";
import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService";
export type LineFilter = (args: {
lines: LineStream;
@ -545,3 +546,43 @@ export async function* showWhateverWeHaveAtXMs(
}
}
}
export async function* noDoubleNewlineAfterClosingBracket(
lines: LineStream,
): LineStream {
const bracketTypeCounts = new Map<string, number>();
for await (const line of lines) {
if (line.trim() === "") {
// Double newline detected
// Check if any bracket counts are negative
let hasNegativeCount = false;
for (const count of bracketTypeCounts.values()) {
if (count < 0) {
hasNegativeCount = true;
break;
}
}
if (hasNegativeCount) {
// Stop the generator if we've closed brackets we didn't open
return;
}
}
yield line;
// Update bracket counts
for (const char of line) {
if (BRACKETS[char]) {
// It's an opening bracket
const count = bracketTypeCounts.get(char) || 0;
bracketTypeCounts.set(char, count + 1);
} else if (BRACKETS_REVERSE[char]) {
// It's a closing bracket
const openingBracket = BRACKETS_REVERSE[char];
const count = bracketTypeCounts.get(openingBracket) || 0;
bracketTypeCounts.set(openingBracket, count - 1);
}
}
}
}

View file

@ -0,0 +1,166 @@
import { noDoubleNewlineAfterClosingBracket } from "./lineStream";
describe("noDoubleNewlineAfterClosingBracket", () => {
// Helper function to convert an array to an async generator
async function* arrayToAsyncGenerator<T>(array: T[]): AsyncGenerator<T> {
for (const item of array) {
yield item;
}
}
// Helper function to collect lines from the async generator
async function collectLines(lines: AsyncIterable<string>): Promise<string[]> {
const result: string[] = [];
for await (const line of lines) {
result.push(line);
}
return result;
}
test("should yield all lines when no double newline and no unmatched brackets", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should yield all lines when double newline but brackets are matched", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
"",
"",
"// End of function",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => {
const inputLines = [
// "function test() {",
' console.log("Hello World");',
// Unmatched closing bracket
"}",
"",
"",
"// This should not be yielded",
'console.log("End");',
];
const expectedOutputLines = [' console.log("Hello World");', "}"];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should yield all lines when unmatched brackets but no double newline", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
// Unmatched closing bracket
")",
"// Continue code",
'console.log("End");',
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should continue yielding if unmatched closing bracket occurs after double newline", async () => {
const inputLines = [
"function test() {",
' console.log("Hello World");',
"}",
"",
"",
// Unmatched closing bracket after double newline
")",
'console.log("End");',
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should yield all lines when brackets are matched even with double newline", async () => {
const inputLines = [
"const arr = [",
" 1, 2, 3,",
"];",
"",
"",
"console.log(arr);",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
test("should stop yielding when unmatched closing bracket occurs before double newline", async () => {
const inputLines = [
"if (condition) {",
" doSomething();",
"}",
// Unmatched closing bracket
"}",
"",
"",
"doSomethingElse();",
];
const expectedOutputLines = [
"if (condition) {",
" doSomething();",
"}",
"}",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(expectedOutputLines);
});
test("should yield all lines when no unmatched closing brackets and double newline", async () => {
const inputLines = [
"while (true) {",
" // Infinite loop",
"}",
"",
"",
"// Loop exited",
];
const lines = arrayToAsyncGenerator(inputLines);
const outputLines = await collectLines(
noDoubleNewlineAfterClosingBracket(lines),
);
expect(outputLines).toEqual(inputLines);
});
});

View file

@ -63,7 +63,7 @@ function sayHello() {
`,
llmOutput: `world!");
`,
expectedCompletion: "world!\");",
expectedCompletion: 'world!");',
},
{
description: "Should autocomplete Java when inside a block",
@ -131,10 +131,6 @@ public class Calculator {
}
`,
expectedCompletion: `
}
public void subtract(double number) {
result -= number;
}`,
},
{
@ -489,8 +485,8 @@ echo calculateArea(5, 3);`,
$colors = array("Red", "Green", <|fim|>);
echo "First color is: " . $colors[0];`,
llmOutput: "\"Blue\"",
expectedCompletion: "\"Blue\"",
llmOutput: '"Blue"',
expectedCompletion: '"Blue"',
filename: "colors.php",
},
{
@ -775,8 +771,10 @@ func main() {
FROM users u
WHERE u.active = 1
<|fim|>`,
llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
llmOutput:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
expectedCompletion:
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
},
{
description:
@ -817,8 +815,8 @@ func main() {
<p>Description text.</p>
</div>
</div>`,
llmOutput: "alt=\"Description of image\"",
expectedCompletion: "alt=\"Description of image\"",
llmOutput: 'alt="Description of image"',
expectedCompletion: 'alt="Description of image"',
filename: "test.html",
},
{
@ -930,8 +928,8 @@ public class App {
<|fim|>
]
}`,
llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }",
expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }",
llmOutput: ', { "id": 3, "name": "Charlie" }',
expectedCompletion: ', { "id": 3, "name": "Charlie" }',
},
{
description: "Should autocomplete within a CSV record",
@ -1237,8 +1235,8 @@ class Counter {
:age 30
<|fim|>
(println "User information loaded"))`,
llmOutput: ":location \"Unknown\"}",
expectedCompletion: ":location \"Unknown\"}",
llmOutput: ':location "Unknown"}',
expectedCompletion: ':location "Unknown"}',
filename: "test.clj",
},
{
@ -1301,8 +1299,8 @@ if (grade >= 90) {
} else {
print("C")
}`,
llmOutput: "print(\"B\")",
expectedCompletion: "print(\"B\")",
llmOutput: 'print("B")',
expectedCompletion: 'print("B")',
},
{
description: "Should autocomplete R ggplot2 plot structure",
@ -1324,8 +1322,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
<|fim|>
}
}`,
llmOutput: "s\"Hello, my name is $name and I am $age years old.\"",
expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"",
llmOutput: 's"Hello, my name is $name and I am $age years old."',
expectedCompletion: 's"Hello, my name is $name and I am $age years old."',
},
{
@ -1335,8 +1333,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
case class Person(name: String, age: Int, address: Address)
val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`,
llmOutput: "\"12345\")",
expectedCompletion: "\"12345\")",
llmOutput: '"12345")',
expectedCompletion: '"12345")',
},
{
@ -2066,8 +2064,8 @@ export default {
<ChildComponent <|fim|> />
</main>
`,
llmOutput: "name=\"World\"",
expectedCompletion: "name=\"World\"",
llmOutput: 'name="World"',
expectedCompletion: 'name="World"',
},
{

View file

@ -0,0 +1,215 @@
import { jest } from "@jest/globals";
import { GeneratorReuseManager } from "./GeneratorReuseManager";
function createMockGenerator(
data: string[],
delay: number = 0,
): () => AsyncGenerator<string> {
const mockGenerator = async function* () {
for (const chunk of data) {
yield chunk;
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
};
const newGenerator = jest
.fn<() => AsyncGenerator<string>>()
.mockReturnValue(mockGenerator());
return newGenerator;
}
describe("GeneratorReuseManager", () => {
let reuseManager: GeneratorReuseManager;
let onErrorMock: jest.Mock;
beforeEach(() => {
onErrorMock = jest.fn();
reuseManager = new GeneratorReuseManager(onErrorMock);
});
afterEach(() => {
jest.clearAllMocks();
});
test("creates new generator when there is no current generator", async () => {
const data = ["hello ", "world"];
const newGenerator = createMockGenerator(data);
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(data);
expect(newGenerator).toHaveBeenCalledTimes(1);
});
test("reuses generator when prefix matches pending completion", async () => {
const newGenerator = createMockGenerator(["llo ", "world"]);
// First call with initial prefix
const prefix1 = "he";
const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
const output1: string[] = [];
for await (const chunk of generator1) {
output1.push(chunk);
}
expect(output1).toEqual(["llo ", "world"]);
// Second call with extended prefix that matches pending completion
const prefix2 = "hello ";
const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
const output2: string[] = [];
for await (const chunk of generator2) {
output2.push(chunk);
}
expect(output2).toEqual(["world"]);
// Ensure generator was reused (newGenerator should be called only once)
expect(newGenerator).toHaveBeenCalledTimes(1);
});
test("creates new generator when prefix does not match pending completion", async () => {
const data = ["goodbye ", "world"];
const newGenerator = createMockGenerator(data);
// Initial generator with different prefix
reuseManager.pendingGeneratorPrefix = "hello ";
reuseManager.pendingCompletion = "world";
const prefix = "good";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(data);
// Ensure a new generator was created
expect(newGenerator).toHaveBeenCalledTimes(1);
});
test("handles multiline=false by stopping at newline", async () => {
const data = ["first line\n", "second line"];
const newGenerator = createMockGenerator(data);
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, false);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(["first line"]);
// Ensure it stops after the first newline
});
test("handles multiline=true by not stopping at newline", async () => {
const data = ["first line\n", "second line"];
const newGenerator = createMockGenerator(data);
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
for await (const chunk of generator) {
output.push(chunk);
}
expect(output).toEqual(data);
});
test("cancels previous generator when creating a new one", async () => {
const data1 = ["data from generator 1", "not generated"];
const data2 = ["data from generator 2"];
const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
const newGenerator2 = createMockGenerator(data2);
const prefix1 = "prefix1";
const prefix2 = "prefix2";
// First generator
const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
const output1: string[] = [];
for await (const chunk of generator1) {
output1.push(chunk);
// Simulate the generator being canceled before completing
reuseManager.currentGenerator?.cancel();
}
expect(output1.length).toEqual(1);
expect(output1[0]).toEqual(data1[0]);
// Second generator
const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
const output2: string[] = [];
for await (const chunk of generator2) {
output2.push(chunk);
}
expect(output2).toEqual(data2);
});
test("calls onError when generator throws an error", async () => {
const error = new Error("Generator error");
const mockGenerator = async function* () {
throw error;
};
const newGenerator = jest
.fn<() => AsyncGenerator<string>>()
.mockReturnValue(mockGenerator());
const prefix = "";
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
const output: string[] = [];
await expect(async () => {
for await (const chunk of generator) {
output.push(chunk);
}
}).not.toThrow(); // getGenerator handles errors internally
expect(onErrorMock).toHaveBeenCalledWith(error);
expect(output).toEqual([]);
});
test("handles backspacing by creating new generator when prefix is shorter", async () => {
const data = ["hello world"];
const newGenerator1 = createMockGenerator(data);
const newGenerator2 = createMockGenerator(data);
// First prefix
const prefix1 = "hello world";
const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
const output1: string[] = [];
for await (const chunk of generator1) {
output1.push(chunk);
}
// Simulate backspace (prefix is shorter)
const prefix2 = "hello worl";
const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
const output2: string[] = [];
for await (const chunk of generator2) {
output2.push(chunk);
}
// Ensure a new generator was created
expect(newGenerator1).toHaveBeenCalledTimes(1);
expect(newGenerator2).toHaveBeenCalledTimes(1);
});
});

View file

@ -21,47 +21,54 @@ export class GeneratorReuseManager {
this.currentGenerator = listenableGen;
}
private shouldReuseExistingGenerator(prefix: string): boolean {
return (
!!this.currentGenerator &&
!!this.pendingGeneratorPrefix &&
(this.pendingGeneratorPrefix + this.pendingCompletion).startsWith(
prefix,
) &&
// for e.g. backspace
this.pendingGeneratorPrefix?.length <= prefix?.length
);
}
async *getGenerator(
prefix: string,
newGenerator: () => AsyncGenerator<string>,
multiline: boolean,
): AsyncGenerator<string> {
// Check if current can be reused
if (
!(
this.currentGenerator &&
this.pendingGeneratorPrefix &&
(this.pendingGeneratorPrefix + this.pendingCompletion).startsWith(
prefix,
) &&
// for e.g. backspace
this.pendingGeneratorPrefix?.length <= prefix?.length
)
) {
// If we can't reuse, then create a new generator
if (!this.shouldReuseExistingGenerator(prefix)) {
// Create a wrapper over the current generator to fix the prompt
this._createListenableGenerator(newGenerator(), prefix);
}
let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || "";
// Already typed characters are those that are new in the prefix from the old generator
let typedSinceLastGenerator =
prefix.slice(this.pendingGeneratorPrefix?.length) || "";
for await (let chunk of this.currentGenerator?.tee() ?? []) {
if (!chunk) {
continue;
}
while (chunk.length && alreadyTyped.length) {
if (chunk[0] === alreadyTyped[0]) {
alreadyTyped = alreadyTyped.slice(1);
// Ignore already typed characters in the completion
while (chunk.length && typedSinceLastGenerator.length) {
if (chunk[0] === typedSinceLastGenerator[0]) {
typedSinceLastGenerator = typedSinceLastGenerator.slice(1);
chunk = chunk.slice(1);
} else {
break;
}
}
// Break at newline unless we are in multiline mode
const newLineIndex = chunk.indexOf("\n");
if (multiline || newLineIndex === -1) {
yield chunk;
} else {
if (newLineIndex >= 0 && !multiline) {
yield chunk.slice(0, newLineIndex);
break;
} else if (chunk !== "") {
yield chunk;
}
}
}

View file

@ -0,0 +1,149 @@
import { jest } from "@jest/globals";
import { ListenableGenerator } from "./ListenableGenerator";
describe("ListenableGenerator", () => {
// Helper function to create an async generator
async function* asyncGenerator<T>(values: T[], delay = 0) {
for (const value of values) {
if (delay > 0) {
await new Promise((resolve) => setTimeout(resolve, delay));
}
yield value;
}
}
it("should yield values from the source generator via tee()", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const result: number[] = [];
for await (const value of lg.tee()) {
result.push(value);
}
expect(result).toEqual(values);
expect(onError).not.toHaveBeenCalled();
});
it("should allow listeners to receive values", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const listener = jest.fn();
// Add listener after some delay to simulate late subscription
setTimeout(() => {
lg.listen(listener);
}, 15);
// Wait for generator to finish
await new Promise((resolve) => setTimeout(resolve, 50));
expect(listener).toHaveBeenCalledWith(1);
expect(listener).toHaveBeenCalledWith(2);
expect(listener).toHaveBeenCalledWith(3);
// Listener should receive null at the end
expect(listener).toHaveBeenCalledWith(null);
});
it("should buffer values for listeners added after some values have been yielded", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values, 10);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const initialListener = jest.fn();
lg.listen(initialListener);
// Wait for the first value to be yielded
await new Promise((resolve) => setTimeout(resolve, 15));
// Add a second listener
const newListener = jest.fn();
lg.listen(newListener);
// Wait for generator to finish
await new Promise((resolve) => setTimeout(resolve, 50));
// Both listeners should have received all values
[initialListener, newListener].forEach((listener) => {
expect(listener).toHaveBeenCalledWith(1);
expect(listener).toHaveBeenCalledWith(2);
expect(listener).toHaveBeenCalledWith(3);
expect(listener).toHaveBeenCalledWith(null);
});
});
it("should handle cancellation", async () => {
const values = [1, 2, 3, 4, 5];
const source = asyncGenerator(values, 10);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const result: number[] = [];
const teeIterator = lg.tee();
const consume = async () => {
for await (const value of teeIterator) {
result.push(value);
if (value === 3) {
lg.cancel();
}
}
};
await consume();
expect(result).toEqual([1, 2, 3]);
expect(lg["_isEnded"]).toBe(true);
});
it("should call onError when the source generator throws an error", async () => {
async function* errorGenerator() {
yield 1;
throw new Error("Test error");
}
const source = errorGenerator();
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const result: number[] = [];
for await (const value of lg.tee()) {
result.push(value);
}
expect(result).toEqual([1]);
expect(onError).toHaveBeenCalledTimes(1);
expect(onError).toHaveBeenCalledWith(new Error("Test error"));
});
it("should notify listeners when the generator ends", async () => {
const values = [1, 2, 3];
const source = asyncGenerator(values);
const onError = jest.fn();
const lg = new ListenableGenerator<number>(source, onError);
const listener = jest.fn();
lg.listen(listener);
// Wait for the generator to finish
await new Promise((resolve) => setTimeout(resolve, 10));
expect(listener).toHaveBeenCalledWith(1);
expect(listener).toHaveBeenCalledWith(2);
expect(listener).toHaveBeenCalledWith(3);
expect(listener).toHaveBeenCalledWith(null);
});
});