1

@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 文档,但我没有找到任何可能阐明这个问题的东西。

4

1 回答 1

3

_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将默默地放弃执行一些测试,并且很难找出原因。

于 2020-04-20T17:10:09.523 回答