0
0
PytestHow-ToBeginner ยท 3 min read

How to Use @pytest.mark.parametrize for Parameterized Tests

Use @pytest.mark.parametrize to run a test function multiple times with different input values. It takes two arguments: a string of parameter names and a list of tuples with values. This helps test many cases easily without writing separate test functions.
๐Ÿ“

Syntax

The @pytest.mark.parametrize decorator requires two main parts:

  • Parameter names: A string with one or more variable names separated by commas.
  • Values list: A list of tuples, where each tuple contains values matching the parameter names.

Each tuple runs the test once with those values.

python
@pytest.mark.parametrize("input,expected", [(1, 2), (3, 4), (5, 6)])
def test_example(input, expected):
    assert input + 1 == expected
๐Ÿ’ป

Example

This example shows a test that checks if adding 1 to a number gives the expected result. The test runs three times with different inputs and expected outputs.

python
import pytest

@pytest.mark.parametrize("input,expected", [
    (1, 2),
    (3, 4),
    (5, 6),
])
def test_add_one(input, expected):
    assert input + 1 == expected
Output
============================= test session starts ============================== collected 3 items test_add_one.py ... [100%] ============================== 3 passed in 0.01s ===============================
โš ๏ธ

Common Pitfalls

Common mistakes when using @pytest.mark.parametrize include:

  • Not matching the number of parameters in the string with the values in tuples.
  • Using mutable default arguments inside the test function.
  • Passing a single tuple instead of a list of tuples.

Always ensure parameter names and values align exactly.

python
import pytest

# Wrong: values not in a list
@pytest.mark.parametrize("x,y", (1, 2))
def test_wrong(x, y):
    assert x + y == 3

# Right: values inside a list of tuples
@pytest.mark.parametrize("x,y", [(1, 2)])
def test_right(x, y):
    assert x + y == 3
๐Ÿ“Š

Quick Reference

PartDescriptionExample
Parameter namesComma-separated string of variable names"input, expected"
Values listList of tuples with values for each test run[(1, 2), (3, 4)]
Test functionFunction with parameters matching namesdef test_func(input, expected): ...
โœ…

Key Takeaways

Use @pytest.mark.parametrize to run one test with many input sets easily.
Match parameter names exactly with values in each tuple.
Provide values as a list of tuples, not a single tuple.
Each tuple runs the test once with those values.
Avoid mutable defaults inside parameterized test functions.