0
0
PyTesttesting~10 mins

Dynamic fixture selection in PyTest - Test Execution Trace

Choose your learning style9 modes available
Test Overview

This test demonstrates how to select a fixture dynamically in pytest based on a test parameter. It verifies that the correct fixture is used and returns the expected value.

Test Code - pytest
PyTest
import pytest

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

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

@pytest.fixture
 def dynamic_fixture(request):
     if request.param == "a":
         return request.getfixturevalue("fixture_a")
     elif request.param == "b":
         return request.getfixturevalue("fixture_b")
     else:
         pytest.skip("Unsupported fixture parameter")

@pytest.mark.parametrize("dynamic_fixture", ["a", "b"], indirect=True)
 def test_dynamic_fixture(dynamic_fixture):
     assert dynamic_fixture in ["Data from fixture A", "Data from fixture B"]
Execution Trace - 9 Steps
StepActionSystem StateAssertionResult
1Test startspytest test runner initialized-PASS
2pytest collects test_dynamic_fixture with parameter 'a'Test function ready to run with dynamic_fixture param 'a'-PASS
3pytest calls dynamic_fixture fixture with param 'a'Inside dynamic_fixture, param is 'a'-PASS
4dynamic_fixture calls fixture_a using getfixturevaluefixture_a returns 'Data from fixture A'-PASS
5test_dynamic_fixture runs with dynamic_fixture='Data from fixture A'Test function executingAssert dynamic_fixture is in ['Data from fixture A', 'Data from fixture B']PASS
6pytest collects test_dynamic_fixture with parameter 'b'Test function ready to run with dynamic_fixture param 'b'-PASS
7pytest calls dynamic_fixture fixture with param 'b'Inside dynamic_fixture, param is 'b'-PASS
8dynamic_fixture calls fixture_b using getfixturevaluefixture_b returns 'Data from fixture B'-PASS
9test_dynamic_fixture runs with dynamic_fixture='Data from fixture B'Test function executingAssert dynamic_fixture is in ['Data from fixture A', 'Data from fixture B']PASS
Failure Scenario
Failing Condition: dynamic_fixture receives an unsupported parameter value
Execution Trace Quiz - 3 Questions
Test your understanding
What does the dynamic_fixture fixture do when the parameter is 'a'?
AIt returns the value from fixture_a
BIt returns the value from fixture_b
CIt skips the test
DIt raises an error
Key Result
Using dynamic fixture selection with request.param and getfixturevalue allows flexible test setups based on parameters, improving test reuse and clarity.