Bird
Raised Fist0
PyTesttesting~20 mins

Fixture composition in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Fixture Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of composed pytest fixtures
What is the output when running this pytest test with the given fixtures?
PyTest
import pytest

@pytest.fixture
def base_data():
    return [1, 2, 3]

@pytest.fixture
def extended_data(base_data):
    return base_data + [4, 5]

def test_sum(extended_data):
    assert sum(extended_data) == 15
    print(sum(extended_data))
ATypeError
B15
C14
DAssertionError
Attempts:
2 left
💡 Hint
Think about how fixtures can use other fixtures as input and how the list is extended.
assertion
intermediate
2:00remaining
Correct assertion for nested fixture output
Given these fixtures, which assertion correctly verifies the final output in the test?
PyTest
import pytest

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

@pytest.fixture
def user_with_email(user):
    user['email'] = 'alice@example.com'
    return user

def test_user_email(user_with_email):
    # Which assertion is correct here?
Aassert user_with_email['email'] == 'bob@example.com'
Bassert user_with_email['age'] == 25
Cassert 'email' not in user_with_email
Dassert user_with_email['email'] == 'alice@example.com' and user_with_email['age'] == 30
Attempts:
2 left
💡 Hint
Check how the email is added in the second fixture and the age remains unchanged.
🔧 Debug
advanced
2:00remaining
Identify the cause of fixture reuse error
Why does this pytest test raise an error about fixture scope when running?
PyTest
import pytest

@pytest.fixture(scope='function')
def db_connection():
    return 'db_conn'

@pytest.fixture(scope='module')
def user_session(db_connection):
    return f'session using {db_connection}'

def test_session(user_session):
    assert 'session' in user_session
AFixture 'user_session' has a wider scope than 'db_connection', causing a scope mismatch error.
BThe 'db_connection' fixture is missing a return statement.
CThe test function is missing a parameter for 'db_connection'.
DThe 'user_session' fixture should not depend on another fixture.
Attempts:
2 left
💡 Hint
Think about pytest fixture scopes and their allowed dependencies.
framework
advanced
2:00remaining
Best practice for fixture composition in pytest
Which option correctly describes a best practice when composing fixtures in pytest?
AFixtures should never return mutable objects to avoid side effects.
BAvoid using fixtures as parameters to other fixtures; use global variables instead.
CAlways keep fixture scopes compatible; a fixture should not depend on another fixture with a narrower scope.
DUse fixtures only for setup, never for providing test data.
Attempts:
2 left
💡 Hint
Think about how pytest manages fixture lifetimes and dependencies.
🧠 Conceptual
expert
3:00remaining
Understanding fixture teardown order in composed fixtures
Given these fixtures, in what order will the teardown code run after the test completes?
PyTest
import pytest

@pytest.fixture
def resource_a():
    print('Setup A')
    yield 'A'
    print('Teardown A')

@pytest.fixture
def resource_b(resource_a):
    print('Setup B')
    yield 'B'
    print('Teardown B')

def test_resources(resource_b):
    print('Test running')
A1,2,3,4,5
B2,1,3,4,5
C1,2,3,5,4
D2,1,3,5,4
Attempts:
2 left
💡 Hint
Fixtures teardown in reverse order of setup, respecting dependencies.

Practice

(1/5)
1. What is the main benefit of using fixture composition in pytest?
easy
A. It speeds up test execution by running tests in parallel.
B. It automatically generates test data without coding.
C. It replaces the need for assertions in tests.
D. It allows reusing simple fixtures to build complex test setups.

Solution

  1. Step 1: Understand fixture composition purpose

    Fixture composition means using simple fixtures inside other fixtures to build complex setups.
  2. Step 2: Identify the main benefit

    This avoids repeating code and makes tests easier to maintain by reusing fixtures.
  3. Final Answer:

    It allows reusing simple fixtures to build complex test setups. -> Option D
  4. Quick Check:

    Fixture composition = reuse fixtures [OK]
Hint: Fixture composition means combining fixtures to reuse setup code [OK]
Common Mistakes:
  • Thinking fixture composition auto-generates data
  • Confusing fixture composition with test parallelization
  • Believing it removes the need for assertions
2. Which of the following is the correct way to use a fixture inside another fixture in pytest?
easy
A. def fixture_a(fixture_b): pass
B. def fixture_a(): fixture_b()
C. @pytest.fixture class fixture_a(fixture_b): pass
D. def fixture_a(): yield fixture_b

Solution

  1. Step 1: Recall fixture dependency syntax

    In pytest, to use one fixture inside another, list the dependent fixture as a parameter.
  2. Step 2: Check options for correct syntax

    def fixture_a(fixture_b): pass shows a fixture function with another fixture as a parameter, which is correct.
  3. Final Answer:

    def fixture_a(fixture_b): pass -> Option A
  4. Quick Check:

    Fixture dependency = parameter in fixture function [OK]
Hint: Use fixture names as parameters to compose fixtures [OK]
Common Mistakes:
  • Calling fixture functions directly inside another fixture
  • Using class syntax for fixtures incorrectly
  • Yielding fixture names instead of using parameters
3. Given the code below, what will be the output when running 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}")
medium
A. Test fails with assertion error
B. Test passes and prints 'Result: 10'
C. RuntimeError due to missing fixture
D. SyntaxError in fixture definition

Solution

  1. Step 1: Trace fixture values

    The fixture data returns 5. The fixture multiplier uses data and returns 5 * 2 = 10.
  2. Step 2: Analyze test behavior

    The test receives multiplier as 10, asserts it equals 10 (true), then prints 'Result: 10'.
  3. Final Answer:

    Test passes and prints 'Result: 10' -> Option B
  4. Quick Check:

    Fixture value = 10, assertion true [OK]
Hint: Follow fixture return values step-by-step to predict output [OK]
Common Mistakes:
  • Assuming fixture returns original data, not multiplied
  • Expecting runtime errors without missing fixtures
  • Confusing syntax errors with correct fixture code
4. Identify the error in the following fixture composition code:
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 == 5
medium
A. test_value should not take composed_fixture as parameter
B. composed_fixture should not return a value
C. Missing parentheses when calling base_value fixture inside composed_fixture
D. base_value fixture should be a class, not a function

Solution

  1. Step 1: Check how base_value is used inside composed_fixture

    Inside composed_fixture, value = base_value assigns the function, not its result.
  2. Step 2: Correct usage of fixture call

    Fixtures are injected by pytest, but inside another fixture you must accept them as parameters or call them properly. Here, base_value should be a parameter or called with parentheses if used directly.
  3. Final Answer:

    Missing parentheses when calling base_value fixture inside composed_fixture -> Option C
  4. Quick Check:

    Fixture call needs parentheses or parameter injection [OK]
Hint: Use fixture names as parameters, not direct calls without parentheses [OK]
Common Mistakes:
  • Assigning fixture function instead of calling it
  • Returning values incorrectly from fixtures
  • Misunderstanding fixture injection in tests
5. You want to create a fixture 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?
hard
A. import pytest @pytest.fixture def full_setup(db_connection, user_data): return {**db_connection, **user_data}
B. import pytest @pytest.fixture def full_setup(): db = db_connection() user = user_data() return {**db, **user}
C. import pytest @pytest.fixture def full_setup(): return {**db_connection, **user_data}
D. import pytest @pytest.fixture def full_setup(db_connection, user_data): return db_connection + user_data

Solution

  1. Step 1: Understand fixture composition with parameters

    Fixtures can be composed by listing dependent fixtures as parameters in the fixture function.
  2. Step 2: Check correct dictionary merging

    import pytest @pytest.fixture def full_setup(db_connection, user_data): return {**db_connection, **user_data} correctly accepts both fixtures as parameters and merges their dictionaries using unpacking syntax.
  3. Final Answer:

    import pytest @pytest.fixture def full_setup(db_connection, user_data): return {**db_connection, **user_data} -> Option A
  4. Quick Check:

    Fixture composition with parameters and dict merge [OK]
Hint: List fixtures as parameters and merge results properly [OK]
Common Mistakes:
  • Calling fixtures like functions inside another fixture
  • Trying to merge fixtures without parameters
  • Using unsupported operations like + on dicts