Files
Alfred/tests/server/routes/providers.test.ts
lanyuanxiaoyao 34e915ccf4 refactor: 简化模型管理,移除启用/禁用,优化测试和布局
- 移除供应商/模型启用禁用能力,清理DB schema/migration/API/前端
- 供应商测试改为Base URL连通性+/models探测
- 新增POST /api/models/test模型连接测试
- 新增GET /api/providers/options专用供应商选项接口
- 统一工具栏为ModelsToolbar,参考项目管理布局
- 模型弹窗优化:默认能力、响应式3列标签、并排数值
- 前后端正整数校验、供应商下拉loading/error/empty状态
- 表格列宽统一,操作列/名称列固定宽度
2026-05-29 18:03:33 +08:00

252 lines
8.9 KiB
TypeScript

import type Database from "bun:sqlite";
import { describe, expect, mock, test } from "bun:test";
import type { Provider, ProviderOption, RuntimeMode } from "../../../src/shared/api";
import { createModel } from "../../../src/server/db/models";
import { createProvider } from "../../../src/server/db/providers";
import { createMigratedMemoryTestDatabase } from "../../helpers";
const MODE: RuntimeMode = "test";
void mock.module("ai", () => ({
createProviderRegistry: () => ({
languageModel: () => ({}),
}),
}));
async function createProviderViaHandler(req: Request, db: Database): Promise<Response> {
const { handleCreateProvider: h } = await import("../../../src/server/routes/providers/create");
return h(req, db, MODE);
}
function createTestProvider(db: Database, name = "测试供应商", baseUrl = "https://api.test.com/v1"): Provider {
const result = createProvider(db, {
apiKey: "sk-test",
baseUrl,
name,
type: "openai",
});
if ("error" in result) throw new Error(result.error);
return result.provider;
}
async function deleteProviderViaHandler(req: Request, db: Database): Promise<Response> {
const { handleDeleteProvider: h } = await import("../../../src/server/routes/providers/delete");
return h(req, db, MODE);
}
async function getProviderViaHandler(req: Request, db: Database): Promise<Response> {
const { handleGetProvider: h } = await import("../../../src/server/routes/providers/get");
return h(req, db, MODE);
}
async function listProviderOptionsViaHandler(_req: Request, db: Database): Promise<Response> {
const { handleListProviderOptions: h } = await import("../../../src/server/routes/providers/options");
return h(db, MODE);
}
async function listProvidersViaHandler(req: Request, db: Database): Promise<Response> {
const { handleListProviders: h } = await import("../../../src/server/routes/providers/list");
return h(req, db, MODE);
}
async function testProviderConfigViaHandler(req: Request, db: Database): Promise<Response> {
const { handleTestProviderConfig: h } = await import("../../../src/server/routes/providers/test");
return h(req, db, MODE);
}
async function updateProviderViaHandler(req: Request, db: Database): Promise<Response> {
const { handleUpdateProvider: h } = await import("../../../src/server/routes/providers/update");
return h(req, db, MODE);
}
async function withProviderServer(
modelsResponse: Response,
callback: (baseUrl: string) => Promise<void>,
): Promise<void> {
const server = Bun.serve({
fetch(request) {
if (request.method === "HEAD") return new Response(null, { status: 200 });
return modelsResponse;
},
port: 0,
});
try {
await callback(`http://127.0.0.1:${server.port}/v1`);
} finally {
await server.stop(true);
}
}
async function withRouteDb(callback: (db: Database) => Promise<void>): Promise<void> {
const handle = createMigratedMemoryTestDatabase("route-provider-test");
try {
await callback(handle.db);
handle.close();
} finally {
handle.cleanup();
}
}
describe("供应商 API 路由", () => {
test("POST /api/providers 创建供应商", async () => {
await withRouteDb(async (db) => {
const req = new Request("http://localhost/api/providers", {
body: JSON.stringify({
apiKey: "sk-test",
baseUrl: "https://api.openai.com/v1",
name: "OpenAI",
type: "openai",
}),
headers: { "Content-Type": "application/json" },
method: "POST",
});
const res = await createProviderViaHandler(req, db);
expect(res.status).toBe(201);
const body = (await res.json()) as { provider: Provider };
expect(body.provider.name).toBe("OpenAI");
expect(body.provider.type).toBe("openai");
});
});
test("GET /api/providers 列表查询", async () => {
await withRouteDb(async (db) => {
createTestProvider(db, "A供应商");
createTestProvider(db, "B供应商");
const req = new Request("http://localhost/api/providers?page=1&pageSize=20");
const res = await listProvidersViaHandler(req, db);
expect(res.status).toBe(200);
const body = (await res.json()) as { items: Provider[]; total: number };
expect(body.total).toBe(2);
expect(body.items.length).toBe(2);
});
});
test("GET /api/providers/options 返回最小字段", async () => {
await withRouteDb(async (db) => {
createTestProvider(db, "选项供应商");
const req = new Request("http://localhost/api/providers/options");
const res = await listProviderOptionsViaHandler(req, db);
expect(res.status).toBe(200);
const body = (await res.json()) as { items: ProviderOption[] };
expect(body.items).toHaveLength(1);
expect(typeof body.items[0]?.id).toBe("string");
expect(body.items[0]).toMatchObject({ name: "选项供应商", type: "openai" });
expect(body.items[0]).not.toHaveProperty("apiKey");
expect(body.items[0]).not.toHaveProperty("enabled");
});
});
test("GET /api/providers/:id 获取详情", async () => {
await withRouteDb(async (db) => {
const provider = createTestProvider(db, "详情路由");
const req = new Request(`http://localhost/api/providers/${provider.id}`);
const res = await getProviderViaHandler(req, db);
expect(res.status).toBe(200);
const body = (await res.json()) as { provider: Provider };
expect(body.provider.name).toBe("详情路由");
});
});
test("PATCH /api/providers/:id 更新供应商", async () => {
await withRouteDb(async (db) => {
const provider = createTestProvider(db, "更新路由");
const req = new Request(`http://localhost/api/providers/${provider.id}`, {
body: JSON.stringify({ name: "已更新" }),
headers: { "Content-Type": "application/json" },
method: "PATCH",
});
const res = await updateProviderViaHandler(req, db);
expect(res.status).toBe(200);
const body = (await res.json()) as { provider: Provider };
expect(body.provider.name).toBe("已更新");
});
});
test("DELETE /api/providers/:id 删除供应商", async () => {
await withRouteDb(async (db) => {
const provider = createTestProvider(db, "删除路由");
const req = new Request(`http://localhost/api/providers/${provider.id}`, { method: "DELETE" });
const res = await deleteProviderViaHandler(req, db);
expect(res.status).toBe(204);
});
});
test("DELETE /api/providers/:id 存在关联模型时返回 409", async () => {
await withRouteDb(async (db) => {
const provider = createTestProvider(db, "有关联模型");
const modelResult = createModel(db, {
capabilities: ["text"],
modelId: "gpt-4o",
name: "GPT-4o",
providerId: provider.id,
});
if ("error" in modelResult) throw new Error(modelResult.error);
const req = new Request(`http://localhost/api/providers/${provider.id}`, { method: "DELETE" });
const res = await deleteProviderViaHandler(req, db);
expect(res.status).toBe(409);
const body = (await res.json()) as { error: string };
expect(body.error).toContain("存在模型");
});
});
test("POST /api/providers/test 使用表单配置测试连通性", async () => {
await withRouteDb(async (db) => {
await withProviderServer(Response.json({ data: [{ id: "gpt-4o" }] }), async (baseUrl) => {
const req = new Request("http://localhost/api/providers/test", {
body: JSON.stringify({
apiKey: "sk-test",
baseUrl,
name: "OpenAI",
type: "openai",
}),
headers: { "Content-Type": "application/json" },
method: "POST",
});
const res = await testProviderConfigViaHandler(req, db);
expect(res.status).toBe(200);
const body = (await res.json()) as { providerTestResponse: { message: string; ok: boolean } };
expect(body.providerTestResponse.ok).toBe(true);
expect(body.providerTestResponse.message).toContain("/models 返回 1 个模型");
});
});
});
test("创建同名供应商返回 409", async () => {
await withRouteDb(async (db) => {
const req1 = new Request("http://localhost/api/providers", {
body: JSON.stringify({
apiKey: "sk-a",
baseUrl: "https://a.com",
name: "重复名",
type: "openai",
}),
headers: { "Content-Type": "application/json" },
method: "POST",
});
await createProviderViaHandler(req1, db);
const req2 = new Request("http://localhost/api/providers", {
body: JSON.stringify({
apiKey: "sk-b",
baseUrl: "https://b.com",
name: "重复名",
type: "openai",
}),
headers: { "Content-Type": "application/json" },
method: "POST",
});
const res = await createProviderViaHandler(req2, db);
expect(res.status).toBe(409);
});
});
});