重命名pytest中的参数化测试

时间:2019-09-26 01:11:04

标签: python pytest

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更新中被破坏的修改?

谢谢

2 个答案:

答案 0 :(得分:4)

通过重写所收集项目的nodeid,这肯定可以实现。在下面的示例中,我在pytest_collection_modifyitems挂钩的自定义印象中重写了nodeid。将以下代码放入您的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

答案 1 :(得分:0)

根据pytest中提供的文档,我想告诉您pytest.mark.paramterize中 ids 的工作方式就像您在问题中提到的输出一样。

格式为:- 文件名-测试名-ids值

参考:-https://hackebrot.github.io/pytest-tricks/param_id_func/