[Answered ]-Testing messages when using RequestFactory()

0👍

After digging a little deeper the message(s) can be found here:

request._messages._queued_messages[0]

And therefore the assertEqual would be:

self.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')
👤Radial

1👍

After digging a little deeper the message(s) can be found here: request._messages._queued_messages[0] And therefore the
assertEqual would be: self.assertEqual(str(request._messages._queued_messages[0]), 'Something went wrong, please try to register again')

It seemed a bit hacky, and after a few hours of research, I found a slightly more robust way to achieve a way to test user messages generated by a view (nb of messages, presence of some string inside last generated/only message, presence on specific strings in each generated messages):

from django.contrib.messages import get_messages

self.assertEqual(len(get_messages(request)), expected_nb_messages)


user_messages_sent = [str(i) for i in get_messages(request)] 
# the resulting BaseStorage class has an iterator method
# string conversion is needed to access to the actual text of the Message object 
           
if type(text_to_test_in_message)==dict:
   for k,v in text_to_test_in_message.items():
       self.assertIn(v, user_messages_sent[k])
   else:
       self.assertIn(text_to_test_in_message, user_messages_sent[-1])
👤Skratt

Leave a comment