Files
OmniRoute/tests/unit/cli-server-commands.test.ts
diegosouzapw 34e8b3e243 test: repair pre-existing test-suite failures (batch 2) + real source-bug fixes
Repaired 47 of 49 pre-existing failing unit test files on release/v3.8.2 (down to
docs-site-overhaul, a tr46/tsx/Node24 toolchain blocker, tracked separately).

Stale tests reconciled with current source (catalog/registry/version drift), the
notable ones: openai gpt-4o / gpt-4o-mini removed from the registry; Antigravity
Claude models removed from the public catalog; DEFAULT_CLAUDE_CODE_VERSION and
DEFAULT_CODEX_CLIENT_VERSION bumps; voyage-3-large → voyage-4; model-alias seed now
routes via gemini-cli; remapToolNames API change; getLKGP return shape; sidebar nav
overhaul; CLI commands now write via process.stdout.write; cloudEnabled default true.

Real SOURCE bugs found by the tests and fixed (not masked):
- fix(db): commandCodeAuth.toSafeStatus + evals.ts read the `*Json` camel keys that
  rowToCamel does not produce — it auto-parses `*_json` columns under the base name,
  so metadata/outputs/summary/results/tags were always empty. Read the base keys.
- fix(executors): re-register claude-web / cw-web in the executor index (the provider
  shipped in #2476 but was never wired into the registry).
- fix(validation): build the OpenAI-like /models probe with addModelsSuffix so an
  OpenAI base URL validates against /v1/models, not /v1/chat/completions/models;
  honor a ya29.* Google OAuth token as Bearer even when authType is apikey/header
  (it was shadowed by an unreachable else-if); make the Anthropic /models probe
  best-effort (try/catch) so a 404/malformed-URL throw no longer marks a valid key invalid.
- fix(security): add the requireCliToolsAuth guard to the GET handlers of
  cli-tools/guide-settings/[toolId] and cli-tools/hermes-agent-settings (host config
  access was unguarded).
- revert(stream): restore the SSE heartbeat default to 15s (the 4s round-8 change
  regressed runtime-timeouts; #2544's early-keepalive route wrapper remains the fix).

Also: env-doc sync (OMNIROUTE_SKIP_DB_HEALTHCHECK) and new sidebar i18n keys.
2026-05-22 13:10:48 -03:00

166 lines
6.4 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
const ORIGINAL_FETCH = globalThis.fetch;
function makeResponse(data: unknown, status = 200) {
return {
ok: status >= 200 && status < 300,
status,
headers: new Headers({ "content-type": "application/json" }),
json: async () => data,
text: async () => JSON.stringify(data),
} as unknown as Response;
}
async function withServerFetch(mockFetch: typeof fetch, fn: () => Promise<void>) {
globalThis.fetch = mockFetch;
try {
await fn();
} finally {
globalThis.fetch = ORIGINAL_FETCH;
}
}
// ── health ────────────────────────────────────────────────────────────────────
test("health returns 1 when server is offline", async () => {
await withServerFetch(
(async () => {
throw new Error("offline");
}) as typeof fetch,
async () => {
const { runHealthCommand } = await import("../../bin/cli/commands/health.mjs");
const originalError = console.error;
console.error = () => {};
const result = await runHealthCommand({});
console.error = originalError;
assert.equal(result, 1);
}
);
});
test("health --json returns 0 when server responds", async () => {
const mockData = { status: "ok", uptime: "1h", version: "3.8.0" };
const mockFetch = (async (url: string) => {
return makeResponse(String(url).includes("health") ? mockData : { status: "ok" });
}) as typeof fetch;
await withServerFetch(mockFetch, async () => {
const { runHealthCommand } = await import("../../bin/cli/commands/health.mjs");
const lines: string[] = [];
const originalLog = console.log;
console.log = (msg: string) => lines.push(msg);
const result = await runHealthCommand({ json: true });
console.log = originalLog;
assert.equal(result, 0);
const parsed = JSON.parse(lines.join("\n"));
assert.equal(parsed.status, "ok");
});
});
// ── quota ─────────────────────────────────────────────────────────────────────
test("quota returns 1 when server is offline", async () => {
await withServerFetch(
(async () => {
throw new Error("offline");
}) as typeof fetch,
async () => {
const { runQuotaCommand } = await import("../../bin/cli/commands/quota.mjs");
const originalError = console.error;
console.error = () => {};
const result = await runQuotaCommand({});
console.error = originalError;
assert.equal(result, 1);
}
);
});
// ── mcp ───────────────────────────────────────────────────────────────────────
test("mcp status --json returns 0 when server responds", async () => {
const mcpStatus = { running: true, toolsCount: 37, transport: "stdio" };
const mockFetch = (async (url: string) => makeResponse(mcpStatus)) as typeof fetch;
await withServerFetch(mockFetch, async () => {
const { runMcpStatusCommand } = await import("../../bin/cli/commands/mcp.mjs");
const lines: string[] = [];
const originalLog = console.log;
console.log = (msg: string) => lines.push(msg);
const result = await runMcpStatusCommand({ json: true });
console.log = originalLog;
assert.equal(result, 0);
const parsed = JSON.parse(lines.join("\n"));
assert.equal(parsed.running, true);
});
});
// ── completion ────────────────────────────────────────────────────────────────
test("completion bash outputs bash script", async () => {
const { runCompletionCommand } = await import("../../bin/cli/commands/completion.mjs");
const chunks: string[] = [];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = (chunk: any) => {
chunks.push(String(chunk));
return true;
};
const result = await runCompletionCommand("bash");
process.stdout.write = originalWrite;
assert.equal(result, 0);
assert.ok(chunks.join("").includes("_omniroute"));
});
test("completion zsh outputs zsh script", async () => {
const { runCompletionCommand } = await import("../../bin/cli/commands/completion.mjs");
const chunks: string[] = [];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = (chunk: any) => {
chunks.push(String(chunk));
return true;
};
const result = await runCompletionCommand("zsh");
process.stdout.write = originalWrite;
assert.equal(result, 0);
assert.ok(chunks.join("").includes("#compdef omniroute"));
});
test("completion fish outputs fish script", async () => {
const { runCompletionCommand } = await import("../../bin/cli/commands/completion.mjs");
const chunks: string[] = [];
const originalWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = (chunk: any) => {
chunks.push(String(chunk));
return true;
};
const result = await runCompletionCommand("fish");
process.stdout.write = originalWrite;
assert.equal(result, 0);
assert.ok(chunks.join("").includes("complete -c omniroute"));
});
// ── env ───────────────────────────────────────────────────────────────────────
test("env show returns 0", async () => {
const { runEnvShowCommand } = await import("../../bin/cli/commands/env.mjs");
const originalLog = console.log;
console.log = () => {};
const result = await runEnvShowCommand({});
console.log = originalLog;
assert.equal(result, 0);
});
test("env get returns 0 and prints env value", async () => {
process.env.__OMNIROUTE_TEST_KEY__ = "hello";
const { runEnvGetCommand } = await import("../../bin/cli/commands/env.mjs");
const lines: string[] = [];
const originalLog = console.log;
console.log = (msg: string) => lines.push(msg);
const result = await runEnvGetCommand("__OMNIROUTE_TEST_KEY__");
console.log = originalLog;
delete process.env.__OMNIROUTE_TEST_KEY__;
assert.equal(result, 0);
assert.ok(lines.join("").includes("hello"));
});