用途:当用户在 Python 代码库中要求编写、脚手架化或重构 pytest 测试,配置 conftest.py 与夹具作用域,添加参数化用例或自定义标记,在 pyproject.toml 中配置 pytest、覆盖率或并行运行,修复不稳定、慢或顺序依赖的测试,或用 pytest-mock、monkeypatch 添加 mock 时触发。不适用于 JavaScript/TypeScript 测试框架(Jest、Vitest)或非 pytest 的 Python 框架,除非用户明确要求迁移到 pytest。
主要能力与规范:一个测试只验证一个行为,测试体按 Arrange-Act-Assert 分块;共享设置使用 conftest.py 夹具而非 setUp/tearDown;夹具默认 function 作用域,仅对昂贵只读资源放宽到 module 或 session;用 @pytest.mark.parametrize 替代循环并为非平凡值提供 ids;测试隔离且顺序无关,可配合 pytest-xdist;在拥有边界处 mock,打补丁打在名称被查找的位置。配置集中在 pyproject.toml,声明 testpaths、addopts、markers 和覆盖率项,CI 使用 --strict-markers 与 -ra。测试目录置于 src 之外并镜像包结构,各层 conftest.py 使夹具向下级联、不向上泄漏。
必要用法:安装 pip install "pytest>=8" pytest-cov pytest-xdist pytest-mock。常用命令:pytest -m smoke、pytest -m "not slow"、pytest -m "integration and not slow"、pytest --cov --cov-report=term-missing、pytest -n auto、pytest -n auto --cov --cov-report=xml。数据库测试用事务包裹每个测试并回滚;文件操作使用 tmp_path,服务器绑定端口 0,时间用夹具冻结。异常断言始终带 match=,浮点用 pytest.approx。
限制与反模式:避免在单个测试内循环用例、session 作用域可变夹具、time.sleep 等待、以日志作为主要断言、硬编码端口路径时间戳,以及 try/except 代替 pytest.raises。覆盖率阈值配置在 pyproject.toml 而非 CI 脚本。资料未提供该技能的收费、价格或版本信息。