0

I have a class with an attribute that calls a function:

users.mixins.py:

from django.contrib import messages    
from ..utils.services import redirect_to_previous

class AdminRightsMixin:

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_admin:
            messages.warning(
                request, 'You must have administrator rights to view this page.'
            )
            redirect_to_previous(request)
        return super().dispatch(request, *args, **kwargs)

I want to test that redirect_to_previous is called, but I don't know how to mock this in my test.

For example:

@patch.object(AdminRightsMixin.dispatch, 'redirect_to_previous')
def test_admin_mixin(self, mock_class):
    // code

Results in AttributeError: <function AdminRightsMixin.dispatch at 0x000001D54FDB6430> does not have the attribute 'redirect_to_previous'

alias51
  • 8,178
  • 22
  • 94
  • 166
  • 1
    You have to mock `redirect_to_previous` from where it is imported - check [where to patch](https://docs.python.org/3/library/unittest.mock.html#id6). If it is a function of `AdminRightsMixin`, you have to patch it in that class, e.g. `@patch.object(AdminRightsMixin, 'redirect_to_previous')` – MrBean Bremen Aug 08 '20 at 18:25
  • Thanks, that still results in `AttributeError: does not have the attribute 'redirect_to_previous'` presumably because it's not an attribute but a function inside an attribute? – alias51 Aug 09 '20 at 18:26
  • 1
    Well, I don't know where it is defined - that was only a guess (wrong guess, as it is not called using 'self'', missed that) - but it is obviously a function that is either defined in this module, or imported from somewhere. Can you adapt your question to show where it comes from? – MrBean Bremen Aug 09 '20 at 18:45
  • Yes of course, thank you. Please see the update. – alias51 Aug 09 '20 at 19:03
  • 1
    I guess the path is `users/mixins.py`. In this case `@patch('users.mixins.redirect_to_previous')` should work, as the function reference you want to patch lives in that module. Check for example [my previous answer to another question](https://stackoverflow.com/a/62625882/12480730). – MrBean Bremen Aug 09 '20 at 19:09
  • Got it, if you want to add this as an answer I will accept it. Thanks – alias51 Aug 09 '20 at 19:36
  • 1
    This has been answered before (like in my own answer linked in the previous comment), so it is probably not worth it. Glad I could help anyway! – MrBean Bremen Aug 09 '20 at 19:40

0 Answers0