Looks like true way to Control skipping of tests according to command line option is mark tests as skip dynamically:使用 pytest_addoption 钩子添加 option 如下:add option using pytest_addoption hook like this:def pytest_addoption(parser): parser.addoption( "--runslow", action="store_true", default=False, help="run slow tests" )使用 pytest_collection_modifyitems 钩子添加如下标记:Use pytest_collection_modifyitems hook to add marker like this: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.slowdef test_func_slow(): pass如果您想在测试中使用来自 CLI 的数据,例如,它是凭据,足以指定一个 skip option 从 pytestconfig:If you want to use the data from the CLI in a test, for example, it`s credentials, enough to specify a skip option when retrieving them from the pytestconfig:使用 pytest_addoption 钩子添加 option 如下:add option using pytest_addoption hook like this:def pytest_addoption(parser): parser.addoption( "--credentials", action="store", default=None, help="credentials to ..." )从 pytestconfig 获取时使用 skip 选项@pytest.fixture(scope="session")def super_secret_fixture(pytestconfig): credentials = pytestconfig.getoption('--credentials', skip=True) ...在测试中照常使用夹具:def test_with_fixture(super_secret_fixture): ...在这种情况下,你会得到这样的东西,你不需要向 CLI 发送 --credentials 选项:In this case you will got something like this it you not send --credentials option to CLI:Skipped: no 'credentials' option found最好使用 _pytest.config.get_config 而不是已弃用的 pytest.config 如果您仍然不想使用 pytest.mark.skipif 像这样:It is better to use _pytest.config.get_config instead of deprecated pytest.config If you still wont to use pytest.mark.skipif like this:@pytest.mark.skipif(not _pytest.config.get_config().getoption('--credentials'), reason="--credentials was not specified") 这篇关于在 pytest skip-if 条件中使用命令行选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-28 05:44