|-- my_module
| |-- __init__.py
| |-- function.py
`-- test.py
在function.py中:
import other_function
def function():
doStuff()
other_function()
return
在__init__.py中
from .function import function
在我的test.py中
from django.test import TestCase
from mock import patch
from my_module import function
class Test(TestCase):
@patch('my_module.function.other_function')
def function_test(self, mock_other_function):
function()
当我运行这个时,我得到了一个
AttributeError:
这意味着我正在尝试修补功能“功能”而不是模块“功能”。我不知道该如何修补我要修补的模块。
我也想避免重命名我的模块或功能。
有任何想法吗?
[编辑]
您可以在https://github.com/vthorey/example_mock中找到一个示例
运行
python manage.py test
最佳答案
您可以使用__init__.py
中的其他名称使模块可用:
from . import function as function_module
from .function import function
然后,您可以在
test.py
中执行以下操作:from django.test import TestCase
from mock import patch
from my_module import function
class Test(TestCase):
@patch('my_module.function_module.other_function')
def function_test(self, mock_other_function):
function()
我认为这不是一个特别优雅的解决方案-随便的读者都不太清楚代码。
关于python - 与模块python django模拟同名的patch函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40509588/