Unit testing decorators in Python

decorator, django, python, unit-testing

Solution

I suppose that you can easily mock the `request` object, then decorate a trivial function with your decorator and pass that request a parameter.

I also suppose that your `_wrapper` does not really have an unused `request` parameter?

Problem

I wrote the following decorator to be used in some Django views where I don't want the user to be logged in (like register and forgot-password): ``` def not_logged_in(view, redirect_url=None): def _wrapper(request, *args, **kwargs): if request.user.is_authenticated(): return HttpResponseRedirect( redirect_url or '/' ) return view(*args, **kwargs) return _wrapper ``` Once I have it, I can easily write: ``` @not_logged_in def register(request): ... ``` I have written unit tests for the views that are using it, and it is working without problems, but I'm wondering what would be the best way of unit testing the `not_logged_in` function alone?

Original source