用途
pytest-advanced 是一个高级 pytest 模式技能,用于构建健壮、可维护的测试套件。当需要实现测试基础设施、编写 fixture、进行复杂参数化、配置 pytest 插件(如覆盖率、并行)或组织 conftest.py 层级时使用本技能。若只是基础测试结构问题、简单 assert 模式、运行已有测试或同步单元测试,则应改用 python-testing。
主要能力
- Fixtures:支持 function、class、module、session 四种作用域,以及 autouse 自动应用;支持参数化 fixture(含 indirect 参数化)和工厂模式(factory pattern),可在测试结束后清理创建的对象。
- Markers:内置 skip、skipif、xfail、timeout 等标记;支持 parametrize 参数化并可为每个用例指定 id;可通过
-m按标记筛选或组合标记运行。 - 常用插件:pytest-cov(覆盖率)、pytest-xdist(并行)、pytest-asyncio(异步测试)、pytest-mock(mock)、pytest-timeout(超时)。
- 异步测试:通过 pytest-asyncio,可在配置中设置
asyncio_mode = "auto",并支持异步 fixture。 - Mocking:通过 pytest-mock 的 mocker fixture 进行 patch 与断言调用。
- 运行与调试:支持按文件/用例运行、
-k模式匹配、并行(-n auto)、覆盖率报告、仅运行上次失败(--lf)、失败优先(--ff)、首次失败即停止(-x)、最大失败数、--pdb调试、-s显示输出、--collect-only干跑等。 - CI 集成:提供 GitHub Actions 工作流示例,输出覆盖率 XML 与 JUnit XML。
- Agentic 优化:针对快速检查、快速失败、并行快速、指定测试、按标记、覆盖率检查、CI 模式、上次失败、调试等场景给出推荐命令。
使用方式
安装(核心 + 常用插件):
uv add --dev pytest pytest-cov pytest-asyncio pytest-xdist pytest-mock
配置(pyproject.toml)示例:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = [
"-v",
"--strict-markers",
"--tb=short",
"-ra",
"--cov=src",
"--cov-report=term-missing",
"--cov-fail-under=80",
]
markers = [
"slow: marks tests as slow (deselect with '-m \"not slow\"')",
"integration: marks tests as integration tests",
]
asyncio_mode = "auto"
[tool.coverage.run]
branch = true
source = ["src"]
[tool.coverage.report]
exclude_lines = ["pragma: no cover", "if TYPE_CHECKING:", "@abstractmethod"]
运行示例:
pytest # 全部测试
pytest tests/test_models.py::test_user # 指定测试
pytest -k "user and not slow" # 模式匹配
pytest -n auto # 并行,使用全部 CPU
pytest -n 4 # 4 个 worker
pytest --cov=src --cov-report=html --cov-report=term-missing # 覆盖率
pytest --lf # 仅上次失败
pytest --ff # 失败优先
pytest -x # 首次失败即停止
pytest --maxfail=3 # 3 次失败后停止
pytest -x --pdb # 失败时调试
pytest -s # 显示 print 输出
pytest --collect-only # 干跑
CI 集成(.github/workflows/test.yml)示例:
- name: Run tests
run: |
uv run pytest \
--cov=src \
--cov-report=xml \
--cov-report=term-missing \
--junitxml=test-results.xml
适用场景
- 编写带作用域或工厂模式的 fixture。
- 使用复杂数据进行参数化测试。
- 配置 pytest 插件(cov、xdist)。
- 组织 conftest.py 层级。
- 使用 pytest-asyncio 进行异步测试。
- 在 CI 中运行带覆盖率与 JUnit 报告的测试。
限制
资料未提供该技能的具体版本、许可证、依赖版本约束、性能基准或收费信息。更详细的 conftest.py 层级、异步测试、测试组织与常见模式需参见 REFERENCE.md(资料中未展开其内容)。