Search code examples
python-3.xdjangopython-unittestdjango-testing

How to mock a function that returns a user object


I am trying to mock a method that returns a user object like so

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

It's failing with the error: NameError: name 'self' is not defined . I defined self.user2 in the setup method of the test class.


Solution

  • You cannot use self in the decorator - the object is not defined yet at the point this is parsed.

    Instead you can move the patching into the method:

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

    or

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