遵循suggested in the pytest docs 的方法,因此the answer of @Manu_CJ,肯定是这里的方法。
我只是想展示如何调整它以轻松定义多个选项:
canonical example given by the pytest docs 很好地突出了如何通过命令行选项添加单个标记。但是,让它添加多个标记可能并不简单,因为三个钩子 pytest_addoption、pytest_configure 和 pytest_collection_modifyitems 都需要被调用以允许通过命令行添加单个标记选项。
这是调整规范示例的一种方式,如果您有多个标记,例如 'flag1'、'flag2' 等,您希望能够通过命令行添加选项:
# content of conftest.py
import pytest
# Create a dict of markers.
# The key is used as option, so --{key} will run all tests marked with key.
# The value must be a dict that specifies:
# 1. 'help': the command line help text
# 2. 'marker-descr': a description of the marker
# 3. 'skip-reason': displayed reason whenever a test with this marker is skipped.
optional_markers = {
"flag1": {"help": "<Command line help text for flag1...>",
"marker-descr": "<Description of the marker...>",
"skip-reason": "Test only runs with the --{} option."},
"flag2": {"help": "<Command line help text for flag2...>",
"marker-descr": "<Description of the marker...>",
"skip-reason": "Test only runs with the --{} option."},
# add further markers here
}
def pytest_addoption(parser):
for marker, info in optional_markers.items():
parser.addoption("--{}".format(marker), action="store_true",
default=False, help=info['help'])
def pytest_configure(config):
for marker, info in optional_markers.items():
config.addinivalue_line("markers",
"{}: {}".format(marker, info['marker-descr']))
def pytest_collection_modifyitems(config, items):
for marker, info in optional_markers.items():
if not config.getoption("--{}".format(marker)):
skip_test = pytest.mark.skip(
reason=info['skip-reason'].format(marker)
)
for item in items:
if marker in item.keywords:
item.add_marker(skip_test)
现在您可以在测试模块中使用optional_markers 中定义的标记:
# content of test_module.py
import pytest
@pytest.mark.flag1
def test_some_func():
pass
@pytest.mark.flag2
def test_other_func():
pass