title: How do I setup messaging and session middleware in a Django RequestFactory during unit testing
body: <p>I have a function I need to test which takes a request as its argument. It is not exposed as a view by URL so I cannot test it with the test client.</p>
  
  <p>I need to pass a request object to it, and the request object needs to have the messaging middleware enabled because messaging middleware is used in the function.</p>
  
  <p>I am using the RequestFactory to create my request. The <a href="https://docs.djangoproject.com/en/dev/topics/testing/advanced/#django.test.client.RequestFactory">documentation</a> says:</p>
  
  <blockquote>
    <p>It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.</p>
  </blockquote>
  
  <p><strong>How do I setup the messaging middleware with the RequestFactory?</strong> I think I will also need the session middleware to make the messaging middleware work</p>
  
  <p>This is the error my test currently produces when using the vanilla RequestFactory.</p>
  
  <pre><code>MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
  </code></pre>
  
  <p>This is my function under test, in case it helps with understanding this problem:</p>
  
  <pre><code>from django.contrib import messages as django_messages
  
  def store_to_request(self, request):
          """
          Place all the messages stored in this class into message storage in
          the request object supplied.
          :param request: The request object to which we should store all the messages
          :return: Does not return anything
          """
          for message in self._messages:
              django_messages.add_message(request, message.level, message.message, message.extra_tags,
                                      message.fail_silently)
  </code></pre>