Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/308.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python PyTest:在运行时动态生成测试名称_Python_Python 3.x_Pytest_Parametrized Testing - Fatal编程技术网

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

Python PyTest:在运行时动态生成测试名称,python,python-3.x,pytest,parametrized-testing,Python,Python 3.x,Pytest,Parametrized Testing,当我使用@pytest.mark.parametrize(“value”,values\u list)fixture运行测试时,我想在运行时动态命名测试。 例如: values_list=['apple','tomatoes','potatoes'] @pytest.mark.parametrize("value",values_list) def test_xxx(self,value): assert value==value 我想看到的最终结果是3个测试,名称如下: 苹果试验

当我使用
@pytest.mark.parametrize(“value”,values\u list)
fixture运行测试时,我想在运行时动态命名测试。 例如:

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

@pytest.mark.parametrize("value",values_list)
def test_xxx(self,value):
    assert value==value
我想看到的最终结果是3个测试,名称如下:

苹果试验

番茄试验

马铃薯试验


我尝试查看pytest文档,但我没有找到任何可以说明此问题的内容。

您可以通过重写测试项的
\u nodeid
attibute来更改测试执行中显示的名称。示例:在项目/测试根目录中创建名为
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

注意,覆盖
\u nodeid
时要小心,因为每个nodeid都应该保持唯一性。否则,
pytest
将自动停止执行某些测试,并且很难找出原因。

您不能这样做。您所能做的就是通过设置
ids
参数为
参数化中的每个选项设置自定义名称。看看(test
test\u timedistance\u v1
)。您可以在测试运行期间自定义方括号中显示的值。感谢您的尝试,并让您知道它非常有效,但现在我想添加另一层复杂性。让我们假设:``values\u list=[{'apple':'5'},{'tomatos':'1'},{'potations':'32}]``我希望测试的名称是test\u 5,test\u 1等等,有办法访问这些值吗?我曾尝试通过测试类本身中的setup_方法来实现这一点,但我无法从那里访问字典(即使在调试中)。事先感谢您,但我设法找到了答案,这需要一些挖掘,但最终我发现它位于一个未登录的结构中:iitem.own_markers[0]。args[1]因此,我对这些数据进行了一些编译,并设法提取出所需的字段