如何正确分组Pytest中的参数化测试?

2024-09-29 17:12:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正在使用以下Pytest挂钩组合为特定模块自定义节点ID:

# In test_module.py
def pytest_generate_tests(metafunc):
    if not is_relevant_metafunc(metafunc):
        return
    args = []
    fids = []
    for test_class, test_name, test_args in collect_external_tests():
        args.append(test_args)
        fids.append("Tests.%s.%s" % (test_class, test_name))

    metafunc.parametrize(["arg1", "arg2"], args, ids=fids)

# In conftest.py
def pytest_collection_modifyitems(session, config, items):
    for item in items:
        if not is_relevant_item(item):
            continue
        item._nodeid = item.callspec.id
        item._location = tuple(list(item.location)[:-1] + [item.callspec.id])

这样做的平均原因是,我希望参数化测试在输出junitxml文件中被分割成不同的部分(“类”),然后可以分别聚合和显示

默认情况下,pytest创建以下层次结构:

root
 |_ test_module
    |_ test_module.test_func[param_a_1]
    |_ test_module.test_func[param_b_2]
    |_ ...
    |_ test_module.test_func[param_z_36]

我想要类似于以下层次结构的东西:

root
 |_ test_module
    |_ a
       |_ test_module.test_func[param_a_1]
       |_ ...
       |_ test_module.test_func[param_a_25]
    |_ b
       |_ test_module.test_func[param_b_1]
       |_ ...
       |_ test_module.test_func[param_b_12]
    |_ ...

有没有更好的办法


Tags: inpytestifparampytestdefnot

热门问题