python - How to test if a view is decorated with "login_required" (Django) -
i'm doing (isolated) unit test view decorated "login_required". example:
@login_required def my_view(request): return httpresponse('test')
is possible test "my_view" function decorated "login_required"?
i know can test behaviour (anonymous user redirected login page) integration test (using test client) i'd isolated test.
any idea?
thanks!
sure, must possible test in way. it's not worth it, though. writing isolated unit test check decorator applied result in complicated test. there way higher chance test wrong tested behaviour wrong. discourage it.
the easiest way test use django's client
fake request associated url, , check redirect. if you're using of django's testcases 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 more complicated, bit more isolated test call view directly using requestfactory create request object. assertredirects()
won't work in case, since depends on attributes set client
:
from django.test.client import requestfactory class mytestcase(django.test.testcase): @classmethod def 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) ...
Comments
Post a Comment