Python修补导入模块中的函数



我正在尝试创建一个使用Python补丁的单元测试,但我无法使其工作。我试过各种方法来修补,但都没有成功。

要测试的文件:test_me.py导入另一个File.py,它包含这里需要的两个函数(以及许多其他函数(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中,我有两个模拟函数,还需要对这些函数进行修补。

测试中.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):

最新更新