0
0
PyTesttesting~5 mins

Conftest fixtures (shared across files) in PyTest

Choose your learning style9 modes available
Introduction

Conftest fixtures let you share setup code across many test files easily. This helps avoid repeating the same code in each test.

You want to open a database connection once and use it in many test files.
You need to prepare test data that many tests will use.
You want to create a reusable login session for web tests across files.
You want to clean up resources after tests run in multiple files.
You want to keep your test setup organized and avoid duplication.
Syntax
PyTest
In conftest.py file:

import pytest

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

The conftest.py file should be placed in the test directory or a parent directory.

Fixtures defined here are automatically available to all test files in the same directory or subdirectories.

Examples
This fixture returns a simple list that tests can use.
PyTest
import pytest

@pytest.fixture
def sample_data():
    return [1, 2, 3]
This fixture shows setup and teardown using yield.
PyTest
import pytest

@pytest.fixture
def resource():
    print('Setup resource')
    yield 'resource ready'
    print('Teardown resource')
Sample Program

The fixture greeting is defined once in conftest.py. The test in test_example.py uses it without importing. It asserts the value and prints it.

PyTest
### conftest.py ###
import pytest

@pytest.fixture
def greeting():
    return 'Hello from conftest'


### test_example.py ###

def test_use_greeting(greeting):
    assert greeting == 'Hello from conftest'
    print(greeting)
OutputSuccess
Important Notes

Do not import conftest.py in your test files; pytest finds it automatically.

Keep conftest.py clean and focused on fixtures to avoid confusion.

Summary

Conftest fixtures let you share setup code across multiple test files.

Place fixtures in conftest.py in your test folder or above.

Tests can use these fixtures automatically without imports.