test(db): unit tests for F2 modules

This commit is contained in:
diegosouzapw
2026-05-27 19:24:30 -03:00
parent 47c0dce062
commit 80fa37f30f
5 changed files with 662 additions and 0 deletions

View File

@@ -0,0 +1,133 @@
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-db-agent-bridge-bypass-")
);
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const mod = await import("../../src/lib/db/agentBridgeBypass.ts");
async function resetStorage() {
core.resetDbInstance();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: any) {
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
const DEFAULT_PATTERNS = [
"*.googleapis.com",
"*.gstatic.com",
"accounts.google.com",
"login.microsoftonline.com",
];
test("getAllBypassPatterns returns empty array when table is empty", () => {
const rows = mod.getAllBypassPatterns();
assert.deepEqual(rows, []);
});
test("seedDefaultBypassPatterns inserts default patterns with source=default", () => {
mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS);
const rows = mod.getAllBypassPatterns();
assert.equal(rows.length, DEFAULT_PATTERNS.length);
for (const row of rows) {
assert.equal(row.source, "default");
assert.ok(DEFAULT_PATTERNS.includes(row.pattern));
}
});
test("seedDefaultBypassPatterns is idempotent — calling twice does not duplicate", () => {
mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS);
mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS);
const rows = mod.getAllBypassPatterns();
assert.equal(rows.length, DEFAULT_PATTERNS.length);
});
test("getUserBypassPatterns returns only user patterns", () => {
mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS);
mod.replaceUserBypassPatterns(["*.internal.example.com", "localhost"]);
const userPatterns = mod.getUserBypassPatterns();
assert.equal(userPatterns.length, 2);
assert.ok(userPatterns.includes("*.internal.example.com"));
assert.ok(userPatterns.includes("localhost"));
// Defaults should not appear in user patterns
for (const p of DEFAULT_PATTERNS) {
assert.ok(!userPatterns.includes(p));
}
});
test("replaceUserBypassPatterns replaces only user entries — defaults untouched", () => {
mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS);
mod.replaceUserBypassPatterns(["custom.host.1"]);
mod.replaceUserBypassPatterns(["custom.host.2", "custom.host.3"]);
const allRows = mod.getAllBypassPatterns();
const defaultRows = allRows.filter((r) => r.source === "default");
const userRows = allRows.filter((r) => r.source === "user");
assert.equal(defaultRows.length, DEFAULT_PATTERNS.length);
assert.equal(userRows.length, 2);
const userPatterns = userRows.map((r) => r.pattern);
assert.ok(!userPatterns.includes("custom.host.1"), "old user pattern must be replaced");
assert.ok(userPatterns.includes("custom.host.2"));
assert.ok(userPatterns.includes("custom.host.3"));
});
test("replaceUserBypassPatterns with empty array clears all user patterns", () => {
mod.seedDefaultBypassPatterns(DEFAULT_PATTERNS);
mod.replaceUserBypassPatterns(["temp.host"]);
mod.replaceUserBypassPatterns([]);
const userPatterns = mod.getUserBypassPatterns();
assert.equal(userPatterns.length, 0);
// Defaults remain
const allRows = mod.getAllBypassPatterns();
assert.equal(allRows.length, DEFAULT_PATTERNS.length);
});
test("getAllBypassPatterns returns both default and user patterns", () => {
mod.seedDefaultBypassPatterns(["*.example.com"]);
mod.replaceUserBypassPatterns(["custom.host"]);
const allRows = mod.getAllBypassPatterns();
assert.equal(allRows.length, 2);
const sources = new Set(allRows.map((r) => r.source));
assert.ok(sources.has("default"));
assert.ok(sources.has("user"));
});

View File

@@ -0,0 +1,126 @@
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-db-agent-bridge-mappings-")
);
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const mod = await import("../../src/lib/db/agentBridgeMappings.ts");
async function resetStorage() {
core.resetDbInstance();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: any) {
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("getMappingsForAgent returns empty array when no mappings exist", () => {
const rows = mod.getMappingsForAgent("antigravity");
assert.deepEqual(rows, []);
});
test("setMappings inserts and retrieves mappings for an agent", () => {
mod.setMappings("copilot", [
{ source: "gpt-4", target: "openai/gpt-4.1" },
{ source: "gpt-3.5-turbo", target: "openai/gpt-4o-mini" },
]);
const rows = mod.getMappingsForAgent("copilot");
assert.equal(rows.length, 2);
const sources = rows.map((r) => r.source_model);
assert.ok(sources.includes("gpt-4"));
assert.ok(sources.includes("gpt-3.5-turbo"));
const gpt4Row = rows.find((r) => r.source_model === "gpt-4");
assert.equal(gpt4Row?.target_model, "openai/gpt-4.1");
assert.equal(gpt4Row?.agent_id, "copilot");
});
test("setMappings is transactional — replaces all mappings idempotently", () => {
// First set
mod.setMappings("cursor", [
{ source: "claude-3-5-sonnet", target: "anthropic/claude-sonnet-4-5" },
]);
// Second set — should replace (not accumulate)
mod.setMappings("cursor", [
{ source: "claude-3-opus", target: "anthropic/claude-opus-4" },
{ source: "gpt-4o", target: "openai/gpt-4.1" },
]);
const rows = mod.getMappingsForAgent("cursor");
assert.equal(rows.length, 2);
const sources = rows.map((r) => r.source_model);
assert.ok(!sources.includes("claude-3-5-sonnet"), "old mapping should be replaced");
assert.ok(sources.includes("claude-3-opus"));
assert.ok(sources.includes("gpt-4o"));
});
test("setMappings with empty array clears all mappings for agent", () => {
mod.setMappings("zed", [{ source: "gpt-4", target: "openai/gpt-4.1" }]);
mod.setMappings("zed", []);
const rows = mod.getMappingsForAgent("zed");
assert.equal(rows.length, 0);
});
test("setMappings does not affect mappings for other agents", () => {
mod.setMappings("kiro", [{ source: "gpt-4", target: "openai/gpt-4.1" }]);
mod.setMappings("codex", [{ source: "o3", target: "openai/o3" }]);
mod.setMappings("kiro", [{ source: "gpt-4o", target: "openai/gpt-4o" }]);
const codexRows = mod.getMappingsForAgent("codex");
assert.equal(codexRows.length, 1);
assert.equal(codexRows[0].source_model, "o3");
});
test("deleteMapping removes a specific source mapping", () => {
mod.setMappings("antigravity", [
{ source: "gpt-4", target: "openai/gpt-4.1" },
{ source: "gpt-3.5-turbo", target: "openai/gpt-4o-mini" },
]);
mod.deleteMapping("antigravity", "gpt-4");
const rows = mod.getMappingsForAgent("antigravity");
assert.equal(rows.length, 1);
assert.equal(rows[0].source_model, "gpt-3.5-turbo");
});
test("deleteMapping is a no-op when mapping does not exist", () => {
mod.setMappings("claude-code", [{ source: "claude-3", target: "anthropic/claude-opus-4" }]);
mod.deleteMapping("claude-code", "nonexistent-model");
const rows = mod.getMappingsForAgent("claude-code");
assert.equal(rows.length, 1);
});

View File

@@ -0,0 +1,113 @@
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-db-agent-bridge-state-"));
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const mod = await import("../../src/lib/db/agentBridgeState.ts");
async function resetStorage() {
core.resetDbInstance();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: any) {
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("migration is idempotent — running getDbInstance twice does not throw", () => {
// First init
const db1 = core.getDbInstance();
assert.ok(db1);
core.resetDbInstance();
// Second init — migrations should skip already-applied files
const db2 = core.getDbInstance();
assert.ok(db2);
});
test("getAgentBridgeState returns null for unknown agent", () => {
const result = mod.getAgentBridgeState("unknown-agent");
assert.equal(result, null);
});
test("upsertAgentBridgeState creates a new row with defaults", () => {
mod.upsertAgentBridgeState({ agent_id: "copilot" });
const row = mod.getAgentBridgeState("copilot");
assert.ok(row);
assert.equal(row.agent_id, "copilot");
assert.equal(row.dns_enabled, false);
assert.equal(row.cert_trusted, false);
assert.equal(row.setup_completed, false);
assert.equal(row.last_started_at, null);
assert.equal(row.last_error, null);
});
test("upsertAgentBridgeState updates an existing row", () => {
mod.upsertAgentBridgeState({ agent_id: "cursor" });
mod.upsertAgentBridgeState({ agent_id: "cursor", dns_enabled: true, cert_trusted: true });
const row = mod.getAgentBridgeState("cursor");
assert.ok(row);
assert.equal(row.dns_enabled, true);
assert.equal(row.cert_trusted, true);
assert.equal(row.setup_completed, false);
});
test("setLastStarted persists timestamp and auto-creates row if missing", () => {
const ts = new Date().toISOString();
mod.setLastStarted("kiro", ts);
const row = mod.getAgentBridgeState("kiro");
assert.ok(row);
assert.equal(row.last_started_at, ts);
});
test("setLastError persists error string and clears it with null", () => {
mod.upsertAgentBridgeState({ agent_id: "codex" });
mod.setLastError("codex", "upstream timeout");
let row = mod.getAgentBridgeState("codex");
assert.equal(row?.last_error, "upstream timeout");
mod.setLastError("codex", null);
row = mod.getAgentBridgeState("codex");
assert.equal(row?.last_error, null);
});
test("getAllAgentBridgeStates returns all rows", () => {
mod.upsertAgentBridgeState({ agent_id: "antigravity" });
mod.upsertAgentBridgeState({ agent_id: "zed" });
const rows = mod.getAllAgentBridgeStates();
assert.ok(rows.length >= 2);
const ids = rows.map((r) => r.agent_id);
assert.ok(ids.includes("antigravity"));
assert.ok(ids.includes("zed"));
});

View File

@@ -0,0 +1,141 @@
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-db-inspector-custom-hosts-")
);
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const mod = await import("../../src/lib/db/inspectorCustomHosts.ts");
async function resetStorage() {
core.resetDbInstance();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: any) {
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("listCustomHosts returns empty array initially", () => {
const rows = mod.listCustomHosts();
assert.deepEqual(rows, []);
});
test("addCustomHost inserts a host with defaults", () => {
mod.addCustomHost("api.openai.com");
const rows = mod.listCustomHosts();
assert.equal(rows.length, 1);
assert.equal(rows[0].host, "api.openai.com");
assert.equal(rows[0].enabled, true);
assert.equal(rows[0].kind, "custom");
assert.equal(rows[0].label, null);
assert.equal(rows[0].last_seen_at, null);
assert.ok(rows[0].added_at);
});
test("addCustomHost respects kind and label parameters", () => {
mod.addCustomHost("api.anthropic.com", "llm", "Anthropic API");
const rows = mod.listCustomHosts();
const row = rows.find((r) => r.host === "api.anthropic.com");
assert.ok(row);
assert.equal(row.kind, "llm");
assert.equal(row.label, "Anthropic API");
});
test("addCustomHost is idempotent — duplicate inserts are ignored", () => {
mod.addCustomHost("api.openai.com");
mod.addCustomHost("api.openai.com");
const rows = mod.listCustomHosts();
assert.equal(rows.length, 1);
});
test("toggleCustomHost disables an enabled host", () => {
mod.addCustomHost("api.openai.com");
mod.toggleCustomHost("api.openai.com", false);
const rows = mod.listCustomHosts();
assert.equal(rows[0].enabled, false);
});
test("toggleCustomHost re-enables a disabled host", () => {
mod.addCustomHost("api.openai.com");
mod.toggleCustomHost("api.openai.com", false);
mod.toggleCustomHost("api.openai.com", true);
const rows = mod.listCustomHosts();
assert.equal(rows[0].enabled, true);
});
test("listCustomHosts with enabledOnly=true excludes disabled hosts", () => {
mod.addCustomHost("api.openai.com");
mod.addCustomHost("api.anthropic.com");
mod.toggleCustomHost("api.anthropic.com", false);
const all = mod.listCustomHosts();
const enabledOnly = mod.listCustomHosts({ enabledOnly: true });
assert.equal(all.length, 2);
assert.equal(enabledOnly.length, 1);
assert.equal(enabledOnly[0].host, "api.openai.com");
});
test("removeCustomHost deletes the host", () => {
mod.addCustomHost("api.openai.com");
mod.addCustomHost("api.anthropic.com");
mod.removeCustomHost("api.openai.com");
const rows = mod.listCustomHosts();
assert.equal(rows.length, 1);
assert.equal(rows[0].host, "api.anthropic.com");
});
test("removeCustomHost is a no-op for non-existent hosts", () => {
mod.addCustomHost("api.openai.com");
mod.removeCustomHost("nonexistent.host");
const rows = mod.listCustomHosts();
assert.equal(rows.length, 1);
});
test("touchLastSeen updates last_seen_at timestamp", () => {
mod.addCustomHost("api.openai.com");
const before = mod.listCustomHosts()[0];
assert.equal(before.last_seen_at, null);
mod.touchLastSeen("api.openai.com");
const after = mod.listCustomHosts()[0];
assert.ok(after.last_seen_at !== null);
assert.ok(Date.parse(after.last_seen_at as string) > 0);
});

View File

@@ -0,0 +1,149 @@
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-db-inspector-sessions-")
);
process.env.DATA_DIR = TEST_DATA_DIR;
const core = await import("../../src/lib/db/core.ts");
const mod = await import("../../src/lib/db/inspectorSessions.ts");
async function resetStorage() {
core.resetDbInstance();
for (let attempt = 0; attempt < 10; attempt++) {
try {
if (fs.existsSync(TEST_DATA_DIR)) {
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
}
break;
} catch (error: any) {
if ((error?.code === "EBUSY" || error?.code === "EPERM") && attempt < 9) {
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)));
} else {
throw error;
}
}
}
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
}
test.beforeEach(async () => {
await resetStorage();
});
test.after(async () => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
});
test("createSession returns a uuid and started_at timestamp", () => {
const { id, started_at } = mod.createSession();
assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i);
assert.ok(Date.parse(started_at) > 0);
});
test("createSession persists name and profile", () => {
const { id } = mod.createSession({ name: "My Session", profile: "llm" });
const row = mod.getSession(id);
assert.ok(row);
assert.equal(row.name, "My Session");
assert.equal(row.profile, "llm");
assert.equal(row.ended_at, null);
assert.equal(row.request_count, 0);
});
test("listSessions returns all created sessions", () => {
const { id: id1 } = mod.createSession({ name: "First" });
const { id: id2 } = mod.createSession({ name: "Second" });
const sessions = mod.listSessions();
assert.ok(sessions.length >= 2);
const ids = sessions.map((s) => s.id);
assert.ok(ids.includes(id1), "First session should be in the list");
assert.ok(ids.includes(id2), "Second session should be in the list");
});
test("appendSessionRequest increments seq atomically and updates request_count", () => {
const { id } = mod.createSession();
mod.appendSessionRequest(id, JSON.stringify({ a: 1 }));
mod.appendSessionRequest(id, JSON.stringify({ a: 2 }));
mod.appendSessionRequest(id, JSON.stringify({ a: 3 }));
const session = mod.getSession(id);
assert.equal(session?.request_count, 3);
const requests = mod.getSessionRequests(id);
assert.equal(requests.length, 3);
assert.equal(requests[0].seq, 1);
assert.equal(requests[1].seq, 2);
assert.equal(requests[2].seq, 3);
});
test("getSessionRequests returns payloads in seq order", () => {
const { id } = mod.createSession();
mod.appendSessionRequest(id, "payload-A");
mod.appendSessionRequest(id, "payload-B");
mod.appendSessionRequest(id, "payload-C");
const requests = mod.getSessionRequests(id);
assert.equal(requests[0].payload, "payload-A");
assert.equal(requests[1].payload, "payload-B");
assert.equal(requests[2].payload, "payload-C");
});
test("stopSession sets ended_at timestamp", () => {
const { id } = mod.createSession();
const before = mod.getSession(id);
assert.equal(before?.ended_at, null);
mod.stopSession(id);
const after = mod.getSession(id);
assert.ok(after?.ended_at !== null);
assert.ok(Date.parse(after?.ended_at as string) > 0);
});
test("renameSession updates the name", () => {
const { id } = mod.createSession({ name: "Old Name" });
mod.renameSession(id, "New Name");
const row = mod.getSession(id);
assert.equal(row?.name, "New Name");
});
test("deleteSession removes session and cascade-deletes requests", () => {
const { id } = mod.createSession();
mod.appendSessionRequest(id, "payload-1");
mod.appendSessionRequest(id, "payload-2");
mod.deleteSession(id);
const session = mod.getSession(id);
assert.equal(session, null);
const requests = mod.getSessionRequests(id);
assert.equal(requests.length, 0);
});
test("getSession returns null for non-existent id", () => {
const row = mod.getSession("00000000-0000-4000-8000-000000000000");
assert.equal(row, null);
});
test("getSessionRequests returns empty array for session with no requests", () => {
const { id } = mod.createSession();
const requests = mod.getSessionRequests(id);
assert.deepEqual(requests, []);
});