Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test django messages?

In my django application, I'm trying to write a unit test that performs an action and then checks the messages in the response.

As far as I can tell, there is no nice way of doing this.

I'm using the CookieStorage storage method, and I'd like to do something similar to the following:

    response = self.client.post('/do-something/', follow=True)     self.assertEquals(response.context['messages'][0], "fail.") 

The problem is, all I get back is a

print response.context['messages'] <django.contrib.messages.storage.cookie.CookieStorage object at 0x3c55250> 

How can I turn this into something useful, or am I doing it all wrong?

Thanks, Daniel

like image 222
dvydra Avatar asked May 24 '10 14:05

dvydra


People also ask

How do you write unit test cases in Django?

To write a test you derive from any of the Django (or unittest) test base classes (SimpleTestCase, TransactionTestCase, TestCase, LiveServerTestCase) and then write separate methods to check that specific functionality works as expected (tests use "assert" methods to test that expressions result in True or False values ...

Does Django use unittest?

Writing testsDjango's unit tests use a Python standard library module: unittest . This module defines tests using a class-based approach. When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.


2 Answers

I found a really easy approach:

response = self.client.post('/foo/') messages = list(response.context['messages']) self.assertEqual(len(messages), 1) self.assertEqual(str(messages[0]), 'my message') 

If you need to check for messages on a response that has no context you can use the following:

from django.contrib.messages import get_messages messages = list(get_messages(response.wsgi_request)) self.assertEqual(len(messages), 1) self.assertEqual(str(messages[0]), 'my message') 

The fallback storage doesn't support indexing, however it is an iterable.

like image 88
daveoncode Avatar answered Sep 30 '22 04:09

daveoncode


From django documentation:

Outside of templates, you can use get_messages()

So, you could write something like:

from django.contrib.messages import get_messages  [...]  messages = [m.message for m in get_messages(response.wsgi_request)] self.assertIn('My message', messages) 

like image 26
moppag Avatar answered Sep 30 '22 04:09

moppag