Django测试收到200而不是403

时间:2014-09-15 03:11:29

标签: python django

这与此不重复:AssertionError: 200 != 403

我正在运行一些自动化测试,并且遇到状态码断言问题。

在常规浏览器中,使用凭据错误的用户浏览my.server/item/22,会显示自定义的403页:

enter image description here

自定义页面显示正确:

enter image description here

万岁,一切都很好......除非我进行测试:

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")

为什么在测试套件中会出现这种情况?

1 个答案:

答案 0 :(得分:0)

就像写完问题的那样,我发现了我的问题:

django.shortcuts.render可以获取状态代码,并明确设置此项可确保正确的错误代码返回测试套件。

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

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