【问题标题】:Django test recieves 200 not 403Django 测试收到 200 而不是 403
【发布时间】:2014-11-08 12:35:11
【问题描述】:

这不是重复的:AssertionError: 200 != 403

我正在运行一些自动化测试,但在有关状态代码的断言方面遇到问题。

在常规浏览器中,使用具有错误凭据的用户浏览到 my.server/item/22,会提供自定义 403 页面:

并且自定义页面正确显示:

万岁,一切都很好...除了我运行测试时:

def test_editor_can_view(self):
    self.logout()
    response = self.client.post(reverse('django.contrib.auth.views.login'), {'username': 'eddie', 'password': 'editor'})
    self.assertEqual(response.status_code,302) # Redirect to homepage, thats ok.
    response = self.client.post(self.get_page(self.item1))
    self.assertEqual(response.status_code,200) # This should work, and does.
    response = self.client.post(self.get_page(self.item2))
    print response
    self.assertEqual(response.status_code,403) # This does not.

在测试输出中:

======================================================================
FAIL: test_editor_can_view (aristotle_mdr.tests.SupersedePages)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/my_app/tests.py", line 377, in test_editor_can_view
    self.assertEqual(response.status_code,403)
AssertionError: 200 != 403

但检查response 显示:

<h1 class="unauthorised">Unauthorised</h1>
<p>
The page you have requested is not

accessible via your current account. You can <a href="/accounts/logout">log out</a> and try with a different accoun
t

or contact an administrator to see why you can't access this page.
</p>

所以用户被告知他们无法正确访问它。所以不知何故,403 错误被吃掉了,变成了 403。Unlike my last question,这绝对是应该(并且在某些情况下)返回 403 的情况。

在 urls.py 中,我有这个:

handler403 = 'my_app.views.unauthorised'

在views.py中我有这个:

def unauthorised(request, path=''):
    return render(request,"403.html")

为什么这在测试套件中被破坏了?

【问题讨论】:

标签: python django


【解决方案1】:

就像写出问题一样,我发现了我的问题:

django.shortcuts.render 可以接受状态码,并且显式设置它可以确保正确的错误码返回到测试套件。

def unauthorised(request, path=''):
    return render(request,"403.html",status=403)

虽然这并不能完全解释为什么我的浏览器会得到正确的错误代码。

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2014-03-17
    • 2019-08-01
    • 2022-01-07
    • 2021-06-07
    • 2017-07-06
    • 1970-01-01
    • 2020-08-22
    • 1970-01-01
    相关资源
    最近更新 更多