How to Parametrize pytest Tests with Multiple Input Cases in Python
This code shows how to use pytest's @pytest.mark.parametrize decorator to run the same test function across multiple input-output combinations, checking that an add function behaves correctly for each case.
pip install pytest
Python code
19 linesimport pytest
def add(a, b):
return a + b
@pytest.mark.parametrize("a,b,expected", [
(1, 2, 3),
(5, 5, 10),
(-1, 1, 0),
(0, 0, 0),
(10, -3, 7),
])
def test_add(a, b, expected):
assert add(a, b) == expected
if __name__ == "__main__":
pytest.main([__file__, "-v"])
Output
============================= test session starts ==============================
platform linux -- Python 3.11.3, pytest-8.2.2, pluggy-1.5.0
rootdir: /home/user
collected 5 items
test_add.py::test_add[1-2-3] PASSED
ntest_add.py::test_add[5-5-10] PASSED
test_add.py::test_add[-1-1-0] PASSED
test_add.py::test_add[0-0-0] PASSED
test_add.py::test_add[10--3-7] PASSED
============================== 5 passed in 0.01s ==============================
How it works
The @pytest.mark.parametrize decorator tells pytest to call test_add once for each tuple in the list, unpacking the values into the function parameters a, b, and expected. This avoids writing separate test functions for each case, keeping the test suite concise and readable. When a parameterized test fails, pytest reports the exact input combination that caused the failure, making debugging straightforward. Each parameter set is reported as an individual test item in the output, so you get precise pass/fail counts per case.
Common mistakes
- Forgetting to import pytest before using the decorator
- Mismatching the number of parameters in the decorator list with the function signature
- Not running pytest as a module (`python -m pytest`) when in a virtual environment
- Assuming parametrize values are evaluated lazily; they are evaluated at collection time
Variations
- Use `@pytest.mark.parametrize` with separate decorators for each parameter to test combinations (cartesian product)
- Move test data to an external file or use `pytest_generate_tests` for dynamic parametrization
Real-world use cases
- Testing a financial calculation function with a table of known inputs and expected outputs.
- Validating API response parsing across multiple sample payloads with different field values.
- Checking a data-cleaning function against a set of edge-case string inputs (empty, whitespace, special characters).
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.