如何让pytest显示fixture参数的自定义字符串表示?
当你在使用内置类型作为测试参数时,pytest会在测试报告中显示这些参数的值。例如:
@fixture(params=['hello', 'world']
def data(request):
return request.param
def test_something(data):
pass
如果你用 py.test --verbose
来运行这个测试,输出的内容会像这样:
test_example.py:7: test_something[hello]
PASSED
test_example.py:7: test_something[world]
PASSED
注意,参数的值会在测试名称后面用方括号括起来显示。
现在,如果你用一个自己定义的类的对象作为参数,比如这样:
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就只会列出值的数量(比如 p0
, p1
等等):
test_example.py:7: test_something[p0]
PASSED
test_example.py:7: test_something[p1]
PASSED
即使你在自己定义的类中提供了自定义的 __str__
和 __repr__
方法,这种行为也不会改变。那么,有没有办法让pytest显示一些比 p0
更有用的信息呢?
我在Windows 7上使用的是Python 2.7.6和pytest 2.5.2。
1 个回答
12
这个fixture装饰器有一个ids
参数,可以用来替换自动生成的参数名称:
@fixture(params=[Param('hello'), Param('world')], ids=['hello', 'world'])
def data(request):
return request.param
如上所示,它接受一个名称列表,用来对应params列表中的每个项目。