I am trying to use unittest.mock, but I am getting an error:
AttributeError: does not have the attribute 'get_pledge_frequency'
I have the following file structure:
pledges/views/
├── __init__.py
├── util.py
└── user_profile.py
pledges/tests/unit/profile
├── __init__.py
└── test_user.py
Inside pledges/views/__init___.py I have:
from .views import *
from .account import account
from .splash import splash
from .preferences import preferences
from .user_profile import user_profile
Inside, user_profile.py I have a function called user_profile which calls a function inside util.py called get_pledge_frequency as follows:
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
I have a test inside test_user.py as follows:
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
I have checked other questions, but the answers do not cover when there is a function called as the module, and it is imported in the __init__ file.
So, is there any way to solve this problem? I have basically renamed the file user_profile.py to profile and then I have changed the tests to refer to the function inside this module, but I wonder if it is possible to keep the function and the module with the same name.