7

Using the Django messages framework, I am passing messages to the template to render in various scenarios - user account creation successful etc. The message is stored within the cookie for the session:

print response.cookies['messages']
Set-Cookie: messages="b6870b4797b65640bb535519a5b53808fdc0ea24$[[\"__json_message\"\05420\054\"Account verified\054 you are now logged in\"]]"; Path=/

The cookie is a Morsel object, but I don't appear to be able to pull out the constituent parts of it to test the message content. Any help would be much appreciated!

jvc26
  • 6,363
  • 6
  • 46
  • 75

1 Answers1

8

Edit: 10-05-2014:

An alternative method is to iterate the messages in the response context. Using the Django Test Client, the response message items can be parsed via:

for message in response.context['messages']:

Which returns each Django Message object, you can then interrogate the attributes for your tests. This is a cleaner alternative to the original option.

Original Solution:

For archive purposes, the original working solution was to interrogate the Cookie morsel objects in the response cookies. This is less clean than the new solution.

self.assertTrue('Account verified' in response.cookies['messages'].value)

in the unittest. It seems quite an ugly solution, but since there won't be another 'Account verified' set, nor another simultaneous message, then it seems acceptable.

jvc26
  • 6,363
  • 6
  • 46
  • 75
  • 1
    looks like the `response.text` solution won't work if the view returns a redirect tho. thanks for the `response.cookies` solution tho! I wonder if I can figure out how to turn them back into proper message objects... – hwjp May 02 '16 at 14:27
  • Thanks! That's exactly what I was looking for: `response.cookies['messages'].value` – AnaPana May 12 '16 at 14:43