PyTest parameterized named tests

Author: Swen Kooij

Date: 2021-11-19

PyTest allows parameterizing tests by using the @pytest.mark.parametrize decorator:

import pytest

@pytest.mark.parametrize("data", [
    dict(name="john"),
    dict(name="jane"),
])
def test_something(data):
    ...

With this set up, the test will run twice. Once for each dictionary specified in the decorator. Unfortunately, the names assigned to the generated test are not very pretty:

test_something[data0]
test_something[data1]

PyTest allows specifying labels to customize the name assigned to these generated tests. With the ids keyword argument we can specify custom names for each item:

import pytest

@pytest.mark.parametrize("data",
    [
        dict(name="john"),
        dict(name="jane"),
    ],
    ids=["john", "jane"],
)
def test_something(data):
    ...

The resulting test names are much cleaner:

test_something[john]
test_something[jane]