python - 如何使 pytest 显示 fixture 参数的自定义字符串表示形式?

标签 python 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 将简单地枚举值的数量(p0p1 等):

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/

相关文章:

python - Django 3.1.3 中的电子邮件激活链接问题

python - 在 MAC OS X Mavericks 中安装多个版本的 PyQt 和其他 python 模块

python - 如何使用 wx.displaySize() 查找两台显示器的屏幕尺寸

python - 异步单元测试 Sanic 应用程序会抛出 RuntimeError : this event loop is already running

python - pytest 传递数据进行清理

类似于 R 中的 %in% 的 Python 运算符

python - 将 Pandas Dataframe 转换为 numpy 数组

python - 更改 py.test 测试的名称

c++ - py.test 与非 python 测试(具体来说,与 cxxtest)

python - @pytest.mark.filterwarnings 如何工作?