【发布时间】:2020-12-21 17:38:06
【问题描述】:
我正在尝试检查我的应用是否在我的 Http404 调用旁边传递了一条消息。但是,我无法在测试中访问该消息,只能通过在 shell 中手动破解。
my_app.views.py:
from django.http import Http404
def index(request):
raise Http404("My message")
然后在这个应用程序的测试文件中我调用:
from django.test import TestCase
from django.urls import reverse
class AppIndexView(TestCase):
def test_index_view(self):
response = self.client.get(reverse("my_app:index"))
self.assertEqual(response.status_code, 404)
# This checks
self.assertEqual(response.context["reason"], "My message"
# This gives: KeyError: 'reason'
# However if I manually trace these steps I can access this key.
self.assertContains(response, "My Message")
# This gives: AssertionError: 404 != 200 : Couldn't
# retrieve content: Response code was 404 (expected 200)
# This is in accordance with the previous status_code check, so:
self.assertContains(response, "My Message", status_code=404)
# This gives: AssertionError: False is not true : Couldn't find 'My
# Message' in response
我也尝试了各种版本来获取带有 response.exception、response.context.exception 等的消息,详见this question
如果我在 django 的 shell 中执行,我可以通过两种不同的方式访问该消息:
>>> from django.test import Client
>>> from django.urls import reverse
>>> from django.test.utils import setup_test_environment
>>> setup_test_environment()
>>> client=Client()
>>> response = client.get(reverse("my_app:index"))
>>> response.context["reason"]
'My Message'
>>> response.content
b'[lots of html...]<div id="info">\n \n <p>My Message</p>\n \n </div>[...some more html]
如何在我的 tests.py 中访问此消息?
【问题讨论】: