Files
lpt-ai/src/admin/routes.test.ts
T
cat-shark 935f4781a4 feat: 采集 LLM token 用量并上报 lpt-be
- 客户端解析上游 usage(含 DeepSeek 缓存命中/未命中),跨重试累加
- 新增计价表(三档单价 + 峰谷时段),费用在结算时冻结
- 新增用量上报与本地 outbox 重试;4xx 判定为确定性拒绝,不无限重试
- 面板补充 Token/费用/调用次数与计价快照
- 顺带修复面板内联脚本转义错误(模板字面量吃掉 \n 与 \',面板一直空白)
2026-10-10 18:46:01 +08:00

130 lines
4.3 KiB
TypeScript

import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import Fastify from "fastify";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { adminRoutes } from "./routes.js";
import { logStore, resetLogStoreForTest } from "./store.js";
const originalToken = process.env.LPT_AI_TOKEN;
const originalDataDir = process.env.LPT_AI_DATA_DIR;
let workDir: string;
// 必须指向临时目录:单例默认写 process.cwd()/data,不隔离会把开发者真实的面板数据清掉
beforeEach(() => {
workDir = mkdtempSync(join(tmpdir(), "lpt-ai-admin-"));
process.env.LPT_AI_DATA_DIR = workDir;
});
afterEach(() => {
if (originalToken === undefined) {
delete process.env.LPT_AI_TOKEN;
} else {
process.env.LPT_AI_TOKEN = originalToken;
}
if (originalDataDir === undefined) {
delete process.env.LPT_AI_DATA_DIR;
} else {
process.env.LPT_AI_DATA_DIR = originalDataDir;
}
rmSync(workDir, { recursive: true, force: true });
});
async function buildApp() {
const app = Fastify();
await app.register(adminRoutes);
await app.ready();
return app;
}
function scriptOf(html: string): string {
const match = /<script>([\s\S]*)<\/script>/.exec(html);
if (!match) throw new Error("面板 HTML 里找不到内联脚本");
return match[1];
}
describe("管理面板", () => {
it("内联脚本必须能被解析", async () => {
const app = await buildApp();
const response = await app.inject({ method: "GET", url: "/admin" });
expect(response.statusCode).toBe(200);
const script = scriptOf(response.body);
// 面板 HTML 是模板字面量拼出来的:`\n` / `\'` 会被模板先吃掉,
// 落到产物里就是字符串里的裸换行或提前截断的引号——整套面板会静默变成空白页。
// 这里直接解析产物脚本,把这类转义错误挡在提交之前。
expect(() => new Function(script)).not.toThrow();
await app.close();
});
it("未配置令牌时面板与日志接口都放行", async () => {
delete process.env.LPT_AI_TOKEN;
const app = await buildApp();
expect((await app.inject({ method: "GET", url: "/admin" })).statusCode).toBe(200);
expect((await app.inject({ method: "GET", url: "/admin/logs" })).statusCode).toBe(200);
await app.close();
});
it("配置令牌后无令牌请求被拒", async () => {
process.env.LPT_AI_TOKEN = "secret-token";
const app = await buildApp();
expect((await app.inject({ method: "GET", url: "/admin" })).statusCode).toBe(401);
expect((await app.inject({ method: "GET", url: "/admin/logs" })).statusCode).toBe(401);
await app.close();
});
it("用 ?token= 打开面板时换发 HttpOnly cookie,后续 fetch 才能通过", async () => {
process.env.LPT_AI_TOKEN = "secret-token";
const app = await buildApp();
const page = await app.inject({ method: "GET", url: "/admin?token=secret-token" });
expect(page.statusCode).toBe(200);
const setCookie = String(page.headers["set-cookie"]);
expect(setCookie).toContain("lpt_ai_token=secret-token");
expect(setCookie).toContain("HttpOnly");
expect(setCookie).toContain("Path=/admin");
// 面板内部的 fetch 不带 query,只靠 cookie
const logs = await app.inject({
method: "GET",
url: "/admin/logs",
headers: { cookie: "lpt_ai_token=secret-token" },
});
expect(logs.statusCode).toBe(200);
await app.close();
});
it("日志摘要按 isLlmCall 区分,非 LLM 请求不计入用量分母", async () => {
delete process.env.LPT_AI_TOKEN;
resetLogStoreForTest();
const app = await buildApp();
logStore.add({
timestamp: "2026-10-10T09:00:00.000Z",
endpoint: "/fetch-title",
taskType: "fetch-title",
model: "",
isLlmCall: false,
durationMs: 10,
status: 200,
requestBody: {},
responseBody: {},
});
const response = await app.inject({ method: "GET", url: "/admin/logs" });
const body = JSON.parse(response.body) as {
stats: { total: number; llmCalls: number; cacheHitRate: number | null };
};
expect(body.stats.total).toBe(1);
expect(body.stats.llmCalls).toBe(0);
// 分母为 0 时返回 null,面板显示「—」而不是 0%
expect(body.stats.cacheHitRate).toBeNull();
resetLogStoreForTest();
await app.close();
});
});