How to Use pytest Fixtures and conftest.py for Shared Setup in Python

Learn how to define reusable pytest fixtures for shared setup and use them to keep tests clean and maintainable.

Easy Python 3.9+ Aug 9, 2026 Modern tooling 13 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

28 lines
Python 3.9+
import pytest

class Calculator:
    def add(self, a, b):
        return a + b

    def multiply(self, a, b):
        return a * b


@pytest.fixture
def calc():
    return Calculator()


@pytest.fixture
def sample_numbers():
    return (3, 5)


def test_add(calc, sample_numbers):
    a, b = sample_numbers
    assert calc.add(a, b) == 8


def test_multiply(calc, sample_numbers):
    a, b = sample_numbers
    assert calc.multiply(a, b) == 15

Output

stdout
2 passed in 0.02s

How it works

Pytest fixtures are functions decorated with @pytest.fixture that provide reusable setup or objects to tests. By declaring a fixture as a parameter in a test function, pytest automatically calls the fixture and injects its return value. This makes tests explicit about their dependencies and reduces repetitive setup code. Fixtures can also be placed in a conftest.py file to be shared across multiple test modules. The fixture's return value is calculated once per test by default, ensuring a fresh instance for each test.

Common mistakes

  • Fixtures are not automatically imported if defined in a separate file without conftest.py
  • Forgetting to include the fixture name in the test function parameters
  • Using fixture scope='module' without understanding that state persists across tests
  • Naming a fixture the same as a built-in pytest fixture, causing unexpected behavior

Variations

  1. Use fixture scope='module' to create the fixture once and share it across multiple tests
  2. Return a tuple from a fixture to provide multiple objects (e.g., calculator and numbers together)

Real-world use cases

  • Setting up a database connection or test client once and reusing it across test modules.
  • Loading configuration or mock data for integration tests in a shared conftest.py.
  • Providing common fixtures like temporary directories or API clients to streamline unit tests.

Sponsored

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Modern tooling

Related tutorials and quizzes for this topic.