[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6MG19FYTQC661BRS0PWKWJB":3,"skill-same:01M6MG19FYTQC661BRS0PWKWJB":63},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":30,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":44,"ownerHtmlUrl":45,"ownerBlogUrl":46,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M6MG19FYTQC661BRS0PWKWJB","api-testing",null,"hashgraph-online\u002Fawesome-codex-plugins","hashgraph-online","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F160371962?v=4","01M6CNB6NRJVNNGN14TR01Q6D3","HOL (Hashgraph Online)","01M6JT1HSKKG9V68KQAQGBA7XP",1575,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fapi-testing\u002FSKILL.md",[17,22,25],{"categoryNo":18,"categoryName":19,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000008","测试与质量","SCENARIO","使用场景",{"categoryNo":23,"categoryName":24,"taxonomyType":20,"taxonomyTypeDesc":21},"01JBSEEDCAT000000000000010","后端与接口",{"categoryNo":26,"categoryName":27,"taxonomyType":28,"taxonomyTypeDesc":29},"01JBSEEDCAT000000000000030","开发工程师","PROFESSION","适用职业",[31,32,33],"testing","api","api testing","2026-11-10 10:12:30",false,"---\n\nname: qa\u002Fapi-testing\ndescription: API 接口测试方法论，覆盖 RESTful\u002FGraphQL 接口的功能、边界、安全、契约测试，参考 Supertest、REST Assured 等开源实践\nversion: 1.0.0\nagent: qa\ntype: methodology\nuser-invocable: false\nagent-invocable: true\ndependencies:\n- shared\u002Ftech-stack-detection\n  triggers:\n- 需要编写或执行 API 接口测试时\n- 需要验证 API 契约一致性时\n- 需要覆盖接口边界和安全场景时\n  metadata:\n  internal: true\n\n---\n\n# API 接口测试方法论\n\n> 参考开源实践：Supertest、REST Assured、Postman\u002FNewman、HTTPie、Testcontainers\n\n## 适用场景\n\n- 后端 API 端点需要功能验证\n- 需要测试接口边界值、错误处理、权限控制\n- 需要验证 API 契约（请求\u002F响应 schema 一致性）\n- 需要覆盖认证、授权、越权等安全场景\n- 需要测试完整业务流程的 API 链路\n\n## 测试类型矩阵\n\n| 测试类型     | 目的                    | 工具                     | 示例                            |\n| ------------ | ----------------------- | ------------------------ | ------------------------------- |\n| **功能测试** | 验证接口正常行为        | Supertest \u002F REST Assured | 创建资源返回 201                |\n| **边界测试** | 验证边界值和错误处理    | Supertest                | 空 payload、超长字符串、非法 ID |\n| **安全测试** | 认证、授权、越权        | Supertest + auth header  | 无 Token 访问受保护资源         |\n| **契约测试** | 请求\u002F响应 schema 一致性 | Zod \u002F JSON Schema        | 响应字段类型校验                |\n| **流程测试** | 多接口业务链路          | Supertest 链式调用       | 注册→登录→下单→支付             |\n\n## 1. RESTful API 测试\n\n### 1.1 Node.js (Supertest + Jest\u002FVitest)\n\n```typescript\n\u002F\u002F tests\u002Fapi\u002Fusers.test.ts\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\n\ndescribe('User API', () => {\n  describe('POST \u002Fapi\u002Fusers', () => {\n    it('creates user with valid data', async () => {\n      const res = await request(app)\n        .post('\u002Fapi\u002Fusers')\n        .send({ name: 'Alice', email: 'alice@example.com' })\n        .expect(201)\n        .expect('Content-Type', \u002Fjson\u002F);\n\n      expect(res.body.success).toBe(true);\n      expect(res.body.data).toMatchObject({ name: 'Alice', email: 'alice@example.com' });\n      expect(res.body.data.id).toBeDefined();\n    });\n\n    it('rejects empty name with 400', async () => {\n      const res = await request(app)\n        .post('\u002Fapi\u002Fusers')\n        .send({ name: '', email: 'test@example.com' })\n        .expect(400);\n\n      expect(res.body.error.code).toBe('VALIDATION_ERROR');\n    });\n\n    it('rejects duplicate email with 409', async () => {\n      await request(app).post('\u002Fapi\u002Fusers').send({ name: 'A', email: 'dup@example.com' });\n      const res = await request(app)\n        .post('\u002Fapi\u002Fusers')\n        .send({ name: 'B', email: 'dup@example.com' })\n        .expect(409);\n\n      expect(res.body.error.code).toBe('CONFLICT');\n    });\n  });\n});\n```\n\n### 1.2 Python (pytest + requests)\n\n```python\n# tests\u002Fapi\u002Ftest_users.py\nimport pytest\nimport requests\n\nBASE_URL = \"http:\u002F\u002Flocalhost:3000\"\n\ndef test_create_user():\n    res = requests.post(f\"{BASE_URL}\u002Fapi\u002Fusers\", json={\"name\": \"Alice\", \"email\": \"alice@example.com\"})\n    assert res.status_code == 201\n    assert res.json()[\"data\"][\"name\"] == \"Alice\"\n\ndef test_create_user_empty_name():\n    res = requests.post(f\"{BASE_URL}\u002Fapi\u002Fusers\", json={\"name\": \"\", \"email\": \"test@example.com\"})\n    assert res.status_code == 400\n```\n\n### 1.3 Go (net\u002Fhttp\u002Fhttptest)\n\n```go\n\u002F\u002F handlers\u002Fusers_test.go\nfunc TestCreateUser(t *testing.T) {\n    app := setupTestApp()\n    body := strings.NewReader(`{\"name\":\"Alice\",\"email\":\"alice@example.com\"}`)\n    req := httptest.NewRequest(\"POST\", \"\u002Fapi\u002Fusers\", body)\n    req.Header.Set(\"Content-Type\", \"application\u002Fjson\")\n    w := httptest.NewRecorder()\n\n    app.ServeHTTP(w, req)\n\n    if w.Code != http.StatusCreated {\n        t.Errorf(\"expected 201, got %d\", w.Code)\n    }\n}\n```\n\n## 2. GraphQL API 测试\n\n```typescript\n\u002F\u002F tests\u002Fapi\u002Fgraphql.test.ts\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\n\ndescribe('GraphQL API', () => {\n  it('queries user by id', async () => {\n    const query = `\n      query GetUser($id: ID!) {\n        user(id: $id) { id name email }\n      }\n    `;\n    const res = await request(app)\n      .post('\u002Fgraphql')\n      .send({ query, variables: { id: '1' } })\n      .expect(200);\n\n    expect(res.body.data.user).toBeDefined();\n    expect(res.body.errors).toBeUndefined();\n  });\n\n  it('mutates: create user', async () => {\n    const mutation = `\n      mutation CreateUser($input: CreateUserInput!) {\n        createUser(input: $input) { id name }\n      }\n    `;\n    const res = await request(app)\n      .post('\u002Fgraphql')\n      .send({ mutation, variables: { input: { name: 'Bob', email: 'bob@example.com' } } })\n      .expect(200);\n\n    expect(res.body.data.createUser.id).toBeDefined();\n  });\n});\n```\n\n## 3. 认证与授权测试\n\n### 3.1 Token 认证\n\n```typescript\ndescribe('Protected endpoints', () => {\n  let token: string;\n\n  beforeAll(async () => {\n    const res = await request(app)\n      .post('\u002Fapi\u002Fauth\u002Flogin')\n      .send({ email: 'admin@example.com', password: '\u003CPASSWORD>' });\n    token = res.body.data.token;\n  });\n\n  it('returns 401 without token', async () => {\n    await request(app).get('\u002Fapi\u002Fusers\u002Fprofile').expect(401);\n  });\n\n  it('returns 401 with invalid token', async () => {\n    await request(app)\n      .get('\u002Fapi\u002Fusers\u002Fprofile')\n      .set('Authorization', 'Bearer \u003CINVALID_TOKEN>')\n      .expect(401);\n  });\n\n  it('returns 200 with valid token', async () => {\n    await request(app)\n      .get('\u002Fapi\u002Fusers\u002Fprofile')\n      .set('Authorization', `Bearer ${token}`)\n      .expect(200);\n  });\n});\n```\n\n### 3.2 权限\u002F越权测试\n\n```typescript\ndescribe('Authorization', () => {\n  let adminToken: string;\n  let userToken: string;\n\n  beforeAll(async () => {\n    adminToken = await login('admin@example.com', '\u003CPASSWORD>');\n    userToken = await login('user@example.com', '\u003CPASSWORD>');\n  });\n\n  it('admin can delete any user', async () => {\n    await request(app)\n      .delete('\u002Fapi\u002Fusers\u002F123')\n      .set('Authorization', `Bearer ${adminToken}`)\n      .expect(200);\n  });\n\n  it('regular user cannot delete others (403)', async () => {\n    await request(app)\n      .delete('\u002Fapi\u002Fusers\u002F123')\n      .set('Authorization', `Bearer ${userToken}`)\n      .expect(403);\n  });\n});\n```\n\n## 4. 边界值与错误用例\n\n### 4.1 输入边界\n\n```typescript\ndescribe('Input boundaries', () => {\n  it('rejects email exceeding max length', async () => {\n    const longEmail = 'a'.repeat(256) + '@example.com';\n    await request(app).post('\u002Fapi\u002Fusers').send({ name: 'Test', email: longEmail }).expect(400);\n  });\n\n  it('rejects invalid UUID format', async () => {\n    await request(app).get('\u002Fapi\u002Fusers\u002Fnot-a-uuid').expect(400);\n  });\n\n  it('rejects negative quantity', async () => {\n    await request(app)\n      .post('\u002Fapi\u002Forders')\n      .send({ items: [{ productId: '1', quantity: -1 }] })\n      .expect(400);\n  });\n\n  it('rejects SQL injection attempt', async () => {\n    await request(app).get(\"\u002Fapi\u002Fusers?id=1' OR '1'='1\").expect(400);\n  });\n});\n```\n\n### 4.2 业务状态机管控\n\n当接口涉及状态流转时，必须测试状态管控：\n\n```typescript\ndescribe('Order state machine', () => {\n  it('cannot cancel a paid order', async () => {\n    \u002F\u002F 创建并支付订单\n    const order = await createAndPayOrder();\n\n    \u002F\u002F 尝试取消已支付订单\n    const res = await request(app)\n      .post(`\u002Fapi\u002Forders\u002F${order.id}\u002Fcancel`)\n      .set('Authorization', `Bearer ${token}`)\n      .expect(409);\n\n    expect(res.body.error.code).toBe('INVALID_STATE_TRANSITION');\n  });\n\n  it('cannot modify a confirmed order', async () => {\n    const order = await createConfirmedOrder();\n\n    await request(app)\n      .put(`\u002Fapi\u002Forders\u002F${order.id}`)\n      .set('Authorization', `Bearer ${token}`)\n      .send({ items: [] })\n      .expect(409);\n  });\n});\n```\n\n## 5. 契约测试（Schema 校验）\n\n使用 Zod 或 JSON Schema 校验响应结构：\n\n```typescript\nimport { z } from 'zod';\n\nconst UserSchema = z.object({\n  id: z.string().uuid(),\n  name: z.string().min(1).max(100),\n  email: z.string().email(),\n  createdAt: z.string().datetime(),\n});\n\nit('response matches user schema', async () => {\n  const res = await request(app).get('\u002Fapi\u002Fusers\u002F1').expect(200);\n  const result = UserSchema.safeParse(res.body.data);\n  expect(result.success).toBe(true);\n});\n```\n\n## 6. 数据依赖管理\n\n### 6.1 预取数据（Prefetch）\n\n当用例依赖已有数据时，先预取真实 ID 注入变量池：\n\n```typescript\ndescribe('Dependent endpoints', () => {\n  let existingUserId: string;\n\n  beforeAll(async () => {\n    \u002F\u002F 预取一个真实存在的用户 ID\n    const res = await request(app).get('\u002Fapi\u002Fusers?limit=1');\n    existingUserId = res.body.data.items[0]?.id;\n  });\n\n  it('updates existing user', async () => {\n    await request(app).put(`\u002Fapi\u002Fusers\u002F${existingUserId}`).send({ name: 'Updated' }).expect(200);\n  });\n});\n```\n\n### 6.2 破坏性操作安全保护\n\n对 DELETE\u002F逻辑删除类用例，使用假 ID 避免污染真实数据：\n\n```typescript\nit('returns 404 when deleting non-existent user', async () => {\n  await request(app).delete('\u002Fapi\u002Fusers\u002F00000000-0000-0000-0000-000000000000').expect(404);\n});\n```\n\n### 6.3 测试数据隔离\n\n```typescript\nbeforeEach(async () => {\n  \u002F\u002F 每个测试前清理相关表\n  await db.user.deleteMany({ where: { email: { startsWith: 'test-' } } });\n});\n```\n\n## 7. 性能与并发测试\n\n```typescript\nit('handles 10 concurrent user creations', async () => {\n  const promises = Array.from({ length: 10 }, (_, i) =>\n    request(app)\n      .post('\u002Fapi\u002Fusers')\n      .send({ name: `User${i}`, email: `user${i}@test.com` }),\n  );\n\n  const responses = await Promise.all(promises);\n  responses.forEach((res) => expect(res.status).toBe(201));\n});\n```\n\n## 8. 断言策略\n\n### 分层判定原则\n\n| 场景     | 主判据                       | 辅判据                  |\n| -------- | ---------------------------- | ----------------------- |\n| 正常请求 | HTTP 状态码 2xx              | 响应体字段              |\n| 参数错误 | HTTP 400 + 业务码            | 错误消息                |\n| 业务错误 | **业务码**（非 HTTP 状态码） | 错误消息                |\n| 认证失败 | HTTP 401                     | WWW-Authenticate header |\n| 授权失败 | HTTP 403                     | -                       |\n\n> ⚠️ 当后端使用「200 + 业务码」表达错误时，断言应以**业务码语义**为主，不应因 HTTP 200 就判定通过。\n\n## 9. 测试报告要求\n\n每个 API 测试文件必须覆盖：\n- [ ] 正常流程（happy path）\n- [ ] 参数校验（必填、格式、长度、类型）\n- [ ] 认证（无 Token、无效 Token、过期 Token）\n- [ ] 授权（角色权限、越权访问）\n- [ ] 业务状态机（状态流转限制）\n- [ ] 边界值（空、超长、非法、特殊字符）\n- [ ] 安全（SQL 注入、XSS、路径遍历）\n- [ ] 并发与幂等\n\n## 10. 检查清单\n\n- [ ] 所有 CRUD 端点都有功能测试\n- [ ] 每个端点至少有 1 个错误\u002F边界用例\n- [ ] 认证端点覆盖成功和失败场景\n- [ ] 受保护资源覆盖 401\u002F403 场景\n- [ ] 响应体通过 schema 校验\n- [ ] 测试数据相互隔离，可重复运行\n- [ ] 破坏性操作使用假 ID 或测试数据\n- [ ] 不依赖外部服务（mock 第三方 API）\n","# API 接口测试方法论\n\n> 参考开源实践：Supertest、REST Assured、Postman\u002FNewman、HTTPie、Testcontainers\n\n## 适用场景\n\n- 后端 API 端点需要功能验证\n- 需要测试接口边界值、错误处理、权限控制\n- 需要验证 API 契约（请求\u002F响应 schema 一致性）\n- 需要覆盖认证、授权、越权等安全场景\n- 需要测试完整业务流程的 API 链路\n\n## 测试类型矩阵\n\n| 测试类型     | 目的                    | 工具                     | 示例                            |\n| ------------ | ----------------------- | ------------------------ | ------------------------------- |\n| **功能测试** | 验证接口正常行为        | Supertest \u002F REST Assured | 创建资源返回 201                |\n| **边界测试** | 验证边界值和错误处理    | Supertest                | 空 payload、超长字符串、非法 ID |\n| **安全测试** | 认证、授权、越权        | Supertest + auth header  | 无 Token 访问受保护资源         |\n| **契约测试** | 请求\u002F响应 schema 一致性 | Zod \u002F JSON Schema        | 响应字段类型校验                |\n| **流程测试** | 多接口业务链路          | Supertest 链式调用       | 注册→登录→下单→支付             |\n\n## 1. RESTful API 测试\n\n### 1.1 Node.js (Supertest + Jest\u002FVitest)\n\n```typescript\n\u002F\u002F tests\u002Fapi\u002Fusers.test.ts\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\n\ndescribe('User API', () => {\n  describe('POST \u002Fapi\u002Fusers', () => {\n    it('creates user with valid data', async () => {\n      const res = await request(app)\n        .post('\u002Fapi\u002Fusers')\n        .send({ name: 'Alice', email: 'alice@example.com' })\n        .expect(201)\n        .expect('Content-Type', \u002Fjson\u002F);\n\n      expect(res.body.success).toBe(true);\n      expect(res.body.data).toMatchObject({ name: 'Alice', email: 'alice@example.com' });\n      expect(res.body.data.id).toBeDefined();\n    });\n\n    it('rejects empty name with 400', async () => {\n      const res = await request(app)\n        .post('\u002Fapi\u002Fusers')\n        .send({ name: '', email: 'test@example.com' })\n        .expect(400);\n\n      expect(res.body.error.code).toBe('VALIDATION_ERROR');\n    });\n\n    it('rejects duplicate email with 409', async () => {\n      await request(app).post('\u002Fapi\u002Fusers').send({ name: 'A', email: 'dup@example.com' });\n      const res = await request(app)\n        .post('\u002Fapi\u002Fusers')\n        .send({ name: 'B', email: 'dup@example.com' })\n        .expect(409);\n\n      expect(res.body.error.code).toBe('CONFLICT');\n    });\n  });\n});\n```\n\n### 1.2 Python (pytest + requests)\n\n```python\n# tests\u002Fapi\u002Ftest_users.py\nimport pytest\nimport requests\n\nBASE_URL = \"http:\u002F\u002Flocalhost:3000\"\n\ndef test_create_user():\n    res = requests.post(f\"{BASE_URL}\u002Fapi\u002Fusers\", json={\"name\": \"Alice\", \"email\": \"alice@example.com\"})\n    assert res.status_code == 201\n    assert res.json()[\"data\"][\"name\"] == \"Alice\"\n\ndef test_create_user_empty_name():\n    res = requests.post(f\"{BASE_URL}\u002Fapi\u002Fusers\", json={\"name\": \"\", \"email\": \"test@example.com\"})\n    assert res.status_code == 400\n```\n\n### 1.3 Go (net\u002Fhttp\u002Fhttptest)\n\n```go\n\u002F\u002F handlers\u002Fusers_test.go\nfunc TestCreateUser(t *testing.T) {\n    app := setupTestApp()\n    body := strings.NewReader(`{\"name\":\"Alice\",\"email\":\"alice@example.com\"}`)\n    req := httptest.NewRequest(\"POST\", \"\u002Fapi\u002Fusers\", body)\n    req.Header.Set(\"Content-Type\", \"application\u002Fjson\")\n    w := httptest.NewRecorder()\n\n    app.ServeHTTP(w, req)\n\n    if w.Code != http.StatusCreated {\n        t.Errorf(\"expected 201, got %d\", w.Code)\n    }\n}\n```\n\n## 2. GraphQL API 测试\n\n```typescript\n\u002F\u002F tests\u002Fapi\u002Fgraphql.test.ts\nimport request from 'supertest';\nimport { app } from '..\u002F..\u002Fsrc\u002Fapp';\n\ndescribe('GraphQL API', () => {\n  it('queries user by id', async () => {\n    const query = `\n      query GetUser($id: ID!) {\n        user(id: $id) { id name email }\n      }\n    `;\n    const res = await request(app)\n      .post('\u002Fgraphql')\n      .send({ query, variables: { id: '1' } })\n      .expect(200);\n\n    expect(res.body.data.user).toBeDefined();\n    expect(res.body.errors).toBeUndefined();\n  });\n\n  it('mutates: create user', async () => {\n    const mutation = `\n      mutation CreateUser($input: CreateUserInput!) {\n        createUser(input: $input) { id name }\n      }\n    `;\n    const res = await request(app)\n      .post('\u002Fgraphql')\n      .send({ mutation, variables: { input: { name: 'Bob', email: 'bob@example.com' } } })\n      .expect(200);\n\n    expect(res.body.data.createUser.id).toBeDefined();\n  });\n});\n```\n\n## 3. 认证与授权测试\n\n### 3.1 Token 认证\n\n```typescript\ndescribe('Protected endpoints', () => {\n  let token: string;\n\n  beforeAll(async () => {\n    const res = await request(app)\n      .post('\u002Fapi\u002Fauth\u002Flogin')\n      .send({ email: 'admin@example.com', password: '\u003CPASSWORD>' });\n    token = res.body.data.token;\n  });\n\n  it('returns 401 without token', async () => {\n    await request(app).get('\u002Fapi\u002Fusers\u002Fprofile').expect(401);\n  });\n\n  it('returns 401 with invalid token', async () => {\n    await request(app)\n      .get('\u002Fapi\u002Fusers\u002Fprofile')\n      .set('Authorization', 'Bearer \u003CINVALID_TOKEN>')\n      .expect(401);\n  });\n\n  it('returns 200 with valid token', async () => {\n    await request(app)\n      .get('\u002Fapi\u002Fusers\u002Fprofile')\n      .set('Authorization', `Bearer ${token}`)\n      .expect(200);\n  });\n});\n```\n\n### 3.2 权限\u002F越权测试\n\n```typescript\ndescribe('Authorization', () => {\n  let adminToken: string;\n  let userToken: string;\n\n  beforeAll(async () => {\n    adminToken = await login('admin@example.com', '\u003CPASSWORD>');\n    userToken = await login('user@example.com', '\u003CPASSWORD>');\n  });\n\n  it('admin can delete any user', async () => {\n    await request(app)\n      .delete('\u002Fapi\u002Fusers\u002F123')\n      .set('Authorization', `Bearer ${adminToken}`)\n      .expect(200);\n  });\n\n  it('regular user cannot delete others (403)', async () => {\n    await request(app)\n      .delete('\u002Fapi\u002Fusers\u002F123')\n      .set('Authorization', `Bearer ${userToken}`)\n      .expect(403);\n  });\n});\n```\n\n## 4. 边界值与错误用例\n\n### 4.1 输入边界\n\n```typescript\ndescribe('Input boundaries', () => {\n  it('rejects email exceeding max length', async () => {\n    const longEmail = 'a'.repeat(256) + '@example.com';\n    await request(app).post('\u002Fapi\u002Fusers').send({ name: 'Test', email: longEmail }).expect(400);\n  });\n\n  it('rejects invalid UUID format', async () => {\n    await request(app).get('\u002Fapi\u002Fusers\u002Fnot-a-uuid').expect(400);\n  });\n\n  it('rejects negative quantity', async () => {\n    await request(app)\n      .post('\u002Fapi\u002Forders')\n      .send({ items: [{ productId: '1', quantity: -1 }] })\n      .expect(400);\n  });\n\n  it('rejects SQL injection attempt', async () => {\n    await request(app).get(\"\u002Fapi\u002Fusers?id=1' OR '1'='1\").expect(400);\n  });\n});\n```\n\n### 4.2 业务状态机管控\n\n当接口涉及状态流转时，必须测试状态管控：\n\n```typescript\ndescribe('Order state machine', () => {\n  it('cannot cancel a paid order', async () => {\n    \u002F\u002F 创建并支付订单\n    const order = await createAndPayOrder();\n\n    \u002F\u002F 尝试取消已支付订单\n    const res = await request(app)\n      .post(`\u002Fapi\u002Forders\u002F${order.id}\u002Fcancel`)\n      .set('Authorization', `Bearer ${token}`)\n      .expect(409);\n\n    expect(res.body.error.code).toBe('INVALID_STATE_TRANSITION');\n  });\n\n  it('cannot modify a confirmed order', async () => {\n    const order = await createConfirmedOrder();\n\n    await request(app)\n      .put(`\u002Fapi\u002Forders\u002F${order.id}`)\n      .set('Authorization', `Bearer ${token}`)\n      .send({ items: [] })\n      .expect(409);\n  });\n});\n```\n\n## 5. 契约测试（Schema 校验）\n\n使用 Zod 或 JSON Schema 校验响应结构：\n\n```typescript\nimport { z } from 'zod';\n\nconst UserSchema = z.object({\n  id: z.string().uuid(),\n  name: z.string().min(1).max(100),\n  email: z.string().email(),\n  createdAt: z.string().datetime(),\n});\n\nit('response matches user schema', async () => {\n  const res = await request(app).get('\u002Fapi\u002Fusers\u002F1').expect(200);\n  const result = UserSchema.safeParse(res.body.data);\n  expect(result.success).toBe(true);\n});\n```\n\n## 6. 数据依赖管理\n\n### 6.1 预取数据（Prefetch）\n\n当用例依赖已有数据时，先预取真实 ID 注入变量池：\n\n```typescript\ndescribe('Dependent endpoints', () => {\n  let existingUserId: string;\n\n  beforeAll(async () => {\n    \u002F\u002F 预取一个真实存在的用户 ID\n    const res = await request(app).get('\u002Fapi\u002Fusers?limit=1');\n    existingUserId = res.body.data.items[0]?.id;\n  });\n\n  it('updates existing user', async () => {\n    await request(app).put(`\u002Fapi\u002Fusers\u002F${existingUserId}`).send({ name: 'Updated' }).expect(200);\n  });\n});\n```\n\n### 6.2 破坏性操作安全保护\n\n对 DELETE\u002F逻辑删除类用例，使用假 ID 避免污染真实数据：\n\n```typescript\nit('returns 404 when deleting non-existent user', async () => {\n  await request(app).delete('\u002Fapi\u002Fusers\u002F00000000-0000-0000-0000-000000000000').expect(404);\n});\n```\n\n### 6.3 测试数据隔离\n\n```typescript\nbeforeEach(async () => {\n  \u002F\u002F 每个测试前清理相关表\n  await db.user.deleteMany({ where: { email: { startsWith: 'test-' } } });\n});\n```\n\n## 7. 性能与并发测试\n\n```typescript\nit('handles 10 concurrent user creations', async () => {\n  const promises = Array.from({ length: 10 }, (_, i) =>\n    request(app)\n      .post('\u002Fapi\u002Fusers')\n      .send({ name: `User${i}`, email: `user${i}@test.com` }),\n  );\n\n  const responses = await Promise.all(promises);\n  responses.forEach((res) => expect(res.status).toBe(201));\n});\n```\n\n## 8. 断言策略\n\n### 分层判定原则\n\n| 场景     | 主判据                       | 辅判据                  |\n| -------- | ---------------------------- | ----------------------- |\n| 正常请求 | HTTP 状态码 2xx              | 响应体字段              |\n| 参数错误 | HTTP 400 + 业务码            | 错误消息                |\n| 业务错误 | **业务码**（非 HTTP 状态码） | 错误消息                |\n| 认证失败 | HTTP 401                     | WWW-Authenticate header |\n| 授权失败 | HTTP 403                     | -                       |\n\n> ⚠️ 当后端使用「200 + 业务码」表达错误时，断言应以**业务码语义**为主，不应因 HTTP 200 就判定通过。\n\n## 9. 测试报告要求\n\n每个 API 测试文件必须覆盖：\n- [ ] 正常流程（happy path）\n- [ ] 参数校验（必填、格式、长度、类型）\n- [ ] 认证（无 Token、无效 Token、过期 Token）\n- [ ] 授权（角色权限、越权访问）\n- [ ] 业务状态机（状态流转限制）\n- [ ] 边界值（空、超长、非法、特殊字符）\n- [ ] 安全（SQL 注入、XSS、路径遍历）\n- [ ] 并发与幂等\n\n## 10. 检查清单\n\n- [ ] 所有 CRUD 端点都有功能测试\n- [ ] 每个端点至少有 1 个错误\u002F边界用例\n- [ ] 认证端点覆盖成功和失败场景\n- [ ] 受保护资源覆盖 401\u002F403 场景\n- [ ] 响应体通过 schema 校验\n- [ ] 测试数据相互隔离，可重复运行\n- [ ] 破坏性操作使用假 ID 或测试数据\n- [ ] 不依赖外部服务（mock 第三方 API）\n",{},"main","2b63f856ce19c2a797929cacabd9e0fc936812fa","plugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fapi-testing",491,"https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins","https:\u002F\u002Fhol.org\u002Fplugins\u002Fbest-codex-plugins","https:\u002F\u002Fgithub.com\u002Fhashgraph-online","https:\u002F\u002Fhol.org","Open-source standards and developer tools for interoperable AI agents: discovery, identity, communication, payments, privacy and security.","2026-11-14 14:06:13",{"source":7,"skillName":5,"commands":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add hashgraph-online\u002Fawesome-codex-plugins --skill api-testing",{"tool":55,"command":56},"bunx","bunx skills add hashgraph-online\u002Fawesome-codex-plugins --skill api-testing",{"tool":58,"command":59},"pnpm","pnpm dlx skills add hashgraph-online\u002Fawesome-codex-plugins --skill api-testing","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002FechoVic\u002Fboss-skill\u002Fskill\u002Fskills\u002Fqa\u002Fapi-testing\u002FSKILL.md",true,[],[64,74,82,90,98,106],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":68,"licenseFileUrl":69,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":73},"01M7DV332YQMGD8WTRJ9DZQXTB","worktable-review-with-annotations","Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.","MIT","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-review-with-annotations\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":68,"licenseFileUrl":78,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":73},"01M7DV2YGHCZVBEB1AHYB6CGHE","worktable-find-and-synthesize-context","Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-find-and-synthesize-context\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":68,"licenseFileUrl":86,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":73},"01M7DV2TQN1H11ME2SAF9MXN7V","worktable-create-or-update-docs","Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-update-docs\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":68,"licenseFileUrl":94,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":73},"01M7DV2NE452NEA8TXATKSNAJH","worktable-create-or-manage-records","Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-records\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":68,"licenseFileUrl":102,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":73},"01M7DV2HENRBR2KSCVM064WH0Y","worktable-create-or-manage-interactive-html","Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-create-or-manage-interactive-html\u002FSKILL.md",[],[],{"skillNo":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":68,"licenseFileUrl":110,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":73},"01M7DV2CADR5R7RQFFYPNAGR9Y","worktable-collaborate-threads","Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fhashgraph-online\u002Fawesome-codex-plugins\u002Fblob\u002Fmain\u002Fplugins\u002Fworktable\u002Fworktable-plugin\u002Fskills\u002Fworktable-collaborate-threads\u002FSKILL.md",[],[]]