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)
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 .
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.
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!).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With