Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

pytest

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.

like image 275
Björn Pollex Avatar asked May 28 '14 21:05

Björn Pollex


1 Answers

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.

like image 95
flub Avatar answered Nov 10 '22 03:11

flub