PyTest : dynamically generating test name during runtime

坚强是说给别人听的谎言 提交于 2021-01-28 19:08:15

问题


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

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

test_apple

test_tomatoes

test_potatoes

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


回答1:


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

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.



来源:https://stackoverflow.com/questions/61317809/pytest-dynamically-generating-test-name-during-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!