运行 pytest 测试时如何覆盖从另一个模块导入的变量?

问题描述 投票:0回答:1

我正在努力测试更改存储在一个模块中并在另一个模块中使用的变量值的效果。这是一个最小的例子:

我有一个名为 settings.py 的脚本:

from pydantic import BaseSettings, Field
class TestSettings(BaseSettings):
    TEST_BOOL: bool = Field(True, description="Test")
test_env = TestSettings()

在另一个名为 lib.py 的脚本中:

from settings import test_env
def test_bool():
    if test_env.TEST_BOOL == True:
        print(TEST_BOOL is True)
        return True
    else:
        print(TEST_BOOL is False)
        return False

现在尝试使用 pytest 来测试

lib.test_bool
的响应,具体取决于
test_env.TEST_BOOL
是 True 还是 False:

import pytest
import lib
from settings import test_env

@pytest.fixture
def set_env_test_bool():
    # Store the original value
    original_value = test_env.TEST_BOOL
    # Modify the value for testing
    test_env.TEST_BOOL = False
    # Yield control back to the test
    yield
    # Restore the original value
    test_env.TEST_BOOL = original_value

class TestFunctions:
    def test_test_bool_true(self):
        assert lib.test_bool() == True

    @pytest.mark.usefixtures("set_env_test_bool")
    def test_test_bool_false(self):
        assert lib.test_bool() == False

遗憾的是,这不起作用 - 我收到断言错误:

test_test_bool_false - assert True == False
。我还看到打印了“TEST_BOOL is True”。

我做错了什么?为什么 pytest 不使用 TEST_BOOL 的固定值?

我尝试过使用这些灯具的各种组合,但似乎无法使其工作。

python variables pytest fixtures
1个回答
0
投票

尝试将

test_env
对象从
settings.py
动态导入到
test_bool
中的
lib.py
函数中。 当 Python 读取
test_env
的 import 语句时,它会在调用
test_bool
函数之前执行文件并创建对象。当导入 python 模块时,它们会被缓存。我想这就是造成问题的原因。您可以在这里阅读更多相关信息。 尝试这个: 在
lib.py

def test_bool():
   from settings import test_env
   # Rest of the code

这将确保在调用

test_env
函数时使用最新版本的
test_bool

© www.soinside.com 2019 - 2024. All rights reserved.