Why don't my Django unittests know that MessageMiddleware is installed?

Django 1.4 has a bug when you create the request with RequestFactory.

To resolve this issue, create your request with RequestFactory and do this:

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

Works for me!


A way to solve this quite elegant is to mock the messages module using mock

Say you have a class based view named FooView in app named myapp

from django.contrib import messages
from django.views.generic import TemplateView

class FooView(TemplateView):
    def post(self, request, *args, **kwargs):
        ...
        messages.add_message(request, messages.SUCCESS, '\o/ Profit \o/')
        ...

You now can test it with

def test_successful_post(self):
    mock_messages = patch('myapp.views.FooView.messages').start()
    mock_messages.SUCCESS = success = 'super duper'
    request = self.rf.post('/', {})
    view = FooView.as_view()
    response = view(request)
    msg = _(u'\o/ Profit \o/')
    mock_messages.add_message.assert_called_with(request, success, msg)