Amy*_*yth 23 testing django redirect messages django-context
我一直在为我的一个django应用程序编写测试,并且一直在寻找解决这个问题已有一段时间了.我有一个视图,使用django.contrib.messages不同的情况发送消息.该视图类似于以下内容.
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)
Run Code Online (Sandbox Code Playgroud)
现在,在测试此视图client.get的响应时,不包含context包含messages该视图的字典,因为此视图使用重定向.对于渲染模板的视图,我们可以使用访问消息列表messages = response.context.get('messages').我们如何获得messages重定向视图的访问权限?
Ala*_*air 38
使用呼叫中的follow=True选项,client.get()客户端将遵循重定向.然后,您可以测试该消息是否位于您重定向到的视图的上下文中.
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)
Run Code Online (Sandbox Code Playgroud)
小智 6
您可以像这样使用带有response.wsgi_request的get_messages()(在Django 1.10中测试):
from django.contrib.messages import get_messages
...
def test_view(self):
response = self.client.get('/some-url/') # you don't need follow=True
self.assertRedirects(response, '/some-other-url/')
# each element is an instance of django.contrib.messages.storage.base.Message
all_messages = [msg for msg in get_messages(response.wsgi_request)]
# here's how you test the first message
self.assertEqual(all_messages[0].tags, "success")
self.assertEqual(all_messages[0].message, "you have done well")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6505 次 |
| 最近记录: |