0
0
PyTesttesting~5 mins

Parametrized fixtures in PyTest

Choose your learning style9 modes available
Introduction

Parametrized fixtures let you run the same test with different data easily. This helps check many cases without writing repeated code.

You want to test a function with multiple input values.
You need to check how your code behaves with different settings.
You want to avoid writing many similar tests for different data.
You want to keep your tests clean and organized while testing many cases.
Syntax
PyTest
@pytest.fixture(params=[value1, value2, ...])
def fixture_name(request):
    return request.param

The params list holds all values to test with.

The fixture returns each value one by one to the test.

Examples
This fixture will provide 1, then 2, then 3 to tests using it.
PyTest
@pytest.fixture(params=[1, 2, 3])
def number(request):
    return request.param
This fixture gives the test "apple" first, then "banana".
PyTest
@pytest.fixture(params=["apple", "banana"])
def fruit(request):
    return request.param
Sample Program

This test uses the number fixture which runs the test three times with 10, 20, and 30. It checks if the number is even.

PyTest
import pytest

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


def test_is_even(number):
    assert (number % 2 == 0) == True
OutputSuccess
Important Notes

Each test using a parametrized fixture runs once per parameter value.

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

Parametrized fixtures help avoid repeating similar test code.

Summary

Parametrized fixtures run tests multiple times with different data.

They keep tests simple and avoid duplication.

Use @pytest.fixture(params=[...]) and request.param to access values.