Skip to content Skip to sidebar Skip to footer

Test Django Views That Require Login Using Requestfactory

I'm new to Django and I'd like to unit test a view that requires the user to be logged in (@login_requred). Django kindly provides the RequestFactory, which I can theoretically use

Solution 1:

When using RequestFactory, you are testing view with exactly known inputs.

That allows isolating tests from the impact of the additional processing performed by various installed middleware components and thus more precisely testing.

You can setup request with any additional data that view function expect, ie:

request.user = AnonymousUser()
    request.session = {}

My personal recommendation is to use TestClient to do integration testing (ie: entire user checkout process in shop which includes many steps) and RequestFactory to test independent view functions behavior and their output (ie. adding product to cart).

Solution 2:

As @bmihelac mentioned, RequestFactory is only testing known inputs (which means no middleware is included). For details about the reasoning, read here. The accepted solution is great if you want a blank session (and I agree with @dm03514 that Client should be used for integration testing).

However, if you still want to use Django's SessionMiddleware (or any Middleware), you can do something like this in your tests (the example below is for testing a Class Based View):

from django.contrib.sessions.middleware import SessionMiddleware
from django.test import TestCase, RequestFactory
from someapp.views import SomeView  # a Class Based ViewclassSomePageTest(TestCase):

    defsetUp(self):
        self.factory = RequestFactory()

    deftest_some_page_requires_session_middleware(self):
        # Setup
        request = self.factory.get('somepage.html')
        middleware = SessionMiddleware()
        middleware.process_request(request)
        request.session.save()

        response = SomeView.as_view()(request)

        self.assertEqual(response.status_code, 200)

Post a Comment for "Test Django Views That Require Login Using Requestfactory"