使用文件中的 Pytest 标记而不是命令行

问题描述

我在 pytest 中有测试,每个测试都有一个唯一的标记,与我们的测试管理系统 TestRail 中的测试用例编号相关

示例:

@pytest.mark.C1234
def test_mytestC1234():
    pass

@pytest.mark.C1235
def test_mytestC1235():
    pass

我知道我可以从命令行运行测试:

pytest -m C1234 OR C1235

有没有办法从文件中运行标记列表。 该文件将根据 TestRail 中的测试计划即时构建

问题是这个列表会变得非常大,命令行不能支持那么多字符。

类似于:

pytest -mf myfile.txt

文件 myfile.txt 包含标记列表。

解决方法

我找不到执行此操作的内置方法,但您可以添加具有以下内容的 conftest.py 文件(部分基于 this hook)。

RUNTESTS = "--run-tests"


def pytest_addoption(parser):
    group = parser.getgroup("filter")
    group.addoption(
        RUNTESTS,action="store",help="Path to file containing markers to run",)


def pytest_collection_modifyitems(config,items):
    if not config.getoption(RUNTESTS):
        return
    with open(config.getoption(RUNTESTS)) as f:
        markers = set(f.read().strip().split())
    deselected = []
    remaining = []
    for item in items:
        if any([mark.name in markers for mark in item.own_markers]):
            remaining.append(item)
        else:
            deselected.append(item)
    if deselected:
        config.hook.pytest_deselected(items=deselected)
        items[:] = remaining

然后,假设您在 myfile.txt 中有一个以换行符分隔的标记列表,您只能使用这些标记运行测试:

pytest --run-tests myfile.txt