accountProviderKeyUsageScene.test.ts 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. import { describe, expect, it, vi } from "vitest";
  2. import { type ApiClient } from "@zcode/shared";
  3. import { AccountProviderApiClient } from "#src/model-provider/accountProviderApiClient.js";
  4. import { AccountProviderApiKeyResolver } from "#src/model-provider/accountProviderApiKeyResolver.js";
  5. import { resolveAccountTeamPlanRuntimeMaterial } from "#src/model-provider/accountProviderTeamPlanRequestKey.js";
  6. describe.each(["bigmodel", "zai"] as const)("%s Coding Plan Key 用途", (family) => {
  7. it.each([false, true])(
  8. "个人已有 Key=%s,创建时明确套餐用途且不改变查询兼容",
  9. async (existing) => {
  10. const fixture = createApiFixture(existing, false);
  11. const remote = new AccountProviderApiClient(fixture.apiClient);
  12. const resolver = new AccountProviderApiKeyResolver(remote.fetchRemoteData.bind(remote));
  13. await expect(resolver.resolveProviderMaterial(family, "login-token")).resolves.toMatchObject({
  14. token: "project-token",
  15. apiKeyId: "key",
  16. });
  17. assertRequests(fixture.requests, existing, false, family);
  18. },
  19. );
  20. it.each([false, true])("团队已有 Key=%s,keyType 与 usageScene 独立", async (existing) => {
  21. const fixture = createApiFixture(existing, true);
  22. await expect(
  23. resolveAccountTeamPlanRuntimeMaterial({
  24. apiClient: fixture.apiClient,
  25. credentialService: {
  26. load: vi.fn(async (key: string) =>
  27. key === `oauth:${family}:access_token` ? "login-token" : null,
  28. ),
  29. },
  30. access: {
  31. type: "zhipu-account",
  32. family,
  33. planKind: "team-coding-plan",
  34. organizationId: "org",
  35. projectId: "project",
  36. productId: "plan",
  37. },
  38. }),
  39. ).resolves.toMatchObject({ token: "project-token", apiKeyId: "key" });
  40. assertRequests(fixture.requests, existing, true, family);
  41. });
  42. });
  43. function createApiFixture(existing: boolean, team: boolean) {
  44. const requests: Array<{ url: string; init?: RequestInit }> = [];
  45. const entry = {
  46. apiKey: "key",
  47. name: team ? "zcode-team-api-key" : "zcode-api-key",
  48. keyType: 2,
  49. };
  50. const apiClient: ApiClient = {
  51. async request(input, init) {
  52. const url = String(input);
  53. requests.push({ url, init });
  54. let data: unknown;
  55. if (url.endsWith("/getCustomerInfo")) {
  56. data = {
  57. organizations: [{ organizationId: "org", projects: [{ projectId: "project" }] }],
  58. };
  59. } else if (url.endsWith("/api_keys/key/access_tokens")) {
  60. data = {
  61. accessToken: "project-token",
  62. tokenType: "Bearer",
  63. expiresIn: 600,
  64. expiresAt: Math.floor(Date.now() / 1000) + 600,
  65. };
  66. } else if (url.endsWith("/api_keys")) {
  67. data = init?.method === "POST" ? entry : existing ? [entry] : [];
  68. } else throw new Error(`Unexpected URL: ${url}`);
  69. return new Response(JSON.stringify({ code: 200, data }), {
  70. headers: { "content-type": "application/json" },
  71. });
  72. },
  73. };
  74. return { apiClient, requests };
  75. }
  76. function assertRequests(
  77. requests: Array<{ url: string; init?: RequestInit }>,
  78. existing: boolean,
  79. team: boolean,
  80. family: "bigmodel" | "zai",
  81. ) {
  82. for (const request of requests) {
  83. const authorization = new Headers(request.init?.headers).get("authorization");
  84. const expected =
  85. request.url.endsWith("/access_tokens") ||
  86. (family === "zai" && (!team || request.url.endsWith("/getCustomerInfo")))
  87. ? "Bearer login-token"
  88. : "login-token";
  89. expect(authorization, request.url).toBe(expected);
  90. }
  91. expect(requests.some(({ url }) => url.includes("/copy/"))).toBe(false);
  92. expect(requests.at(-1)?.url).toMatch(/\/key\/access_tokens$/);
  93. const creates = requests.filter(
  94. ({ url, init }) => url.endsWith("/api_keys") && init?.method === "POST",
  95. );
  96. expect(creates).toHaveLength(existing ? 0 : 1);
  97. if (!existing) {
  98. expect(JSON.parse(String(creates[0]?.init?.body))).toEqual({
  99. name: team ? "zcode-team-api-key" : "zcode-api-key",
  100. ...(team ? { keyType: 2 } : {}),
  101. usageScene: 1,
  102. });
  103. }
  104. const list = requests.find(
  105. ({ url, init }) => url.endsWith("/api_keys") && init?.method === "GET",
  106. );
  107. expect(list).toBeDefined();
  108. expect(new URL(list!.url).search).toBe("");
  109. }