Parametrizing with indirect fixtures lets you run the same test with different setup data, making tests cleaner and easier to manage.
0
0
Parametrize with indirect fixtures in PyTest
Introduction
You want to test a function with multiple inputs that need special setup.
You have a fixture that prepares data or environment based on parameters.
You want to reuse fixture logic but vary its input for different test cases.
You need to separate test data from test logic for clarity.
You want to avoid repeating setup code for similar test scenarios.
Syntax
PyTest
@pytest.mark.parametrize('fixture_name', [param1, param2], indirect=True) def test_example(fixture_name): # test code using fixture_name
Use indirect=True to tell pytest to pass parameters to the fixture, not directly to the test.
The fixture must accept a request object to access the parameter.
Examples
This example doubles each parameter in the fixture, then tests if the result is even.
PyTest
@pytest.fixture def data(request): return request.param * 2 @pytest.mark.parametrize('data', [1, 2, 3], indirect=True) def test_double(data): assert data % 2 == 0
Fixture sets up environment mode based on parameter, test checks mode is correct.
PyTest
@pytest.fixture def setup_env(request): env = {'mode': request.param} return env @pytest.mark.parametrize('setup_env', ['dev', 'prod'], indirect=True) def test_env_mode(setup_env): assert setup_env['mode'] in ['dev', 'prod']
Sample Program
This test runs three times with numbers 10, 50, and 100. It prints the number and checks it is a multiple of 10.
PyTest
import pytest @pytest.fixture def number(request): # Multiply parameter by 10 return request.param * 10 @pytest.mark.parametrize('number', [1, 5, 10], indirect=True) def test_is_multiple_of_ten(number): print(f'Testing number: {number}') assert number % 10 == 0
OutputSuccess
Important Notes
Indirect parametrization helps when test inputs need processing before use.
Always ensure your fixture uses request.param to get the parameter value.
Use descriptive parameter names to keep tests readable.
Summary
Parametrize with indirect fixtures lets you pass parameters to fixtures, not directly to tests.
This approach helps separate setup logic from test logic.
It makes tests cleaner and easier to maintain when testing multiple inputs.