How to make pytest display a custom string representation for fixture parameters?

pytest, python

Solution

The fixture decorator takes an `ids` parameter which can be used to override the automatic parameter name:

@fixture(params=[Param('hello'), Param('world')], ids=['hello', 'world'])
def data(request):
    return request.param

As shown it takes a list of names to use for the corresponding item in the params list.

Problem

When using builtin types as fixture parameters, pytest prints out the value of the parameters in the test report. For example: ``` @fixture(params=['hello', 'world'] def data(request): return request.param def test_something(data): pass ``` Running this with `py.test --verbose` will print something like: ``` test_example.py:7: test_something[hello] PASSED test_example.py:7: test_something[world] PASSED ``` Note that the value of the parameter is printed in square brackets after the test name. Now, when using an object of a user-defined class as parameter, like so: ``` class Param(object): def __init__(self, text): self.text = text @fixture(params=[Param('hello'), Param('world')] def data(request): return request.param def test_something(data): pass ``` pytest will simply enumerate the number of values (`p0`, `p1`, etc.): ``` test_example.py:7: test_something[p0] PASSED test_example.py:7: test_something[p1] PASSED ``` This behavior does not change even when the user-defined class provides custom `__str__` and `__repr__` implementations. Is there any way to make pytest display something more useful than just `p0` here? I am using pytest 2.5.2 on Python 2.7.6 on Windows 7.

Original source