probe.test.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
  2. import { probeModelsFromUpstream } from "../llm/providers/probe.js";
  3. describe("probeModelsFromUpstream", () => {
  4. const origFetch = globalThis.fetch;
  5. beforeEach(() => {
  6. globalThis.fetch = vi.fn();
  7. });
  8. afterEach(() => {
  9. globalThis.fetch = origFetch;
  10. });
  11. it("正常响应返回 ProbedModel 数组", async () => {
  12. (globalThis.fetch as any).mockResolvedValue({
  13. ok: true,
  14. json: async () => ({ data: [{ id: "gpt-4" }, { id: "gpt-3.5" }] }),
  15. });
  16. const result = await probeModelsFromUpstream("https://api.example.com/v1", "sk-test");
  17. expect(result).toEqual([
  18. { id: "gpt-4", name: "gpt-4", contextWindow: 0 },
  19. { id: "gpt-3.5", name: "gpt-3.5", contextWindow: 0 },
  20. ]);
  21. });
  22. it("非 2xx 返回空数组", async () => {
  23. (globalThis.fetch as any).mockResolvedValue({ ok: false });
  24. const result = await probeModelsFromUpstream("https://api.example.com/v1", "sk-test");
  25. expect(result).toEqual([]);
  26. });
  27. it("fetch 抛错返回空数组", async () => {
  28. (globalThis.fetch as any).mockRejectedValue(new Error("network down"));
  29. const result = await probeModelsFromUpstream("https://api.example.com/v1", "sk-test");
  30. expect(result).toEqual([]);
  31. });
  32. it("响应 json.data 不是数组返回空数组", async () => {
  33. (globalThis.fetch as any).mockResolvedValue({
  34. ok: true,
  35. json: async () => ({ data: "not-an-array" }),
  36. });
  37. const result = await probeModelsFromUpstream("https://api.example.com/v1", "sk-test");
  38. expect(result).toEqual([]);
  39. });
  40. it("baseUrl 或 apiKey 空直接返回空数组,不发请求", async () => {
  41. const r1 = await probeModelsFromUpstream("", "sk-test");
  42. const r2 = await probeModelsFromUpstream("https://x.com", "");
  43. expect(r1).toEqual([]);
  44. expect(r2).toEqual([]);
  45. expect(globalThis.fetch).not.toHaveBeenCalled();
  46. });
  47. it("过滤掉 id 非字符串的 entry", async () => {
  48. (globalThis.fetch as any).mockResolvedValue({
  49. ok: true,
  50. json: async () => ({ data: [{ id: "valid" }, { id: null }, { id: 123 }, {}] }),
  51. });
  52. const result = await probeModelsFromUpstream("https://api.example.com/v1", "sk-test");
  53. expect(result).toEqual([{ id: "valid", name: "valid", contextWindow: 0 }]);
  54. });
  55. });