Parametrize
@pytest.mark.parametrize runs one test function many times with different arguments. Each tuple is a case with its own name in the report.
Detailed Explanation
A table of examples is clearer than ten tests that differ by one number. Parametrize declares the parameter names and a list of values. pytest generates one node per row. A failure shows the row, not just "test_tax failed".
@pytest.mark.parametrize("cents,expected", [(100, 120), (0, 0)]) injects cents and expected. You can stack the decorator for a cartesian product, which grows fast — use it when you mean a product. ids= labels rows. pytest.param(..., marks=pytest.mark.xfail) marks one row.
Parametrize can feed fixtures with indirect=True, or you can parametrize a fixture itself so every test that uses the fixture runs per value. Prefer parametrizing the test unless several tests share the same table.
unittest's subTest is the cousin: one method, a loop, failures recorded per iteration. Parametrize makes each row a first-class collected test, which plays better with -k, xfail, and parallel runners.
Keep rows dumb. Do not put logic in the table that the test then repeats. If setup differs wildly per row, you want separate tests or a fixture factory, not a parameter that is sometimes a database.
A failed row should still leave enough context. Include the input in the assertion message if the values are not obvious in the parameter list. assert tax(cents) == expected already prints both sides.
Code Examples
import pytest
def tax(cents: int) -> int:
return int(cents * 1.2)
@pytest.mark.parametrize(
"cents,expected",
[
(0, 0),
(100, 120),
(999, 1198),
],
ids=["zero", "one-dollar", "odd"],
)
def test_tax(cents, expected):
assert tax(cents) == expected@pytest.mark.parametrize("raw", ["", "x", "12x"])
def test_bad_int(raw):
with pytest.raises(ValueError):
int(raw)Common Gotchas
Cartesian stacking by accident
two parametrize decorators multiply cases. Merge into one table if you did not want a product.
Mutable parameters shared across rows
a list in the table is one object. Use tuples, or build a new list in the test.
Huge tables hide the interesting case
extract the weird row into its own named test.
`subTest` does not create extra nodes
CI that reruns failed node ids works more cleanly with parametrize.