0
0
PyTesttesting~5 mins

Fixture composition in PyTest

Choose your learning style9 modes available
Introduction

Fixture composition helps you reuse setup code by combining simple fixtures into bigger ones. This keeps tests clean and avoids repeating code.

When you have multiple tests needing the same setup steps.
When one fixture depends on another fixture's data or setup.
When you want to organize complex test setups into smaller parts.
When you want to share common resources like database connections or test data.
When you want to keep your test code easy to read and maintain.
Syntax
PyTest
import pytest

@pytest.fixture
def fixture_a():
    return 'data from A'

@pytest.fixture
def fixture_b(fixture_a):
    return f'B uses {fixture_a}'

Fixtures can accept other fixtures as parameters to compose setups.

pytest automatically injects the required fixtures when running tests.

Examples
Here, logged_in_user fixture uses user fixture and adds more setup.
PyTest
import pytest

@pytest.fixture
def user():
    return {'name': 'Alice'}

@pytest.fixture
def logged_in_user(user):
    user['logged_in'] = True
    return user
This shows a fixture prepared_db that depends on db_connection.
PyTest
import pytest

@pytest.fixture
def db_connection():
    return 'db connection'

@pytest.fixture
def prepared_db(db_connection):
    return f'{db_connection} with test data loaded'
Sample Program

This test uses fixture composition: api_endpoint depends on base_url. The test checks the composed URL.

PyTest
import pytest

@pytest.fixture
def base_url():
    return 'http://example.com'

@pytest.fixture
def api_endpoint(base_url):
    return f'{base_url}/api/v1'

def test_api(api_endpoint):
    assert api_endpoint == 'http://example.com/api/v1'

if __name__ == '__main__':
    pytest.main([__file__])
OutputSuccess
Important Notes

Use fixture composition to keep your test setup modular and easy to update.

pytest injects fixtures by matching parameter names, so names must match exactly.

Fixtures can be scoped (function, module, session) to control how often they run.

Summary

Fixture composition lets you build complex setups from simple fixtures.

It avoids repeating code and makes tests easier to maintain.

pytest automatically handles fixture dependencies by matching names.