Labs ICT
โญ Pro Login

conftest.py & Shared Fixtures

Sharing fixtures across tests using conftest.py files.

What is conftest.py?

conftest.py is a special file where pytest looks for fixtures, hooks, and configuration. It is the standard way to share fixtures across multiple test files without importing them.

Sharing Fixtures

Define fixtures in conftest.py and they become available to all test files in that directory:

# conftest.py
import pytest

@pytest.fixture
def sample_data():
    return {"name": "Alice", "age": 30}

@pytest.fixture
def temp_dir(tmp_path):
    return tmp_path / "test_output"
# test_one.py - no import needed!
def test_with_data(sample_data):
    assert sample_data["name"] == "Alice"

# test_two.py - also works without import
def test_with_data(sample_data):
    assert sample_data["age"] == 30

Hierarchical conftest.py

pytest collects conftest.py files at every directory level. A fixture defined in a parent directory is available to all subdirectories:

project/
โ”œโ”€โ”€ conftest.py           # Available everywhere
โ”œโ”€โ”€ tests/
โ”‚   โ”œโ”€โ”€ conftest.py       # Available to tests/ and subdirs
โ”‚   โ”œโ”€โ”€ test_api.py
โ”‚   โ””โ”€โ”€ unit/
โ”‚       โ”œโ”€โ”€ conftest.py   # Available only to unit/
โ”‚       โ””โ”€โ”€ test_math.py

conftest.py is NOT Imported

You never import from conftest.py. pytest loads it automatically. This is different from regular Python modules:

# WRONG - do not do this
from conftest import sample_data

# RIGHT - pytest handles it automatically
def test_something(sample_data):
    pass

๐Ÿงช Quick Quiz

What is the purpose of conftest.py?