为了避免循环导入,我被迫定义一个看起来像这样的函数:
# do_something.py
def do_it():
from .helpers import do_it_helper
# do stuff
Run Code Online (Sandbox Code Playgroud)
现在我希望能够通过do_it_helper修补来测试这个功能.如果导入是顶级导入,
class Test_do_it(unittest.TestCase):
def test_do_it(self):
with patch('do_something.do_it_helper') as helper_mock:
helper_mock.return_value = 12
# test things
Run Code Online (Sandbox Code Playgroud)
会工作得很好.但是,上面的代码给了我:
AttributeError: <module 'do_something'> does not have the attribute 'do_it_helper'
Run Code Online (Sandbox Code Playgroud)
一时兴起,我也尝试将补丁语句更改为:
with patch('do_something.do_it.do_it_helper') as helper_mock:
Run Code Online (Sandbox Code Playgroud)
但这产生了类似的错误.有没有办法模拟这个函数,因为我被迫在它使用的函数中导入它?