[Django]-Test Django views that require login using RequestFactory

54👍

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).

25👍

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 View


class SomePageTest(TestCase):

    def setUp(self):
        self.factory = RequestFactory()

    def test_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)
👤Will

Leave a comment