SuperAPI AI 工具集

pytest-advanced

测试与质量

查看项目

更新于 10-16 04:33

技能介绍

用途:帮助构建可扩展、易维护的 pytest 测试套件,覆盖从测试分类到并行执行和插件开发的进阶实践。

主要能力:

  1. 自定义标记:在 pyproject.toml 的 [tool.pytest.ini_options] 中声明 markers,如 slow、integration、smoke,并通过 pytest -m "not slow" 或 pytest -m smoke 筛选运行。
  2. 并行执行:使用 pytest-xdist,配置 addopts = ["-n", "auto", "--dist", "loadscope"],并利用 worker_id 让每个 worker 使用独立数据库,实现隔离。
  3. 插件与钩子:支持编写 pytest 插件和 hook,如 pytest_configure、collection 相关钩子,以自定义行为、添加计时报告或重排测试。
  4. Fixture 模式:推荐工厂 fixture(如 user_factory),通过 yield 创建并清理数据;异步测试建议使用 pytest-asyncio 的 auto 模式;昂贵初始化应设 session 作用域。
  5. 参数化:支持 parametrize 的 indirect、笛卡尔组合、pytest.param 与 xfail 等进阶用法。

使用方式:在 pyproject.toml 配置 markers 与 addopts,在 conftest.py 放置项目级 fixture 或插件,按需运行 pytest -m 或 -n auto 命令。

适用场景:CI/CD 中按标记运行关键路径或跳过慢测;需要并行加速的大型测试集;跨 worker 的数据库隔离;需要自定义 pytest 行为或复用 fixture 的项目。

限制与约束:避免在非 session 作用域使用昂贵 fixture(如加载 ML 模型),避免修改全局状态导致测试间泄漏,必须保证 fixture 清理(如 db.drop()),禁止使用 time.sleep(应使用 mocking)。相关技能包括 unit-testing、integration-testing、property-based-testing。关于该技能的具体安装命令、收费方式、支持平台与性能数据,资料未提供。