如何让pytest显示夹具参数的自定义字符串表示?

Bjö*_*lex 4 python pytest

当使用内置类型作为夹具参数时,pytest会在测试报告中打印出参数的值.例如:

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

def test_something(data):
    pass
Run Code Online (Sandbox Code Playgroud)

运行此py.test --verbose将打印如下:

test_example.py:7: test_something[hello]
PASSED
test_example.py:7: test_something[world]
PASSED
Run Code Online (Sandbox Code Playgroud)

请注意,参数的值在测试名称后面的方括号中打印.

现在,当使用用户定义的类的对象作为参数时,如下所示:

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
Run Code Online (Sandbox Code Playgroud)

pytest将简单枚举值(数量p0,p1等等):

test_example.py:7: test_something[p0]
PASSED
test_example.py:7: test_something[p1]
PASSED
Run Code Online (Sandbox Code Playgroud)

即使用户定义的类提供自定义__str____repr__实现,此行为也不会更改.有没有办法让pytest显示比p0这里更有用的东西?

我在Windows 7上的Python 2.7.6上使用pytest 2.5.2.

flu*_*lub 6

fixture装饰器接受一个ids参数,该参数可用于覆盖自动参数名称:

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

如图所示,它采用名称列表用于参数列表中的相应项目.