就像这个问题......但更难.
我有一个视图,重定向用户,并使用Django消息框架将它们发送到正确的页面,并添加一个代码如下所示的消息:
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
,如何检查消息是否正确发送?
如果你想在重定向之后测试响应,那么你需要告诉Django测试客户端通过follow
参数"跟随"重定向链.如Django文档中所述:
如果将follow设置为True,则客户端将遵循任何重定向,并且将在包含中间URL和状态代码的元组的响应对象中设置redirect_chain属性.
所以你的测试帖需要看起来像:
response = self.client.post( reverse('aristotle:discussionsPostNewComment', args=[p1.id]), {'body':"Post is closed, so I can NOT comment."}, follow=True )