我正在尝试模拟导入模块时执行的函数调用,下面是我遇到的问题的示例
app/module.py
from util import get_param
PARAM = get_param('param_name')
class sample():
def run_sample(self):
print(PARAM)
app/tests/test_module.py
from app import module
import unittest
class TestSample(unittest.TestCase):
@mock.patch('app.module.get_param')
def test_run_sample(self, mock_get_param):
test_obj = module.sample()
test_obj.run_sample()
这不起作用,它调用原始的 get_param 方法而不是模拟它。
我最近遇到过这种情况,我采用的解决方案有点hacky,涉及修改内部模块缓存。
#define mocked symbol
get_param = Mock()
class TestSample:
@pytest.fixture
def import_time_mock(self):
# Trick python into thinking current test-file is target module
orig = sys.modules["app.module"]
sys.modules["app.module"] = sys.modules[__name__]
nonlocal get_param
yield get_param
# Restore modules cache
sys.modules["app.module"] = orig
def test_run_sample(self, import_time_mock):
from app import module
test_obj = module.sample()
test_obj.run_sample()
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)