Django Testing - check messages for a view that redirects

后端 未结 5 875
我在风中等你
我在风中等你 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:28

    If your views are redirecting and you use follow=true in your request to the test client the above doesn't work. I ended up writing a helper function to get the first (and in my case, only) message sent with the response.

    @classmethod
    def getmessage(cls, response):
        """Helper method to return message from response """
        for c in response.context:
            message = [m for m in c.get('messages')][0]
            if message:
                return message
    

    You include this within your test class and use it like this:

    message = self.getmessage(response)
    

    Where response is what you get back from a get or post to a Client.

    This is a little fragile but hopefully it saves someone else some time.

提交回复
热议问题