[英]PyTest : dynamically generating test name during runtime
当我使用@pytest.mark.parametrize("value",values_list)
夹具运行测试时,我想在运行时动态命名测试。 例如:
values_list=['apple','tomatoes','potatoes']
@pytest.mark.parametrize("value",values_list)
def test_xxx(self,value):
assert value==value
我想看到的最终结果是 3 个具有以下名称的测试:
测试苹果
test_tomatoes
test_potatoes
我尝试查看 pytest 文档,但我没有找到任何可能阐明此问题的内容。
您可以通过重写测试项的_nodeid
属性来更改测试执行中显示的名称。 示例:在您的项目/测试根目录中创建一个名为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[', '')
运行您的测试现在将产生
test_fruits.py::test_apple PASSED
test_fruits.py::test_tomatoes PASSED
test_fruits.py::test_potatoes PASSED
请注意,覆盖_nodeid
应谨慎使用,因为每个 nodeid 应保持唯一。 否则, pytest
会默默地放弃执行一些测试,很难找出原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.