import { test } from "node:test" import assert from "node:assert/strict" import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises" import os from "node:os" import path from "node:path" import { parseIntelGpuTop, sampleIntelGpu } from "../dist/linux.js" async function fakeGpuTool(t, ignoreInterrupt) { const directory = await mkdtemp(path.join(os.tmpdir(), "system-monitor-gpu-test-")) const pidFile = path.join(directory, "pid") const originalPath = process.env.PATH const source = `#!${process.execPath} import { writeFileSync } from "node:fs"; writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); process.stdout.write('[{"engines":{"Render/0":{"busy":31}}}'); process.on("SIGINT", () => { ${ignoreInterrupt ? "" : 'process.stdout.write("]"); process.exit(0);'} }); setInterval(() => {}, 1000); ` await writeFile(path.join(directory, "intel_gpu_top"), source, { mode: 0o755 }) await writeFile(path.join(directory, "package.json"), '{"type":"module"}') process.env.PATH = `${directory}:${originalPath}` t.after(async () => { process.env.PATH = originalPath // Clean up our own fake process if an assertion or the collector fails. try { const pid = Number(await readFile(pidFile, "utf8")) try { process.kill(pid, "SIGKILL") } catch { /* already exited */ } } catch { /* process never started */ } await rm(directory, { recursive: true, force: true }) }) return async () => Number(await readFile(pidFile, "utf8")) } test("Linux Intel sampling interrupts the streaming tool and leaves no process running", { skip: process.platform !== "linux" }, async t => { const pid = await fakeGpuTool(t, false) const output = await sampleIntelGpu("/dev/dri/card0") assert.equal(parseIntelGpuTop(output), 31) const childPID = await pid() assert.throws(() => process.kill(childPID, 0), error => error.code === "ESRCH") }) test("Linux Intel sampling forcibly terminates a tool that ignores its interrupt", { skip: process.platform !== "linux" }, async t => { const pid = await fakeGpuTool(t, true) await assert.rejects(sampleIntelGpu("/dev/dri/card0"), /counters unavailable/) const childPID = await pid() assert.throws(() => process.kill(childPID, 0), error => error.code === "ESRCH") })