Django Testing - check messages for a view that redirects

后端 未结 5 878
我在风中等你
我在风中等你 2021-02-02 10:16

I have been writing tests for one of my django applications and have been looking to get around this problem for quite some time now. I have a view that sends messages using

5条回答
  •  广开言路
    2021-02-02 10:31

    You can use get_messages() with response.wsgi_request like this (tested in Django 1.10):

    from django.contrib.messages import get_messages  
    ...
    def test_view(self):
        response = self.client.get('/some-url/') # you don't need follow=True
        self.assertRedirects(response, '/some-other-url/')
        # each element is an instance of  django.contrib.messages.storage.base.Message
        all_messages = [msg for msg in get_messages(response.wsgi_request)]
    
        # here's how you test the first message
        self.assertEqual(all_messages[0].tags, "success")
        self.assertEqual(all_messages[0].message, "you have done well")
    

提交回复
热议问题