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
Simpler version of the stalemate one:
From django documentation:
So, you could write something like:
This works for me (displays all messages):
Also here are a couple of utility methods I have in a test class inherited from Django's TestCase. If you'd prefer to have them as functions, remove the
self
arguments and replaceself.fail()
's with araise
.I found a really easy approach:
If you need to check for messages on a response that has no context you can use the following:
The fallback storage doesn't support indexing, however it is an iterable.
Update
My original answer was written when django was still 1.1 or so. This answer is no longer relevant. See @daveoncode's answer for a better solution.
Original Answer
I did an experiment to test this. I changed the
MESSAGE_STORAGE
setting in one of my projects to'django.contrib.messages.storage.cookie.CookieStorage'
and executed a test that I had written to check for messages. It worked.The key difference from what you were doing is the way I retrieved messages. See below:
This may be worth a try.