[英]Python patch a function from an import module
我正在尝试创建一个使用 Python 补丁的单元测试,但我无法让它工作。 我尝试了各种方法来修补,但没有成功。
要测试的文件:test_me.py 导入 another_file.py,其中包含 2 个函数(以及许多其他函数),func1 和 func2,这是此处需要的。
在 test_me.py 中:
import another_file.py as another_file_alias
# Make use of the 2 functions
another_file_alias.func1()
another_file_alias.func2()
在实际的单元测试 test.py 中,我有 2 个模拟函数,并且还需要修补这些函数。
在 test.py 中:
def func1_mock():
...
def func2_mock():
...
class TestClass(unittest.TestCase):
def setUp(self):
with patch("another_file.func1", side_effect=func1_mock):
with patch("another_file.func2", side_effect=func2_mock):
def test_1(self):
...
您需要在补丁目标中包含模块名称,然后是导入的别名,例如:
def setUp(self):
with patch("test_me.another_file_alias.func1", side_effect=func1_mock):
with patch("test_me.another_file_alias.func2", side_effect=func2_mock):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.