如何为已参数化的pytest测试添加命令行参数?
解决pytest中
fixture 'config' not found错误 问题原因
你在定义xyz fixture时,直接将config作为参数传入,但当前使用的pytest版本不支持直接引用config内置fixture,导致pytest无法找到该fixture。
修正方案
方案一:通过request内置fixture获取配置(兼容性更好)
修改conftest.py中的xyz fixture,改用request内置fixture来获取配置对象:
def pytest_addoption(parser): parser.addoption( "--some_other_option", action="store_true", default=True, help="Skip some tests" ) parser.addoption( "--xyz", action="store_true", default=True, help="Test xyz" ) @pytest.fixture def xyz(request): return request.config.getoption('--xyz')
方案二:直接使用config fixture(仅适用于pytest 6.0+版本)
如果你的pytest版本在6.0及以上,可以直接引用config内置fixture,需先确认环境安装的pytest版本符合要求:
def pytest_addoption(parser): parser.addoption( "--some_other_option", action="store_true", default=True, help="Skip some tests" ) parser.addoption( "--xyz", action="store_true", default=True, help="Test xyz" ) @pytest.fixture def xyz(config): return config.getoption('--xyz')
使用说明
修改完成后,可通过命令行参数控制xyz的值:
- 保持默认
True:直接运行测试,无需额外参数 - 设置为
False:运行测试时添加--no-xyz参数
内容的提问来源于stack exchange,提问作者Hauptideal
相关产品推荐
相关产品推荐

