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
参数为参数化中的每个选项设置自定义名称。看看(testtest\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]因此,我对这些数据进行了一些编译,并设法提取出所需的字段