使用文件中的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文件(部分基于此挂钩(。

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

最新更新