Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

Pytest Best Practices

БесплатноБез исполняемых скриптовНе проверен

Opinionated pytest patterns for AI agents - conftest fixture scoping, parametrize, markers, pyproject config, coverage, xdist parallelism, mocking, and…

PramodDuttaот 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

  1. One assertion concept per test. A test verifies a single behavior. Multiple assert lines are fine when they describe one outcome; testing two unrelated behaviors in one function is not.
  2. 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.
  3. Fixtures over setup methods. Use conftest.py fixtures for shared setup. Never use unittest-style setUp/tearDown in pytest code.
  4. Scope fixtures as narrowly as correctness allows. Default to function scope. Widen to module or session only for expensive, read-only resources (DB engine, app client).
  5. Parametrize instead of looping. A for loop inside a test hides which case failed. @pytest.mark.parametrize gives one test ID per case.
  6. Tests are isolated and order-independent. Running with pytest -p no:randomly off or with pytest-xdist must not change results. No shared mutable module state.
  7. 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.
  8. 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.
  9. Name tests as behavior sentences. test_<unit>_<condition>_<expected> reads like a spec line in the report.
  10. 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
Полный SKILL.md на GitHub

Установить 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), без исполняемых скриптов.

Похожие скиллы

Сравнить Pytest Best Practices с