test-guard - pytest
Test Guard — Python / pytest 模式九条规则在 pytest 项目中的具体应用。在审查或编写 Python 测试时阅读此文件。规则 2Python 中的 mock 边界有理由的 mock 目标HTTP 客户端httpx、requests、aiohttp或使用respx/responses而不是原始 mockLLM SDK 调用openai、anthropic、litellm.completion等数据库会话当数据库不是测试主题时参见规则 9外部路径上的文件系统 I/Otmp_path夹具通常比 mock 更好时钟和随机性time.time、datetime.now、random优先使用freezegun或注入时钟无理由的 mock常见的智能体生成违规用MagicMock()充当 Pydantic 模型或数据类——请构造真实的东西模拟内部工具函数来隔离一个单元模拟json.loads/json.dumps或其他 stdlib 纯函数规则 3参数化# Violation: three copy-pasted tests differing by one valuedeftest_slug_lowercase():...deftest_slug_strips_spaces():...deftest_slug_handles_unicode():...# Fixpytest.mark.parametrize((raw,expected),[(Hello World,hello-world),( padded ,padded),(Café Menu,cafe-menu),],)deftest_slugify_normalizes_input(raw,expected):assertslugify(raw)expected规则 8真实的 Pydantic/数据类实例# Wrong — hides field typos and validation errorsstateMagicMock()state.user_id123state.statusACTIVE# Right — Pydantic validates the construction itselfstateUserState(user_id123,statusACTIVE)如果模型需要很多字段添加工厂夹具或使用factory_boy——不要退回到MagicMock。规则 9通过夹具使用真实数据库使用应用真实迁移的夹具例如带alembic upgrade head的会话级测试数据库以及每次测试回滚的函数级事务。pytest-postgresql、testcontainers或 SQLite 兼容回退都可以关键是当查询或持久化逻辑是测试主题时使用真实模式而不是 mock 的会话。pytest 特有的异味对任何内部内容断言mock.call_count N——规则 1 违规patch堆叠三层或更深——测试与实现耦合重构通过caplog断言没有调用者解析的消息的日志输出——规则 4 违规构建项目类 mock 的夹具——规则 8 违规让夹具构建真实对象