Django Testing-检查消息以获取重定向的视图 [英] Django Testing - check messages for a view that redirects
问题描述
我一直在为我的django应用程序之一编写测试,并且一直在寻找解决此问题的方法.我有一个视图,可以在不同情况下使用django.contrib.messages
发送消息.该视图如下所示.
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 django.contrib.messages
for different cases. The view looks something like the following.
from django.contrib import messages
from django.shortcuts import redirect
import custom_messages
def some_view(request):
""" This is a sample view for testing purposes.
"""
some_condition = models.SomeModel.objects.get_or_none(
condition=some_condition)
if some_condition:
messages.success(request, custom_message.SUCCESS)
else:
messages.error(request, custom_message.ERROR)
redirect(some_other_view)
现在,在测试此视图时,client.get
的响应不包含包含messages
的context
字典,因为此视图使用重定向.对于渲染模板的视图,我们可以使用messages = response.context.get('messages')
访问消息列表.我们如何获得对重定向视图的访问权限messages
?
Now, while testing this view client.get
's response does not contain the context
dictionary that contains the messages
as this view uses a redirect. For views that render templates we can get access to the messages list using messages = response.context.get('messages')
. How can we get access messages
for a view that redirects?
推荐答案
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)
这篇关于Django Testing-检查消息以获取重定向的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!