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.
pip install pytest
Python code
28 linesimport 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
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
- Use fixture scope='module' to create the fixture once and share it across multiple tests
- 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
More from Modern tooling
- Build a Recipe Runner Mock in Python easy
- Build a Textual TUI App Skeleton in Python easy
- Configure ruff linter rules in pyproject.toml with Python easy
- Data Conversion Helper Functions in Python easy
- How to Bind and Mock structlog Context in Python medium
- How to Build a Chainable Filter Helper in Python easy
Keep learning
Related tutorials and quizzes for this topic.