【发布时间】: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")
为什么这在测试套件中被破坏了?
【问题讨论】:
-
这并不能真正回答你的问题,但看看 WebTest,pypi.python.org/pypi/django-webtest 它使这种类型的测试更容易。