Lesson 3 of 9 · 21m
Parametrization Without Megatests
Use @pytest.mark.parametrize to turn repetitive tests into case tables while preserving clear names, diffs, and failure isolation.
New engineers often discover parametrization and immediately compress eighty tests into a wall of tuples no one can read. The goal is not fewer lines. The goal is one failure that points at one meaningful case.
The basic case table
import pytest
@pytest.mark.parametrize(
"raw,expected",
[
("sam@example.com", "sam@example.com"),
(" sam@example.com ", "sam@example.com"),
("SAM@example.com", "sam@example.com"),
],
)
def test_normalize_email(raw, expected):
assert normalize_email(raw) == expectedpytest creates one test per row. Each row fails independently, which is the entire point. A loop inside one test would stop at the first bad case and hide the rest.
IDs are failure messages
Without IDs, pytest invents names like test_normalize_email[raw0-expected0]. That is useless in CI at 2 a.m. Give cases meaningful labels:
@pytest.mark.parametrize(
"raw,expected",
[
pytest.param("sam@example.com", "sam@example.com", id="already-normal"),
pytest.param(" sam@example.com ", "sam@example.com", id="trim-whitespace"),
pytest.param("SAM@example.com", "sam@example.com", id="lowercase-local-part"),
],
)
def test_normalize_email(raw, expected):
assert normalize_email(raw) == expectedThe ID should describe the input condition, not repeat the expected result.
Parametrize inputs, not behavior switches
A parametrized test is healthy when every row exercises the same behavior with different data. It becomes a megatest when rows carry flags that change what is being asserted:
# bad: two behaviors hiding in one test
@pytest.mark.parametrize("payload,expect_error", [(valid, False), (bad, True)])
def test_import(payload, expect_error):
...Split those. Error behavior and success behavior deserve separate tests because they have different contracts.
Stack parametrization sparingly
Multiple decorators produce a cartesian product:
@pytest.mark.parametrize("method", ["GET", "POST"])
@pytest.mark.parametrize("role", ["member", "admin"])
def test_permissions(method, role):
...This creates four tests. It is elegant for truly orthogonal dimensions and disastrous when some combinations are meaningless. If you are writing comments like "this case does not apply," use explicit tuples instead.
Field notes
- Keep one concept per parameter list; giant rows with six positional values are hard to review.
- Use dictionaries or small dataclasses for complex cases instead of tuple unpacking puzzles.
- Put edge cases in the table only when they test the same contract; otherwise write a named test.
pytest -k normalizecan select a family of parametrized tests quickly.- A skipped or expected-failing row can use
pytest.param(..., marks=pytest.mark.xfail(reason="..."))with a real reason.
Was this lesson helpful?