0
0
PyTesttesting~5 mins

Dynamic fixture selection in PyTest

Choose your learning style9 modes available
Introduction

Dynamic fixture selection lets you choose which setup to use during a test run. This helps tests adapt to different needs without changing code.

When you want to run the same test with different data setups.
When tests need different resources based on input or environment.
When you want to reduce duplicate code by reusing fixtures smartly.
When you want to select fixtures based on command line options.
When you want to test multiple configurations in one test function.
Syntax
PyTest
import pytest

@pytest.fixture(params=["option1", "option2"])
def dynamic_fixture(request):
    if request.param == "option1":
        return "Setup for option 1"
    else:
        return "Setup for option 2"


def test_example(dynamic_fixture):
    assert dynamic_fixture in ["Setup for option 1", "Setup for option 2"]

The params argument lets pytest run the test multiple times with each parameter.

The request object helps access the current parameter value inside the fixture.

Examples
This runs the test twice, once with "chrome" and once with "firefox" as the browser.
PyTest
import pytest

@pytest.fixture(params=["chrome", "firefox"])
def browser(request):
    return f"Browser: {request.param}"


def test_browser(browser):
    print(browser)
This fixture chooses config based on a command line option --env.
PyTest
import pytest

@pytest.fixture
def config(request):
    if request.config.getoption('--env') == 'prod':
        return "Production config"
    else:
        return "Test config"


def test_config(config):
    assert "config" in config
Sample Program

This test runs three times, once for each environment. It prints the environment and checks the string format.

PyTest
import pytest

@pytest.fixture(params=["dev", "staging", "prod"])
def environment(request):
    return f"Environment: {request.param}"


def test_environment(environment):
    print(environment)
    assert environment.startswith("Environment:")
OutputSuccess
Important Notes

Dynamic fixtures help run tests with many setups without writing multiple test functions.

Use request.param to get the current parameter inside the fixture.

Remember to keep fixtures simple and focused on setup tasks.

Summary

Dynamic fixture selection lets tests run with different setups automatically.

Use params in fixtures to define multiple options.

Access the current option with request.param inside the fixture.