Pytest无法读取pytest.ini自定义配置 报unknown configuration value错误
pytest自定义ini配置报错
ValueError: unknown configuration value: 'rmse' 解决方案 你的报错是两个核心问题导致的,按以下步骤修复即可:
- 调整
pytest_addoption钩子的放置位置
pytest的配置钩子函数必须放在项目根目录的conftest.py文件中才会被提前加载执行,放在测试文件内的钩子不会在pytest初始化配置阶段被识别,因此pytest无法感知你定义的自定义ini配置项,才会抛出未知配置值的错误。
如果你的项目根目录没有conftest.py,新建后写入以下内容:
def pytest_addoption(parser): parser.addini("rmse", "Min RMSE score for a model to past post-train test") parser.addini( "inference_time", "Max inference time for the model to be making predictions" )
写完后删除测试文件tests/test_post_train.py里的pytest_addoption函数代码。
- 修正测试用例的类型转换逻辑
request.config.getini()读取到的ini配置值默认是字符串类型,你在pytest.ini里写的40_000会被读取为字符串"40_000",直接和整数40_000做断言会失败,需要手动转换为对应数值类型。
修改后的tests/test_post_train.py内容如下:
def test_config(request): score = int(request.config.getini("rmse")) assert score == 40_000 # 读取inference_time的话需要转浮点,示例如下: # infer_time = float(request.config.getini("inference_time")) # assert infer_time == 0.5
- 确认文件位置正确
保证pytest.ini和conftest.py都放在项目根目录,和tests文件夹同级,pytest会自动识别根目录下的这两个配置文件。
内容的提问来源于stack exchange,提问作者yudhiesh
相关产品推荐
相关产品推荐

