我正在尝试使用unittest.mock
,但出现了一个错误:
AttributeError: does not have the attribute 'get_pledge_frequency'
我有以下文件结构:
pledges/views/
├── __init__.py
├── util.py
└── user_profile.py
pledges/tests/unit/profile
├── __init__.py
└── test_user.py
在pledges/views/__init___.py
我有:
from .views import *
from .account import account
from .splash import splash
from .preferences import preferences
from .user_profile import user_profile
在user_profile.py
内部,我有一个名为user_profile
的函数,它在util.py
内部调用一个名为get_pledge_frequency
的函数,如下所示:
def user_profile(request, user_id):
# some logic
# !!!!!!!!!!!!!!!!
a, b = get_pledge_frequency(parameter) # this is the function I want to mock
# more logic
return some_value
我在test_user.py
中有一个测试,如下所示:
def test_name():
with mock.patch(
"pledges.views.user_profile.get_pledge_frequency"
) as get_pledge_frequency:
get_pledge_frequency.return_value = ([], [])
response = c.get(
reverse("pledges:user_profile", kwargs={"user_id": user.id})
) # this calls the function user_profile inside pledges.user_profile
# some asserts to verify functionality
我已经检查了其他问题,但是答案不包括什么时候有一个称为模块的函数,它被导入到__init__
文件中。你知道吗
那么,有没有办法解决这个问题呢?我基本上已经将文件user_profile.py
重命名为profile
,然后我更改了测试以引用这个模块中的函数,但是我想知道是否有可能保持函数和模块的名称相同。你知道吗
事实证明,可以模拟在具有相同名称的模块中的函数中调用的函数。 一个围绕
unittest.mock.patch()
的小包装器可以这样做:代码:
使用方法:
而不是:
您需要:
这是怎么回事?
基本思想是尝试从最长的模块路径向最短的路径导入模块,如果导入成功,则将该模块用作修补对象。你知道吗
测试代码:
中的测试文件module
结果:
相关问题 更多 >
编程相关推荐