0
0
PyTesttesting~5 mins

Conftest.py purpose in PyTest

Choose your learning style9 modes available
Introduction

Conftest.py helps share setup code and fixtures across multiple test files easily.

When you want to run the same setup steps before many tests.
When you need to share data or objects between different test files.
When you want to avoid repeating code in each test file.
When you want to organize your test helpers in one place.
When you want to customize test behavior globally.
Syntax
PyTest
import pytest

@pytest.fixture
def my_fixture():
    # setup code
    resource = None  # define resource before yield
    yield resource
    # teardown code

Conftest.py is automatically discovered by pytest in the test directory.

Fixtures defined here can be used by any test in the same or subdirectories.

Examples
This fixture provides sample data to tests that need it.
PyTest
import pytest

@pytest.fixture
def sample_data():
    return {'name': 'Alice', 'age': 30}
This fixture sets up a database connection once per module and closes it after tests.
PyTest
import pytest

@pytest.fixture(scope='module')
def db_connection():
    conn = connect_to_db()
    yield conn
    conn.close()
Sample Program

This test uses a fixture from conftest.py to get a greeting message and checks it.

PyTest
import pytest

@pytest.fixture
def greeting():
    return 'Hello, world!'

def test_greet(greeting):
    assert greeting == 'Hello, world!'
OutputSuccess
Important Notes

Do not import conftest.py directly; pytest finds it automatically.

Keep conftest.py simple and focused on shared fixtures or hooks.

Summary

Conftest.py shares setup code and fixtures across tests.

It helps avoid repeating code and keeps tests clean.

Pytest automatically finds and uses it in test folders.