Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 897
Rayhan Muktader Avatar asked Sep 10 '26 05:09

Rayhan Muktader


1 Answers

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.

like image 93
Pavel Shishmarev Avatar answered Sep 11 '26 19:09

Pavel Shishmarev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!