pytest parametrize Explained: 7 Patterns with Tested Examples
pytest parametrize runs one test function with many sets of inputs, so you write the logic once and add cases as data. Learn 7 practical patterns, from a basic list of cases to readable ids, expected failures and indirect fixtures, all run with pytest 9.2.
- pytest parametrize uses
@pytest.mark.parametrize("args", [cases])to run one test once per case. - Each case becomes its own test with its own pass or fail, so one bad input never hides the others.
- Give cases readable
ids; then-k zerosruns just that case. - Our file of 7 patterns collected 22 tests from 6 functions: 20 passed, 1 skipped and 1 expected failure, in 0.24 seconds.
Copy-pasting a test five times to check five inputs is slow to write and painful to maintain. A loop inside one test is worse: the first failure stops the loop and hides the rest. pytest parametrize solves both problems. Everything below was run with pytest 9.2.0 on Python 3.13.6, and the outputs are copied from that run. New to pytest? Start with our pytest tutorial.
Why parametrize tests?
- Less code: the test logic is written once.
- Clear failures: every case reports separately with its input in the name.
- Easy growth: a new edge case is one more line of data.
- Better design: it pairs naturally with equivalence partitioning and boundary value analysis, where you test one value from each class or edge.
1. A basic list of cases
import pytest
def is_valid_email(s):
return isinstance(s, str) and s.count("@") == 1 \
and "." in s.split("@")[-1] and " " not in s
@pytest.mark.parametrize("email, expected", [
("demo@example.com", True),
("no-at-sign.com", False),
("two@@example.com", False),
("space in@example.com", False),
("demo@localhost", False),
])
def test_email(email, expected):
assert is_valid_email(email) == expected
The first argument names the parameters as a comma-separated string. The second is a list of tuples, one per case, in the same order. pytest generated five tests from this one function:
test_param.py::test_email[demo@example.com-True]
test_param.py::test_email[no-at-sign.com-False]
test_param.py::test_email[two@@example.com-False]
test_param.py::test_email[space in@example.com-False]
test_param.py::test_email[demo@localhost-False]
When we deliberately broke one expectation, the failure line named the exact input: FAILED test_param.py::test_email[demo@localhost-True]. The other four still passed and reported normally.
2. Readable ids
Default ids are built from the values, which gets ugly for long strings, objects or numbers. Pass ids to name cases yourself:
@pytest.mark.parametrize("a, b, total",
[(1, 2, 3), (0, 0, 0), (-1, 1, 0)],
ids=["positive", "zeros", "negative"])
def test_add(a, b, total):
assert a + b == total
The tests appear as test_add[positive], test_add[zeros] and test_add[negative]. Good ids read like a specification in test reports and CI logs.
3. Stacking decorators for combinations
@pytest.mark.parametrize("x", [1, 2])
@pytest.mark.parametrize("y", ["a", "b", "c"])
def test_grid(x, y):
assert x and y
Stacked decorators produce every combination: 2 × 3 = 6 tests, from test_grid[a-1] to test_grid[c-2]. That is handy for small grids such as browser × locale, but it multiplies fast. For many parameters, choose combinations deliberately; see our pairwise testing guide.
4. pytest.param: ids and marks per case
@pytest.mark.parametrize("value, expected", [
pytest.param("10", 10, id="digits"),
pytest.param(" 7 ", 7, id="spaces"),
pytest.param("abc", None, id="letters",
marks=pytest.mark.xfail(raises=ValueError, strict=True)),
pytest.param("3.5", 3, id="float-string",
marks=pytest.mark.skip(reason="decide rounding rule first")),
])
def test_to_int(value, expected):
assert int(value) == expected
Wrapping a case in pytest.param lets you attach an id and marks to that case only. Here “letters” is an expected failure that must raise ValueError, and “float-string” is skipped with a reason. In our run they showed up as x and s in the progress line. With strict=True, an xfail that unexpectedly passes is reported as a failure, so known bugs cannot be fixed by accident without anyone noticing.
Tip: use xfail with a ticket number in the reason for known bugs, and turn the case back to normal when the bug is fixed. It keeps the suite green without hiding the problem.
5. Indirect parametrization with fixtures
Sometimes the value needs setup before the test can use it, such as creating a user with a role. With indirect, pytest passes each value to a fixture first:
@pytest.fixture
def user(request):
role = request.param
return {"name": "Demo", "role": role, "can_delete": role == "admin"}
@pytest.mark.parametrize("user, allowed",
[("admin", True), ("viewer", False)], indirect=["user"])
def test_permissions(user, allowed):
assert user["can_delete"] is allowed
The fixture reads the raw value from request.param and returns the built object. Listing only ["user"] as indirect means allowed still arrives directly. This keeps expensive setup in fixtures, where it belongs; see our pytest fixtures guide.
6. Cases from a list of dictionaries
CASES = [
{"qty": 1, "price": 100, "total": 100},
{"qty": 3, "price": 50, "total": 150},
]
@pytest.mark.parametrize("case", CASES, ids=lambda c: f"qty{c['qty']}")
def test_cart(case):
assert case["qty"] * case["price"] == case["total"]
ids can be a function that builds a name from each case; ours produced test_cart[qty1] and test_cart[qty3]. The same idea lets you load cases from a JSON or CSV file at import time, which suits data that testers maintain outside the code. Our test data generation guide shows how to create such data.
7. Running only some cases
$ pytest -q -k "zeros or admin"
2 passed, 20 deselected in 0.10s
Because ids become part of the test name, -k can select individual cases. You can also copy a full node id, such as "test_param.py::test_add[zeros]", from a failure report and run just that case while debugging.
Two more patterns: files and classes
Load cases from a JSON file
[{"id": "free-over-500", "total": 600, "fee": 0},
{"id": "boundary-500", "total": 500, "fee": 49},
{"id": "small-order", "total": 120, "fee": 49}]
import json, pathlib, pytest
CASES = json.loads(pathlib.Path(__file__).with_name("cases.json")
.read_text(encoding="utf-8"))
@pytest.mark.parametrize("case", CASES, ids=[c["id"] for c in CASES])
def test_shipping_from_file(case):
assert shipping(case["total"]) == case["fee"]
Testers or analysts can now add cases without touching Python. Each JSON object still becomes its own named test, such as test_shipping_from_file[boundary-500]. Read the file with an explicit encoding="utf-8" so names with accents or symbols load the same on every machine.
Parametrize a whole class
@pytest.mark.parametrize("currency", ["INR", "USD"])
class TestPrices:
def test_symbol(self, currency):
assert {"INR": "₹", "USD": "$"}[currency]
def test_code_length(self, currency):
assert len(currency) == 3
A decorator on the class applies to every test method in it, so two methods × two currencies gave four tests. Together with the file-driven test, this extra module collected 7 tests and all 7 passed in 0.12 seconds.
Our complete run
$ pytest -q
................xs.... [100%]
20 passed, 1 skipped, 1 xfailed in 0.24s
$ pytest --collect-only -q
22 tests collected in 0.01s
Six test functions produced 22 tests. That ratio is the real benefit: broad coverage with very little code. Use --collect-only to check that your cases expand the way you expect before running them.
parametrize vs alternatives
| Approach | Best for | Drawback |
|---|---|---|
| Copy-paste tests | Two very different cases | Duplicate code |
| Loop inside one test | Nothing, really | First failure hides the rest |
@pytest.mark.parametrize |
Known example cases | You must choose the cases |
| Parametrized fixture | Running many tests against several setups | Less visible than a decorator |
| Hypothesis | Generating hundreds of inputs automatically | Extra library and learning |
When you want pytest to invent cases for you, look at property-based testing with Hypothesis.
Tips for maintainable parametrized tests
- One behaviour per test. Parametrize inputs that should behave the same way. If valid and invalid inputs need different assertions, write two tests, each with its own case list.
- Name cases by intent.
boundary-500tells a reviewer why the case exists;case3does not. - Keep data close to the test unless non-programmers maintain it; then move it to JSON or CSV as shown above.
- Cover the edges deliberately. Empty values, zero, negative numbers, the exact boundary and one value past it usually find more bugs than ten ordinary values.
- Read CI output by id. A failure such as
test_email[demo@localhost-True]already tells you the input, so you can reproduce it locally by pasting the node id afterpytest. - Watch the count. If
--collect-onlyshows hundreds of cases, check whether a few well-chosen ones would give the same confidence in less time.
Common mistakes
- Name mismatch: the names in the string must match the function arguments exactly, or pytest errors at collection.
- Single values as tuples: for one parameter, pass a plain list such as
[1, 2, 3], not tuples. - Mutable shared data: if a test changes a dict from the case list, later tests see the change. Copy it first.
- Logic in the test:
if expected:branches inside a parametrized test usually mean you need two tests. - Combinatorial explosion: stacking four decorators of five values each creates 625 tests. Prune deliberately.
Final thoughts
pytest parametrize turns repetitive tests into clean, data-driven ones. Start with a simple list of tuples, add readable ids, use pytest.param for skips and known failures, and move setup into indirect fixtures. Check expansion with --collect-only, and your suite will grow by adding data rather than code.
Frequently asked questions
What does pytest.mark.parametrize do?
It runs the same test function once for each set of arguments you provide, and reports every run as a separate test with its own result.
How do I give parametrized tests readable names?
Pass ids as a list of strings or a function, or wrap each case in pytest.param with id set. The id appears in brackets after the test name.
How do I skip or xfail one parametrized case?
Wrap that case in pytest.param and add marks, for example marks=pytest.mark.skip(reason=…) or marks=pytest.mark.xfail(raises=ValueError).
What is indirect parametrization in pytest?
With indirect, each value is sent to a fixture of the same name, which reads it from request.param and can do setup before returning the object the test receives.
Can I parametrize with multiple decorators?
Yes. Stacking parametrize decorators runs every combination of the values, so two values and three values produce six tests.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.