pytest-advanced
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAdvanced Pytest Patterns
高级Pytest模式
Master pytest's advanced features for scalable, maintainable test suites.
掌握pytest的高级功能,打造可扩展、易维护的测试套件。
Overview
概述
- Building custom test markers for categorization
- Writing pytest plugins and hooks
- Configuring parallel test execution with pytest-xdist
- Creating reusable fixture patterns
- Optimizing test collection and execution
- 构建用于分类的自定义测试标记
- 编写pytest插件与钩子
- 配置基于pytest-xdist的并行测试执行
- 创建可复用的fixture模式
- 优化测试收集与执行
Quick Reference
快速参考
Custom Markers
自定义标记
toml
undefinedtoml
undefinedpyproject.toml
pyproject.toml
[tool.pytest.ini_options]
markers = [
"slow: marks tests as slow (deselect with '-m "not slow"')",
"integration: marks tests requiring external services",
"smoke: critical path tests for CI/CD",
]
```python
import pytest
@pytest.mark.slow
def test_complex_analysis():
result = perform_complex_analysis(large_dataset)
assert result.is_valid[tool.pytest.ini_options]
markers = [
"slow: marks tests as slow (deselect with '-m "not slow"')",
"integration: marks tests requiring external services",
"smoke: critical path tests for CI/CD",
]
```python
import pytest
@pytest.mark.slow
def test_complex_analysis():
result = perform_complex_analysis(large_dataset)
assert result.is_validRun: pytest -m "not slow" # Skip slow tests
Run: pytest -m "not slow" # Skip slow tests
Run: pytest -m smoke # Only smoke tests
Run: pytest -m smoke # Only smoke tests
See [custom-plugins.md](references/custom-plugins.md) for plugin development.
插件开发相关内容请参考[custom-plugins.md](references/custom-plugins.md)。Parallel Execution (pytest-xdist)
并行执行(pytest-xdist)
toml
[tool.pytest.ini_options]
addopts = ["-n", "auto", "--dist", "loadscope"]python
@pytest.fixture(scope="session")
def db_engine(worker_id):
"""Isolate database per worker."""
db_name = "test_db" if worker_id == "master" else f"test_db_{worker_id}"
engine = create_engine(f"postgresql://localhost/{db_name}")
yield engineSee xdist-parallel.md for distribution modes.
toml
[tool.pytest.ini_options]
addopts = ["-n", "auto", "--dist", "loadscope"]python
@pytest.fixture(scope="session")
def db_engine(worker_id):
"""Isolate database per worker."""
db_name = "test_db" if worker_id == "master" else f"test_db_{worker_id}"
engine = create_engine(f"postgresql://localhost/{db_name}")
yield engine分布式模式相关内容请参考xdist-parallel.md。
Factory Fixtures
工厂Fixtures
python
@pytest.fixture
def user_factory(db_session) -> Callable[..., User]:
"""Factory fixture for creating users."""
created = []
def _create(**kwargs) -> User:
user = User(**{"email": f"u{len(created)}@test.com", **kwargs})
db_session.add(user)
created.append(user)
return user
yield _create
for u in created:
db_session.delete(u)python
@pytest.fixture
def user_factory(db_session) -> Callable[..., User]:
"""Factory fixture for creating users."""
created = []
def _create(**kwargs) -> User:
user = User(**{"email": f"u{len(created)}@test.com", **kwargs})
db_session.add(user)
created.append(user)
return user
yield _create
for u in created:
db_session.delete(u)Key Decisions
关键决策
| Decision | Recommendation |
|---|---|
| Parallel execution | pytest-xdist with |
| Marker strategy | Category (smoke, integration) + Resource (db, llm) |
| Fixture scope | Function default, session for expensive setup |
| Plugin location | conftest.py for project, package for reuse |
| Async testing | pytest-asyncio with auto mode |
| 决策 | 推荐方案 |
|---|---|
| 并行执行 | 使用 |
| 标记策略 | 分类(冒烟测试、集成测试)+ 资源(数据库、大语言模型) |
| Fixture作用域 | 默认使用函数作用域,耗时初始化操作使用会话作用域 |
| 插件存放位置 | 项目级使用conftest.py,可复用插件封装为包 |
| 异步测试 | 启用自动模式的pytest-asyncio |
Anti-Patterns (FORBIDDEN)
反模式(禁止)
python
undefinedpython
undefinedNEVER use expensive fixtures without session scope
NEVER use expensive fixtures without session scope
@pytest.fixture # WRONG - loads every test
def model():
return load_ml_model() # 5s each time!
@pytest.fixture # WRONG - loads every test
def model():
return load_ml_model() # 5s each time!
NEVER mutate global state
NEVER mutate global state
@pytest.fixture
def counter():
global _counter
_counter += 1 # WRONG - leaks between tests
@pytest.fixture
def counter():
global _counter
_counter += 1 # WRONG - leaks between tests
NEVER skip cleanup
NEVER skip cleanup
@pytest.fixture
def temp_db():
db = create_db()
yield db
# WRONG - missing db.drop()!
@pytest.fixture
def temp_db():
db = create_db()
yield db
# WRONG - missing db.drop()!
NEVER use time.sleep (use mocking)
NEVER use time.sleep (use mocking)
def test_timeout():
time.sleep(5) # WRONG - slows tests
undefineddef test_timeout():
time.sleep(5) # WRONG - slows tests
undefinedRelated Skills
相关技能
- - Basic pytest patterns and AAA structure
unit-testing - - Database and API testing patterns
integration-testing - - Hypothesis integration with pytest
property-based-testing
- - 基础pytest模式与AAA结构
unit-testing - - 数据库与API测试模式
integration-testing - - Hypothesis与pytest的集成
property-based-testing
References
参考资料
- Xdist Parallel - Parallel execution patterns
- Custom Plugins - Plugin and hook development
- Conftest Template - Production conftest.py
- Xdist Parallel - 并行执行模式
- Custom Plugins - 插件与钩子开发
- Conftest Template - 生产环境级conftest.py模板
Capability Details
能力详情
custom-markers
custom-markers
Keywords: pytest markers, test categorization, smoke tests, slow tests
Solves: Categorize tests, run subsets in CI, skip expensive tests
关键词: pytest标记、测试分类、冒烟测试、慢测试
解决的问题: 对测试进行分类、在CI中运行测试子集、跳过耗时测试
pytest-xdist
pytest-xdist
Keywords: parallel, xdist, distributed, workers, loadscope
Solves: Run tests in parallel, worker isolation, optimize distribution
关键词: 并行、xdist、分布式、工作进程、loadscope
解决的问题: 并行运行测试、工作进程隔离、优化任务分配
pytest-hooks
pytest-hooks
Keywords: hook, plugin, conftest, pytest_configure, collection
Solves: Customize pytest behavior, add timing reports, reorder tests
关键词: 钩子、插件、conftest、pytest_configure、测试收集
解决的问题: 自定义pytest行为、添加计时报告、调整测试顺序
fixture-patterns
fixture-patterns
Keywords: fixture, factory, async fixture, cleanup, scope
Solves: Factory fixtures, async fixtures, ensure cleanup runs
关键词: fixture、工厂、异步fixture、清理、作用域
解决的问题: 工厂fixture、异步fixture、确保清理操作执行
parametrize-advanced
parametrize-advanced
Keywords: parametrize, indirect, cartesian, pytest.param, xfail
Solves: Test multiple scenarios, fixtures with params, expected failures
关键词: 参数化、间接参数化、笛卡尔积、pytest.param、预期失败
解决的问题: 测试多场景、带参数的fixture、处理预期失败用例