test(api): cover ai client helpers
This commit is contained in:
@@ -0,0 +1,63 @@
|
|||||||
|
import { DEFAULT_OPENAI_MODEL } from "@capakraken/shared";
|
||||||
|
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||||
|
import { loggedAiCall, sanitizeDiagnosticError } from "../ai-client.js";
|
||||||
|
import { logger } from "../lib/logger.js";
|
||||||
|
|
||||||
|
vi.mock("../lib/logger.js", () => ({
|
||||||
|
logger: {
|
||||||
|
error: vi.fn(),
|
||||||
|
warn: vi.fn(),
|
||||||
|
info: vi.fn(),
|
||||||
|
debug: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("ai-client diagnostics", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.clearAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("redacts URLs and secret-like tokens from diagnostics", () => {
|
||||||
|
const diagnostic = sanitizeDiagnosticError(
|
||||||
|
new Error(
|
||||||
|
"Request failed at https://example.openai.azure.com/path?api-key=topsecret with Bearer sk-super-secret",
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(diagnostic).toContain("<redacted-url>");
|
||||||
|
expect(diagnostic).toContain("<redacted-secret>");
|
||||||
|
expect(diagnostic).not.toContain("https://example.openai.azure.com");
|
||||||
|
expect(diagnostic).not.toContain("sk-super-secret");
|
||||||
|
expect(diagnostic).not.toContain("topsecret");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("logs sanitized diagnostics when upstream AI calls fail", async () => {
|
||||||
|
const upstreamError = new Error(
|
||||||
|
"upstream 404 from https://example.openai.azure.com/openai/deployments/foo?api-key=topsecret with Bearer sk-secret",
|
||||||
|
);
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
loggedAiCall("azure", DEFAULT_OPENAI_MODEL, 123, async () => {
|
||||||
|
throw upstreamError;
|
||||||
|
}),
|
||||||
|
).rejects.toBe(upstreamError);
|
||||||
|
|
||||||
|
expect(logger.warn).toHaveBeenCalledWith(
|
||||||
|
expect.objectContaining({
|
||||||
|
provider: "azure",
|
||||||
|
model: DEFAULT_OPENAI_MODEL,
|
||||||
|
promptLength: 123,
|
||||||
|
responseTimeMs: expect.any(Number),
|
||||||
|
errorMessage: expect.any(String),
|
||||||
|
}),
|
||||||
|
"External API call failed",
|
||||||
|
);
|
||||||
|
|
||||||
|
const payload = vi.mocked(logger.warn).mock.calls[0]?.[0];
|
||||||
|
expect(payload?.errorMessage).toContain("<redacted-url>");
|
||||||
|
expect(payload?.errorMessage).toContain("<redacted-secret>");
|
||||||
|
expect(payload?.errorMessage).not.toContain("https://example.openai.azure.com");
|
||||||
|
expect(payload?.errorMessage).not.toContain("sk-secret");
|
||||||
|
expect(payload?.errorMessage).not.toContain("topsecret");
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user