Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I setup messaging and session middleware in a Django RequestFactory during unit testing

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.

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.

I am using the RequestFactory to create my request. The documentation says:

It does not support middleware. Session and authentication attributes must be supplied by the test itself if required for the view to function properly.

How do I setup the messaging middleware with the RequestFactory? I think I will also need the session middleware to make the messaging middleware work

This is the error my test currently produces when using the vanilla RequestFactory.

MessageFailure: You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware

This is my function under test, in case it helps with understanding this problem:

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)
like image 447
Devin Avatar asked May 26 '14 00:05

Devin


People also ask

What is RequestFactory in Django?

The request factory The API for the RequestFactory is a slightly restricted subset of the test client API: It only has access to the HTTP methods get() , post() , put() , delete() , head() , options() , and trace() . These methods accept all the same arguments except for follow .

What is self client in Django?

self. client , is the built-in Django test client. This isn't a real browser, and doesn't even make real requests. It just constructs a Django HttpRequest object and passes it through the request/response process - middleware, URL resolver, view, template - and returns whatever Django produces.

Where does Django store test database?

from the docs: When using SQLite, the tests will use an in-memory database by default (i.e., the database will be created in memory, bypassing the filesystem entirely!).


1 Answers

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)
like image 193
DanaG Avatar answered Sep 20 '22 08:09

DanaG