Files
life-echo/.cursor/rules/backend-testing-strategy.mdc

37 lines
1.8 KiB
Plaintext
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
description: Backend testing strategy for meaningful business coverage
globs: api/**/*
alwaysApply: false
---
# Backend Testing Strategy
- 测试必须服务真实业务场景,禁止为了覆盖率、形式化 TDD 或“顺手测一下”而堆低价值用例。
- 自动化优先覆盖:核心用户流程、鉴权/权限/配额/幂等、关键状态写入后的持久化结果、前端依赖的稳定 HTTP 契约。
- 不优先覆盖:第三方库自身行为、纯实现细节、脆弱的调用顺序断言、低价值 getter/常量映射。
- 默认优先写 HTTP 场景测试,而不是先写大量细碎单元测试。
## Test Infrastructure
- 不要直接 import `api/main.py` 跑测试;避免把 `.env`、startup/shutdown、Redis、模型预热等副作用带进测试。
- 优先使用最小 `FastAPI()` 测试 app按需挂载目标 router。
- 用 `app.dependency_overrides` 替换数据库和外部依赖。
- 用 `httpx.AsyncClient` + `ASGITransport` 进行异步 HTTP 测试。
- `api/tests/conftest.py` 和 `api/tests/factories.py` 只提供通用基础设施,不要把具体业务测试硬编码进去。
## Test Layering
- HTTP 场景测试:注册、登录、刷新、登出、受保护资源访问、关键资源 CRUD、重要失败分支。
- 纯单元测试:纯函数、规则计算、序列化、适配器错误分支与格式转换。
- 手工 / E2EWebSocket 多轮对话、真实短信、Celery + Redis + LLM 编排、支付/对象存储/ASR/图像生成联调。
## Decision Filter
新增测试前先问自己:
1. 这个测试保护的是哪条业务承诺?
2. 失败后能否快速定位问题边界?
3. 这个测试是否比只测内部函数更接近真实用户行为?
如果答不上来 2 个以上,通常不该立刻写这个测试。