How can I unit test django messages?

前端 未结 6 674
南笙
南笙 2020-12-24 04:08

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 n

6条回答
  •  猫巷女王i
    2020-12-24 04:52

    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:

    def test_message_sending(self):
        data = dict(...)
        response = self.client.post(reverse('my_view'), data)
        messages = self.user.get_and_delete_messages()
    
        self.assertTrue(messages)
        self.assertEqual('Hey there!', messages[0])
    

    This may be worth a try.

提交回复
热议问题