2

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.

Rayhan Muktader
  • 2,038
  • 2
  • 15
  • 32

1 Answers1

5

You need to mock function by it's 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.

Pavel Shishmarev
  • 1,335
  • 9
  • 24