Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access Django message framework content in Django unit tests

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!

like image 813
jvc26 Avatar asked Feb 08 '12 13:02

jvc26


People also ask

How do I use Django message framework?

Import messages from django. contrib at the top of the file then go to the view function where you wish to add the message(s). In this case, it's a contact view that needs a Django success message and a Django error message. Add a success message just before the return redirect ("main:homepage") stating "Message sent."

How do you write unit test cases in Django?

Writing tests Django'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.


1 Answers

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.

like image 103
jvc26 Avatar answered Nov 14 '22 20:11

jvc26