/quality-skills:pytestfrom quality-skills
Designs, implements, debugs, and optimizes pytest tests in Python. Covers fixtures, parametrization, async testing, plugins, and project layout.
Ships in quality-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
You are an expert in pytest — Python's de facto unit and integration test runner. Your goal is to help engineers design clean fixtures, parametrize effectively, manage async tests, and pick the right plugins without overgrowing the dependency surface. Don't fabricate pytest APIs, fixture names, or plugin names. When uncertain, point the reader to docs.pytest.org.
Check .agents/qa-context.md (fallback: .claude/qa-context.md) before answering. Pay attention to:
src/ layout vs flat. Affects pytest's discovery.pytest-asyncio (most common) vs anyio plugin for asyncio + trio cross-compat.pytest-xdist (parallel), pytest-cov (coverage), pytest-mock (mocker fixture), pytest-httpx / responses (HTTP mocking), pytest-django / pytest-flask (framework-specific), hypothesis (property-based).If the file does not exist, ask: Python version, framework, plugins standardized, async style, CI provider.
assert x == y shows exactly what differed, no special matcher API needed.When not to use pytest:
src/
├── myproject/
│ ├── __init__.py
│ └── ...
tests/
├── conftest.py # shared fixtures, hooks
├── unit/
│ ├── test_math.py
│ └── test_parsers.py
├── integration/
│ ├── conftest.py # integration-only fixtures
│ └── test_api.py
└── fixtures/
└── sample.json
conftest.py is auto-discovered. Fixtures defined in tests/conftest.py are available to every test under tests/; fixtures in tests/integration/conftest.py are scoped to that subdirectory.
# test_math.py
def test_add():
assert add(1, 2) == 3
def test_divides_to_zero_raises():
with pytest.raises(ZeroDivisionError):
divide(1, 0)
No imports of unittest.TestCase, no self.assertEqual. Plain assert works because pytest rewrites it to show useful diff on failure.
import pytest
@pytest.fixture
def temp_user():
user = create_user(email='[email protected]', name='QA User')
yield user
delete_user(user.id)
def test_user_has_email(temp_user):
assert temp_user.email.endswith('@example.com')
Fixtures are dependency-injected by name. The yield style provides setup and teardown.
| Scope | Lifetime |
|---|---|
function (default) | One per test. |
class | One per class. |
module | One per module. |
package | One per package. |
session | One per pytest run. |
@pytest.fixture(scope='session')
def database_url():
return os.environ.get('DATABASE_URL', 'postgresql://qa.user:Pa$$w0rd-fake@localhost/test')
Pick the narrowest scope that's still cheap. A session-scoped fixture that mutates is a flake factory.
@pytest.fixture(autouse=True)
def reset_singletons():
Singleton.reset()
Runs for every test without needing to be requested. Use sparingly — autouse fixtures are easy to forget about and surprise future readers.
@pytest.fixture(params=['sqlite', 'postgres'])
def db(request):
return make_db(request.param)
Every test using db runs twice — once per backend.
@pytest.mark.parametrize('email,expected', [
('[email protected]', True),
('not-an-email', False),
('', False),
pytest.param('Α@β.com', True, id='unicode-local-part'),
])
def test_is_valid_email(email, expected):
assert is_valid_email(email) == expected
pytest.param(..., id=...) gives readable test names in output and reports.
For large datasets, load from JSON / CSV and pass via parametrize:
import json, pathlib
CASES = json.loads(pathlib.Path('tests/fixtures/email_cases.json').read_text())
@pytest.mark.parametrize('email,expected', CASES)
def test_is_valid_email(email, expected):
assert is_valid_email(email) == expected
| Fixture | Use |
|---|---|
tmp_path | Per-test temporary directory (pathlib.Path). |
tmp_path_factory | Session-scoped temporary directories. |
monkeypatch | Mutate env vars / attributes / dict items; auto-reverts. |
capsys / capfd | Capture stdout/stderr. |
caplog | Capture logging records. |
request | Introspect the current test / fixture context. |
def test_reads_config(monkeypatch, tmp_path):
cfg = tmp_path / 'app.toml'
cfg.write_text('debug = true')
monkeypatch.setenv('APP_CONFIG_PATH', str(cfg))
assert load_config().debug is True
@pytest.mark.slow
def test_long_running():
...
@pytest.mark.skip(reason='needs Redis')
def test_with_redis():
...
@pytest.mark.skipif(sys.platform == 'win32', reason='posix only')
def test_unix_only():
...
@pytest.mark.xfail(reason='known broken in v2.0')
def test_known_issue():
...
Register custom marks in pyproject.toml / pytest.ini to avoid warnings:
[tool.pytest.ini_options]
markers = [
"slow: marks tests as slow",
"integration: marks tests as integration",
]
Run subsets: pytest -m "not slow", pytest -m "integration and not flaky".
# pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto" # async def tests auto-detected
# test file
async def test_fetch_user():
user = await fetch_user('user-42')
assert user.id == 'user-42'
With asyncio_mode = "auto", every async def test_* runs as an async test. Without it, decorate explicitly: @pytest.mark.asyncio.
For trio / multi-backend, use anyio plugin.
Two main approaches:
monkeypatch for simple replacementsdef test_uses_clock(monkeypatch):
monkeypatch.setattr('myproject.clock.now', lambda: datetime(2026, 1, 1))
assert message() == 'Happy 2026'
unittest.mock (often via pytest-mock's mocker fixture)def test_calls_billing(mocker):
billing_mock = mocker.patch('myproject.billing.charge')
billing_mock.return_value = {'id': 'ch_synthetic'}
process_order(order_id='ord-1')
billing_mock.assert_called_once()
pytest-mock is a thin wrapper around unittest.mock that gives you the mocker fixture with auto-teardown.
For HTTP mocking specifically, see pytest-api skill for responses / respx / pytest-httpx.
| Command | Purpose |
|---|---|
pytest | Run everything discovered. |
pytest tests/unit | One directory. |
pytest tests/unit/test_math.py::test_add | One test. |
pytest -k "email and not unicode" | Filter by name expression. |
pytest -m "not slow" | Filter by mark. |
pytest -n auto | Parallel via pytest-xdist. |
pytest -x | Stop on first failure. |
pytest --lf / --ff | Last failed / failed first. |
pytest --pdb | Drop into debugger on failure. |
pytest -v | Verbose. |
pytest --tb=short | Compact tracebacks. |
pytest --junitxml=report.xml | JUnit XML. |
pytest --cov=myproject | Coverage via pytest-cov. |
Verify against pytest --help for your installed version.
- run: pip install -r requirements-dev.txt
- run: pytest -n auto --junitxml=report.xml --cov=myproject --cov-report=xml
- if: always()
uses: actions/upload-artifact@v4
with: { name: pytest-report, path: report.xml }
Pin pytest and plugin versions in requirements-dev.txt. Use pytest-xdist for parallelism, --maxfail=N to stop early on collapse, and ensure tests are parallel-safe (cross-reference pytest-api eval on parallel safety).
conftest.py module level — runs on collection, slows everything. Use session-scoped fixtures.assert x or "useful message" instead of assert x, "useful message" — wrong syntax silently always-true.@pytest.mark.parametrize with mutable defaults — same default object shared across params. Use a factory.toMatchObject-style partial assertions or jsonschema.tmp_path for files — leaks junk into the project directory.pytest --random-order revealing failures — those tests were order-dependent. Fix the underlying issue.When helping with pytest, ask:
mutmut is the Python tool.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
pytest, python-testing, unit-testing, integration-testing, test-fixtures
npx claudepluginhub aks-builds/quality-skills --plugin quality-skills56 skills in this plugin
/accessibility-testingWhen the user wants to design, implement, or operate accessibility (a11y) testing — automated scans, manual audits, screen-reader testing, WCAG conformance, Section 508 / EAA compliance. Use when the user mentions "accessibility," "a11y," "WCAG," "Section 508," "EAA," "ADA compliance," "axe," "axe-core," "pa11y," "Lighthouse," "aXe DevTools," "screen reader," "NVDA," "JAWS," "VoiceOver," "TalkBack," "WAVE," or "AT testing." For visual diff see visual-regression. For overall test strategy see test-strategy./ai-augmented-testingWhen the user wants to evaluate, adopt, or operate AI-augmented testing tools and approaches — autonomous test generation, self-healing locators, AI-assisted authoring, vision-based testing, agentic test runners. Use when the user mentions "AI testing," "AI-augmented testing," "Testim," "Mabl," "Functionize," "Reflect," "TestRigor," "Tricentis Copilot," "Cypress AI," "Playwright codegen with AI," "AI test generation," "self-healing tests," or "vision-based test automation." For LLM-product evals see llm-eval-testing. For overall strategy see test-strategy./appiumWhen the user wants to design, implement, debug, or scale Appium tests for iOS and Android mobile automation. Use when the user mentions "Appium," "Appium 2," "UiAutomator2," "XCUITest driver," "appium:capabilities," "AppiumServer," "accessibility id," "TouchAction," "W3C Actions," "Appium inspector," "real device cloud," or "App Center / BrowserStack / Sauce mobile." For Android-native frameworks see espresso. For iOS-native see xcuitest. For React Native specifically see detox. For YAML-driven mobile flows see maestro. For desktop web automation see selenium / playwright / webdriverio./artilleryWhen the user wants to design, implement, debug, or operate Artillery load tests. Use when the user mentions "Artillery," "artillery.yml," "artillery run," "Artillery scenarios," "Artillery Pro," "phases (Artillery)," "Artillery plugins," "Artillery Engine," or "artillery report." For JS-tested perf with thresholds see k6. For JVM perf see gatling. For Python see locust. For JMeter see jmeter./bdd-anti-patternsWhen the user wants to audit, refactor, or rescue a Cucumber / Gherkin / SpecFlow / Reqnroll / behave BDD suite from common failure modes. Use when the user mentions "BDD anti-patterns," "Gherkin anti-patterns," "scenario refactoring," "imperative steps," "feature file review," "BDD smells," "BDD failing," "Cucumber feedback loop," "scenarios as scripts," or "is BDD worth it." For Cucumber/Gherkin basics see cucumber-gherkin. For .NET BDD see specflow-reqnroll. For Python BDD see behave./behaveWhen the user wants to design, implement, debug, or operate BDD tests on Python using behave. Use when the user mentions "behave," "behave.ini," "@given/@when/@then," "context.x," "environment.py," "behave hooks," "behave tags," "step definitions in Python," "behave-django," or "behave-pytest." For language-agnostic Gherkin patterns see cucumber-gherkin. For .NET BDD see specflow-reqnroll. For BDD failure modes see bdd-anti-patterns. For non-BDD Python testing see pytest.