Django测试消息与Http404一起传入

2024-04-27 22:52:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试检查我的应用程序是否在我的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中访问此消息


Tags: djangofromtestimportself消息messageindex
1条回答
网友
1楼 · 发布于 2024-04-27 22:52:29

您可以通过content属性访问HttpResponse对象的内容:

>>> from django.http import HttpResponse
>>> obj = HttpResponse('my message')
>>> obj.content
b'my message'

因此,您应该能够在测试中将response.content与您想要的结果进行比较:

编辑:下面的测试将失败,因为response.content将包含完整的呈现HTML,其中可能包含也可能不包含原始异常消息

class AppIndexView(TestCase):
    def test_index_view(self):
        response = self.client.get(reverse("my_app:index"))
        self.assertEqual(response.status_code, 404)
        self.assertEqual(response.content, "My message")

之所以能够手动解析response.context["reason"],是因为Django可能在默认的404模板上下文中设置了键reason,而这不是您可以从客户端访问的内容

相关问题 更多 >