1. Home
  2. Blog
  3. Test Automation

Test Automation

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.

8 min read
pytest parametrize explained with examples

Key takeaways

  • 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 zeros runs 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-500 tells a reviewer why the case exists; case3 does 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 after pytest.
  • Watch the count. If --collect-only shows 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

Work with Stack Quora

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.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

BM25 Explained: How Keyword Search Ranks Results, With Python Code and Hybrid Search

BM25 explained with a pure Python implementation we ran: the formula, IDF, term saturation, the k1 and b parameters, why…

Read article →
Software Development

HTTP Methods Explained: GET, POST, PUT, PATCH, DELETE, Tested on a Live Server

HTTP methods explained with a small server we ran: GET, POST, PUT, PATCH, DELETE, HEAD and OPTIONS, safe vs idempotent,…

Read article →
DevOps

Git Bisect Explained: Find the Commit That Broke Your Code, Manually or Automatically

Git bisect explained with a tested repository: find the one bad commit among 41 in 5 test runs, automate it…

Read article →
Test Automation

pytest Markers Explained: Custom Marks, skip, skipif, xfail and -m Filters

pytest markers explained with a tested suite: register custom marks, run only smoke tests with -m, combine filters with and,…

Read article →
Software Testing

Positive vs Negative Testing: Differences, 24 Real Test Cases and a Checklist

Positive vs negative testing explained with a real signup form: 6 positive and 18 negative test cases run in pytest,…

Read article →
Databases & SQL

SQL ORDER BY Multiple Columns: ASC, DESC, NULLS LAST, Case and Custom Order

SQL ORDER BY with multiple columns explained with tested queries: mixed ASC and DESC, tie-breakers, NULLS FIRST and LAST, case-insensitive…

Read article →
Databases & SQL

SQL Running Total: SUM OVER, Per-Group Totals, Moving Sums and the RANGE Trap

How to calculate a SQL running total with SUM() OVER: per-group totals, daily cumulative sums, moving sums, percent of total,…

Read article →
Software Development

JavaScript Sort Array: Numbers, Objects, Strings and Why 10 Comes Before 5

How to sort an array in JavaScript correctly: numbers with a compare function, objects by one or more fields, strings…

Read article →
Software Development

Python String Methods: Cheat Sheet, Real Examples and the strip() Trap

Python string methods with tested examples: split, join, strip, replace, find, startswith, is-methods, casefold, partition and translate, plus the strip()…

Read article →
Software Development

Python zip() Explained: Loop Two Lists at Once, Unzip, strict=True and Traps

Python zip() pairs items from several lists in one loop. Tested examples for dicts, unzipping with *, strict=True, zip_longest, sliding…

Read article →
Artificial Intelligence

Cosine Similarity Explained: Formula, Worked Example and Python Code

Cosine similarity explained simply: the formula, a worked example by hand, pure Python and NumPy code, cosine vs Euclidean distance…

Read article →
Software Development

UTF-8 Encoding Explained: How Text Becomes Bytes and How to Fix Garbled Text

UTF-8 encoding explained with byte-level examples we ran in Python: how characters become 1 to 4 bytes, why café turns…

Read article →
DevOps

Git Squash Commits: 4 Easy Ways, Tested Step by Step (rebase -i, reset, merge)

Git squash commits explained with 4 tested methods: interactive rebase, reset –soft, merge –squash and fixup with autosquash. Before-and-after logs,…

Read article →
Test Automation

pytest parametrize Explained: 7 Patterns with Tested Examples

pytest parametrize explained with 7 tested patterns: basic cases, readable ids, stacked decorators, pytest.param with xfail and skip, indirect fixtures…

Read article →
Software Testing

Retesting vs Regression Testing: 8 Key Differences with a Real Bug Fix Example

Retesting vs regression testing explained with a real bug fix run in pytest: retesting confirmed the fix, the regression run…

Read article →
Databases & SQL

Delete Duplicate Rows in SQL: 5 Safe Methods, Tested Step by Step

How to delete duplicate rows in SQL safely: find them, preview them, then remove them with ROW_NUMBER, MIN(id), EXISTS, rowid…

Read article →
Databases & SQL

SQL RANK vs DENSE_RANK vs ROW_NUMBER: Differences with Tested Examples

SQL RANK vs DENSE_RANK vs ROW_NUMBER in one table: how each handles ties, top-N per group, the second-highest salary trap…

Read article →
Software Development

JavaScript Optional Chaining (?.) Explained: 8 Examples, ?? Defaults and Traps

JavaScript optional chaining stops “Cannot read properties of undefined” errors. 8 tested examples for properties, arrays and methods, ?? vs…

Read article →
Artificial Intelligence

RAG Chunking Strategies Explained: Fixed, Overlap, Sentence, Recursive and Headings, Measured

RAG chunking strategies compared on one document with tiktoken 0.14: fixed-size, overlap, sentence packing, recursive splitting and heading-based chunks, measuring…

Read article →
DevOps

Git Stash Explained: Save, Apply, Pop and Untracked Files, Tested

Git stash explained with commands we ran on Git 2.56: push with a message, untracked files, list and show, apply…

Read article →
Software Testing

Pairwise Testing Explained: How All-Pairs Cuts 216 Tests to 13, Tested

Pairwise testing explained with a generator we ran in Python 3.13: a checkout with 216 combinations covered by 13 tests,…

Read article →
Test Automation

Test Doubles Explained: Dummy, Stub, Spy, Mock and Fake, with Tested Python Code

Test doubles explained with one Python example run in pytest 9.2: dummy, stub, spy, mock and fake, when to use…

Read article →
Databases & SQL

SQL COALESCE Explained: Defaults, NULLIF, IFNULL vs ISNULL and Traps, Tested

SQL COALESCE explained with queries we ran in SQLite 3.50: first non-null values, empty strings, NULL in maths, NULLIF for…

Read article →
Databases & SQL

SQL Self Join Explained: Employee-Manager, Pairs and Row Comparisons, Tested

SQL self join explained with queries we ran in SQLite 3.50: employee and manager, earning more than the manager, unique…

Read article →
Artificial Intelligence

LLM Context Window Explained: Tokens, Limits and How to Fit More, Measured

The LLM context window explained with token counts we measured using tiktoken: words vs tokens for prose, code and Hindi,…

Read article →
DevOps

Git Cherry-Pick Explained: Copy the Commit You Need, Safely, Tested

Git cherry-pick explained with commands we ran in Git 2.56: copying a hotfix to a release branch, new hashes and…

Read article →
Test Automation

Snapshot Testing Explained: How It Works, When It Helps and When It Hurts

Snapshot testing explained with a pytest and syrupy demo we ran: creating snapshots, reading the diff after a code change,…

Read article →
Software Testing

Mutation Testing Explained: Why 100% Coverage Still Missed Our Bug

Mutation testing explained with a small mutation tool we built and ran: 14 mutants, a test suite with 100% line…

Read article →
Artificial Intelligence

Prompt Injection Explained: How AI Apps Get Tricked and How to Defend Them

Prompt injection explained for builders: direct and indirect attacks, why keyword filters fail (our test blocked 1 of 4), and…

Read article →
DevOps

DNS Records Explained: A, AAAA, CNAME, MX, TXT and TTL With Real Lookups

DNS records explained with lookups we ran: how resolution works, A and AAAA, CNAME rules, MX and null MX, TXT…

Read article →
DevOps

Feature Flags Explained: Safe Releases, Gradual Rollouts and Flag Hygiene

Feature flags explained with a rollout simulation we ran: flag types, percentage rollouts with stable hashing, kill switches, allow lists,…

Read article →
Test Automation

Test Data Generation With Python Faker: Realistic, Repeatable and Safe Data

Test data generation with Python Faker, run and measured: seeding for repeatable data, locales, unique values, domain-shaped records, edge cases…

Read article →
Software Testing

Shift-Left Testing Explained: Find Bugs Earlier Without Slowing the Team

Shift-left testing explained: what it means, why early defects are cheaper, practices from requirement reviews to CI checks, the tester's…

Read article →
Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →