0
0
PytestConceptBeginner · 3 min read

What is conftest.py in pytest: Purpose and Usage Explained

conftest.py is a special configuration file in pytest used to share fixtures and hooks across multiple test files without importing them explicitly. It helps organize common setup code in one place, making tests cleaner and easier to maintain.
⚙️

How It Works

Think of conftest.py as a shared toolbox for your tests. Instead of repeating the same setup steps in every test file, you put those steps in conftest.py. Pytest automatically finds this file when running tests and makes its fixtures and hooks available to all test files in the same directory or subdirectories.

This means you don’t have to import anything manually. Pytest looks up the folder tree for conftest.py files and loads their contents. It’s like having a helper friend who prepares everything you need before you start testing.

💻

Example

This example shows a fixture defined in conftest.py that provides a simple dictionary to multiple test files.

python
import pytest

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

# In a test file (test_example.py):

def test_name(sample_data):
    assert sample_data["name"] == "Alice"

def test_age(sample_data):
    assert sample_data["age"] == 30
Output
============================= test session starts ============================== collected 2 items test_example.py .. [100%] ============================== 2 passed in 0.01s ===============================
🎯

When to Use

Use conftest.py when you have setup code or fixtures that many test files need. For example, if you need to create a database connection, prepare test data, or configure environment settings, putting these in conftest.py avoids duplication.

This is especially helpful in larger projects where tests are spread across many files and folders. It keeps your tests clean and focused on checking behavior, not setup.

Key Points

  • Automatic discovery: Pytest finds conftest.py files without imports.
  • Shared fixtures: Define reusable setup code once.
  • Organizes tests: Keeps test files simple and clean.
  • Scope control: Fixtures in conftest.py can have different scopes (function, module, session).

Key Takeaways

conftest.py centralizes fixtures and hooks for multiple test files automatically.
It helps avoid repeating setup code and keeps tests clean and maintainable.
Pytest loads conftest.py files by searching directories, no imports needed.
Use it to share common test resources like data, connections, or configurations.
Fixtures in conftest.py can have flexible scopes to optimize test runs.