看起来按照命令行选项控制测试跳过的真正方法是将测试标记为动态 跳过 :
使用 pytest_addoption* 钩子添加 选项, 如下所示: *
def pytest_addoption(parser):
parser.addoption(
“–runslow”, action=”store_true”, default=False, help=”run slow tests”
)使用 pytest_collection_modifyitems 钩子添加标记,如下所示:
def pytest_collection_modifyitems(config, items):
if config.getoption(“–runslow”):
# –runslow given in cli: do not skip slow tests
return
skip_slow = pytest.mark.skip(reason=”need –runslow option to run”)
for item in items:
if “slow” in item.keywords:
item.add_marker(skip_slow)在测试中添加标记:
@pytest.mark.slow
def test_func_slow():
pass
例如,如果您想在测试中使用CLI中的数据,则使用它的 凭据
,足以在从pytestconfig检索数据时指定跳过选项:
使用 pytest_addoption* 钩子添加 选项, 如下所示: *
def pytest_addoption(parser):
parser.addoption(
“–credentials”,
action=”store”,
default=None,
help=”credentials to …”
)从pytestconfig获取它时使用 跳过 选项
@pytest.fixture(scope=”session”)
def super_secret_fixture(pytestconfig):
credentials = pytestconfig.getoption(‘–credentials’, skip=True)
…在测试中照常使用夹具:
def test_with_fixture(super_secret_fixture):
…
在这种情况下,您会收到类似这样的内容,即您不向
--credentialsCLI发送选项:
Skipped: no 'credentials' option found
最好使用_pytest.config.get_config而不是不推荐使用的
pytest.config
如果您仍然不愿意像这样使用pytest.mark.skipif:
@pytest.mark.skipif(not _pytest.config.get_config().getoption('--credentials'), reason="--credentials was not specified")


