PyTest:在运行时动态生成测试名称 [英] PyTest : dynamically generating test name during runtime

查看:59
本文介绍了PyTest:在运行时动态生成测试名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用 @pytest.mark.parametrize("value",values_list) 固定装置运行它们时,我想在运行时动态命名测试.例如:

I want to name the test dynamically during run-time when i run them with the @pytest.mark.parametrize("value",values_list) fixture. for example:

values_list=['apple','tomatoes','potatoes']

@pytest.mark.parametrize("value",values_list)
def test_xxx(self,value):
    assert value==value

我想看到的最终结果是 3 次测试,名称如下:

the final outcome i want to see is 3 tests with the following names:

test_apple

test_tomatoes

test_potatoes

我曾尝试查看 pytest 文档,但我没有发现任何可以解决此问题的信息.

i gave tried looking in to pytest documentation but i haven found anything that might shed light on this problem.

推荐答案

您可以通过重写测试项的 _nodeid 属性来更改在测试执行中显示的名称.示例:在您的项目/测试根目录中创建一个名为 conftest.py 的文件,内容如下:

You can change the names displayed in test execution by rewriting the _nodeid attibute of the test item. Example: create a file named conftest.py in your project/test root dir with the following contents:

def pytest_collection_modifyitems(items):
    for item in items:
        # check that we are altering a test named `test_xxx`
        # and it accepts the `value` arg
        if item.originalname == 'test_xxx' and 'value' in item.fixturenames:
            item._nodeid = item.nodeid.replace(']', '').replace('xxx[', '')

运行您的测试现在将产生

Running your tests will now yield

test_fruits.py::test_apple PASSED
test_fruits.py::test_tomatoes PASSED
test_fruits.py::test_potatoes PASSED

注意覆盖 _nodeid 应该谨慎使用,因为每个 nodeid 应该保持唯一.否则,pytest 会默默地放弃执行一些测试,而且很难找出原因.

Beware that overwriting _nodeid should be enjoyed with caution as each nodeid should remain unique. Otherwise, pytest will silently drop executing some tests and it will be hard to find out why.

这篇关于PyTest:在运行时动态生成测试名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆