Loading...
Loading...
Advanced pytest patterns including custom markers, plugins, hooks, parallel execution, and pytest-xdist. Use when implementing custom test infrastructure, optimizing test execution, or building reusable test utilities.
npx skill4agent add yonatangross/orchestkit pytest-advanced# 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",
]import pytest
@pytest.mark.slow
def test_complex_analysis():
result = perform_complex_analysis(large_dataset)
assert result.is_valid
# Run: pytest -m "not slow" # Skip slow tests
# Run: pytest -m smoke # Only smoke tests[tool.pytest.ini_options]
addopts = ["-n", "auto", "--dist", "loadscope"]@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@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)| 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 |
# NEVER use expensive fixtures without session scope
@pytest.fixture # WRONG - loads every test
def model():
return load_ml_model() # 5s each time!
# NEVER mutate global state
@pytest.fixture
def counter():
global _counter
_counter += 1 # WRONG - leaks between tests
# NEVER skip cleanup
@pytest.fixture
def temp_db():
db = create_db()
yield db
# WRONG - missing db.drop()!
# NEVER use time.sleep (use mocking)
def test_timeout():
time.sleep(5) # WRONG - slows testsunit-testingintegration-testingproperty-based-testing