Add deterministic tests

This commit is contained in:
Andras Schmelczer 2026-03-25 21:34:57 +00:00
commit 0ce82353e0
20 changed files with 1780 additions and 0 deletions

View file

@ -0,0 +1,5 @@
export function assert(value: boolean, message: string): asserts value {
if (!value) {
throw new Error(message);
}
}

View file

@ -0,0 +1,29 @@
import * as net from "node:net";
export interface PortReservation {
port: number;
release: () => void;
}
/**
* Find a free port and keep it reserved until the caller explicitly releases it.
*/
export async function findFreePort(): Promise<PortReservation> {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
if (addr === null || typeof addr === "string") {
server.close();
reject(new Error("Failed to get port from server"));
return;
}
const { port } = addr;
resolve({
port,
release: () => server.close()
});
});
server.on("error", reject);
});
}

View file

@ -0,0 +1,3 @@
export async function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}

View file

@ -0,0 +1,15 @@
export async function withTimeout<T>(
promise: Promise<T>,
timeoutMs: number,
message: string
): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout> | undefined = undefined;
const timeoutPromise = new Promise<never>((_resolve, reject) => {
timeoutId = setTimeout(() => {
reject(new Error(message));
}, timeoutMs);
});
return Promise.race([promise, timeoutPromise]).finally(() => {
clearTimeout(timeoutId);
});
}