I'm doing some (isolated) unit test for a view which is decorated with "login_required". Example:
@login_required
def my_view(request):
return HttpResponse('test')
Is it possible to test that the "my_view" function is decorated with "login_required"?
I know I can test the behaviour (anonymous user is redirected to login page) with an integration test (using the test client) but I'd like to do it with an isolated test.
Any idea?
Thanks!
Use Django's Test Client to check for proper redirects in case a user is loggedin and when not loggedin.
MOCK Library:
For an isolated test or 'pure' unit testing, you can use the
mock
module.Mock is a library for testing in Python. It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used.
Mock is based on the ‘action -> assertion’ pattern instead of ‘record -> replay’ used by many mocking frameworks.
You will have to create a mock object. Mock objects create all attributes and methods as you access them and store details of how they have been used. You can configure them, to specify return values or limit what attributes are available, and then make assertions about how they have been used:
The tests with mock objects will test only whether
my_view
function is decorated withlogin_required
. You don't need to setup other attributes.Check out the docs on how to write tests using mock objects using this link.
Also, following SO links might help on how to monkey-patch a decorator.