How to create a nice id for parameter in parametrized tests in pytest

George Shuklin
OpsOps
Published in
1 min readAug 6, 2021

There was an inconvenience which bothered me for a long time. When you have some crazy parametrization (two fixtures, content of two different files), parameter name (ids for parameter application) are usually boring, like fixture0, or something like that.

There was a solution of using pytest_generate_tests function, but it was very, very ugly. You need to provide two independent iterables, one with values for fixtures, and second with ids. If you have more than one fixture to work with, parameters are multi-dimensional list, and you have crazy time to ‘zip/flip/fold’ them.

Until…

Behold, the most elegant solution of all the times!

def make_testname(testcase):
name = (
testcase["test_path"]
.replace("/current", "")
.replace("/tests", "")
.replace("/", "-")
)
return name
@pytest.fixture(params=get_testcases(), ids=make_testname)
def test_code(request):
....

Yes, you can pass a function into ids parameter. And that function is applied to each parametrized value independently. It takes value and can return whatever name you want.

This thing make my incoming vacation a bliss. It’s so concise and natural!

--

--

George Shuklin
OpsOps

I work at Servers.com, most of my stories are about Ansible, Ceph, Python, Openstack and Linux. My hobby is Rust.