Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/intellij/__tests__/debug.test.ts

Raw
import { mkdtempSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";

const extensionPath = path.resolve(import.meta.dirname, "../index.ts");
let root: string | undefined;
let session: PiSession | undefined;

afterEach(async () => {
	await session?.dispose();
	if (root) rmSync(root, { recursive: true, force: true });
	session = undefined;
	root = undefined;
});

describe("intellij debug harness", () => {
	it("writes its lifecycle records in the isolated sandbox", async () => {
		root = mkdtempSync(path.join(tmpdir(), "pi-ext-intellij-debug-"));
		const localAppData = path.join(root, ".local-app-data");
		session = await createPiSession({
			cwd: root,
			env: { LOCALAPPDATA: localAppData, PI_INTELLIJ_DEBUG: "1" },
			extensionPaths: [extensionPath],
		});
		await session.session.extensionRunner.emit({
			type: "session_start",
			reason: "startup",
		});
		await session.session.extensionRunner.emit({
			type: "session_shutdown",
			reason: "quit",
		});

		const directory =
			process.platform === "win32"
				? path.join(localAppData, "pi-ext", "debug", "intellij")
				: process.platform === "darwin"
					? path.join(root, ".home", "Library", "Logs", "pi-ext", "intellij")
					: path.join(
							session.env["XDG_STATE_HOME"] ?? path.join(root, ".test-state"),
							"pi-ext",
							"debug",
							"intellij",
						);
		// Debug records flush asynchronously; poll until both lifecycle events
		// appear before asserting.
		await vi.waitFor(() => {
			const records = readdirSync(directory).flatMap((file) =>
				readFileSync(path.join(directory, file), "utf8")
					.trim()
					.split("\n")
					.filter(Boolean)
					.map(
						(line) => JSON.parse(line) as { event: string; extension: string },
					),
			);
			expect(records).toContainEqual(
				expect.objectContaining({
					event: "session.start",
					extension: "intellij",
				}),
			);
			expect(records).toContainEqual(
				expect.objectContaining({
					event: "session.shutdown",
					extension: "intellij",
				}),
			);
		});
	});
});