API Test Suite Builder
Tier: POWERFUL
Category: Engineering
Domain: Testing / API Quality
Overview
Scans API route definitions across frameworks (Next.js App Router, Express, FastAPI, Django REST) and
auto-generates comprehensive test suites covering auth, input validation, error codes, pagination, file
uploads, and rate limiting. Outputs ready-to-run test files for Vitest+Supertest (Node) or Pytest+httpx
(Python).
Core Capabilities
- - Route detection — scan source files to extract all API endpoints
- Auth coverage — valid/invalid/expired tokens, missing auth header
- Input validation — missing fields, wrong types, boundary values, injection attempts
- Error code matrix — 400/401/403/404/422/500 for each route
- Pagination — first/last/empty/oversized pages
- File uploads — valid, oversized, wrong MIME type, empty
- Rate limiting — burst detection, per-user vs global limits
When to Use
- - New API added — generate test scaffold before writing implementation (TDD)
- Legacy API with no tests — scan and generate baseline coverage
- API contract review — verify existing tests match current route definitions
- Pre-release regression check — ensure all routes have at least smoke tests
- Security audit prep — generate adversarial input tests
Route Detection
Next.js App Router
CODEBLOCK0
Express
CODEBLOCK1
FastAPI
CODEBLOCK2
Django REST Framework
# urlpatterns extraction
grep -rn "path\|re_path\|url(" . --include="*.py" | grep "urlpatterns" -A 50 | \
grep -E "path\(['\"]" | grep -oE "['\"][^'\"]+['\"]" | head -40
# ViewSet router registration
grep -rn "router\.register\|DefaultRouter\|SimpleRouter" . --include="*.py"
Test Generation Patterns
Auth Test Matrix
For every authenticated endpoint, generate:
| Test Case | Expected Status |
|---|
| No Authorization header | 401 |
| Invalid token format |
401 |
| Valid token, wrong user role | 403 |
| Expired JWT token | 401 |
| Valid token, correct role | 2xx |
| Token from deleted user | 401 |
Input Validation Matrix
For every POST/PUT/PATCH endpoint with a request body:
| Test Case | Expected Status |
|---|
| Empty body INLINECODE0 | 400 or 422 |
| Missing required fields (one at a time) |
400 or 422 |
| Wrong type (string where int expected) | 400 or 422 |
| Boundary: value at min-1 | 400 or 422 |
| Boundary: value at min | 2xx |
| Boundary: value at max | 2xx |
| Boundary: value at max+1 | 400 or 422 |
| SQL injection in string field | 400 or 200 (sanitized) |
| XSS payload in string field | 400 or 200 (sanitized) |
| Null values for required fields | 400 or 422 |
Example Test Files
→ See references/example-test-files.md for details
Generating Tests from Route Scan
When given a codebase, follow this process:
- 1. Scan routes using the detection commands above
- Read each route handler to understand:
- Expected request body schema
- Auth requirements (middleware, decorators)
- Return types and status codes
- Business rules (ownership, role checks)
- 3. Generate test file per route group using the patterns above
- Name tests descriptively:
"returns 401 when token is expired" not INLINECODE2 - Use factories/fixtures for test data — never hardcode IDs
- Assert response shape, not just status code
Common Pitfalls
- - Testing only happy paths — 80% of bugs live in error paths; test those first
- Hardcoded test data IDs — use factories/fixtures; IDs change between environments
- Shared state between tests — always clean up in afterEach/afterAll
- Testing implementation, not behavior — test what the API returns, not how it does it
- Missing boundary tests — off-by-one errors are extremely common in pagination and limits
- Not testing token expiry — expired tokens behave differently from invalid ones
- Ignoring Content-Type — test that API rejects wrong content types (xml when json expected)
Best Practices
- 1. One describe block per endpoint — keeps failures isolated and readable
- Seed minimal data — don't load the entire DB; create only what the test needs
- Use
beforeAll for shared setup, afterAll for cleanup — not beforeEach for expensive ops - Assert specific error messages/fields, not just status codes
- Test that sensitive fields (password, secret) are never in responses
- For auth tests, always test the "missing header" case separately from "invalid token"
- Add rate limit tests last — they can interfere with other test suites if run in parallel
API 测试套件构建器
层级: 强大
类别: 工程
领域: 测试 / API 质量
概述
扫描跨框架(Next.js App Router、Express、FastAPI、Django REST)的 API 路由定义,并自动生成涵盖认证、输入验证、错误码、分页、文件上传和速率限制的全面测试套件。输出可直接运行的测试文件,适用于 Vitest+Supertest(Node)或 Pytest+httpx(Python)。
核心能力
- - 路由检测 — 扫描源文件以提取所有 API 端点
- 认证覆盖 — 有效/无效/过期令牌、缺少认证头
- 输入验证 — 缺少字段、错误类型、边界值、注入尝试
- 错误码矩阵 — 每条路由的 400/401/403/404/422/500
- 分页 — 首页/末页/空页/超大页
- 文件上传 — 有效、超大、错误 MIME 类型、空文件
- 速率限制 — 突发检测、每用户限制与全局限制
使用场景
- - 新增 API — 在编写实现之前生成测试脚手架(TDD)
- 无测试的遗留 API — 扫描并生成基线覆盖
- API 合同审查 — 验证现有测试是否匹配当前路由定义
- 预发布回归检查 — 确保所有路由至少包含冒烟测试
- 安全审计准备 — 生成对抗性输入测试
路由检测
Next.js App Router
bash
查找所有路由处理器
find ./app/api -name route.ts -o -name route.js | sort
从每个路由文件中提取 HTTP 方法
grep -rn export async function\|export function app/api/
/route.ts | \
grep -oE (GET|POST|PUT|PATCH|DELETE|HEAD|OPTIONS) | sort -u
完整路由映射
find ./app/api -name route.ts | while read f; do
route=$(echo $f | sed s|./app|| | sed s|/route.ts||)
methods=$(grep -oE export (async )?function (GET|POST|PUT|PATCH|DELETE) $f | \
grep -oE (GET|POST|PUT|PATCH|DELETE))
echo $methods $route
done
Express
bash
查找所有路由器文件
find ./src -name
.ts -o -name .js | xargs grep -l router\.\(get\|post\|put\|delete\|patch\) 2>/dev/null
提取带行号的路由
grep -rn router\.\(get\|post\|put\|delete\|patch\)\|app\.\(get\|post\|put\|delete\|patch\) \
src/ --include=
.ts | grep -oE (get|post|put|delete|patch)\([\][^\][\]
生成路由映射
grep -rn router\.\|app\. src/ --include=*.ts | \
grep -oE \.(get|post|put|delete|patch)\([\][^\]+[\] | \
sed s/\.\(.
\)(\(.\)/\U\1 \2/
FastAPI
bash
查找所有路由装饰器
grep -rn @app\.\|@router\. . --include=*.py | \
grep -E @(app|router)\.(get|post|put|delete|patch)
提取路径和函数名
grep -rn @\(app\|router\)\.\(get\|post\|put\|delete\|patch\) . --include=*.py | \
grep -oE @(app|router)\.(get|post|put|delete|patch)\([\][^\]*[\]
Django REST Framework
bash
urlpatterns 提取
grep -rn path\|re_path\|url( . --include=*.py | grep urlpatterns -A 50 | \
grep -E path\([\] | grep -oE [\][^\]+[\] | head -40
ViewSet 路由器注册
grep -rn router\.register\|DefaultRouter\|SimpleRouter . --include=*.py
测试生成模式
认证测试矩阵
对于每个需要认证的端点,生成:
| 测试用例 | 预期状态 |
|---|
| 无 Authorization 头 | 401 |
| 无效令牌格式 |
401 |
| 有效令牌,错误用户角色 | 403 |
| 过期的 JWT 令牌 | 401 |
| 有效令牌,正确角色 | 2xx |
| 已删除用户的令牌 | 401 |
输入验证矩阵
对于每个带有请求体的 POST/PUT/PATCH 端点:
| 测试用例 | 预期状态 |
|---|
| 空请求体 {} | 400 或 422 |
| 缺少必填字段(每次一个) |
400 或 422 |
| 错误类型(字符串代替整数) | 400 或 422 |
| 边界:值为 min-1 | 400 或 422 |
| 边界:值为 min | 2xx |
| 边界:值为 max | 2xx |
| 边界:值为 max+1 | 400 或 422 |
| 字符串字段中的 SQL 注入 | 400 或 200(已清理) |
| 字符串字段中的 XSS 载荷 | 400 或 200(已清理) |
| 必填字段的 Null 值 | 400 或 422 |
示例测试文件
→ 详见 references/example-test-files.md
从路由扫描生成测试
给定代码库时,遵循以下流程:
- 1. 扫描路由 — 使用上述检测命令
- 读取每个路由处理器 — 了解:
- 预期的请求体模式
- 认证要求(中间件、装饰器)
- 返回类型和状态码
- 业务规则(所有权、角色检查)
- 3. 按路由组生成测试文件 — 使用上述模式
- 描述性命名测试:令牌过期时返回 401 而非 认证测试 3
- 使用工厂/夹具 生成测试数据 — 绝不硬编码 ID
- 断言响应结构,而不仅仅是状态码
常见陷阱
- - 仅测试快乐路径 — 80% 的 bug 存在于错误路径中;优先测试这些路径
- 硬编码测试数据 ID — 使用工厂/夹具;ID 在不同环境间会变化
- 测试间共享状态 — 始终在 afterEach/afterAll 中清理
- 测试实现而非行为 — 测试 API 返回什么,而非如何实现
- 缺少边界测试 — 分页和限制中的差一错误极为常见
- 未测试令牌过期 — 过期令牌与无效令牌行为不同
- 忽略 Content-Type — 测试 API 拒绝错误的内容类型(期望 json 时传入 xml)
最佳实践
- 1. 每个端点一个 describe 块 — 保持失败隔离和可读性
- 播种最少数据 — 不要加载整个数据库;只创建测试所需的数据
- 使用 beforeAll 进行共享设置,afterAll 进行清理 — 对昂贵操作不要使用 beforeEach
- 断言特定的错误消息/字段,而不仅仅是状态码
- 测试敏感字段(密码、密钥)永远不会出现在响应中
- 对于认证测试,始终将缺少头情况与无效令牌分开测试
- 最后添加速率限制测试 — 如果并行运行,它们可能干扰其他测试套件