简体   繁体   English

PyTest:在运行时动态生成测试名称

[英]PyTest : dynamically generating test name during runtime

I want to name the test dynamically during run-time when i run them with the @pytest.mark.parametrize("value",values_list) fixture.当我使用@pytest.mark.parametrize("value",values_list)夹具运行测试时,我想在运行时动态命名测试。 for example:例如:

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

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

the final outcome i want to see is 3 tests with the following names:我想看到的最终结果是 3 个具有以下名称的测试:

test_apple测试苹果

test_tomatoes test_tomatoes

test_potatoes test_potatoes

i gave tried looking in to pytest documentation but i haven found anything that might shed light on this problem.我尝试查看 pytest 文档,但我没有找到任何可能阐明此问题的内容。

You can change the names displayed in test execution by rewriting the _nodeid attibute of the test item.您可以通过重写测试项的_nodeid属性来更改测试执行中显示的名称。 Example: create a file named conftest.py in your project/test root dir with the following contents:示例:在您的项目/测试根目录中创建一个名为conftest.py的文件,其内容如下:

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

Beware that overwriting _nodeid should be enjoyed with caution as each nodeid should remain unique.请注意,覆盖_nodeid应谨慎使用,因为每个 nodeid 应保持唯一。 Otherwise, pytest will silently drop executing some tests and it will be hard to find out why.否则, pytest会默默地放弃执行一些测试,很难找出原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM