用途:本资料面向使用 pytest 编写 Python 测试的场景,涵盖 fixture、mock、参数化与异步测试等模式。触发时机为编写 Python 测试、使用 pytest、模拟依赖或测试异步代码。
主要能力与用法:
- 测试组织:用类(如 TestUserService)或独立函数组织测试,用 assert 断言,用 pytest.raises(ValueError, match="...") 断言异常。
- Fixtures:用 @pytest.fixture 定义,支持 scope(function、module、session)与 yield 实现 setup/teardown;共享 fixture 放在 tests/conftest.py。
- Mock:用 unittest.mock 的 patch、MagicMock 在边界处模拟 HTTP、DB、文件系统等外部依赖,可设置 return_value 与 side_effect。
- 参数化:用 @pytest.mark.parametrize 做数据驱动测试。
- 标记与选择执行:@pytest.mark.slow、integration、skip、skipif,在 pytest.ini 或 pyproject.toml 注册 markers,用 pytest -m "not slow" 等筛选。
- 异步测试:用 @pytest.mark.asyncio 与 pytest_asyncio.fixture。
- 工厂 fixture:用 yield 返回创建函数并在结束后清理。
常用命令:pytest -v、pytest -k "user"、pytest --cov=src --cov-report=html、pytest -n auto、pytest --lf、pytest -x。
规则与限制:fixture 是测试 setup 与依赖注入的必需机制,不用 setUp/tearDown;数据驱动用 parametrize,避免复制粘贴;外部依赖须 mock,不让测试访问真实服务;异步测试必须加 @pytest.mark.asyncio,否则协程不会真正执行;fixture scope 要正确,宽 scope 且修改共享状态会导致测试顺序依赖。反模式包括无断言的测试与相互依赖的测试。
资料未提供安装命令、版本要求、收费与平台信息。