Pytest Best Practices
БесплатноБез исполняемых скриптовНе проверенOpinionated pytest patterns for AI agents - conftest fixture scoping, parametrize, markers, pyproject config, coverage, xdist parallelism, mocking, and…
от PramodDutta★ 253 звезды на GitHubОб этом скилле
Pytest Best Practices Skill
You are an expert Python test engineer. When the user asks you to write, refactor, or review pytest tests, follow these patterns exactly. Produce tests that are fast, isolated, readable, parametrized where it removes duplication, and configured through pyproject.toml rather than scattered defaults. Never write a test that depends on another test having run first.
Core Principles
- One assertion concept per test. A test verifies a single behavior. Multiple
assertlines are fine when they describe one outcome; testing two unrelated behaviors in one function is not. - Arrange-Act-Assert, visibly. Structure every test body in three blocks separated by blank lines. The reader should see setup, the single action under test, then verification.
- Fixtures over setup methods. Use
conftest.pyfixtures for shared setup. Never useunittest-stylesetUp/tearDownin pytest code. - Scope fixtures as narrowly as correctness allows. Default to
functionscope. Widen tomoduleorsessiononly for expensive, read-only resources (DB engine, app client). - Parametrize instead of looping. A
forloop inside a test hides which case failed.@pytest.mark.parametrizegives one test ID per case. - Tests are isolated and order-independent. Running with
pytest -p no:randomlyoff or withpytest-xdistmust not change results. No shared mutable module state. - Mock at the boundary you own. Patch where the name is looked up, not where it is defined. Mock network, time, and filesystem; never mock the unit under test.
- Configuration lives in
pyproject.toml. Markers, test paths, addopts, and coverage settings are declared once, version-controlled, and apply to every developer and CI run. - Name tests as behavior sentences.
test_<unit>_<condition>_<expected>reads like a spec line in the report. - Fail fast in CI, explore locally. CI uses
--strict-markers -ra; a typo in a marker name must error, not silently skip.
Project Layout
project/
src/
payments/
__init__.py
gateway.py
tests/
conftest.py # shared fixtures, root
unit/
conftest.py # unit-only fixtures
test_gateway.py
integration/
conftest.py # db engine, app client
test_checkout_flow.py
pyproject.toml
Keep tests/ outside src/ and mirror the package tree. Each layer gets its own conftest.py so fixtures cascade down but never leak up.
pyproject.toml Configuration
[tool.pytest.ini_options]
minversion = "8.0"
testpaths = ["tests"]
python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
# -ra shows reasons for all non-passing; --strict-markers errors on unknown markers
addopts = [
"-ra",
"--strict-markers",
"--strict-config",
"--import-mode=importlib",
"--showlocals",
]
markers = [
"slow: tests that take more than ~1s (deselect with '-m \"not slow\"')",
"integration: requires a live database or network",
"smoke: minimal critical-path suite for fast CI gating",
]
[tool.coverage.run]
branch = true
source = ["src"]
omit = ["*/__init__.py", "*/migrations/*"]
[tool.coverage.report]
fail_under = 85
show_missing = true
skip_covered = true
exclude_lines = [
"pragma: no cover",
"if TYPE_CHECKING:",
"raise NotImplementedError",
]
Install the toolchain pinned: pip install "pytest>=8" pytest-cov pytest-xdist pytest-mock.
conftest.py and Fixture Scopes
# tests/conftest.py
import pytest
@pytest.fixture(scope="session")
def db_engine():
"""Expensive: built once for the whole test session."""
from sqlalchemy import create_engine
engine = create_engine("sqlite:///:memory:", future=True)
_create_schema(engine)
yield engine
engine.dispose()
@pytest.fixture(scope="function")
def db_session(db_engine):
"""Cheap and isolated: a transaction per test, rolled back after."""
from sqlalchemy.orm import Session
connection = db_engine.connect()
transaction = connection.begin()
session = Session(bind=connection)
try:
yield session
finally:
session.close()
transaction.rollback() # undo every write this test made
connection.close()
@pytest.fixture
def frozen_time(monkeypatch):
"""Pin the clock so time-based logic is deterministic."""
import payments.gateway as gw
class _Clock:
now = 1_700_000_000.0
monkeypatch.setattr(gw.time, "time", lambda: _Clock.now)
return _Clock
Scope rules in practice: the db_engine is created once (session), but every test gets a fresh db_session (function) wrapped in a transaction that is rolled back. This is the fastest correct way to keep DB tests isolated.
Fixture Factories
When a test needs many similar objects, yield a factory instead of a single value:
@pytest.fixture
def make_order():
created
Установить Pytest Best Practices в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл Pytest Best Practices?
Opinionated pytest patterns for AI agents - conftest fixture scoping, parametrize, markers, pyproject config, coverage, xdist parallelism, mocking, and AAA-structured test naming.
Как установить скилл Pytest Best Practices?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл Pytest Best Practices запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic