pythondjangopython-unittestdjango-testingpython-unittest.mock

How do I mock a function in Django?


I expect the following call to which_user to return self.user no matter what is passed into it but it's behaving as if it is not mocked at all.

def test_user_can_retrieve_favs_using_impersonation(self):
        with mock.patch('impersonate.helpers.which_user', return_value=self.user):
            user = which_user(self.user2)

What am I doing wrong here? I imported which_user like so: from impersonate.helpers import which_user if that helps.


Solution

  • You need to mock function by its path to which it's imported. For example, you use your function inside myapp's views. So you need to do it in following way:

    with mock.patch('myapp.views.which_user', return_value=self.user):
            user = which_user(self.user2)
    

    This is because it patches only variables defined in testable module, not patching original libraries and packages in the system or venv.