[Fixed]-How do I setup messaging and session middleware in a Django RequestFactory during unit testing

21👍

This issue was raised, so as there said, you can fix your unit tests using that code:

from django.contrib.messages.storage.fallback import FallbackStorage
setattr(request, 'session', 'session')
messages = FallbackStorage(request)
setattr(request, '_messages', messages)
👤DanaG

4👍

If you don’t need to test the behaviour of the request object itself you could mock the request using the mock library instead of RequestFactory e.g:

import mock

request = mock.MagicMock()

# Call your function using the mocked request
store_to_request(request)

2👍

An effictively equivalent method to Danag’s anwer would be to pass the request object through the process_request methods of the session and message middlewares (in that order) before passing it to the view/function:

from django.contrib.sessions.middleware import SessionMiddleware
from django.contrib.messages.middleware import MessageMiddleware

request = request_factory.get()
sm = SessionMiddleware()
sm.process_request(request)
mm = MessageMiddleware()
mm.process_request(request)

You can do the above in a method for convenience:

class MessageDependentTests(TestCase):
    
    def setUp(self):
        self.rf = RequestFactory()
        self.sm = SessionMiddleware()
        self.mm = MessageMiddleware()
        return super().setUp()
        
    def prepare_request(self, request):
        self.sm.process_request(request)
        self.mm.process_request(request)

    def test_something(self):
        request = self.rf.get('/')
        self.prepare_request(request)
        response = my_view(request)
        # test response below

Leave a comment