diff --git a/README.md b/README.md index 9b0d7e3..1b7e645 100644 --- a/README.md +++ b/README.md @@ -1422,6 +1422,8 @@ npm run build | `npx tsx scripts/run-tests.ts ` | Run just the tests whose path matches, such as `cliche` or `unit/`. | | `npx tsx test/unit/test-cliche.ts` | Run a single test script directly, from the repo root. | +The runner gives each test its own temp folder (`TMPDIR`) and removes it when the test ends, however it ends, so test runs leave nothing in the system temp dir. A test run directly removes the store `test/env.ts` made for it; other temp folders it makes stay until the system cleans them. + ### Env vars | Variable | Purpose | diff --git a/scripts/run-tests.ts b/scripts/run-tests.ts index 3bb2f7c..258faca 100644 --- a/scripts/run-tests.ts +++ b/scripts/run-tests.ts @@ -18,10 +18,16 @@ // npm run test:full — test/unit, test/browser and test/e2e // npm test — test:fast // +// Each test gets its own temp folder (TMPDIR, TMP and TEMP point at it), removed +// when the test ends — passed, failed or timed out — so the stores, repos and +// Chrome profiles tests make under os.tmpdir() never pile up. +// // Pass substrings of a test's path to run a subset: `npx tsx scripts/run-tests.ts cliche` // or `unit/` for a folder. `--root ` reads the folders from another directory // (the runner's own tests use it). -import { existsSync, readdirSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync } from 'node:fs'; +import { userInfo } from 'node:os'; +import { tmpdir } from 'node:os'; import { dirname, join, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; import { spawn, type ChildProcess } from 'node:child_process'; @@ -62,23 +68,53 @@ const selected = TIER_FOLDERS[tier] .flatMap(discover) .filter((t) => filters.length === 0 || filters.some((q) => t.includes(q))); -/** The test running now. Its own process group doesn't get the terminal's - * Ctrl-C, so the runner passes an interrupt on before exiting. */ +/** The test running now and its temp folder. Its own process group doesn't + * get the terminal's Ctrl-C, so the runner passes an interrupt on, and + * removes the folder, before exiting. */ let current: ChildProcess | undefined; +let currentScratch: string | undefined; for (const signal of ['SIGINT', 'SIGTERM'] as const) { process.on(signal, () => { if (current?.pid) { try { process.kill(-current.pid, 'SIGKILL'); } catch { /* already gone */ } } + if (currentScratch) removeScratch(currentScratch); process.exit(130); }); } +/** The system temp dir; each test's folder sits in it. A runner started by a + * test (the runner's own tests) inherits the outer runner's base instead of + * nesting its folders inside that test's, because tsx opens a Unix socket + * under TMPDIR and macOS caps socket paths at about 104 characters. */ +const SYSTEM_TMP = process.env.FRAMESMITH_RUN_TMP_BASE || tmpdir(); + +/** Caches that live in os.tmpdir(): tsx's compile cache (and its IPC socket) + * and Node's module compile cache. A link to the shared one keeps each warm + * across tests; removing the test's folder removes the link, never the cache. */ +const SHARED_CACHES = [`tsx-${userInfo().uid}`, 'node-compile-cache']; +function linkCaches(scratch: string): void { + for (const name of SHARED_CACHES) { + const shared = join(SYSTEM_TMP, name); + try { mkdirSync(shared, { recursive: true }); symlinkSync(shared, join(scratch, name), 'dir'); } catch { /* the tool makes its own */ } + } +} + +function removeScratch(dir: string): void { + try { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); } catch { /* a file still held open; the OS temp cleaner gets it */ } +} + type Result = { test: string; ok: boolean; why: string; ms: number }; function run(test: string): Promise { const unit = test.startsWith('unit/'); - const env = unit - ? { ...process.env, FRAMESMITH_CHROME_PATH: NO_CHROME, PUPPETEER_EXECUTABLE_PATH: NO_CHROME } - : process.env; + const scratch = mkdtempSync(join(SYSTEM_TMP, 'framesmith-run-')); + currentScratch = scratch; + linkCaches(scratch); + const env = { + ...process.env, + TMPDIR: scratch, TMP: scratch, TEMP: scratch, + FRAMESMITH_RUN_TMP_BASE: SYSTEM_TMP, + ...(unit ? { FRAMESMITH_CHROME_PATH: NO_CHROME, PUPPETEER_EXECUTABLE_PATH: NO_CHROME } : {}), + }; return new Promise((done) => { const started = Date.now(); // Its own process group, so a timeout kills npx AND the tsx under it. @@ -92,6 +128,8 @@ function run(test: string): Promise { const timer = setTimeout(() => process.kill(-child.pid!, 'SIGKILL'), TIMEOUT_MS); child.on('close', (code, signal) => { clearTimeout(timer); + removeScratch(scratch); + currentScratch = undefined; const ms = Date.now() - started; if (signal === 'SIGKILL') return done({ test, ok: false, why: `timed out after ${TIMEOUT_MS / 1000}s`, ms }); if (code === 0) return done({ test, ok: true, why: '', ms }); diff --git a/test/env.ts b/test/env.ts index 866017e..209e90c 100644 --- a/test/env.ts +++ b/test/env.ts @@ -8,11 +8,17 @@ // // ES-module side effects run in import order, so a first-position import // guarantees FRAMESMITH_HOME is set before any src module evaluates. The guard -// respects tests that set their own FRAMESMITH_HOME. -import { mkdtempSync } from 'node:fs'; +// respects tests that set their own FRAMESMITH_HOME, and removes the store it +// made when the process exits (the test runner also removes each test's whole +// temp folder, which covers a test killed before it could exit). +import { mkdtempSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; if (!process.env.FRAMESMITH_HOME) { - process.env.FRAMESMITH_HOME = mkdtempSync(join(tmpdir(), 'framesmith-test-')); + const home = mkdtempSync(join(tmpdir(), 'framesmith-test-')); + process.env.FRAMESMITH_HOME = home; + process.on('exit', () => { + try { rmSync(home, { recursive: true, force: true }); } catch { /* best effort */ } + }); } diff --git a/test/unit/test-runner-temp.ts b/test/unit/test-runner-temp.ts new file mode 100644 index 0000000..4d5e284 --- /dev/null +++ b/test/unit/test-runner-temp.ts @@ -0,0 +1,91 @@ +// Tests must not leave temp folders behind. scripts/run-tests.ts gives each +// test its own temp folder (TMPDIR, TMP, TEMP) and removes it when the test +// ends, however it ends; test/env.ts removes the store it made when its process +// exits, which covers a test run on its own. Before this, every run left a +// store, repo copies and Chrome profiles in the system temp dir: 5 GB of them +// had filled the disk by 2026-11-24. +// +// This runs the real runner over a temp root whose unit/ folder holds a test +// that passes, one that fails and one that hangs past a 10s timeout. Each makes +// folders under os.tmpdir() and records where. Then it runs test/env.ts on its +// own, exiting cleanly and with an error. +// +// Usage: npx tsx test/unit/test-runner-temp.ts + +import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { spawn, spawnSync } from 'node:child_process'; + +let allPass = true; +function check(name: string, cond: boolean, extra?: string) { + if (!cond) allPass = false; + console.log(`${cond ? 'PASS' : 'FAIL'} ${name}${extra ? ` — ${extra}` : ''}`); +} + +// Under the runner, nested test folders sit beside this test's, in its base. +const base = process.env.FRAMESMITH_RUN_TMP_BASE || tmpdir(); +const dir = mkdtempSync(join(tmpdir(), 'framesmith-runner-temp-')); +const marks = join(dir, 'marks'); +mkdirSync(join(dir, 'unit')); +mkdirSync(marks); + +/** A test body that makes a folder and a file under os.tmpdir() and records + * where it saw the temp dir, then ends the way `tail` says. */ +const body = (name: string, tail: string) => ` +import { mkdtempSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +const made = mkdtempSync(join(tmpdir(), 'leftover-')); +writeFileSync(join(made, 'data.json'), '{}'); +writeFileSync(join(${JSON.stringify(marks)}, ${JSON.stringify(name)}), JSON.stringify({ tmp: tmpdir(), made })); +${tail} +`; +writeFileSync(join(dir, 'unit/test-a-pass.ts'), body('pass', "console.log('PASS made temp files');")); +writeFileSync(join(dir, 'unit/test-b-fail.ts'), body('fail', "console.log('FAIL on purpose'); process.exit(1);")); +writeFileSync(join(dir, 'unit/test-c-hang.ts'), body('hang', 'setInterval(() => {}, 1_000);')); + +const runner = spawn(resolve('node_modules/.bin/tsx'), [resolve('scripts/run-tests.ts'), '--root', dir], { + env: { ...process.env, FRAMESMITH_TEST_TIMEOUT_MS: '10000' }, + stdio: ['ignore', 'pipe', 'pipe'], + detached: true, +}); +let out = ''; +runner.stdout.on('data', (d) => { out += d; }); +runner.stderr.on('data', (d) => { out += d; }); +const finished = await new Promise((done) => { + const guard = setTimeout(() => done(false), 90_000); + runner.on('close', () => { clearTimeout(guard); done(true); }); +}); +if (!finished) { try { process.kill(-runner.pid!, 'SIGKILL'); } catch { /* already gone */ } } + +check('the runner finishes', finished); +check('it reports the pass, the failure and the timeout', /ok {4}unit\/test-a-pass\.ts/.test(out) && /FAIL {2}unit\/test-b-fail\.ts/.test(out) && /FAIL {2}unit\/test-c-hang\.ts {2}timed out/.test(out), out.slice(0, 400)); + +const seen = Object.fromEntries(['pass', 'fail', 'hang'].map((n) => { + const file = join(marks, n); + return [n, existsSync(file) ? JSON.parse(readFileSync(file, 'utf-8')) as { tmp: string; made: string } : null]; +})); +check('every test ran and recorded its temp dir', Object.values(seen).every(Boolean), JSON.stringify(seen)); +const tmps = Object.values(seen).map((s) => s?.tmp); +check('each test had its own temp dir, not the system one', new Set(tmps).size === 3 && tmps.every((t) => t && t !== base && t !== tmpdir() && t.startsWith(base)), JSON.stringify(tmps)); +check('a nested runner puts its folders beside the outer one, not inside it', tmps.every((t) => t && !t.slice(base.length + 1).includes('/')), JSON.stringify(tmps)); +for (const [name, s] of Object.entries(seen)) { + check(`the ${name} test's temp dir is gone after it ends`, !!s && !existsSync(s.tmp) && !existsSync(s.made), s?.tmp); +} +check('the shared caches survive the cleanup', existsSync(join(base, `tsx-${process.getuid?.() ?? ''}`)) && existsSync(join(base, 'node-compile-cache'))); +check('no folder of these tests is left in the temp base', !readdirSync(base).some((f) => tmps.includes(join(base, f)))); + +// test/env.ts on its own: the store it made is removed on exit, clean or not. +for (const [label, code] of [['a clean exit', 0], ['process.exit(1)', 1]] as const) { + const script = join(dir, `env-${code}.ts`); + writeFileSync(script, `import ${JSON.stringify(resolve('test/env.ts'))};\nimport { writeFileSync } from 'node:fs';\nwriteFileSync(join(${JSON.stringify(dir)}, 'home-${code}'), process.env.FRAMESMITH_HOME!);\nimport { join } from 'node:path';\nprocess.exit(${code});\n`); + const env: NodeJS.ProcessEnv = { ...process.env }; + delete env.FRAMESMITH_HOME; + spawnSync(resolve('node_modules/.bin/tsx'), [script], { env, stdio: 'ignore' }); + const home = existsSync(join(dir, `home-${code}`)) ? readFileSync(join(dir, `home-${code}`), 'utf-8') : ''; + check(`env.ts removes its store after ${label}`, home.includes('framesmith-test-') && !existsSync(home), home); +} + +rmSync(dir, { recursive: true, force: true }); +process.exit(allPass ? 0 : 1);