【发布时间】:2018-05-11 23:38:16
【问题描述】:
我有一个要测试的 Python 文件 (my_code.py):
import some_module
if some_module.DO_IMPORT:
import other_module
def my_func(self):
print(some_module.DO_IMPORT)
if some_module.DO_IMPORT:
print(other_module.OTHER_VAR)
return true
return false
这是我的测试类(test_my_code.py):
from unittest.mock import patch, Mock
import my_code
class TestMyCode(self):
@patch('my_code.other_module', OTHER_VAR='Other Var')
@patch('my_code.some_module', DO_IMPORT=True)
def_test_my_func(self, *_):
ret = my_code.my_func()
self.assertTrue(ret)
这是抛出错误:
NameError: name 'other_module' is not defined
即使我已修补 some_module.DO_IMPORT 以返回 True,它也不会导入 other_module。 (我确信这一点,因为 some_module.DO_IMPORT 打印为 True)。 some_module.DO_IMPORT 的实际值设置为 False。我可以修补它,但导入仍然无法正常工作。如何让它发挥作用?
【问题讨论】:
-
other_module没有被导入,因为some_module.DO_IMPORT是 False 当它被检查时 - 只有在执行my_func时它才会被猴子修补为 True。 -
感谢@Josh。有解决方法吗?我想覆盖单元测试中的所有代码,但不能更改 DO_IMPORT 的实际值。
标签: python unit-testing mocking patch