Bird
Raised Fist0
PyTesttesting~20 mins

Dynamic fixture selection in PyTest - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Dynamic Fixture Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of dynamic fixture selection with parameter
What is the output of the following pytest test when run with pytest -s?
PyTest
import pytest

@pytest.fixture
def data_a():
    return "Data A"

@pytest.fixture
def data_b():
    return "Data B"

@pytest.fixture(params=["data_a", "data_b"])
def dynamic_data(request):
    return request.getfixturevalue(request.param)

def test_dynamic(dynamic_data):
    print(dynamic_data)
    assert dynamic_data in ["Data A", "Data B"]
AData B
BData B\nData A
CData A
DData A\nData B
Attempts:
2 left
💡 Hint
Think about how pytest runs tests with parameterized fixtures.
❓ assertion
intermediate
1:30remaining
Correct assertion for dynamic fixture value
Given a dynamic fixture that returns either 10 or 20, which assertion correctly verifies the value inside the test?
PyTest
import pytest

@pytest.fixture(params=[10, 20])
def number(request):
    return request.param

def test_number(number):
    # Which assertion is correct here?
    pass
Aassert number == 10 and number == 20
Bassert number in [10, 20]
Cassert number == 10 or number == 20
Dassert number != 10 or number != 20
Attempts:
2 left
💡 Hint
Check which assertion logically matches the possible values.
🔧 Debug
advanced
2:00remaining
Identify the error in dynamic fixture usage
What error will this pytest code raise when running the test?
PyTest
import pytest

@pytest.fixture(params=["fix1", "fix2"])
def dynamic(request):
    return request.getfixturevalue("fix3")

@pytest.fixture
def fix1():
    return "Fix 1"

@pytest.fixture
def fix2():
    return "Fix 2"

def test_dynamic(dynamic):
    assert dynamic in ["Fix 1", "Fix 2"]
AFixtureLookupError: The fixture 'fix3' is not found
BTypeError: getfixturevalue() missing required positional argument
CAssertionError: dynamic value not in expected list
DNo error, test passes
Attempts:
2 left
💡 Hint
Check the fixture name passed to getfixturevalue.
❓ framework
advanced
2:30remaining
Best practice for dynamic fixture selection in pytest
Which approach is best to dynamically select a fixture based on a test parameter in pytest?
AUse pytest hooks to modify fixture behavior at runtime
BUse if-else inside the test to call fixture functions directly
CUse a parameterized fixture with request.getfixturevalue to call fixtures by name
DUse global variables to store fixture data and select dynamically
Attempts:
2 left
💡 Hint
Consider pytest's built-in features for fixture parameterization.
🧠 Conceptual
expert
3:00remaining
Understanding fixture scope impact on dynamic fixture selection
If you have a session-scoped dynamic fixture that selects between two fixtures with different scopes (one 'function' and one 'session'), what is the expected behavior when running tests?
Apytest raises an error because fixtures with different scopes cannot be mixed dynamically
BThe dynamic fixture adopts the broader scope of the selected fixtures automatically
CThe dynamic fixture runs with the narrower scope of the selected fixture for each test run
DThe test results are unpredictable and may cause flaky tests
Attempts:
2 left
💡 Hint
Think about pytest's rules for fixture scope hierarchy.

Practice

(1/5)
1. What is the main purpose of dynamic fixture selection in pytest?
easy
A. To automatically generate test data without fixtures
B. To statically assign fixtures before running tests
C. To choose which fixture to use during test execution based on runtime conditions
D. To skip tests that use fixtures

Solution

  1. Step 1: Understand fixture selection

    Dynamic fixture selection means deciding which fixture to use while the test runs, not before.
  2. Step 2: Compare options

    Only To choose which fixture to use during test execution based on runtime conditions describes choosing fixtures during test execution based on conditions.
  3. Final Answer:

    To choose which fixture to use during test execution based on runtime conditions -> Option C
  4. Quick Check:

    Dynamic fixture selection = runtime choice [OK]
Hint: Dynamic means choosing fixtures while tests run [OK]
Common Mistakes:
  • Confusing static fixture assignment with dynamic selection
  • Thinking fixtures generate test data automatically
  • Believing dynamic selection skips tests
2. Which of the following is the correct syntax to select a fixture dynamically inside a test using request.getfixturevalue()?
easy
A. fixture_name = request.getfixturevalue('my_fixture')
B. fixture_name = request.getfixture('my_fixture')
C. fixture_name = request.getfixturevalue(my_fixture)
D. fixture_name = request.getfixture('my_fixture')()

Solution

  1. Step 1: Recall correct method name

    The method to get a fixture by name dynamically is getfixturevalue, not getfixture.
  2. Step 2: Check argument type

    The fixture name must be a string, so it should be quoted.
  3. Final Answer:

    fixture_name = request.getfixturevalue('my_fixture') -> Option A
  4. Quick Check:

    Use getfixturevalue('fixture_name') [OK]
Hint: Use getfixturevalue with string fixture name [OK]
Common Mistakes:
  • Using getfixture instead of getfixturevalue
  • Passing fixture name without quotes
  • Calling getfixture as a function
3. Given the code below, what will be the output when running test_dynamic_fixture?
import pytest

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

@pytest.fixture
def fixture_b():
    return 'B'

@pytest.mark.parametrize('use_a', [True, False])
def test_dynamic_fixture(request, use_a):
    fixture_name = 'fixture_a' if use_a else 'fixture_b'
    value = request.getfixturevalue(fixture_name)
    print(value)
    assert value in ['A', 'B']
medium
A. Prints 'A' twice and passes both tests
B. Prints 'B' then 'A' and fails one test
C. Raises an error because getfixturevalue is used incorrectly
D. Prints 'A' then 'B' and passes both tests

Solution

  1. Step 1: Understand parameterization

    The test runs twice: once with use_a=True, once with use_a=False.
  2. Step 2: Trace fixture selection and output

    When use_a=True, fixture_name='fixture_a' returns 'A'. When False, fixture_name='fixture_b' returns 'B'. Both print and assert succeed.
  3. Final Answer:

    Prints 'A' then 'B' and passes both tests -> Option D
  4. Quick Check:

    Param True->A, False->B [OK]
Hint: Param True uses fixture_a, False uses fixture_b [OK]
Common Mistakes:
  • Assuming getfixturevalue causes error
  • Mixing order of printed values
  • Thinking test fails due to assertion
4. Identify the error in the following test code that tries to select a fixture dynamically:
import pytest

@pytest.fixture
def fix1():
    return 10

@pytest.fixture
def fix2():
    return 20

@pytest.mark.parametrize('name', ['fix1', 'fix2'])
def test_select(request, name):
    value = request.getfixture(name)
    assert value in [10, 20]
medium
A. Incorrect assert statement
B. Using request.getfixture instead of request.getfixturevalue
C. Missing parentheses when calling fixtures
D. Passing fixture name as a string instead of variable

Solution

  1. Step 1: Check method name for dynamic fixture

    The correct method to get a fixture dynamically is getfixturevalue, not getfixture.
  2. Step 2: Confirm usage of fixture name

    The fixture name is correctly passed as a string variable, so no issue there.
  3. Final Answer:

    Using request.getfixture instead of request.getfixturevalue -> Option B
  4. Quick Check:

    Use getfixturevalue, not getfixture [OK]
Hint: Remember method name: getfixturevalue, not getfixture [OK]
Common Mistakes:
  • Confusing method names for fixture retrieval
  • Passing fixture name incorrectly
  • Misunderstanding assert logic
5. You want to write a test that uses different database connection fixtures based on an environment variable DB_TYPE. Which approach correctly implements dynamic fixture selection in pytest? A) Use request.getfixturevalue() inside the test to select the fixture by name. B) Use @pytest.mark.usefixtures() with all fixtures and skip unwanted ones. C) Use pytest_generate_tests() hook to parametrize fixtures. D) Use yield in fixtures to switch dynamically.
hard
A. Use request.getfixturevalue() inside the test to select the fixture by name.
B. Use @pytest.mark.usefixtures() with all fixtures and skip unwanted ones.
C. Use pytest_generate_tests() hook to parametrize fixtures.
D. Use yield in fixtures to switch dynamically.

Solution

  1. Step 1: Understand environment-based fixture selection

    Choosing a fixture based on an environment variable requires runtime decision inside the test.
  2. Step 2: Evaluate options for dynamic selection

    Use request.getfixturevalue() inside the test to select the fixture by name. uses request.getfixturevalue() to pick the fixture by name at runtime, which fits the need.
  3. Step 3: Exclude other options

    Use @pytest.mark.usefixtures() with all fixtures and skip unwanted ones. applies all fixtures upfront, not dynamic. Use pytest_generate_tests() hook to parametrize fixtures. is for test parametrization, not fixture selection. Use yield in fixtures to switch dynamically. misuses yield; it does not switch fixtures dynamically.
  4. Final Answer:

    Use request.getfixturevalue() inside the test to select the fixture by name. -> Option A
  5. Quick Check:

    Dynamic fixture selection = getfixturevalue() [OK]
Hint: Use getfixturevalue() for runtime fixture choice [OK]
Common Mistakes:
  • Trying to parametrize fixtures instead of selecting dynamically
  • Using usefixtures decorator incorrectly
  • Misunderstanding yield usage in fixtures
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard