我如何使用 HTTPResponseRedirect 对 django 消息进行单元测试?

How can I unit test django messages... with a HTTPResponseRedirect?

Just like this question... but harder.

我有一个重定向用户的视图,并使用 Django messages framework 将他们发送到正确的页面,并使用如下代码添加消息:

def new_comment(request,pid):
    post = get_object_or_404(DiscussionPost,pk=pid)
    if post.closed:
        messages.error(request, _('This post is closed. Your comment was not added.'))
        return HttpResponseRedirect(reverse("discussionsPost",args=[post.pk]))

现在这对用户来说效果很好,但在测试时消息不可用。

在单元测试中我做的:

    response = self.client.post(reverse('aristotle:discussionsPostNewComment',args=[p1.id]),
        {'body':"Post is closed, so I can NOT comment."}
    )
    #the below assertion passes
    self.assertRedirects(response,reverse('aristotle:discussionsPost',args=[p1.id]))

    print response
    print response.context['messages']       

第一个打印结果为:

Vary: Accept-Language, Cookie
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Location: http://testserver/discussions/post/1
Content-Language: en

第二次失败并出现错误:

Traceback (most recent call last):
  File "/home/ubuntu/workspace/aristotle_mdr/tests/main/test_discussions.py", line 393, in test_post_to_closed_discussion
    print response.context['messages']
TypeError: 'NoneType' object has no attribute '__getitem__'

而且无法使用 messages.get_messages 因为没有可以使用的请求项目。

既然HTTPResponseRedirect中没有context字典,如何查看消息是否正确发送?

如果你想在重定向后测试响应,那么你需要告诉Django测试客户端"follow"重定向链,通过follow 参数。如 Django documentation 中所述:

If you set follow to True the client will follow any redirects and a redirect_chain attribute will be set in the response object containing tuples of the intermediate urls and status codes.

因此您的测试 post 需要类似于:

    response = self.client.post(
        reverse('aristotle:discussionsPostNewComment', args=[p1.id]),
        {'body':"Post is closed, so I can NOT comment."},
        follow=True
    )