Test fixture composition with pytest fixtures
Preconditions (2)
✅ Expected Result: The test passes confirming that fixture composition works correctly
Jump into concepts and practice - no test required
import pytest @pytest.fixture def db_connection(): return 'db_connected' @pytest.fixture def user(db_connection): return f'user_from_{db_connection}' def test_user_fixture(user): assert user == 'user_from_db_connected'
The db_connection fixture returns a simple string representing a database connection.
The user fixture depends on db_connection by accepting it as a parameter. It composes a new string using the value from db_connection.
The test function test_user_fixture uses the user fixture and asserts that the returned value matches the expected composed string.
This shows how pytest fixtures can be composed by passing one fixture into another, making tests modular and reusable.
Now add data-driven testing with 3 different db_connection values and verify the composed user fixture for each.
test_combined?
import pytest
@pytest.fixture
def data():
return 5
@pytest.fixture
def multiplier(data):
return data * 2
def test_combined(multiplier):
assert multiplier == 10
print(f"Result: {multiplier}")data returns 5. The fixture multiplier uses data and returns 5 * 2 = 10.multiplier as 10, asserts it equals 10 (true), then prints 'Result: 10'.import pytest
@pytest.fixture
def base_value():
return 3
@pytest.fixture
def composed_fixture():
value = base_value
return value + 2
def test_value(composed_fixture):
assert composed_fixture == 5composed_fixture, value = base_value assigns the function, not its result.full_setup that uses two fixtures db_connection and user_data. The full_setup should return a dictionary combining both. Which code correctly composes these fixtures?