Files
9router/tests/setup/isolateDataDir.js
T
MUH. IQRAM BAHRING 9c37af90a9 test(harness): isolate DATA_DIR so tests never write to the real DB
Root cause of fake connections in Usage (zed-live-*@example.com,
guard-*@example.com, zed "Account N", kimchi-nope): route-level tests
(zed-live-models, zed-native-auth) call createProviderConnection, which
persists to $DATA_DIR/db/data.sqlite. With DATA_DIR unset — the default
for `npx vitest run` — that resolved to the user's real ~/.9router DB,
appending test rows on every run. Both files documented "RUN WITH AN
ISOLATED DB" but never enforced it.

Add tests/setup/isolateDataDir.js (wired via vitest setupFiles) that
points DATA_DIR at a throwaway temp dir before src/lib/dataDir.js is
imported. Opt out with RUN_REAL=1 or an explicit DATA_DIR (used by the
*.real.test.js suites that read live credentials).

Verified: a full suite run now leaves the real DB byte-count unchanged;
new guard test tests/unit/test-data-dir-isolation.test.js locks it in.
2026-09-19 12:37:57 +08:00

27 lines
1.1 KiB
JavaScript

// Global test isolation: never let the unit/translator suite write to the user's
// real database (~/.9router). Some tests (e.g. zed-live-models, zed-native-auth)
// exercise real route handlers that call createProviderConnection — without this
// they append test rows ("zed-live-*@example.com", "guard-*@example.com",
// "Account N") straight into the live DB.
//
// DATA_DIR must be set before src/lib/dataDir.js is imported (it reads the env
// at module-eval time), which is exactly what a vitest setupFile guarantees.
//
// Escape hatches:
// - RUN_REAL=1 → keep the real DATA_DIR so *.real.test.js can read it.
// - DATA_DIR=<path> → respect an explicit override (CI / manual isolation).
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const RUN_REAL = process.env.RUN_REAL === "1";
const explicit = process.env.DATA_DIR;
if (!RUN_REAL && !explicit) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "9router-test-"));
process.env.DATA_DIR = dir;
process.on("exit", () => {
try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* best effort */ }
});
}