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!
Sure, it must be possible to test it in some way. It's definitely not worth it, though. Writing a fully isolated unit test to check that the decorator is applied will only result in a very complicated test. There is a way higher chance that the test will be wrong than that the tested behaviour is wrong. I would strongly discourage it.
The easiest way to test it is to use Django's Client
to fake a request to the associated url, and check for a redirect. If you're using any of Django's testcases as your base class:
class MyTestCase(django.test.TestCase):def test_login_required(self):response = self.client.get(reverse(my_view))self.assertRedirects(response, reverse('login'))
A slightly more complicated, but a bit more isolated test would be to call the view directly using the RequestFactory to create a request object. assertRedirects()
won't work in this case, since it depends on attributes set by the Client
:
from django.test.client import RequestFactoryclass MyTestCase(django.test.TestCase):@classmethoddef setUpClass(cls):super(MyTestCase, cls).setUpClass()self.rf = RequestFactory()def test_login_required(self):request = self.rf.get('/path/to/view')response = my_view(request, *args, **kwargs)self.assertEqual(response.status_code, 302)self.assertEqual(response['Location'], login_url)...