Django Testing - check messages for a view that redirects

后端 未结 5 881
我在风中等你
我在风中等你 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-02-02 10:37

    Use the follow=True option in the client.get() call, and the client will follow the redirect. You can then test that the message is in the context of the view you redirected to.

    def test_some_view(self):
        # use follow=True to follow redirect
        response = self.client.get('/some-url/', follow=True)
    
        # don't really need to check status code because assertRedirects will check it
        self.assertEqual(response.status_code, 200)
        self.assertRedirects(response, '/some-other-url/')
    
        # get message from context and check that expected text is there
        message = list(response.context.get('messages'))[0]
        self.assertEqual(message.tags, "success")
        self.assertTrue("success text" in message.message)
    

提交回复
热议问题