Parametrised Tests: One Test, Many Cases

Parametrised Tests: One Test, Many Cases in Python: Here is a test everyone writes at some point: It looks thorough.

Concept Explanation

Here is a test everyone writes at some point:

def test_is_even():
    assert is_even(2) is True
    assert is_even(4) is True
    assert is_even(3) is False
    assert is_even(-1) is False
    assert is_even(0) is True

It looks thorough. It is actually the worst version of this test, for one reason: the first failing assertion stops the function. If is_even(4) breaks, you never find out whether the negative-number cases pass. You get one red test and no information about scope.

@pytest.mark.parametrize splits that into five independent tests from the same body:

import pytest

@pytest.mark.parametrize("number, expected", [
    (2, True),
    (4, True),
    (3, False),
    (-1, False),
    (0, True),
])
def test_is_even(number, expected):
    assert is_even(number) is expected

Now a broken is_even reports 3 passed, 2 failed and names exactly which inputs failed. Same lines of code, far more diagnostic value.

The Syntax

@pytest.mark.parametrize("arg1, arg2", [(v1, v2), (v3, v4)])
  • First argument: a comma-separated string of parameter names, matching the test function's parameters.
  • Second argument: a list of tuples, one per case. A single parameter can use bare values instead of one-tuples.

Naming Cases with pytest.param

Pytest generates ids from the values, which gets unreadable for long strings or objects. Name them yourself:

@pytest.mark.parametrize("raw, expected", [
    pytest.param("2024-01-15", date(2024, 1, 15), id="iso_format"),
    pytest.param("15/01/2024", date(2024, 1, 15), id="uk_format"),
    pytest.param("garbage", None, id="unparseable"),
])
def test_parse_date(raw, expected):
    assert parse_date(raw) == expected

Run with -v and you see test_parse_date[iso_format] — a test name you can read in CI output and re-run individually.

Stacking Decorators Multiplies Cases

@pytest.mark.parametrize("x", [1, 2, 3])
@pytest.mark.parametrize("y", [10, 20])
def test_combinations(x, y):
    ...        # runs 6 times: every x paired with every y

Useful for genuine matrices. Dangerous otherwise — three stacked decorators of five values each is 125 tests, and most of them tell you nothing new.

Expected Failures Belong in the Table

@pytest.mark.parametrize("value, expected", [
    (10, 3.16),
    pytest.param(-1, None, marks=pytest.mark.xfail(raises=ValueError)),
])
def test_sqrt(value, expected):
    assert round(sqrt(value), 2) == expected

Code Example #1 (Basic)

Testing a validator across its whole input space.

# password.py
import re

def check_password(password: str) -> list[str]:
    """Return a list of problems. Empty list means the password is acceptable."""
    problems = []
    if len(password) < 8:
        problems.append("too_short")
    if not re.search(r"[A-Z]", password):
        problems.append("no_uppercase")
    if not re.search(r"[0-9]", password):
        problems.append("no_digit")
    if password.lower() in {"password", "letmein", "qwerty"}:
        problems.append("too_common")
    return problems
# test_password.py
import pytest
from password import check_password

@pytest.mark.parametrize("password, expected", [
    pytest.param("Str0ngPass",   [],                            id="valid"),
    pytest.param("Sh0rt",        ["too_short"],                 id="five_chars"),
    pytest.param("alllower123",  ["no_uppercase"],              id="missing_upper"),
    pytest.param("NoDigitsHere", ["no_digit"],                  id="missing_digit"),
    pytest.param("abc",          ["too_short", "no_uppercase", "no_digit"], id="three_problems"),
    pytest.param("Password",     ["no_digit", "too_common"],    id="common_word"),
    pytest.param("",             ["too_short", "no_uppercase", "no_digit"], id="empty"),
])
def test_check_password(password, expected):
    assert check_password(password) == expected

Seven named tests from one function body. pytest -v prints each id, so a regression tells you which rule broke, not just that something did.

Code Example #2 (Intermediate)

Combining parametrisation with fixtures, and generating cases programmatically.

import pytest
from decimal import Decimal

# ---- A parametrised FIXTURE: every test using it runs once per backend ----
@pytest.fixture(params=["memory", "temp_file"])
def store(request, tmp_path):
    """Yields a store implementation; the test body never changes."""
    if request.param == "memory":
        yield {}
    else:
        import shelve
        with shelve.open(str(tmp_path / "db")) as shelf:
            yield shelf

def test_round_trip(store):
    store["key"] = "value"
    assert store["key"] == "value"      # runs twice: once per backend


# ---- Generating cases from data ----
TAX_BANDS = [
    (Decimal("0"),      Decimal("0.00")),
    (Decimal("10000"),  Decimal("0.00")),
    (Decimal("25000"),  Decimal("2500.00")),
    (Decimal("60000"),  Decimal("13000.00")),
]

@pytest.mark.parametrize(
    "income, expected_tax",
    TAX_BANDS,
    ids=[f"income_{int(income)}" for income, _ in TAX_BANDS],
)
def test_tax_bands(income, expected_tax):
    assert calculate_tax(income) == expected_tax


# ---- indirect parametrisation: the value goes to the fixture, not the test ----
@pytest.fixture
def user(request):
    return {"name": "test", "role": request.param}

@pytest.mark.parametrize("user", ["admin", "editor", "viewer"], indirect=True)
def test_permissions(user):
    assert can_read(user) is True

Three distinct techniques worth knowing apart: a parametrised fixture multiplies every test that consumes it, an ids= list keeps generated names readable, and indirect=True routes the parameter through a fixture so it can be turned into a real object before the test sees it.


Common Mistakes

  1. Mismatched names: the string "number, expected" must match the function's parameters exactly. A typo produces fixture 'expcted' not found, which reads like a fixture bug rather than a spelling one.
  2. Mutable values in the parameter list: [({}, 1), ({}, 2)] shares those dicts across the whole session, so one test mutating it corrupts another. Build mutable objects inside the test or a fixture.
  3. Stacking decorators without doing the arithmetic: three parametrize decorators of five values each is 125 tests. Check whether you need the full cross product or just a few representative pairs.
  4. Cramming logic into the test body: if expected is None: with pytest.raises(...) means you have two tests wearing one coat. Split them.
  5. Forgetting ids for non-trivial values: test_parse[<Foo object at 0x7f2>] cannot be re-run from the terminal and tells you nothing.
  6. Parametrising the assertion instead of the input: if each case needs a different check, they are different tests. Parametrisation is for the same logic over different data.

Best Practices

  • One assertion concept per test: parametrise the inputs, keep the check identical.
  • Give every non-obvious case an id: id="empty_string" beats [""] in a CI log.
  • Put the edge cases in the table: empty, zero, negative, maximum, None, and the boundary value on each side. A parametrised test makes adding a regression case a one-line change — which is exactly why bug fixes should land as a new row.
  • Keep case data next to the test: a module-level list is fine; a JSON file two directories away is not.
  • Use parametrised fixtures to test across backends: the same suite proving your code works on both SQLite and PostgreSQL is enormous value for four lines.
  • Run pytest --collect-only -q when a matrix surprises you — it lists every generated test without running anything.
  • Mark slow cases: marks=pytest.mark.slow lets developers run -m "not slow" locally while CI runs everything.

Practice Exercises

  1. The Refactor: Take a test containing five sequential asserts and convert it to a parametrised test with named ids. Break the function deliberately and compare the two failure reports.
  2. The Edge Case Sweep: Write parse_duration("1h30m") -> 5400, then parametrise its test with at least eight cases including empty string, whitespace, missing units, an invalid unit, and zero — using pytest.raises inside the table via marks=pytest.mark.xfail where an error is correct.
  3. The Dual Backend: Write a parametrised fixture that yields both an in-memory dict and a real tmp_path file store, then write three tests that pass against both without a single if in the test bodies.