How to Parametrize Tests with IDs in pytest for Clearer Reports
In
pytest, you can add ids to @pytest.mark.parametrize to give each test case a readable name. This helps make test reports clearer by showing descriptive names instead of just parameter values.Syntax
The ids argument in @pytest.mark.parametrize accepts a list of strings or a function to name each test case. It matches the order of the parameter sets.
Example parts:
argnames: parameter names as a comma-separated string.argvalues: list of tuples with test data.ids: list of strings or a function to name each test case.
python
@pytest.mark.parametrize(
argnames='input,expected',
argvalues=[
(1, 2),
(3, 4),
],
ids=['one_plus_one', 'three_plus_one']
)
def test_add(input, expected):
assert input + 1 == expectedExample
This example shows how to parametrize a test with ids to give each case a clear name. The test adds 1 to the input and checks the result.
python
import pytest @pytest.mark.parametrize( 'input,expected', [ (1, 2), (3, 4), (5, 6), ], ids=['one_plus_one', 'three_plus_one', 'five_plus_one'] ) def test_add_one(input, expected): assert input + 1 == expected
Output
============================= test session starts ==============================
collected 3 items
test_example.py::test_add_one[one_plus_one] PASSED
test_example.py::test_add_one[three_plus_one] PASSED
test_example.py::test_add_one[five_plus_one] PASSED
============================== 3 passed in 0.01s ===============================
Common Pitfalls
Common mistakes when using ids include:
- Providing fewer or more
idsthan parameter sets, causing errors. - Using non-string values in
ids, which pytest does not accept. - Not using
idsat all, leading to unclear test names in reports.
Always ensure the ids list length matches the number of parameter tuples.
python
import pytest # Wrong: fewer ids than parameters @pytest.mark.parametrize( 'x,y', [(1,2), (3,4)], ids=['case1'] # Missing one id ) def test_wrong_ids(x, y): assert x < y # Correct: matching ids @pytest.mark.parametrize( 'x,y', [(1,2), (3,4)], ids=['case1', 'case2'] ) def test_correct_ids(x, y): assert x < y
Quick Reference
| Feature | Description | Example |
|---|---|---|
| argnames | Names of parameters as string | 'input,expected' |
| argvalues | List of tuples with test data | [(1,2), (3,4)] |
| ids | List of strings naming each test case | ['case1', 'case2'] |
| ids as function | Function returning string for each parameter set | ids=lambda val: f"val_{val}" |
Key Takeaways
Use the ids argument in @pytest.mark.parametrize to name test cases clearly.
Ensure the ids list length matches the number of parameter sets exactly.
Ids can be a list of strings or a function returning strings for dynamic naming.
Clear ids improve test report readability and debugging.
Avoid non-string ids and mismatched lengths to prevent errors.