conftest.py: shared fixtures

RoadmapsPython

Overview

**conftest.py** is a special pytest file used to share fixtures across multiple test files. Any fixture placed in `conftest.py` is automatically available to all tests in that folder, without needing to import it. Here is a worked example showing two files in a folder: ```python # File: conftest.py import pytest @pytest.fixture def fake_user(): return {'name': 'Amit'} ``` ```python # File: test_profile.py # Notice there is no import statement for fake_user! def test_user_name(fake_user): assert fake_user['name'] == 'Amit' ``` pytest automatically discovers `conftest.py` and loads `fake_user`. `test_profile.py` can use it instantly. Now, look at this faded example where one step is blank: ```python # File: test_orders.py def test_cart(_______): assert fake_user['name'] == 'Amit' ``` To use the fixture from `conftest.py`, we fill in the blank with `fake_user`. We do not need an import statement.

When projects grow, you will have many test files needing the same setups (like test databases or fake users). `conftest.py` prevents you from copying the same fixtures everywhere.

Where used: pytest setups across multiple directories

Why learn this

Code walkthrough

# Simulated behavior of pytest

def conftest_fixture():
  return 'SharedData'

def test_my_func(data):
  print(f'Using {data}')

# pytest automatically does this:
test_my_func(conftest_fixture())

Focus: test_my_func(conftest_fixture())

Aha moment

# File: conftest.py
import pytest
@pytest.fixture
def config(): return 'Global'

# File: test_local.py
import pytest
@pytest.fixture
def config(): return 'Local'

def test_mode(config):
  print(config)

Prediction: What does test_mode print? 'Global' or 'Local'?

Common guess: 'Global', because conftest.py affects everything.

It prints 'Local'. If a test file defines a fixture with the same name as one in `conftest.py`, the local file's fixture overrides the shared one for those tests.

Common mistakes

Recall questions

Understanding checks

Where is the bug in this file?

The line `from conftest import db_fixture` is incorrect.

Fixtures in `conftest.py` are injected automatically by pytest. Explicitly importing from `conftest.py` breaks pytest's magic and leads to errors.

Can test_api.py in folderB use the secret_key fixture from folderA?

No, it cannot.

`conftest.py` only shares fixtures with tests in its own folder and subfolders. `folderB` is outside `folderA`'s scope.

Practice tasks

Use the shared fixture

Given a `conftest.py` that provides a `test_client` fixture, write the test function to use it without importing it.

Challenge

Create a shared fixture

Write the exact contents of a `conftest.py` file that creates a fixture named `api_url` which returns the string `'http://localhost'`.

Continue learning

Previous: Fixtures and fixture scope

Return to Python Roadmap