Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/loop/__tests__/gates.test.ts

Raw
import { describe, expect, it, vi } from "vitest";
import {
	CAPTURE_LIMIT,
	type Gate,
	parseGates,
	runGate,
	runGatePass,
} from "../src/gates.ts";

const node = (script: string, name?: string): Gate => ({
	...(name ? { name } : {}),
	command: process.execPath,
	args: ["-e", script],
});
const live = () => new AbortController().signal;

describe("gate pass", () => {
	it("passes only when every gate exits 0", async () => {
		const pass = await runGatePass(
			[node("process.exit(0)"), node("process.exit(0)")],
			process.cwd(),
			live(),
		);
		expect(pass.failedIndex).toBeNull();
		expect(pass.results.map((r) => r.exitCode)).toEqual([0, 0]);
	});

	it("stops at the first failing gate and keeps its output", async () => {
		const pass = await runGatePass(
			[
				node("process.exit(0)"),
				node(
					"console.log('PASS claimed'); console.error('boom'); process.exit(3)",
				),
				node("process.exit(0)"),
			],
			process.cwd(),
			live(),
		);
		expect(pass.failedIndex).toBe(1);
		expect(pass.results).toHaveLength(2);
		expect(pass.results[1]).toMatchObject({
			exitCode: 3,
			error: null,
			stdout: "PASS claimed\n",
			stderr: "boom\n",
		});
	});

	it("rejects a pre-aborted signal without spawning", async () => {
		const controller = new AbortController();
		controller.abort();
		const result = await runGate(
			node("require('fs').writeFileSync('should-not-exist', '')"),
			process.cwd(),
			controller.signal,
		);
		expect(result.exitCode).toBeNull();
		expect(result.error).toMatch(/cancelled before start/u);
	});

	it("never accepts exit 0 after cancellation mid-run", async () => {
		const controller = new AbortController();
		const pending = runGate(
			node("setTimeout(() => process.exit(0), 5000)"),
			process.cwd(),
			controller.signal,
		);
		setTimeout(() => controller.abort(), 100);
		const result = await pending;
		expect(result.error).toMatch(/cancelled/u);
	});

	it("reports a missing executable as an error, not an exit code", async () => {
		const result = await runGate(
			{ command: "loop-gate-missing-executable" },
			process.cwd(),
			live(),
		);
		expect(result.exitCode).toBeNull();
		expect(result.error).toMatch(/ENOENT/u);
	});

	it("delivers the trailing live output during silence without waiting for completion", async () => {
		const cancel = new AbortController();
		let output = "";
		const pending = runGate(
			node(
				"console.log('first');setTimeout(()=>console.log('second'),25);setInterval(()=>{},1000)",
			),
			process.cwd(),
			cancel.signal,
			(value) => {
				output = value.stdout;
			},
		);
		try {
			await vi.waitFor(() => expect(output).toContain("second"));
			expect(output).toContain("first");
		} finally {
			cancel.abort();
			await pending;
		}
	});

	it("keeps only the bounded tail of large output", async () => {
		const result = await runGate(
			node(`process.stdout.write('a'.repeat(${CAPTURE_LIMIT * 3}) + 'END')`),
			process.cwd(),
			live(),
		);
		expect(result.truncated).toBe(true);
		expect(result.stdout.length).toBe(CAPTURE_LIMIT);
		expect(result.stdout.endsWith("END")).toBe(true);
	});

	it("passes env and cwd to the gate", async () => {
		const result = await runGate(
			{
				...node("console.log(process.env.LOOP_PROBE + ':' + process.cwd())"),
				env: { LOOP_PROBE: "seen" },
				cwd: "..",
			},
			process.cwd(),
			live(),
		);
		expect(result.stdout.trim().startsWith("seen:")).toBe(true);
	});
});

describe("gate parsing", () => {
	it("accepts JSON gate lists", () => {
		expect(
			parseGates('[{"name":"tests","command":"npm","args":["test"]}]'),
		).toEqual([{ name: "tests", command: "npm", args: ["test"] }]);
	});

	it.each([
		["empty list", "[]"],
		["not a list", '{"command":"x"}'],
		["blank command", '[{"command":" "}]'],
		["unknown field", '[{"command":"x","shell":true}]'],
		["non-string args", '[{"command":"x","args":[1]}]'],
		["non-string env", '[{"command":"x","env":{"A":1}}]'],
	])("rejects %s", (_name, raw) => {
		expect(() => parseGates(raw)).toThrow();
	});
});