Parameterized tests
suggest changeA parameterized test is one test function that runs many times, once for each set of inputs. Instead of copying the same test body for every case, you write the logic once and list the cases as data.
Each case is reported as a separate test, so when one case fails you see exactly which inputs broke and the other cases still run.
This article covers:
@pytest.mark.parametrizewith one or more arguments- readable test IDs
- marking individual cases as
xfailorskip - testing for exceptions in a table of cases
- stacking decorators to get every combination
- parameterizing classes and whole modules
- parameterized fixtures and
indirect - generating cases dynamically with
pytest_generate_testsand loading them from files subTestinunittest, and thesubtestsfixture- common pitfalls
The examples use pytest 9. See Unit tests with pytest and Intro to Test Fixtures for pytest basics.
The problem
Here's a small function we want to test:
# slug.py
import re
def slugify(text: str) -> str:
text = text.strip().lower()
text = re.sub(r"[^a-z0-9]+", "-", text)
return text.strip("-")
The naive approach is one test per case, or one test with many asserts:
def test_slugify():
assert slugify("Hello World") == "hello-world"
assert slugify(" padded ") == "padded"
assert slugify("Python 3.13!") == "python-3-13"
Both are bad. Separate functions are repetitive. A single test stops at the first failing assert, so you don't know whether the cases after it pass or fail.
pytest.mark.parametrize
@pytest.mark.parametrize takes the argument names and a list of values. pytest calls the test once per value:
# test_basic.py
import pytest
from slug import slugify
@pytest.mark.parametrize(
"text, expected",
[
("Hello World", "hello-world"),
(" padded ", "padded"),
("Python 3.13!", "python-3-13"),
("already-a-slug", "already-a-slug"),
("", ""),
],
)
def test_slugify(text, expected):
assert slugify(text) == expected
$ pytest -v test_basic.py
test_basic.py::test_slugify[Hello World-hello-world] PASSED [ 20%]
test_basic.py::test_slugify[ padded -padded] PASSED [ 40%]
test_basic.py::test_slugify[Python 3.13!-python-3-13] PASSED [ 60%]
test_basic.py::test_slugify[already-a-slug-already-a-slug] PASSED [ 80%]
test_basic.py::test_slugify[-] PASSED [100%]
============================== 5 passed in 0.56s ==============================
The argument names can be a comma-separated string ("text, expected") or a list/tuple of strings (["text", "expected"]). Each item in the list of values is a tuple with one value per argument. With a single argument, the values don't need to be tuples:
@pytest.mark.parametrize("n", [0, 1, 2, 100])
def test_square_is_non_negative(n):
assert n * n >= 0
What a failure looks like
When a case fails, pytest shows its ID and the argument values:
# test_fail.py
import pytest
def is_leap(year: int) -> bool:
return year % 4 == 0 # buggy: ignores the century rule
@pytest.mark.parametrize("year, expected", [
(2024, True),
(2023, False),
(1900, False),
(2000, True),
])
def test_is_leap(year, expected):
assert is_leap(year) == expected
$ pytest -q test_fail.py
..F. [100%]
================================== FAILURES ===================================
__________________________ test_is_leap[1900-False] ___________________________
year = 1900, expected = False
...
> assert is_leap(year) == expected
E assert True == False
E + where True = is_leap(1900)
test_fail.py:13: AssertionError
=========================== short test summary info ===========================
FAILED test_fail.py::test_is_leap[1900-False] - assert True == False
1 failed, 3 passed in 0.03s
The case for 2000 still ran and passed, even though the case before it failed.
Test IDs
pytest builds an ID for each case from the argument values. Numbers, strings, booleans and None are used as they are. Other objects get the argument name plus an index, which doesn't tell you much:
from datetime import timedelta
import pytest
def parse_duration(s: str) -> timedelta:
units = {"s": "seconds", "m": "minutes", "h": "hours", "d": "days"}
value, unit = s[:-1], s[-1:]
if unit not in units or not value.isdigit():
raise ValueError(f"bad duration: {s!r}")
return timedelta(**{units[unit]: int(value)})
CASES = [
("30s", timedelta(seconds=30)),
("5m", timedelta(minutes=5)),
("2h", timedelta(hours=2)),
]
@pytest.mark.parametrize("text, expected", CASES)
def test_default_ids(text, expected):
assert parse_duration(text) == expected
test_ids.py::test_default_ids[30s-expected0] PASSED
test_ids.py::test_default_ids[5m-expected1] PASSED
test_ids.py::test_default_ids[2h-expected2] PASSED
You can control the IDs in three ways.
A list of strings, one per case:
@pytest.mark.parametrize("text, expected", CASES, ids=["seconds", "minutes", "hours"])
def test_list_ids(text, expected):
assert parse_duration(text) == expected
test_ids.py::test_list_ids[seconds] PASSED
test_ids.py::test_list_ids[minutes] PASSED
test_ids.py::test_list_ids[hours] PASSED
A function, called for each value. Return a string, or None to keep the default ID for that value:
def idfn(value):
if isinstance(value, timedelta):
return f"{value.total_seconds():g}sec"
return None
@pytest.mark.parametrize("text, expected", CASES, ids=idfn)
def test_callable_ids(text, expected):
assert parse_duration(text) == expected
test_ids.py::test_callable_ids[30s-30sec] PASSED
test_ids.py::test_callable_ids[5m-300sec] PASSED
test_ids.py::test_callable_ids[2h-7200sec] PASSED
pytest.param(..., id=...), which keeps each ID next to its case. This is the easiest to maintain when the list is long:
@pytest.mark.parametrize(
"text, expected",
[
pytest.param("1d", timedelta(days=1), id="one-day"),
pytest.param("90m", timedelta(hours=1, minutes=30), id="minutes-overflow"),
],
)
def test_param_ids(text, expected):
assert parse_duration(text) == expected
test_ids.py::test_param_ids[one-day] PASSED
test_ids.py::test_param_ids[minutes-overflow] PASSED
Good IDs pay off: they show up in failure reports and CI logs, and you can use them to select tests.
Non-ASCII characters in IDs are escaped by default (Zażółć becomes Za\u017c\xf3\u0142\u0107), which is another reason to give such cases an explicit ID.
Selecting cases
Every case has a node ID that you can pass on the command line to run just that case:
$ pytest "test_ids.py::test_list_ids[minutes]"
-k matches against test names and IDs:
$ pytest test_basic.py -k "padded or World" -v
test_basic.py::test_slugify[Hello World-hello-world] PASSED [ 50%]
test_basic.py::test_slugify[ padded -padded] PASSED [100%]
======================= 2 passed, 3 deselected in 0.02s =======================
To list all generated cases without running them, use pytest --collect-only -q.
Marking individual cases
pytest.param also takes marks, so you can mark a single case as an expected failure or skip it without touching the others:
import sys
import pytest
from slug import slugify
@pytest.mark.parametrize(
"text, expected",
[
("Hello World", "hello-world"),
pytest.param("Zażółć gęślą", "zazolc-gesla", id="polish",
marks=pytest.mark.xfail(reason="no transliteration yet")),
pytest.param("x" * 300, "x" * 100, id="very-long",
marks=pytest.mark.skip(reason="length limit not decided")),
pytest.param("tab\there", "tab-here",
marks=pytest.mark.skipif(sys.version_info < (3, 12), reason="needs 3.12+")),
],
)
def test_slugify(text, expected):
assert slugify(text) == expected
$ pytest -q -rxs test_marks.py
=========================== short test summary info ===========================
XFAIL test_marks.py::test_slugify[polish] - no transliteration yet
SKIPPED [1] test_marks.py:5: length limit not decided
2 passed, 1 skipped, 1 xfailed in 0.06s
This is a good way to record a known bug as a test case before you fix it. Once the fix lands, the xfail case starts passing and is reported as XPASS. Add strict=True to the xfail mark, or set xfail_strict = true in your config, and an unexpected pass counts as a failure, which reminds you to remove the mark.
Testing exceptions
For a list of inputs that should all be rejected, put pytest.raises in the test body:
@pytest.mark.parametrize("bad", ["", "5", "abc", "-3m", "10x"])
def test_parse_duration_rejects(bad):
with pytest.raises(ValueError, match="bad duration"):
parse_duration(bad)
Cases like these find bugs. An earlier version of parse_duration used s[-1] instead of s[-1:], and the "" case failed with IndexError instead of ValueError.
To mix valid and invalid inputs in one table, make the expected outcome a context manager. contextlib.nullcontext stands in for "no exception":
from contextlib import nullcontext as does_not_raise
import pytest
def divide(a, b):
return a / b
@pytest.mark.parametrize(
"a, b, expectation",
[
(6, 3, does_not_raise()),
(1, 0, pytest.raises(ZeroDivisionError)),
("6", 3, pytest.raises(TypeError)),
],
)
def test_divide(a, b, expectation):
with expectation:
assert divide(a, b) is not None
test_raises.py::test_divide[6-3-expectation0] PASSED
test_raises.py::test_divide[1-0-expectation1] PASSED
test_raises.py::test_divide[6-3-expectation2] PASSED
Use this sparingly. When a test has to branch on what kind of case it got, two separate tests (one for valid inputs, one for invalid) are usually easier to read. See Testing Exceptions for more on pytest.raises.
Stacking decorators: all combinations
When you stack several parametrize decorators, pytest runs the test for every combination of values (the cartesian product):
import json
import pytest
@pytest.mark.parametrize("indent", [None, 2])
@pytest.mark.parametrize("sort_keys", [False, True])
@pytest.mark.parametrize("value", [{"b": 1, "a": [1, 2]}, [], "text"])
def test_json_roundtrip(value, sort_keys, indent):
text = json.dumps(value, sort_keys=sort_keys, indent=indent)
assert json.loads(text) == value
test_stack.py::test_json_roundtrip[value0-False-None] PASSED
test_stack.py::test_json_roundtrip[value0-False-2] PASSED
test_stack.py::test_json_roundtrip[value0-True-None] PASSED
test_stack.py::test_json_roundtrip[value0-True-2] PASSED
test_stack.py::test_json_roundtrip[value1-False-None] PASSED
...
test_stack.py::test_json_roundtrip[text-True-2] PASSED
============================= 12 passed in 0.03s ==============================
3 values x 2 x 2 = 12 tests. The count grows quickly, so stack only parameters that really interact. If a parameter has nothing to do with the others, give it a separate test.
Parameterizing a class or a module
A parametrize mark on a class applies to every test method in it. To parameterize every test in a module, assign the mark to a module-level variable named pytestmark:
import pytest
pytestmark = pytest.mark.parametrize("n", [0, 1, 255])
def test_non_negative(n):
assert n >= 0
@pytest.mark.parametrize("base, spec", [(2, "b"), (8, "o"), (16, "x")])
class TestFormatting:
def test_roundtrip(self, n, base, spec):
assert int(format(n, spec), base) == n
def test_not_empty(self, n, base, spec):
assert format(n, spec) != ""
$ pytest --collect-only -q test_class.py
test_class.py::test_non_negative[0]
test_class.py::test_non_negative[1]
test_class.py::test_non_negative[255]
test_class.py::TestFormatting::test_roundtrip[2-b-0]
test_class.py::TestFormatting::test_roundtrip[2-b-1]
test_class.py::TestFormatting::test_roundtrip[2-b-255]
...
21 tests collected
Every test in the module must accept n, otherwise pytest reports an error. The class methods get both parameter sets: 3 x 3 x 2 = 18 tests, plus 3 for test_non_negative.
Parameterized fixtures
parametrize varies a test's inputs. A parameterized fixture varies the environment the tests run in. Every test that uses the fixture runs once for each fixture parameter, and the fixture can do setup and teardown.
A typical use is running the same tests against several implementations of an interface:
import sqlite3
import pytest
class MemoryStore:
def __init__(self):
self._data = {}
def put(self, key, value):
self._data[key] = value
def get(self, key):
return self._data.get(key)
def close(self):
pass
class SqliteStore:
def __init__(self):
self._db = sqlite3.connect(":memory:")
self._db.execute("CREATE TABLE kv (key TEXT PRIMARY KEY, value TEXT)")
def put(self, key, value):
self._db.execute("INSERT OR REPLACE INTO kv VALUES (?, ?)", (key, value))
def get(self, key):
row = self._db.execute("SELECT value FROM kv WHERE key = ?", (key,)).fetchone()
return row[0] if row else None
def close(self):
self._db.close()
@pytest.fixture(params=[MemoryStore, SqliteStore], ids=["memory", "sqlite"])
def store(request):
s = request.param() # the current parameter
yield s
s.close()
def test_get_missing(store):
assert store.get("nope") is None
def test_put_then_get(store):
store.put("lang", "python")
assert store.get("lang") == "python"
def test_overwrite(store):
store.put("k", "v1")
store.put("k", "v2")
assert store.get("k") == "v2"
test_fixture.py::test_get_missing[memory] PASSED [ 16%]
test_fixture.py::test_get_missing[sqlite] PASSED [ 33%]
test_fixture.py::test_put_then_get[memory] PASSED [ 50%]
test_fixture.py::test_put_then_get[sqlite] PASSED [ 66%]
test_fixture.py::test_overwrite[memory] PASSED [ 83%]
test_fixture.py::test_overwrite[sqlite] PASSED [100%]
The tests don't know there are two stores. When you add a third implementation, add it to params and every test covers it.
params can contain pytest.param(...) entries too, with their own id and marks.
indirect: passing parameters through a fixture
Sometimes each case needs setup that a plain value can't provide, like a file on disk. With indirect, pytest passes the value to the fixture with the same name (as request.param) instead of straight to the test, and the test gets whatever the fixture returns:
import pytest
@pytest.fixture
def config_file(request, tmp_path):
path = tmp_path / "app.ini"
path.write_text(request.param)
return path
def read_port(path):
for line in path.read_text().splitlines():
key, _, value = line.partition("=")
if key.strip() == "port":
return int(value)
return 8080
@pytest.mark.parametrize(
"config_file, expected",
[
("port = 9000\n", 9000),
("host = example.com\n", 8080),
("host = x\nport=1234\n", 1234),
],
indirect=["config_file"],
)
def test_read_port(config_file, expected):
assert read_port(config_file) == expected
test_indirect.py::test_read_port[port = 9000\n-9000] PASSED
test_indirect.py::test_read_port[host = example.com\n-8080] PASSED
test_indirect.py::test_read_port[host = x\nport=1234\n-1234] PASSED
indirect=["config_file"] sends only that argument through the fixture, while expected goes straight to the test. indirect=True would send all of them.
Loading cases from a file
When there are many cases, or people who don't write Python maintain them, keep them in a data file and load it when the module is imported:
[
{"number": 1, "roman": "I"},
{"number": 4, "roman": "IV"},
{"number": 9, "roman": "IX"},
{"number": 1994, "roman": "MCMXCIV"}
]
import json
from pathlib import Path
import pytest
def to_roman(n: int) -> str:
table = [(1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"),
(90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"),
(5, "V"), (4, "IV"), (1, "I")]
out = []
for value, letters in table:
count, n = divmod(n, value)
out.append(letters * count)
return "".join(out)
CASES = json.loads((Path(__file__).parent / "data" / "roman.json").read_text())
@pytest.mark.parametrize("case", CASES, ids=lambda c: c["roman"])
def test_to_roman(case):
assert to_roman(case["number"]) == case["roman"]
test_data.py::test_to_roman[I] PASSED
test_data.py::test_to_roman[IV] PASSED
test_data.py::test_to_roman[IX] PASSED
test_data.py::test_to_roman[MCMXCIV] PASSED
Build the path from __file__ so the tests work no matter which directory you run pytest from.
pytest_generate_tests: deciding at collection time
The pytest_generate_tests hook lets you compute parameters while pytest collects tests, for example from a command-line option. Put it in conftest.py:
# conftest.py
def pytest_addoption(parser):
parser.addoption("--locales", default="en_US", help="comma-separated locales")
def pytest_generate_tests(metafunc):
if "locale_name" in metafunc.fixturenames:
locales = metafunc.config.getoption("locales").split(",")
metafunc.parametrize("locale_name", locales)
# test_gen.py
def test_locale_format(locale_name):
lang, _, region = locale_name.partition("_")
assert lang.islower() and region.isupper()
$ pytest -v test_gen.py --locales=en_US,de_DE,pl_PL
test_gen.py::test_locale_format[en_US] PASSED [ 33%]
test_gen.py::test_locale_format[de_DE] PASSED [ 66%]
test_gen.py::test_locale_format[pl_PL] PASSED [100%]
Without the option, only en_US runs. metafunc.parametrize takes the same arguments as the decorator (ids, indirect and so on).
unittest: subTest
The standard library's unittest has no decorator for this. Instead, self.subTest() marks a block inside a loop as its own sub-test. A failing sub-test is reported with its parameters, and the loop keeps going:
import unittest
def is_leap(year: int) -> bool:
return year % 4 == 0 # buggy: ignores the century rule
class TestLeap(unittest.TestCase):
def test_is_leap(self):
cases = [(2024, True), (2023, False), (1900, False), (2100, False), (2000, True)]
for year, expected in cases:
with self.subTest(year=year):
self.assertEqual(is_leap(year), expected)
if __name__ == "__main__":
unittest.main()
$ python test_sub.py
FF
======================================================================
FAIL: test_is_leap (__main__.TestLeap.test_is_leap) (year=1900)
----------------------------------------------------------------------
Traceback (most recent call last):
...
AssertionError: True != False
======================================================================
FAIL: test_is_leap (__main__.TestLeap.test_is_leap) (year=2100)
----------------------------------------------------------------------
Traceback (most recent call last):
...
AssertionError: True != False
----------------------------------------------------------------------
Ran 1 test in 0.001s
FAILED (failures=2)
Both failing years are reported, not just the first one. Unlike pytest's cases, sub-tests are not separate tests: you can't select or re-run just one.
Since version 9.0, pytest understands subTest too, and it has a subtests fixture that does the same thing in plain pytest functions. It's useful when you only know the cases at run time, for example the files in a directory:
def test_all_files_are_valid_toml(subtests, tmp_path):
import tomllib
(tmp_path / "a.toml").write_text('name = "a"\n')
(tmp_path / "b.toml").write_text('name = \n')
(tmp_path / "c.toml").write_text('[tool]\nx = 1\n')
for path in sorted(tmp_path.glob("*.toml")):
with subtests.test(file=path.name):
tomllib.loads(path.read_text())
SUBFAILED(file='b.toml') test_subtests.py::test_all_files_are_valid_toml - to...
FAILED test_subtests.py::test_all_files_are_valid_toml - contains 1 failed su...
2 failed, 2 subtests passed in 0.08s
If you know the cases when the tests are collected, prefer parametrize: each case gets its own ID and you can run it by itself.
Pitfalls
Mutable parameter values are shared. pytest doesn't copy parameter values. When decorators are stacked, the same object is passed to every combination, so a test that changes it affects the cases that run after it:
@pytest.mark.parametrize("item", ["apple", "pear"])
@pytest.mark.parametrize("cart", [[]])
def test_add_to_cart(cart, item):
cart.append(item)
assert cart == [item]
FAILED test_mut.py::test_add_to_cart[cart0-pear] - AssertionError: assert ['a...
1 failed, 1 passed in 0.03s
The pear case got the list that the apple case had already appended to. Don't mutate parameters. Copy them in the test, or build fresh objects in a fixture.
Keep the test body free of logic. If the test needs if statements to work out what to expect for each case, the table is hiding several different tests. Split them up.
Watch the number of cases. Stacked decorators and parameterized fixtures multiply. A fixture with 3 params used by a test with two stacked parametrize decorators of 4 values each produces 48 tests. Check with pytest --collect-only -q | tail -1.
Expensive values are built at import time. The argument list is evaluated when the module is imported, even if you only run one unrelated test. Move expensive setup (database connections, large files) into a fixture and pass the cheap parameters through indirect.
Parameterized tests only check the cases you thought of. For checking properties over many generated inputs, look at property-based testing with the hypothesis package, which works together with pytest.