Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/git-safe/__tests__/spawn.test.ts

Raw
import { describe, expect, it } from "vitest";
import { SpawnTimeoutError, spawnExpect, spawnWithTimeout } from "../spawn";

describe("spawnWithTimeout", () => {
	it("marks timed-out processes as killed", async () => {
		const result = await spawnWithTimeout(
			process.execPath,
			["-e", "setTimeout(() => {}, 10_000)"],
			{ timeout: 50 },
		);

		expect(result.killed).toBe(true);
		expect(result.code).not.toBe(0);
	});

	it("preserves UTF-8 characters split across subprocess chunks", async () => {
		const result = await spawnWithTimeout(process.execPath, [
			"-e",
			"process.stdout.write(Buffer.from([0xe2])); setTimeout(() => process.stdout.write(Buffer.from([0x82, 0xac])), 25)",
		]);
		expect(result).toMatchObject({
			stdout: "€",
			code: 0,
			outputLimitExceeded: false,
		});
	});

	it("does not mark successful processes as killed", async () => {
		const result = await spawnWithTimeout(
			process.execPath,
			["-e", "process.stdout.write(process.env.GIT_TERMINAL_PROMPT ?? '')"],
			{ timeout: 5_000 },
		);

		expect(result).toMatchObject({ stdout: "0", code: 0, killed: false });
	});

	it("bounds combined stdout and stderr and terminates an overflowing process", async () => {
		const result = await spawnWithTimeout(
			process.execPath,
			[
				"-e",
				"process.stdout.write('x'.repeat(768)); process.stderr.write('y'.repeat(768)); setInterval(() => {}, 1000)",
			],
			{ timeout: 5000, maxOutputBytes: 1024 },
		);
		expect(result).toMatchObject({ outputLimitExceeded: true, killed: true });
		expect(
			Buffer.byteLength(result.stdout) + Buffer.byteLength(result.stderr),
		).toBeLessThanOrEqual(1024);
	});

	it("reports output overflow distinctly from a timeout", async () => {
		await expect(
			spawnExpect(
				process.execPath,
				["-e", "process.stdout.write('x'.repeat(2048))"],
				{ maxOutputBytes: 1024 },
			),
		).rejects.toThrow(/output limit/);
	});

	it("throws SpawnTimeoutError through spawnExpect", async () => {
		await expect(
			spawnExpect(process.execPath, ["-e", "setTimeout(() => {}, 10_000)"], {
				timeout: 50,
			}),
		).rejects.toBeInstanceOf(SpawnTimeoutError);
	});
});