我正在检查this,试图在模块级变量中赋值一个方法调用,目的是只执行一次,但不确定为什么在运行任何单元测试之前,它将遍历模块的所有全局引用,问题是我有一个第三方方法,该方法正在分配给一个全局变量,但由于试图执行第一次传递中的实际方法,我发现即使在一个简单的本地方法中,这种行为也是相同的,这里是一个复制它的示例,它位于一个名为
project_name.app.py
def printing_values():
# this is corrected mocked, as I am using patch in unit test to
# mock this but only available in the context of the test but not
# globally
print('from mocked printing_values method', SSM_VALUE)
return SSM_VALUE
def get_ssm():
return "value_from_method"
# this line will execute get_ssm before any unit test,
# how mock this to always have a mock value
SSM_VALUE = get_ssm()这是我的单元测试
""" response_transformer TESTS """
import unittest
from unittest import mock
import project_name.app
class TestGlobalVariable(unittest.TestCase):
@mock.patch('project_name.app.SSM_VALUE', 'testing_value')
def test_success_response_global_variable(self):
response = project_name.app.printing_values()
assert response == "testing_value"因此,我想模拟SSM_VALUE,但不执行与它相关的get_ssm方法,我应该如何实现这一点?
发布于 2022-07-02 10:49:45
""" response_transformer TESTS """
import unittest from unittest import mock
import project_name.app
class TestGlobalVariable(unittest.TestCase):
@mock.patch('project_name.app.printing_values')
def test_success_response_global_variable(self, mock_printing_values):
mock_printing_values.return_value = 'testing_value'
response = project_name.app.printing_values()
assert response == "testing_value"https://stackoverflow.com/questions/67662815
复制相似问题