【发布时间】:2021-03-24 13:40:59
【问题描述】:
我们有一个 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 中有一种简单的方法可以解决这个问题,但还没有发现这个秘密。有什么方法可以避免在测试运行之前加载常量文件?任何想法都表示赞赏。
【问题讨论】:
-
这对测试没有多大意义,因为您基本上是在测试 os.environ.get 是否有效。
标签: python pytest monkeypatching