How can I unit test django messages?

前端 未结 6 667
南笙
南笙 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条回答
  •  轮回少年
    2020-12-24 05:03

    Test helpers for validation of response messages count and content

    def get_response_messages(self, response):
        from django.contrib.messages import get_messages
        return list(get_messages(response.wsgi_request))
    
    
    def check_response_messages(self, response, message_index=None, message_value=None, exp_count=None):
        messages = self.get_response_messages(response)
        if exp_count is not None:
            self.assertEqual(len(messages), exp_count)
    
        if message_index is not None:
            message = messages[message_index]
            self.assertIn(message_value, str(message))
    

    Can be used like this

    message_value = "You can not switch to another type of account"
    self.check_response_messages(response, exp_count=1, message_index=0, message_value=message_value)
    

提交回复
热议问题