verify-service.test.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { describe, it, expect, vi, afterEach } from "vitest";
  2. import { verifyService } from "../llm/providers/verify.js";
  3. describe("verifyService (B9)", () => {
  4. const originalFetch = global.fetch;
  5. afterEach(() => {
  6. global.fetch = originalFetch;
  7. vi.restoreAllMocks();
  8. });
  9. it("probe 成功 → probe.ok=true + chat 字段非 null(chat 步骤被执行)", async () => {
  10. global.fetch = vi.fn()
  11. // probe /models 成功
  12. .mockResolvedValueOnce({
  13. ok: true,
  14. json: async () => ({ data: [{ id: "gpt-4o" }, { id: "gpt-4o-mini" }] }),
  15. } as any)
  16. // 后续 chat 请求失败(测试环境没真实 openai SDK 支持),但这 OK —— 只要 chat 被尝试了就行
  17. .mockRejectedValue(new Error("test: no real chat backend"));
  18. const result = await verifyService("openai", "sk-test");
  19. expect(result.probe.ok).toBe(true);
  20. expect(result.probe.models).toBe(2);
  21. // chat 字段不为 null 说明 checkModel 存在 + chat 步骤被执行(ok=true/false 都可以)
  22. expect(result.chat).not.toBeNull();
  23. expect(typeof result.chat?.ok).toBe("boolean");
  24. expect(result.chat?.latencyMs).toBeGreaterThanOrEqual(0);
  25. });
  26. it("probe 401 → probe.ok=false, error 带 401", async () => {
  27. global.fetch = vi.fn().mockResolvedValue({
  28. ok: false,
  29. status: 401,
  30. statusText: "Unauthorized",
  31. } as any) as typeof fetch;
  32. const result = await verifyService("openai", "wrong-key");
  33. expect(result.probe.ok).toBe(false);
  34. expect(result.probe.error).toContain("401");
  35. });
  36. it("probe 网络挂 → probe.ok=false, error 是 fetch 错误", async () => {
  37. global.fetch = vi.fn().mockRejectedValue(new Error("ECONNREFUSED")) as typeof fetch;
  38. const result = await verifyService("openai", "sk-test");
  39. expect(result.probe.ok).toBe(false);
  40. expect(result.probe.error).toContain("ECONNREFUSED");
  41. });
  42. it("provider 没 checkModel(custom baseUrl 空)→ chat 字段返回 null,不发 chat 请求", async () => {
  43. // custom 没 checkModel,verifyService 跳过 chat step
  44. const result = await verifyService("custom", "sk-x");
  45. expect(result.chat).toBeNull();
  46. });
  47. it("未知 service → probe 报 '无 baseUrl'", async () => {
  48. const result = await verifyService("nonexistent-xyz", "sk-test");
  49. expect(result.probe.ok).toBe(false);
  50. expect(result.probe.error).toContain("baseUrl");
  51. });
  52. });