api-openapi-spec.test.ts 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /**
  2. * OpenAPI 规范验证测试
  3. *
  4. * 目的:
  5. * - 验证生成的 OpenAPI 文档符合 3.1.0 规范
  6. * - 确保所有端点都有必要的文档字段(summary, description, tags)
  7. * - 验证 schema 定义完整性
  8. *
  9. * 用法:
  10. * bun run test:api
  11. */
  12. import { beforeAll, describe, expect, test } from "vitest";
  13. import { callActionsRoute } from "../test-utils";
  14. // 类型定义(避免引入 OpenAPI 类型包)
  15. type OpenAPIDocument = {
  16. openapi: string;
  17. info: {
  18. title: string;
  19. version: string;
  20. description?: string;
  21. contact?: { name: string; url: string };
  22. license?: { name: string; url: string };
  23. };
  24. servers: Array<{ url: string; description: string }>;
  25. paths: Record<
  26. string,
  27. Record<
  28. string,
  29. {
  30. summary?: string;
  31. description?: string;
  32. tags?: string[];
  33. parameters?: unknown[];
  34. requestBody?: unknown;
  35. responses?: Record<string, unknown>;
  36. security?: unknown[];
  37. }
  38. >
  39. >;
  40. tags?: Array<{ name: string; description?: string }>;
  41. components?: {
  42. securitySchemes?: Record<string, unknown>;
  43. schemas?: Record<string, unknown>;
  44. };
  45. };
  46. type JsonSchemaProperty = {
  47. minimum?: number;
  48. maximum?: number;
  49. properties?: Record<string, JsonSchemaProperty>;
  50. };
  51. function getJsonRequestSchema(
  52. openApiDoc: OpenAPIDocument,
  53. path: string
  54. ): JsonSchemaProperty | undefined {
  55. const requestBody = openApiDoc.paths[path]?.post?.requestBody as
  56. | {
  57. content?: {
  58. "application/json"?: {
  59. schema?: JsonSchemaProperty;
  60. };
  61. };
  62. }
  63. | undefined;
  64. return requestBody?.content?.["application/json"]?.schema;
  65. }
  66. describe("OpenAPI 规范验证", () => {
  67. let openApiDoc: OpenAPIDocument;
  68. beforeAll(async () => {
  69. const { response, json } = await callActionsRoute({
  70. method: "GET",
  71. pathname: "/api/actions/openapi.json",
  72. });
  73. expect(response.ok).toBe(true);
  74. expect(response.headers.get("content-type")).toContain("application/json");
  75. openApiDoc = json as OpenAPIDocument;
  76. expect(openApiDoc).toBeDefined();
  77. });
  78. test("应该符合 OpenAPI 3.1.0 规范", () => {
  79. expect(openApiDoc.openapi).toBe("3.1.0");
  80. expect(openApiDoc.info).toBeDefined();
  81. expect(openApiDoc.info.title).toBe("Claude Code Hub API");
  82. expect(openApiDoc.info.version).toBeDefined();
  83. });
  84. test("应该包含项目元信息", () => {
  85. expect(openApiDoc.info.contact).toBeDefined();
  86. expect(openApiDoc.info.contact?.name).toBe("项目维护团队");
  87. expect(openApiDoc.info.contact?.url).toContain("github.com");
  88. expect(openApiDoc.info.license).toBeDefined();
  89. expect(openApiDoc.info.license?.name).toBe("MIT License");
  90. });
  91. test("应该定义 servers 配置", () => {
  92. expect(openApiDoc.servers).toBeDefined();
  93. expect(openApiDoc.servers.length).toBeGreaterThan(0);
  94. for (const server of openApiDoc.servers) {
  95. expect(server.url).toBeDefined();
  96. expect(server.description).toBeDefined();
  97. }
  98. });
  99. test("应该定义所有标签分组", () => {
  100. const expectedTags = [
  101. "用户管理",
  102. "密钥管理",
  103. "供应商管理",
  104. "模型价格",
  105. "统计分析",
  106. "使用日志",
  107. "概览",
  108. "敏感词管理",
  109. "Session 管理",
  110. "通知管理",
  111. ];
  112. expect(openApiDoc.tags).toBeDefined();
  113. expect(openApiDoc.tags!.length).toBe(expectedTags.length);
  114. for (const tagName of expectedTags) {
  115. const tag = openApiDoc.tags!.find((t) => t.name === tagName);
  116. expect(tag).toBeDefined();
  117. expect(tag!.description).toBeDefined();
  118. expect(tag!.description!.length).toBeGreaterThan(10); // 确保描述足够详细
  119. }
  120. });
  121. test("应该定义 Cookie 认证方案", () => {
  122. expect(openApiDoc.components?.securitySchemes).toBeDefined();
  123. expect(openApiDoc.components!.securitySchemes!.cookieAuth).toBeDefined();
  124. });
  125. test("所有端点都应该有 summary 字段", () => {
  126. const paths = openApiDoc.paths;
  127. const pathsWithoutSummary: string[] = [];
  128. for (const [path, methods] of Object.entries(paths)) {
  129. for (const [method, operation] of Object.entries(methods)) {
  130. if (!operation.summary) {
  131. pathsWithoutSummary.push(`${method.toUpperCase()} ${path}`);
  132. }
  133. }
  134. }
  135. expect(pathsWithoutSummary).toEqual([]);
  136. });
  137. test("所有端点都应该有 description 字段", () => {
  138. const paths = openApiDoc.paths;
  139. const pathsWithoutDescription: string[] = [];
  140. for (const [path, methods] of Object.entries(paths)) {
  141. for (const [method, operation] of Object.entries(methods)) {
  142. if (!operation.description) {
  143. pathsWithoutDescription.push(`${method.toUpperCase()} ${path}`);
  144. }
  145. }
  146. }
  147. expect(pathsWithoutDescription).toEqual([]);
  148. });
  149. test("所有端点都应该有 tags 分组", () => {
  150. const paths = openApiDoc.paths;
  151. const pathsWithoutTags: string[] = [];
  152. for (const [path, methods] of Object.entries(paths)) {
  153. for (const [method, operation] of Object.entries(methods)) {
  154. if (!operation.tags || operation.tags.length === 0) {
  155. pathsWithoutTags.push(`${method.toUpperCase()} ${path}`);
  156. }
  157. }
  158. }
  159. expect(pathsWithoutTags).toEqual([]);
  160. });
  161. test("所有 POST 端点都应该定义响应 schema", () => {
  162. const paths = openApiDoc.paths;
  163. const pathsWithoutResponses: string[] = [];
  164. for (const [path, methods] of Object.entries(paths)) {
  165. const postOperation = methods.post;
  166. if (postOperation && !postOperation.responses) {
  167. pathsWithoutResponses.push(`POST ${path}`);
  168. }
  169. }
  170. expect(pathsWithoutResponses).toEqual([]);
  171. });
  172. test("应该包含标准错误响应定义", () => {
  173. const paths = openApiDoc.paths;
  174. const firstPath = Object.values(paths)[0];
  175. const firstOperation = Object.values(firstPath)[0];
  176. expect(firstOperation.responses).toBeDefined();
  177. expect(firstOperation.responses!["200"]).toBeDefined();
  178. expect(firstOperation.responses!["400"]).toBeDefined();
  179. expect(firstOperation.responses!["401"]).toBeDefined();
  180. expect(firstOperation.responses!["500"]).toBeDefined();
  181. });
  182. test("端点数量应该符合预期", () => {
  183. const totalPaths = Object.keys(openApiDoc.paths).length;
  184. // 端点数量会随着功能模块增长而变化:这里只做“合理范围”约束
  185. expect(totalPaths).toBeGreaterThanOrEqual(40);
  186. expect(totalPaths).toBeLessThanOrEqual(80);
  187. });
  188. test("summary 和 description 应该不同", () => {
  189. const paths = openApiDoc.paths;
  190. const violations: string[] = [];
  191. const totalPaths = Object.keys(paths).length;
  192. for (const [path, methods] of Object.entries(paths)) {
  193. for (const [method, operation] of Object.entries(methods)) {
  194. if (operation.summary && operation.description) {
  195. // summary 应该是简短版本,description 可以包含更多信息
  196. // 如果完全相同,可能需要优化
  197. if (operation.summary === operation.description) {
  198. violations.push(`${method.toUpperCase()} ${path}`);
  199. }
  200. }
  201. }
  202. }
  203. // 允许部分端点 summary 和 description 相同(简单操作)
  204. // 但不应该太多(允许 35% 以内)
  205. expect(violations.length).toBeLessThan(totalPaths * 0.35);
  206. });
  207. test("users 列表请求 schema 应与兼容参数归一化保持一致", () => {
  208. for (const path of ["/api/actions/users/getUsers", "/api/actions/users/getUsersBatch"]) {
  209. const schema = getJsonRequestSchema(openApiDoc, path);
  210. const pageSchema = schema?.properties?.page;
  211. const limitSchema = schema?.properties?.limit;
  212. expect(pageSchema?.minimum).toBe(0);
  213. expect(limitSchema).toBeDefined();
  214. expect(limitSchema?.maximum).toBeUndefined();
  215. }
  216. });
  217. });