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.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 14 views 0 copies

Requires third-party packages — install first
pip install pytest

Python code

19 lines
Python 3.9+
import 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

stdout
============================= 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

  1. Use `@pytest.mark.parametrize` with separate decorators for each parameter to test combinations (cartesian product)
  2. 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

Run locally

This sample needs third-party packages, so it cannot run in the browser IDE. Copy the code above, install the packages shown at the top, then run it in your own Python environment.

More from Testing & modern typing

Related tutorials and quizzes for this topic.