Files
OmniRoute/tests/integration/cli-settings-pi.test.ts
Diego Rodrigues de Sa e Souza 3d4f3e4960 test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966) (#11968)
* test(infra): retry recursive temp-dir removal instead of failing a shard on ENOTEMPTY (#11966)

Two shards on release/v3.8.51 went red in one day with the same signature —
"ENOTEMPTY, Directory not empty: /tmp/omniroute-<test>-XXXXXX" — from
combo-same-provider-cascade (Unit Tests fast-path 4/4, on a PR that touches only
.github/) and auth-policy-embeddings-webfetch-7785 (the 20k-test TIA step). Both pass
alone and on re-run: the cleanup races something still writing into the directory
(SQLite WAL/-shm checkpoint, a worker, the backup) and under a loaded hosted runner
the window opens. 1154 test files do their own cleanup with
fs.rmSync(dir, { recursive: true, force: true }); 57 already asked for retries.

One-shot codemod (scripts/ad-hoc/codemod-rm-maxretries.mjs, kept for the record):
every rm / rmSync / rmdirSync option object with `recursive: true` and no
`maxRetries` gains `maxRetries: 5, retryDelay: 100` — Node itself then retries
ENOTEMPTY/EBUSY/EPERM for up to ~0.5 s before giving up. 2243 call sites in 1292
files under tests/, the shared tests/_setup/isolateDataDir.ts exit hook included.
Only the option object changes: no call site, assertion or import is touched.

Validation: prettier and ESLint (with the frozen suppressions) clean on all 1292
files; a random 20-file sample runs green (quota-redis-store hangs identically on
the untouched tree — it needs a Redis on localhost, an environment matter). The
four unit shards on this PR are the full run.

* fix(quality): let check-forgotten-sibling-tests read a 1,000-file diff

The gate shells out to `git diff` through execFileSync with Node's default 1 MB
maxBuffer; the 1,292-file codemod in this PR is the first diff large enough to
overflow it, and the gate died with `spawnSync git ENOBUFS` before comparing
anything. 64 MB is far above any real PR and costs nothing when unused.
2026-08-29 01:17:40 -03:00

189 lines
7.0 KiB
TypeScript

/**
* Integration tests for /api/cli-tools/pi-settings
* Plan 14 F3 — settings handler for Pi (configType: "custom")
*/
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-pi-settings-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.API_KEY_SECRET = "test-api-key-secret-pi";
process.env.JWT_SECRET = "test-jwt-secret-pi";
const core = await import("../../src/lib/db/core.ts");
const localDb = await import("../../src/lib/localDb.ts");
const { GET, POST, DELETE } = await import("../../src/app/api/cli-tools/pi-settings/route.ts");
async function resetStorage() {
delete process.env.INITIAL_PASSWORD;
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
async function enableAuth() {
process.env.INITIAL_PASSWORD = "test-bootstrap";
await localDb.updateSettings({ requireLogin: true, password: "" });
}
test.beforeEach(async () => {
await resetStorage();
});
// ── Test 1: GET without auth → 401 ──────────────────────────────────────────
test("pi-settings GET: returns 401 when auth required and no token", async () => {
await enableAuth();
const res = await GET(new Request("http://localhost/api/cli-tools/pi-settings"));
assert.equal(res.status, 401, `Expected 401, got ${res.status}`);
});
// ── Test 2: GET without auth requirement → 200 ───────────────────────────────
test("pi-settings GET: returns 200 when auth not required", async () => {
const res = await GET(new Request("http://localhost/api/cli-tools/pi-settings"));
assert.equal(res.status, 200, `Expected 200, got ${res.status}`);
const body = await res.json();
assert.ok(
"installed" in body || "config" in body,
"Response should contain installed or config field"
);
});
// ── Test 3: POST with invalid body → 400 ─────────────────────────────────────
test("pi-settings POST: 400 when baseUrl is missing", async () => {
const res = await POST(
new Request("http://localhost/api/cli-tools/pi-settings", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ apiKey: "sk-test", model: "gpt-5" }),
})
);
assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
const body = await res.json();
assert.ok(body.error !== undefined);
});
test("pi-settings POST: 400 when model is missing", async () => {
const res = await POST(
new Request("http://localhost/api/cli-tools/pi-settings", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ baseUrl: "http://localhost:20128", apiKey: "sk-test" }),
})
);
assert.equal(res.status, 400, `Expected 400, got ${res.status}`);
});
// ── Test 4: POST with valid body → writes config.json ───────────────────────
test("pi-settings POST: writes config.json with valid body", async () => {
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "pi-home-"));
const origHome = process.env.HOME;
process.env.HOME = tmpHome;
try {
const res = await POST(
new Request("http://localhost/api/cli-tools/pi-settings", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
baseUrl: "http://localhost:20128",
apiKey: "sk-test-pi-key",
model: "gpt-5.4-mini",
}),
})
);
assert.ok([200, 403, 500].includes(res.status), `Unexpected status ${res.status}`);
if (res.status === 200) {
const body = await res.json();
assert.equal(body.success, true);
const configPath = path.join(tmpHome, ".pi", "config.json");
if (fs.existsSync(configPath)) {
const written = JSON.parse(fs.readFileSync(configPath, "utf-8"));
assert.equal(written._managedBy, "omniroute");
assert.ok(written.baseUrl.includes("localhost:20128"));
assert.equal(written.model, "gpt-5.4-mini");
}
}
} finally {
process.env.HOME = origHome;
fs.rmSync(tmpHome, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
// ── Test 5: DELETE → removes OmniRoute fields ────────────────────────────────
test("pi-settings DELETE: removes OmniRoute fields from existing config", async () => {
const tmpHome = fs.mkdtempSync(path.join(os.tmpdir(), "pi-home-del-"));
const origHome = process.env.HOME;
process.env.HOME = tmpHome;
try {
const piDir = path.join(tmpHome, ".pi");
fs.mkdirSync(piDir, { recursive: true });
fs.writeFileSync(
path.join(piDir, "config.json"),
JSON.stringify({
_managedBy: "omniroute",
baseUrl: "http://localhost:20128",
apiKey: "sk-test",
model: "gpt-5",
})
);
const res = await DELETE(
new Request("http://localhost/api/cli-tools/pi-settings", { method: "DELETE" })
);
assert.ok([200, 403, 500].includes(res.status), `Expected 200/403/500, got ${res.status}`);
if (res.status === 200) {
const body = await res.json();
assert.equal(body.success, true);
}
} finally {
process.env.HOME = origHome;
fs.rmSync(tmpHome, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
}
});
// ── Test 6: Error sanitization (Hard Rule #12) ───────────────────────────────
test("pi-settings: error responses do not leak stack traces", async () => {
const badReq = new Request("http://localhost/api/cli-tools/pi-settings", {
method: "POST",
headers: { "content-type": "application/json" },
body: "{ bad json }",
});
const res = await POST(badReq);
const bodyStr = JSON.stringify(await res.json());
assert.ok(
!bodyStr.match(/\s+at\s+\/[^\s]/),
"Error response must not contain absolute-path stack traces"
);
});
// ── Test 7: Hard Rule #13 (no exec/spawn) ────────────────────────────────────
test("pi-settings route.ts: does not call exec() or spawn() directly", () => {
const routePath = path.resolve(
import.meta.dirname,
"../../src/app/api/cli-tools/pi-settings/route.ts"
);
const content = fs.readFileSync(routePath, "utf-8");
assert.ok(!content.match(/\bexec\s*\(/), "Handler must not use exec()");
assert.ok(!content.match(/\bspawn\s*\(/), "Handler must not use spawn()");
});
test.after(async () => {
await resetStorage();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
delete process.env.DATA_DIR;
delete process.env.API_KEY_SECRET;
delete process.env.JWT_SECRET;
});