test: overhaul deterministic suite architecture

This commit is contained in:
morluto
2026-07-29 22:00:38 +00:00
parent 7f2348619a
commit 513d9b1555
371 changed files with 30879 additions and 24389 deletions
+69
View File
@@ -0,0 +1,69 @@
import { resolve } from "node:path";
import {
processTest,
type ProcessResult,
type TestProcesses,
} from "../process/processFixture.js";
/** Caller-controlled values for one compiled REA CLI invocation. */
export interface CliInvocation {
readonly arguments: readonly string[];
readonly cwd?: string;
readonly environment?: NodeJS.ProcessEnv;
readonly input?: string | Uint8Array;
readonly timeoutMs?: number;
}
/** Normalized result from the compiled REA CLI. */
export interface CliResult extends ProcessResult {
readonly json: unknown | undefined;
}
/** Compiled REA CLI driver owned by one test. */
export interface TestCli {
run(invocation: CliInvocation): Promise<CliResult>;
}
const parseJson = (stdout: string): unknown | undefined => {
const document = stdout.trim();
if (document.length === 0) return undefined;
try {
return JSON.parse(document) as unknown;
} catch {
return undefined;
}
};
/** Create a compiled CLI driver backed by the supplied process registry. */
export const createTestCli = (processes: TestProcesses): TestCli => ({
run: async ({
arguments: arguments_,
cwd,
environment,
input,
timeoutMs,
}) => {
const result = await processes.run(
process.execPath,
[resolve("scripts/rea.mjs"), ...arguments_],
{
cwd: cwd ?? process.cwd(),
env: {
PATH: process.env.PATH ?? "",
...environment,
},
...(input === undefined ? {} : { input }),
...(timeoutMs === undefined ? {} : { timeoutMs }),
},
);
return { ...result, json: parseJson(result.stdout) };
},
});
/** Vitest API extended with an owned process registry and compiled CLI driver. */
export const cliTest = processTest.extend<{ cli: TestCli }>({
cli: async ({ processes }, use) => {
await use(createTestCli(processes));
},
});
+61
View File
@@ -0,0 +1,61 @@
import { cliTest } from "./cli/cliFixture.js";
import {
createTestLoopback,
type TestLoopback,
} from "./network/loopbackFixture.js";
import { createTestMcp, type TestMcp } from "./mcp/mcpFixture.js";
import {
createTestWorkspace,
removeTestWorkspace,
type TestWorkspace,
} from "./workspace/workspaceFixture.js";
const withWorkspace = cliTest.extend<{ workspace: TestWorkspace }>({
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
workspace: async ({}, use) => {
const workspace = await createTestWorkspace();
try {
await use(workspace);
} finally {
await removeTestWorkspace(workspace.root);
}
},
});
const withLoopback = withWorkspace.extend<{ loopback: TestLoopback }>({
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
loopback: async ({}, use) => {
const loopback = createTestLoopback();
try {
await use(loopback);
} finally {
await loopback.close();
}
},
});
/** Vitest API with all reusable, test-scoped REA resource fixtures. */
export const fixtureTest = withLoopback.extend<{ mcp: TestMcp }>({
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
mcp: async ({}, use) => {
const mcp = createTestMcp();
try {
await use(mcp);
} finally {
await mcp.close();
}
},
});
export type { CliInvocation, CliResult, TestCli } from "./cli/cliFixture.js";
export type {
LoopbackEndpoint,
TestLoopback,
} from "./network/loopbackFixture.js";
export type { McpClientIdentity, TestMcp } from "./mcp/mcpFixture.js";
export type {
ProcessResult,
ProcessRunOptions,
TestProcesses,
} from "./process/processFixture.js";
export type { TestWorkspace } from "./workspace/workspaceFixture.js";
+72
View File
@@ -0,0 +1,72 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import type { McpServer } from "@modelcontextprotocol/server";
import { test as base } from "vitest";
/** Client identity used during an in-memory MCP negotiation. */
export interface McpClientIdentity {
readonly name: string;
readonly version: string;
}
/** Registry for production MCP servers and SDK clients owned by one test. */
export interface TestMcp {
connect(server: McpServer, identity?: McpClientIdentity): Promise<Client>;
close(): Promise<void>;
}
const DEFAULT_CLIENT_IDENTITY: McpClientIdentity = {
name: "rea-vitest",
version: "1.0.0",
};
/** Create an MCP connection registry for a fixture composition root. */
export const createTestMcp = (): TestMcp => {
const connections: { readonly client: Client; readonly server: McpServer }[] =
[];
return {
connect: async (server, identity = DEFAULT_CLIENT_IDENTITY) => {
const client = new Client(identity);
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
} catch (cause) {
await Promise.allSettled([client.close(), server.close()]);
throw cause;
}
connections.push({ client, server });
return client;
},
close: async () => {
const results = await Promise.allSettled(
[...connections].reverse().map(async ({ client, server }) => {
try {
await client.close();
} finally {
await server.close();
}
}),
);
const failure = results.find(
(result): result is PromiseRejectedResult =>
result.status === "rejected",
);
if (failure !== undefined) throw failure.reason;
},
};
};
/** Vitest API extended with production-server/in-memory-client MCP wiring. */
export const mcpTest = base.extend<{ mcp: TestMcp }>({
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
mcp: async ({}, use) => {
const mcp = createTestMcp();
try {
await use(mcp);
} finally {
await mcp.close();
}
},
});
+72
View File
@@ -0,0 +1,72 @@
import { createServer as createHttpServer } from "node:http";
import type { RequestListener } from "node:http";
import type { AddressInfo, Server, Socket } from "node:net";
/** A listening server bound to an ephemeral IPv4 loopback port. */
export interface LoopbackEndpoint {
readonly host: "127.0.0.1";
readonly port: number;
readonly origin: string;
}
/** Registry for loopback servers and accepted sockets owned by one test. */
export interface TestLoopback {
listen(server: Server): Promise<LoopbackEndpoint>;
http(listener: RequestListener): Promise<LoopbackEndpoint>;
close(): Promise<void>;
}
const closeServer = (server: Server): Promise<void> =>
new Promise((resolve, reject) => {
if (!server.listening) {
resolve();
return;
}
server.close((error) => {
if (error === undefined) resolve();
else reject(error);
});
});
/** Create a loopback registry for a fixture composition root. */
export const createTestLoopback = (): TestLoopback => {
const servers: Server[] = [];
const sockets = new Set<Socket>();
const listen = async (server: Server): Promise<LoopbackEndpoint> => {
server.on("connection", (socket) => {
sockets.add(socket);
socket.once("close", () => sockets.delete(socket));
});
await new Promise<void>((resolve, reject) => {
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
server.removeListener("error", reject);
resolve();
});
});
servers.push(server);
const address = server.address() as AddressInfo;
return {
host: "127.0.0.1",
port: address.port,
origin: `http://127.0.0.1:${address.port}`,
};
};
return {
listen,
http: (listener) => listen(createHttpServer(listener)),
close: async () => {
for (const socket of sockets) socket.destroy();
const results = await Promise.allSettled(
[...servers].reverse().map(closeServer),
);
const failure = results.find(
(result): result is PromiseRejectedResult =>
result.status === "rejected",
);
if (failure !== undefined) throw failure.reason;
},
};
};
+157
View File
@@ -0,0 +1,157 @@
import {
spawn as nodeSpawn,
type ChildProcessWithoutNullStreams,
type SpawnOptionsWithoutStdio,
} from "node:child_process";
import { test as base } from "vitest";
const SHUTDOWN_GRACE_MS = 1_000;
/** Captured output and termination state from one child process. */
export interface ProcessResult {
readonly exitCode: number | null;
readonly signal: NodeJS.Signals | null;
readonly stdout: string;
readonly stderr: string;
}
/** Options for a bounded, output-capturing child process invocation. */
export interface ProcessRunOptions extends SpawnOptionsWithoutStdio {
readonly timeoutMs?: number;
readonly input?: string | Uint8Array;
}
/** Registry for child processes owned by one test. */
export interface TestProcesses {
spawn(
command: string,
arguments_: readonly string[],
options?: SpawnOptionsWithoutStdio,
): ChildProcessWithoutNullStreams;
run(
command: string,
arguments_: readonly string[],
options?: ProcessRunOptions,
): Promise<ProcessResult>;
shutdown(): Promise<void>;
}
const waitForExit = (
child: ChildProcessWithoutNullStreams,
timeoutMs: number,
): Promise<boolean> =>
new Promise((resolve) => {
if (child.exitCode !== null || child.signalCode !== null) {
resolve(true);
return;
}
const timer = setTimeout(() => {
child.removeListener("exit", onExit);
resolve(false);
}, timeoutMs);
timer.unref();
const onExit = (): void => {
clearTimeout(timer);
resolve(true);
};
child.once("exit", onExit);
});
const stopChild = async (
child: ChildProcessWithoutNullStreams,
): Promise<void> => {
if (child.exitCode !== null || child.signalCode !== null) return;
child.kill("SIGTERM");
if (await waitForExit(child, SHUTDOWN_GRACE_MS)) return;
child.kill("SIGKILL");
await waitForExit(child, SHUTDOWN_GRACE_MS);
};
/** Create a child-process registry for a fixture composition root. */
export const createTestProcessRegistry = (): TestProcesses => {
const children = new Set<ChildProcessWithoutNullStreams>();
const spawn = (
command: string,
arguments_: readonly string[],
options: SpawnOptionsWithoutStdio = {},
): ChildProcessWithoutNullStreams => {
const child = nodeSpawn(command, arguments_, {
...options,
stdio: ["pipe", "pipe", "pipe"],
});
children.add(child);
child.once("exit", () => children.delete(child));
return child;
};
return {
spawn,
run: async (command, arguments_, options = {}) => {
const { input, timeoutMs, ...spawnOptions } = options;
const child = spawn(command, arguments_, spawnOptions);
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
child.stdout.on("data", (chunk: Buffer) => stdout.push(chunk));
child.stderr.on("data", (chunk: Buffer) => stderr.push(chunk));
if (input === undefined) child.stdin.end();
else child.stdin.end(input);
let timedOut = false;
let killTimeout: NodeJS.Timeout | undefined;
const timeout =
timeoutMs === undefined
? undefined
: setTimeout(() => {
timedOut = true;
child.kill("SIGTERM");
killTimeout = setTimeout(() => {
child.kill("SIGKILL");
}, SHUTDOWN_GRACE_MS);
killTimeout.unref();
}, timeoutMs);
timeout?.unref();
const result = await new Promise<ProcessResult>((resolve, reject) => {
child.once("error", reject);
child.once("close", (exitCode, signal) =>
resolve({
exitCode,
signal,
stdout: Buffer.concat(stdout).toString("utf8"),
stderr: Buffer.concat(stderr).toString("utf8"),
}),
);
}).finally(() => {
if (timeout !== undefined) clearTimeout(timeout);
if (killTimeout !== undefined) clearTimeout(killTimeout);
});
if (timedOut) {
throw new Error(`Test process exceeded its ${timeoutMs}ms deadline`, {
cause: result,
});
}
return result;
},
shutdown: async () => {
await Promise.allSettled([...children].reverse().map(stopChild));
if (children.size > 0) {
throw new Error(`${children.size} test child process(es) leaked`);
}
},
};
};
/** Vitest API extended with a bounded child-process registry. */
export const processTest = base.extend<{ processes: TestProcesses }>({
// oxlint-disable-next-line no-empty-pattern -- Vitest parses fixture dependencies from object destructuring.
processes: async ({}, use) => {
const processes = createTestProcessRegistry();
try {
await use(processes);
} finally {
await processes.shutdown();
}
},
});
@@ -0,0 +1,88 @@
import {
mkdir,
mkdtemp,
readFile,
realpath,
rm,
writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
/** An isolated filesystem and environment projection owned by one test. */
export interface TestWorkspace {
readonly root: string;
readonly home: string;
readonly xdgConfigHome: string;
readonly xdgCacheHome: string;
readonly environment: NodeJS.ProcessEnv;
path(...segments: readonly string[]): string;
mkdir(relativePath: string): Promise<string>;
read(relativePath: string): Promise<string>;
write(relativePath: string, contents: string | Uint8Array): Promise<string>;
}
/** Remove a workspace previously returned by createTestWorkspace. */
export const removeTestWorkspace = async (root: string): Promise<void> => {
await rm(root, {
recursive: true,
force: true,
maxRetries: 3,
retryDelay: 25,
});
};
/** Create one isolated workspace for a fixture composition root. */
export const createTestWorkspace = async (
prefix = "rea-test-workspace-",
): Promise<TestWorkspace> => {
const canonicalTemporaryRoot = await realpath(tmpdir());
const root = await realpath(
await mkdtemp(join(canonicalTemporaryRoot, prefix)),
);
const home = join(root, "home");
const xdgConfigHome = join(root, "xdg", "config");
const xdgCacheHome = join(root, "xdg", "cache");
await Promise.all([
mkdir(home, { recursive: true }),
mkdir(xdgConfigHome, { recursive: true }),
mkdir(xdgCacheHome, { recursive: true }),
]);
const resolvePath = (...segments: readonly string[]): string => {
const path = resolve(root, ...segments);
const displacement = relative(root, path);
if (displacement === ".." || displacement.startsWith(`..${sep}`)) {
throw new TypeError("Test workspace paths must remain beneath its root");
}
if (isAbsolute(displacement)) {
throw new TypeError("Test workspace paths must remain beneath its root");
}
return path;
};
return {
root,
home,
xdgConfigHome,
xdgCacheHome,
environment: {
HOME: home,
XDG_CONFIG_HOME: xdgConfigHome,
XDG_CACHE_HOME: xdgCacheHome,
},
path: resolvePath,
mkdir: async (relativePath) => {
const path = resolvePath(relativePath);
await mkdir(path, { recursive: true });
return path;
},
read: (relativePath) => readFile(resolvePath(relativePath), "utf8"),
write: async (relativePath, contents) => {
const path = resolvePath(relativePath);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, contents);
return path;
},
};
};