Bor*_*002 4 python pytest python-3.x parametrized-testing
当我使用夹具运行测试时,我想在运行时动态命名测试@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
Run Code Online (Sandbox Code Playgroud)
我想看到的最终结果是 3 个测试,名称如下:
测试苹果
测试番茄
测试土豆
我尝试查看 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[', '')
Run Code Online (Sandbox Code Playgroud)
运行你的测试现在会产生
test_fruits.py::test_apple PASSED
test_fruits.py::test_tomatoes PASSED
test_fruits.py::test_potatoes PASSED
Run Code Online (Sandbox Code Playgroud)
_nodeid请注意,应谨慎进行覆盖,因为每个节点 ID 应保持唯一。否则,pytest会默默地放弃执行一些测试,并且很难找出原因。