0
0
PyTesttesting~5 mins

Combining multiple parametrize decorators in PyTest

Choose your learning style9 modes available
Introduction

Combining multiple parametrize decorators lets you test many input combinations easily. It saves time and finds bugs faster.

You want to test a function with different sets of inputs for two or more parameters.
You need to check all combinations of two lists of values in your tests.
You want to avoid writing many similar test cases manually.
You want clear, organized tests that cover multiple scenarios.
You want to reuse parameter sets across different tests.
Syntax
PyTest
@pytest.mark.parametrize('param2', [values2])
@pytest.mark.parametrize('param1', [values1])
def test_function(param1, param2):
    # test code here

Each @pytest.mark.parametrize decorator adds a parameter and its values.

pytest runs the test for every combination of the parameters.

Examples
This runs 4 tests: (1,3), (1,4), (2,3), (2,4).
PyTest
@pytest.mark.parametrize('y', [3, 4])
@pytest.mark.parametrize('x', [1, 2])
def test_sum(x, y):
    assert x + y > 0
Tests all color and shape pairs.
PyTest
@pytest.mark.parametrize('shape', ['circle', 'square'])
@pytest.mark.parametrize('color', ['red', 'blue'])
def test_shape_color(color, shape):
    assert isinstance(shape, str) and isinstance(color, str)
Sample Program

This test runs 4 times with all combinations of a and b. It checks multiplication and prints the values.

PyTest
import pytest

@pytest.mark.parametrize('b', [10, 20])
@pytest.mark.parametrize('a', [1, 2])
def test_multiply(a, b):
    result = a * b
    assert result in [10, 20, 20, 40]
    print(f'Testing a={a}, b={b}, result={result}')
OutputSuccess
Important Notes

Order of decorators matters: the last decorator changes fastest.

Use descriptive parameter names for clarity.

Combining parametrize decorators creates a Cartesian product of parameters.

Summary

Multiple parametrize decorators test all combinations of parameters.

This helps cover many cases with less code.

It improves test coverage and saves time.