当使用内置类型作为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。
最佳答案
fixture 装饰器接受一个 ids
参数,可用于覆盖自动参数名称:
@fixture(params=[Param('hello'), Param('world')], ids=['hello', 'world'])
def data(request):
return request.param
如图所示,它需要一个名称列表以用于参数列表中的相应项目。
关于python - 如何使 pytest 显示 fixture 参数的自定义字符串表示形式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23922109/