StackPractices
intermediate By Mathias Paulenko

Pytest in Production Guide

Pytest for production: advanced fixtures, custom markers, parametrization, xdist parallelism, plugins, and CI integration patterns.

Topics: testing

Introduction

Your test suite passed 400 tests in forty seconds — on your laptop. Then it hits CI, takes nine minutes, fails on three tests that pass locally, and nobody remembers which marker means what. That’s the moment pytest stops being a test runner and becomes infrastructure.

This guide covers the parts of pytest that matter once your suite grows past a hundred files: fixture scopes and factories, custom markers, parametrization, xdist parallelism, plugins, CI integration, and the debugging flags that save you when something breaks at 2 a.m. For the broader testing strategy this fits into, see Software Testing Strategy.

When to Reach for pytest

Situationpytestunittestnose
New project, any size✅ default choiceacceptable❌ dead (unmaintained)
Deep fixture sharing✅ conftest + scopessetUp/tearDown only—
Parametrized cases✅ @parametrizesubTest (verbose)—
Parallel runs✅ pytest -n autono built-in—
Plugin ecosystem✅ 1000+ pluginslimited—
Zero-dependency constraint❌ third-party✅ stdlib—

unittest still makes sense when you’re inside a codebase that already uses it or when dependencies are restricted. Everything else points to pytest — it can even run existing unittest.TestCase classes, so migration can be incremental.

Fixture Fundamentals

Basic fixtures

# tests/conftest.py — Shared fixtures
import pytest
from myapp.db import Database
from myapp.models import User

@pytest.fixture
def db():
    """Provide a test database connection."""
    db = Database("postgresql://localhost/test_db")
    db.create_tables()
    yield db
    db.drop_tables()
    db.close()

@pytest.fixture
def user(db):
    """Create a test user in the database."""
    return User.create(db, email="test@example.com", name="Test User")

Everything after yield is teardown — it runs even when the test fails, so cleanup doesn’t depend on assertions passing.

Fixture scopes

# tests/conftest.py — Fixture scopes control lifecycle
import pytest

@pytest.fixture(scope="function")
def function_scoped():
    """Created and destroyed for each test (default)."""
    return {"count": 0}

@pytest.fixture(scope="class")
def class_scoped():
    """Created once per test class."""
    return {"count": 0}

@pytest.fixture(scope="module")
def module_scoped():
    """Created once per module."""
    return {"count": 0}

@pytest.fixture(scope="session")
def session_scoped():
    """Created once for the entire test session."""
    return {"count": 0}
Mermaid flowchart LR diagram

Choosing a scope is a speed-vs-isolation trade: session scope means setup once but shared state risk; function scope means isolation but repeated setup cost.

ScopeUse forWatch out
sessionDB engine, app instance, containers, configMutable state leaks between tests
moduleSeed data, file parsers, API clientsSame-file tests share mutations
classClass-level setup like a logged-in userOnly works inside classes
functionMutable objects, transactions, per-test dataSlow if setup is expensive

The classic production bug: a session-scoped fixture returning a mutable dict that one test modifies and the next test reads. If it can’t be mutated, session scope is safe; if it can, drop to function scope.

Fixture factories with closures

# tests/conftest.py — Dynamic fixture factories
import pytest
from myapp.models import Order, Product

@pytest.fixture
def make_order(db):
    """Factory fixture: creates orders with custom data."""
    created = []

    def _make(**kwargs):
        defaults = {
            "product": Product.create(db, name="Widget", price=10.00),
            "quantity": 1,
            "status": "pending",
        }
        defaults.update(kwargs)
        order = Order.create(db, **defaults)
        created.append(order)
        return order

    yield _make

    # Cleanup all created orders
    for order in created:
        order.delete(db)

# Usage
def test_order_processing(db, make_order):
    order = make_order(quantity=5, status="shipped")
    assert order.total == 50.00

def test_multiple_orders(db, make_order):
    o1 = make_order(quantity=2)
    o2 = make_order(quantity=3)
    assert Order.count(db) == 2

The factory pattern is how you stop copy-pasting setup blocks: each test asks for exactly the shape it needs, and the fixture tracks what it created so teardown can clean up all of it.

Fixture parametrization

# tests/test_calculator.py — Parametrize fixtures
import pytest

@pytest.fixture(params=[
    {"input": [1, 2], "expected": 3},
    {"input": [0, 0], "expected": 0},
    {"input": [-1, 1], "expected": 0},
    {"input": [100, 200], "expected": 300},
])
def calc_case(request):
    return request.param

def test_add(calc_case):
    from myapp.calculator import add
    result = add(*calc_case["input"])
    assert result == calc_case["expected"]

Fixture dependency chains

# tests/conftest.py — Fixtures depending on fixtures
import pytest
from myapp.app import create_app
from myapp.db import Database

@pytest.fixture(scope="session")
def db():
    db = Database("postgresql://localhost/test_db")
    db.create_tables()
    yield db
    db.drop_tables()

@pytest.fixture(scope="session")
def app(db):
    app = create_app(db, testing=True)
    yield app

@pytest.fixture(scope="function")
def client(app):
    """Test client for HTTP requests."""
    with app.test_client() as client:
        yield client

@pytest.fixture(scope="function")
def auth_client(client, db):
    """Authenticated test client."""
    from myapp.models import User
    user = User.create(db, email="test@example.com", password="hashed")
    token = user.generate_token()
    yield client.with_headers({"Authorization": f"Bearer {token}"})
    user.delete(db)

Note the chain mirrors the scopes: session-scoped db and app created once, function-scoped client and auth_client fresh per test. with_headers returns a client with the header set — the exact method name varies by framework (test_client in Flask, TestClient in FastAPI), but the pattern holds.

Custom Markers

Built-in markers

# tests/test_api.py — Using built-in markers
import pytest
import sys

@pytest.mark.skip(reason="Not implemented yet")
def test_future_feature():
    pass

@pytest.mark.skipif(
    sys.platform == "win32",
    reason="Unix-only feature"
)
def test_unix_feature():
    pass

@pytest.mark.xfail(reason="Known bug #123")
def test_known_bug():
    assert buggy_function() == expected

@pytest.mark.slow
def test_large_dataset():
    data = load_large_dataset()
    assert process(data) is not None

Custom markers

Register them in pytest.ini — unregistered markers emit warnings, and with --strict-markers (recommended) they’re hard errors, which is how you catch pytest.mark.slwo typos:

# pytest.ini
[pytest]
markers =
    slow: marks tests as slow (deselect with '-m "not slow"')
    integration: marks tests as integration tests
    unit: marks tests as unit tests
    smoke: marks tests as smoke tests
    security: marks tests as security tests
    requires_db: marks tests that need a database
    requires_redis: marks tests that need Redis
# tests/test_orders.py — Using custom markers
import pytest

@pytest.mark.unit
def test_order_calculation():
    assert calculate_total(10, 2) == 20

@pytest.mark.integration
@pytest.mark.requires_db
def test_order_persistence(db, make_order):
    order = make_order()
    fetched = Order.get(db, order.id)
    assert fetched.status == "pending"

@pytest.mark.smoke
def test_api_responds(client):
    response = client.get("/health")
    assert response.status_code == 200

@pytest.mark.security
def test_sql_injection_prevention(client):
    response = client.get("/api/users?id=1; DROP TABLE users")
    assert response.status_code == 400

Running by marker

# Run only unit tests
pytest -m unit

# Run everything except slow tests
pytest -m "not slow"

# Run integration and security tests
pytest -m "integration or security"

# Run smoke tests only, stop on first failure
pytest -m smoke -x

# Run tests that need database but not Redis
pytest -m "requires_db and not requires_redis"

Marker expressions are the mechanism behind staged CI: fast unit subset on every commit, integration on PRs, slow nightly. Same suite, different slices.

Parametrized Tests

Basic parametrization

# tests/test_string_utils.py — Parametrized tests
import pytest
from myapp.utils import normalize_email

@pytest.mark.parametrize("input, expected", [
    ("User@Example.COM", "user@example.com"),
    ("  user@example.com  ", "user@example.com"),
    ("USER+tag@example.com", "user+tag@example.com"),
    ("user.name@example.com", "user.name@example.com"),
    ("", ""),
    (None, None),
])
def test_normalize_email(input, expected):
    assert normalize_email(input) == expected

One function, six cases — and failures point at the exact input, not a for-loop index.

Parametrization with IDs

# tests/test_pagination.py — Named parametrized cases
import pytest

@pytest.mark.parametrize(
    "page, per_page, expected_offset",
    [
        pytest.param(1, 10, 0, id="first-page"),
        pytest.param(2, 10, 10, id="second-page"),
        pytest.param(3, 20, 40, id="third-page-larger"),
        pytest.param(10, 5, 45, id="tenth-page-small"),
    ]
)
def test_pagination_offset(page, per_page, expected_offset):
    assert calculate_offset(page, per_page) == expected_offset

Named IDs turn test_pagination_offset[3] into test_pagination_offset[tenth-page-small] — worth it the moment you’ve got more than a handful of cases.

Multi-parameter parametrization

# tests/test_validation.py — Complex parametrization
import pytest
from myapp.validators import validate_password

@pytest.mark.parametrize("password, is_valid, errors_count", [
    ("Short1!", False, 1),
    ("NoDigitsHere!", False, 1),
    ("nouppercase1!", False, 1),
    ("NOLOWERCASE1!", False, 1),
    ("ValidPass1!", True, 0),
    ("AnotherValid123$", True, 0),
])
def test_password_validation(password, is_valid, errors_count):
    result = validate_password(password)
    assert result.is_valid == is_valid
    assert len(result.errors) == errors_count

Parametrize with fixtures (indirect)

# tests/test_api_endpoints.py — Indirect parametrization
import pytest

@pytest.fixture
def api_client(request):
    """Create client with specific auth level."""
    auth_level = request.param
    client = create_test_client(auth=auth_level)
    return client

@pytest.mark.parametrize("api_client", ["admin", "user", "guest"], indirect=True)
def test_get_user_profile(api_client):
    response = api_client.get("/api/profile")
    assert response.status_code in [200, 403]

indirect=True routes the parameter through the fixture — the clean way to run the same test against different environments, auth levels, or backends.

Parallel Execution with pytest-xdist

Basic parallel execution

# Run tests in parallel using all CPU cores
pytest -n auto

# Run with specific number of workers
pytest -n 4

# Run with load balancing (default is load scope)
pytest -n 4 --dist loadscope

# Run with loadfile distribution (per-file)
pytest -n 4 --dist loadfile

A serial suite that takes ten minutes usually drops under two on a modern CI runner. The catch: workers are separate processes, so anything shared — a database, a file, a port — collides unless you isolate per worker.

Parallel-safe fixtures

# tests/conftest.py — xdist-compatible fixtures
import pytest
import os
import uuid
from myapp.db import Database

@pytest.fixture(scope="session")
def db_url():
    """Each worker gets its own database."""
    worker_id = os.environ.get("PYTEST_XDIST_WORKER", "gw0")
    return f"postgresql://localhost/test_db_{worker_id}"

@pytest.fixture(scope="session")
def db(db_url):
    db = Database(db_url)
    db.create_tables()
    yield db
    db.drop_tables()

@pytest.fixture(scope="function")
def unique_email():
    """Generate unique email per test to avoid collisions."""
    return f"test-{uuid.uuid4()}@example.com"

PYTEST_XDIST_WORKER is the key: gw0, gw1, gw2… give every worker its own database/schema/namespace and most parallel flakiness disappears.

Controlling parallel scope

# tests/conftest.py — Group tests by class for xdist
import pytest

@pytest.fixture(scope="class")
def shared_state():
    """Shared within a class — xdist runs class tests on same worker."""
    return {"initialized": False}

class TestOrderFlow:
    """All tests in this class run on the same worker."""
    def test_create_order(self, shared_state, client):
        shared_state["initialized"] = True
        response = client.post("/api/orders", json={"item": "widget"})
        assert response.status_code == 201

    def test_view_order(self, shared_state, client):
        assert shared_state["initialized"]
        response = client.get("/api/orders/1")
        assert response.status_code == 200

--dist loadscope keeps all tests in a class (or module) on the same worker — required when tests legitimately share setup state within that scope.

Plugins

conftest.py as a local plugin

# tests/conftest.py — Local plugin patterns
import pytest
import time

@pytest.fixture(autouse=True)
def reset_state(db):
    """Auto-used fixture: runs for every test without explicit request."""
    db.reset()
    yield
    db.cleanup()

def pytest_runtest_setup(item):
    """Hook: called before each test's fixtures resolve."""
    if "requires_db" in item.keywords and os.environ.get("NO_DB"):
        pytest.skip("Database not available in this environment")

def pytest_runtest_makereport(item, call):
    """Hook: capture test results for reporting."""
    if call.when == "call":
        outcome = "passed" if call.excinfo is None else "failed"
        print(f"\n{item.nodeid}: {outcome}")

@pytest.fixture
def timer():
    """Measure test execution time."""
    start = time.time()
    yield
    elapsed = time.time() - start
    print(f"\nTest took {elapsed:.3f}s")

Custom assertion rewriting

# tests/conftest.py — Custom assertion messages
import pytest

def pytest_assertrepr_compare(op, left, right):
    """Custom assertion comparison output."""
    if op == "==" and isinstance(left, dict) and isinstance(right, dict):
        missing = set(right.keys()) - set(left.keys())
        if missing:
            return [f"Missing keys: {missing}"]
        for key in left:
            if left[key] != right[key]:
                return [
                    f"Key mismatch for '{key}':",
                    f"  left:  {left[key]}",
                    f"  right: {right[key]}",
                ]

This hook makes failures readable: instead of a 40-line dict diff, you get “Key mismatch for ‘status’: left ‘pending’, right ‘shipped’”.

Creating a reusable plugin

# mypytestplugin/plugin.py — Installable pytest plugin
import pytest
import os
import tempfile

def pytest_addoption(parser):
    """Add custom command-line options."""
    parser.addoption(
        "--env",
        action="store",
        default="test",
        help="Test environment: test, staging, prod"
    )
    parser.addoption(
        "--retry",
        action="store",
        type=int,
        default=0,
        help="Number of retries for failed tests"
    )

@pytest.fixture(scope="session")
def env(request):
    return request.config.getoption("--env")

@pytest.fixture(scope="session")
def retry_count(request):
    return request.config.getoption("--retry")

def pytest_configure(config):
    """Register markers and configure."""
    config.addinivalue_line("markers", "flaky: test may fail intermittently")

# setup.py or pyproject.toml
# [project.entry-points.pytest11]
# mypytestplugin = "mypytestplugin.plugin"

The pytest11 entry point is how a conftest graduates to an installable plugin — useful when fixtures get shared across repos.

Test Organization

Directory structure

tests/
├── conftest.py              # Root conftest: shared fixtures
├── unit/
│   ├── conftest.py          # Unit test fixtures
│   ├── test_models.py
│   ├── test_validators.py
│   └── test_utils.py
├── integration/
│   ├── conftest.py          # Integration fixtures (db, redis)
│   ├── test_api_orders.py
│   ├── test_api_users.py
│   └── test_db_queries.py
├── e2e/
│   ├── conftest.py          # E2E fixtures (selenium, playwright)
│   ├── test_checkout_flow.py
│   └── test_user_registration.py
└── fixtures/
    ├── __init__.py
    ├── factories.py          # Test data factories
    └── mock_data.py          # Static mock data

The nested conftest.py files are the point: fixtures in tests/integration/conftest.py only exist for integration tests, so the unit suite never waits on a database fixture it doesn’t need.

Test factories

# tests/fixtures/factories.py — Reusable test data factories
import factory
from myapp.models import User, Order, Product

class UserFactory(factory.Factory):
    class Meta:
        model = User

    email = factory.Sequence(lambda n: f"user{n}@example.com")
    name = factory.Faker("name")
    is_active = True

class ProductFactory(factory.Factory):
    class Meta:
        model = Product

    name = factory.Faker("word")
    price = factory.Faker("pydecimal", left_digits=2, right_digits=2, positive=True)

class OrderFactory(factory.Factory):
    class Meta:
        model = Order

    user = factory.SubFactory(UserFactory)
    product = factory.SubFactory(ProductFactory)
    quantity = 1
    status = "pending"

factory_boy complements fixture factories: the fixture factory pattern above works per-test-session, while factory_boy generates realistic data on demand — ideal when the shape matters more than the values.

CI Integration

GitHub Actions

# .github/workflows/tests.yml — Pytest in GitHub Actions
name: Tests
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        python-version: ["3.11", "3.12", "3.13"]

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_PASSWORD: test
          POSTGRES_DB: test_db
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

      redis:
        image: redis:7
        ports:
          - 6379:6379

    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: ${{ matrix.python-version }}
      - run: pip install -e ".[test]"
      - run: pytest -n auto --cov=myapp --cov-report=xml -m "not slow"
      - uses: codecov/codecov-action@v4
        with:
          file: ./coverage.xml

Coverage configuration

# .coveragerc — Coverage settings
[run]
source = myapp
omit =
    myapp/__init__.py
    myapp/migrations/*
    myapp/tests/*

[report]
exclude_lines =
    pragma: no cover
    def __repr__
    raise NotImplementedError
    if __name__ == .__main__.:
    @abstractmethod
fail_under = 80
show_missing = True

[html]
directory = htmlcov

pytest configuration

# pytest.ini — Production pytest configuration
[pytest]
minversion = 8.0
testpaths = tests
addopts =
    -v
    --strict-markers
    --strict-config
    --tb=short
    --cov=myapp
    --cov-report=term-missing
    --cov-report=html
    --cov-fail-under=80
markers =
    slow: marks tests as slow
    integration: marks tests as integration tests
    unit: marks tests as unit tests
    smoke: marks tests as smoke tests
    security: marks tests as security tests
    requires_db: marks tests that need a database
    requires_redis: marks tests that need Redis
    flaky: marks tests that may fail intermittently
filterwarnings =
    error
    ignore::DeprecationWarning:myapp.legacy.*

filterwarnings = error turns warnings into failures — the cheapest way to catch deprecated API usage before it breaks on the next dependency upgrade.

Advanced Patterns

Snapshot testing

# tests/test_api_snapshots.py — Snapshot testing with syrupy
import pytest
from myapp.app import create_app

def test_user_list(client, snapshot):
    """syrupy's snapshot fixture compares against stored snapshots."""
    response = client.get("/api/users")
    assert response.json == snapshot

# Regenerate after intentional changes: pytest --snapshot-update

Property-based testing with Hypothesis

# tests/test_sort_property.py — Property-based testing
from hypothesis import given, strategies as st, settings
from myapp.sorting import quick_sort

@given(st.lists(st.integers(), min_size=0, max_size=100))
@settings(max_examples=500)
def test_sort_idempotent(items):
    """Sorting twice produces the same result."""
    sorted_once = quick_sort(items)
    sorted_twice = quick_sort(sorted_once)
    assert sorted_once == sorted_twice

@given(st.lists(st.integers(), min_size=1))
def test_sort_preserves_length(items):
    assert len(quick_sort(items)) == len(items)

@given(st.lists(st.integers(), min_size=1))
def test_sort_first_element_is_min(items):
    sorted_items = quick_sort(items)
    assert sorted_items[0] == min(items)

Hypothesis drops into pytest as if @given were just another parametrization — for the full property-testing workflow (strategies, shrinking, stateful testing), see Property-Based Testing Guide.

Mocking external services

# tests/test_external_api.py — Mock external HTTP calls
import pytest
from unittest.mock import patch, Mock
from myapp.services import PaymentService

@patch("myapp.services.requests.post")
def test_payment_success(mock_post, db, make_order):
    mock_post.return_value = Mock(
        status_code=200,
        json=lambda: {"id": "pay_123", "status": "succeeded"}
    )

    order = make_order(quantity=1)
    result = PaymentService.charge(order, amount=10.00)

    assert result.status == "succeeded"
    mock_post.assert_called_once()

@patch("myapp.services.requests.post")
def test_payment_retry_on_timeout(mock_post, db, make_order):
    mock_post.side_effect = [
        TimeoutError("Connection timeout"),
        Mock(status_code=200, json=lambda: {"status": "succeeded"}),
    ]

    order = make_order()
    result = PaymentService.charge(order, amount=10.00)

    assert result.status == "succeeded"
    assert mock_post.call_count == 2

Mock at the boundary (requests.post), not inside your own service logic — mocking internals makes the test re-verify the mock, not the code. The recipe Mock External APIs covers the boundary patterns in more depth.

Debugging Failed Tests

Useful flags

# Run only the tests that failed last time
pytest --lf

# Run failed tests first, then the rest
pytest --ff

# Drop to debugger on failure
pytest --pdb

# Show local variables on failure
pytest --showlocals

# Run with maximum verbosity and no output capture
pytest -vv -s

# Stop on first failure, show full traceback
pytest -x --tb=long

# Run only tests matching pattern
pytest -k "test_order"

# Show slowest 10 tests
pytest --durations=10

--lf and --ff are the two flags you reach for most in a big suite: --lf reruns only what broke, --ff puts the failures first and then runs everything — the right order for “did my fix work?” runs.

Using breakpoints

# tests/test_debug.py — Debugging with breakpoints
import pytest

def test_complex_logic(db, make_order):
    order = make_order(quantity=5)
    result = process_order(order)

    # Drop into debugger if assertion fails
    assert result.status == "shipped"
    assert result.tracking_number is not None

# Run with: pytest -s --pdb tests/test_debug.py
# The -s flag disables output capture so you can interact with pdb

Troubleshooting

SymptomLikely causeFix
fixture 'db' not foundconftest in the wrong directory, or fixture defined after importconftest lives next to or above the tests that use it; never import fixtures
ImportError when collecting conftestconftest importing app code without installed packagepip install -e . so tests import the real package, not relative paths
Tests pass alone, fail togetherShared mutable state via session/class-scoped fixtureFunction scope for mutable data, or reset in teardown
xdist runs everything on one worker--dist loadscope grouping, or tests in one classSpread tests across modules; check --dist mode
xdist flaky on shared resourcesWorkers hitting the same DB/port/fileNamespace per worker via PYTEST_XDIST_WORKER
Coverage reports 0%Source path wrong or xdist without --cov-appendsource = myapp in .coveragerc; use pytest-cov with xdist flag
Unknown mark warningsCustom marker not registeredDeclare in markers = ini; --strict-markers makes it an error
Snapshot diffs everywhereNon-deterministic output (timestamps, random ids)Exclude volatile fields or freeze them before snapshotting
Suite slower after xdistSetup cost dominates when suite is smallxdist pays off past ~200-300 tests; below that, serial is faster

Best Practices

  • Use conftest.py for shared fixtures — never import fixtures across modules
  • Keep unit tests fast — mock external dependencies, use in-memory databases
  • Use markers consistently — they enable staged CI (unit on commit, slow nightly)
  • Parametrize instead of copy-pasting — one test function, many inputs
  • Set --strict-markers — catch typos in marker names at startup
  • Use --cov-fail-under in CI — prevent coverage regression
  • Isolate tests — no test should depend on another test’s side effects
  • Name tests descriptively — test_order_total_includes_tax, not test_order_1
  • Use factory fixtures for complex objects — avoid long setup blocks in each test
  • Run fast tests first — -m "not slow" for quick feedback in development
  • Give each xdist worker its own namespace — databases, ports, files
  • Keep conftest small — a 500-line conftest is a plugin waiting to be extracted

Common Mistakes

  • Shared state between tests: tests pass individually but fail when run together. Use function-scoped fixtures or explicit cleanup.
  • Order-dependent tests: test B depends on test A running first. Each test should be independent — xdist will expose this instantly.
  • Over-mocking: mocking everything makes tests brittle and tests the mocks, not the code. Mock at boundaries only.
  • No parallel testing: test suite takes 10 minutes because it runs serially. Add pytest-xdist and -n auto.
  • Fixture scope too broad: session-scoped mutable fixtures cause flaky tests. Use function scope for mutable data.
  • Missing --strict-markers: typos in markers silently pass. Always enable strict mode.
  • Importing fixtures: from conftest import db doesn’t work the way you expect — fixtures are discovered, not imported. Put them in a shared conftest.
  • autouse everything: autouse=True fixtures run for every test including ones that don’t need them — reserve for true cross-cutting concerns.
  • Huge conftest.py: hundreds of fixtures in one file means nobody finds anything — split by directory scope or extract to a plugin.

See Also

Frequently Asked Questions

What is the difference between conftest.py and regular test files?

conftest.py files contain shared fixtures and hooks. Pytest automatically discovers them without imports. Place a conftest.py in each directory to scope fixtures to that directory and its subdirectories — fixtures in tests/integration/conftest.py only exist for tests under tests/integration/.

How do I run tests in parallel with pytest?

Install pytest-xdist and run pytest -n auto. Use --dist loadscope to group tests by class or module, which reduces fixture setup overhead and keeps scoped state together on the same worker.

What is the best fixture scope for database connections?

Use scope="session" for the connection/engine (expensive to create) and scope="function" for test data (needs isolation). This gives you speed from session scope and isolation from function scope — the single most impactful scope decision in a DB-backed suite.

How do I skip tests conditionally?

Use pytest.mark.skipif with a condition, or pytest.skip() inside a fixture or test. For environment-dependent skips, use a pytest_runtest_setup hook that checks markers — e.g., skip requires_db tests when NO_DB is set.

How do I measure test coverage?

Install pytest-cov and run pytest --cov=myapp --cov-report=term-missing. Add --cov-fail-under=80 to fail CI when coverage drops below 80%, and pair it with the recipe Measure Test Coverage with pytest-cov for report options.

Why does my session-scoped fixture run multiple times?

Because scope is per runner, not global: under pytest -n 4, each of the 4 workers creates its own session-scoped fixtures. That's usually what you want (isolated state per worker), but if the fixture is expensive, make workers share via a resource keyed on PYTEST_XDIST_WORKER or reduce worker count for that job.