Check Django messages (quantity and type) in unit tests

Ok, in this short (but I hope very helpful post), I’m gonna show how to check messages (Django messages framework) in your tests.
I don’t know if there is a better or “normalized” way to do this, but it’s the simplest and effective way I found by myself… so, let’s suppose we have a test in which we want to check that if the submitted form data is invalid, an error message is sent back with the response context:

def testIfSubmittedDataIsInvalidAnErrorMessageIsReturned(self):
    response = self.client.post(self.url, {})
    messages = list(response.context['messages'])
    self.assertEqual(len(messages), 1)
    self.assertEqual(messages[0].level, MSG.ERROR)

MSG is a reference to messages levels constants imported in this way:

from django.contrib.messages import constants as MSG
  • lolo

    Hey this actually Works!!! thanks so much!

  • Amir Qayyum Khan

    getting error

    response = self.client.post(url, data=data, follow=True)
    messages = list(response.context[‘messages’])
    TypeError: ‘NoneType’ object has no attribute ‘__getitem__”

  • that means you don’t actually have the context object in the response (__getitem__ is automatically called when accessing a dictionary key using the brackets notation)