首页 > 解决方案 > 使用 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 中有一种简单的方法可以解决这个问题,但还没有发现这个秘密。有什么方法可以避免在测试运行之前加载常量文件?任何想法表示赞赏。

标签: pythonpytestmonkeypatching

解决方案


问题很可能是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专门设置您需要的变量。如果您不需要更改所有环境变量,这更容易使用。


推荐阅读