gpt4 book ai didi

python - 在pytest中重命名参数化测试

转载 作者:太空宇宙 更新时间:2023-11-03 14:36:10 24 4
gpt4 key购买 nike

Pytest 中的参数化测试具有以下 id 格式: <function name>[<param identifier>] .

当这些被参数化时,我希望能够完全控制测试用例的名称。

例如我目前有如下代码:

import pytest

list_args = ["a", "b", "c"]


@pytest.fixture(params=list_args)
def prog_arg(request):
yield request.param


def test_001():
# This should not be changed
pass

def test_002(prog_arg):
# This should be test_002_01, test_002_02, ...
print(prog_arg)


ids = [f"test_003_{i+1:02d}" for i in range(len(list_args))]


@pytest.mark.parametrize("arg", list_args, ids=ids)
def test_003(arg):
# This should be test_003_01, test_003_02, ...
print(prog_arg)

当我运行 (pytest 5.1.3) 时,我有:

test_rename_id.py::test_TC_001 PASSED
test_rename_id.py::test_TC_002[a] PASSED
test_rename_id.py::test_TC_002[b] PASSED
test_rename_id.py::test_TC_002[c] PASSED
test_rename_id.py::test_TC_003[test_003_01] PASSED
test_rename_id.py::test_TC_003[test_003_02] PASSED
test_rename_id.py::test_TC_003[test_003_03] PASSED

我想要的是:

test_rename_id.py::test_TC_001 PASSED
test_rename_id.py::test_TC_002_01 PASSED
test_rename_id.py::test_TC_002_02 PASSED
test_rename_id.py::test_TC_002_03 PASSED
test_rename_id.py::test_TC_003_01 PASSED
test_rename_id.py::test_TC_003_02 PASSED
test_rename_id.py::test_TC_003_03 PASSED

是否可以不对请求进行过多的黑客攻击 object (或在 pytest 的 future 更新中可能被破坏的其他修改?

谢谢

最佳答案

这肯定可以通过重写所收集项目的 nodeid 来实现。在下面的示例中,我在 pytest_collection_modifyitems 的自定义实现中重写了 nodeids钩。将以下代码放入您的 conftest.py:

# conftest.py

import itertools as it
import re


def grouper(item):
return item.nodeid[:item.nodeid.rfind('[')]


def pytest_collection_modifyitems(items):
for _, group in it.groupby(items, grouper):
for i, item in enumerate(group):
item._nodeid = re.sub(r'\[.*\]', '_{:02d}'.format(i + 1), item.nodeid)

从问题中运行您的测试模块现在产生:

test_spam.py::test_001 PASSED
test_spam.py::test_002_01 PASSED
test_spam.py::test_002_02 PASSED
test_spam.py::test_002_03 PASSED
test_spam.py::test_003_01 PASSED
test_spam.py::test_003_02 PASSED
test_spam.py::test_003_03 PASSED

关于python - 在pytest中重命名参数化测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108292/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com