Sub topic 10
Running one test over many inputs with parametrize
This chapter assumes you can write and run pytest test functions, use plain assert, and use pytest.raises and pytest.approx. It also assumes you can read the output of pytest -v.
Test code often repeats itself. You write test_total_a, test_total_b and test_total_c, and the bodies differ only in their data. pytest.mark.parametrize removes that repetition. You write the test body once and give pytest a table of inputs. Pytest runs the body once per row and reports each row as a separate test.
The basic form
The examples use the total function from cart.py:
# cart.py
def total(prices, tax_rate=0.0):
if tax_rate < 0:
raise ValueError("tax_rate must be non-negative")
return sum(prices) * (1 + tax_rate)Here is a parametrized test for it:
# test_cart_params.py
import pytest
from cart import total
@pytest.mark.parametrize(
"prices, expected",
[
([], 0),
([5], 5),
([1, 2, 3], 6),
],
)
def test_total_sums_prices(prices, expected):
assert total(prices) == expectedThe decorator takes two arguments:
- A string of comma-separated argument names. A list or tuple of names, such as
["prices", "expected"], also works. - A list of cases. Each case is a tuple whose values line up with the names.
The names must match parameters of the test function exactly. If they don't, pytest reports an error at collection time and runs nothing from that test.
With one argument name, the list holds plain values, not one-element tuples:
@pytest.mark.parametrize("rate", [-0.1, -1, -100])
def test_negative_rates_rejected(rate):
with pytest.raises(ValueError, match="non-negative"):
total([1], tax_rate=rate)What pytest reports
The expansion happens during collection, before any test runs. Run pytest -v test_cart_params.py and you see three lines:
pytest -v test_cart_params.pytest_cart_params.py::test_total_sums_prices[prices0-0] PASSED
test_cart_params.py::test_total_sums_prices[prices1-5] PASSED
test_cart_params.py::test_total_sums_prices[prices2-6] PASSEDThe text in brackets is the test ID. Pytest builds it from the values of the case:
- Strings, numbers, booleans and
Noneappear as themselves. - Other objects, such as lists, get the argument name plus the case index. That gives
prices0andprices1above.
Each case passes or fails on its own. If case two fails, cases one and three still run, which is the main advantage over a for loop inside one test. A loop stops at the first failing assertion and hides the rest.
Readable IDs with pytest.param
IDs like prices1-5 tell you little when one fails. Use pytest.param to wrap a case and give it a name:
import pytest
from cart import total
@pytest.mark.parametrize(
"prices, tax_rate, expected",
[
pytest.param([], 0.0, 0, id="empty-cart"),
pytest.param([10, 20], 0.0, 30, id="no-tax"),
pytest.param([10, 20], 0.1, 33.0, id="ten-percent-tax"),
],
)
def test_total_with_tax(prices, tax_rate, expected):
assert total(prices, tax_rate) == pytest.approx(expected)The IDs become test_total_with_tax[empty-cart] and so on. You can also pass ids=["a", "b", "c"] to parametrize to name every case at once. A list of IDs must have the same length as the list of cases. A function that takes a value and returns a string also works.
Named IDs let you select one case from the command line:
pytest "test_cart_params.py::test_total_with_tax[no-tax]"
pytest -k ten-percentQuote the first form. Square brackets are special characters in many shells.
Marks on individual cases
pytest.param also accepts marks, so you can skip or expect a failure for one row without touching the others:
import pytest
from cart import total
@pytest.mark.parametrize(
"prices, expected",
[
pytest.param([1, 2], 3, id="integers"),
pytest.param(
[0.1, 0.2],
0.3,
id="float-sum",
marks=pytest.mark.xfail(reason="exact float equality is unreliable"),
),
],
)
def test_total_exact(prices, expected):
assert total(prices) == expectedThe first case passes. The second runs, fails because 0.1 + 0.2 is 0.30000000000000004, and is reported as XFAIL rather than a failure. The suite stays green and the known problem stays visible. The real fix is pytest.approx, as shown in the earlier chapter.
Stacking decorators
You can apply parametrize more than once to the same function. Pytest then runs the cartesian product of the lists:
import pytest
from cart import total
@pytest.mark.parametrize("tax_rate", [0.0, 0.1])
@pytest.mark.parametrize("prices", [[1], [1, 2]])
def test_total_is_never_negative(prices, tax_rate):
assert total(prices, tax_rate) >= 0This produces 2 × 2 = 4 tests. Use stacking when the arguments are independent and every combination is meaningful. Use a single decorator with explicit tuples when only certain combinations are valid. Three stacked lists of ten values each produce 1,000 tests, which is easy to do by accident.
Parametrizing error cases
Parametrization works well for invalid inputs. Put the expected exception in the table to cover both success and failure in one test:
import pytest
from cart import total
@pytest.mark.parametrize(
"tax_rate, expectation",
[
pytest.param(0.0, None, id="zero-ok"),
pytest.param(-0.5, ValueError, id="negative-rejected"),
],
)
def test_tax_rate_validation(tax_rate, expectation):
if expectation is None:
assert total([1], tax_rate) == 1
else:
with pytest.raises(expectation):
total([1], tax_rate)The branch inside the test body makes this harder to read than two separate tests. A branch in a test is a warning sign. Prefer separate parametrized tests for success and failure unless the cases are tiny.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| Error at collection: "function uses no argument 'x'" | Name in the decorator does not match a function parameter | Make the names identical, including spelling |
| Error: wrong number of values | A case tuple has more or fewer values than names | Count the values in each tuple |
| One-argument test receives a tuple | Cases were written as `[(1,), (2,)]` | Use plain values: `[1, 2]` |
| `parametrize("a b", ...)` fails | Names were separated by a space only | Separate with commas: `"a, b"` |
| Two cases share one ID | Pytest appends a suffix, such as `0` and `1`, to duplicate IDs | Give each case a unique `id` |
When parametrize is the wrong tool
Parametrize varies data while the test logic stays identical. If the assertions differ between cases, write separate tests. If every case needs expensive setup, use a fixture and keep the table small. Fixtures can also be parametrized with params=, which is useful when the setup itself varies, such as running against two database backends.
Exercise
A test is decorated with @pytest.mark.parametrize("a, b", [(1, 2), (3, 4), (5, 6)]) and a second decorator @pytest.mark.parametrize("flag", [True, False]). How many tests does pytest generate, and how would you run only the case (3, 4) with flag=True if you gave each (a, b) case an id such as mid and the flag cases the ids on and off?
Show answer
Stacked decorators multiply, so pytest generates 3 × 2 = 6 tests. Select one with its node ID, quoted so the shell leaves the brackets alone. The order of IDs inside the brackets follows decorator order, with the bottom decorator first. The flag decorator is on top, so the (a, b) decorator closest to the function comes first: pytest "test_file.py::test_name[mid-on]". You can also run pytest -k "mid and on". Running pytest -v first shows the exact IDs.