python - 使用 pytest 测试常量声明
问题描述
我们有一个 Python 3.7 应用程序,它有一个声明为以下形式的 constants.py 文件:
APP_CONSTANT_1 = os.environ.get('app-constant-1-value')
在 test.py 中,我们希望使用类似这样的方法来测试这些常量的设置(这是高度简化的,但代表了核心问题):
class TestConfig:
"""General config tests"""
@pytest.fixture
def mock_os_environ(self, monkeypatch):
""" """
def mock_get(*args, **kwargs):
return 'test_config_value'
monkeypatch.setattr(os.environ, "get", mock_get)
def test_mock_env_vars(self, mock_os_environ):
import constants
assert os.environ.get('app-constant-1-value') == 'test_config_value' #passes
assert constants.APP_CONSTANT_1 == 'test_config_value' #fails
第二个断言失败,因为 constants.constants.APP_CONSTANT_1 为 None。事实证明,constants.py 似乎是在 pytest 的“收集”阶段加载的,因此在运行测试时已经设置好了。
我们在这里缺少什么?我觉得在 pytest 中有一种简单的方法可以解决这个问题,但还没有发现这个秘密。有什么方法可以避免在测试运行之前加载常量文件?任何想法表示赞赏。
解决方案
问题很可能是constants
以前加载过的。为确保它获得修补后的值,您必须重新加载它:
import os
from importlib import reload
import pytest
import constants
class TestConfig:
"""General config tests"""
@pytest.fixture
def mock_os_environ(self, monkeypatch):
""" """
monkeypatch.setenv('app-constant-1-value', 'test_config_value')
reload(constants)
def test_mock_env_vars(self, mock_os_environ):
assert os.environ.get('app-constant-1-value') == 'test_config_value'
assert app.APP_CONSTANT_1 == 'test_config_value'
请注意,我曾经monkeypatch.setenv
专门设置您需要的变量。如果您不需要更改所有环境变量,这更容易使用。
推荐阅读
- java - 使用 Android Emulator 从 Eclipse 执行简单的 Appium 脚本时遇到问题,请帮助我确定问题
- flutter - 如何在颤动的计时器应用程序中添加振动
- reactjs - 我想在将api调用传递给redux saga之前拦截它们以检查是否需要刷新Access Token
- c++ - Arduino 代码 - 每分钟执行相同的操作
- java - 尝试显示不在菜单中的片段时,导航抽屉活动项目中的片段重叠
- python - 我如何覆盖 Django Rest Auth 注册?
- python - AttributeError: 'str' 对象没有属性 'ndim' [Python | 喀拉斯]
- python - 在 Python 中使用 AutoReg 函数进行 1 个月预测
- python - Formset 保存除 0 以外的任何小数,即使 formset 已保存且 is_valid() 通过
- java - 如何在 java 中编写(和修复)没有循环的代码