Tôi đang sử dụng ứng dụng khách thử nghiệm Django, django.test.client.Client
, để kiểm tra một số chế độ xem trong ứng dụng Django. Đặc biệt, tôi đang thử nghiệm trường hợp chế độ xem gọi phương thức get_object_or_404
và đối tượng không có ở đó, do đó, 404 phải được trả lại.Thử nghiệm cho dự kiến 404 với khách hàng thử nghiệm Django dẫn đến ngoại lệ unhandled
mã kiểm tra của tôi trông như thế này:
class ViewTests(TestCase):
fixtures=['test.json']
def test_thing_not_there_get(self):
url = '/foo/30afda98-b9d7-4e26-a59a-76ac1b6a001f/'
c = django.test.client.Client()
response = c.get(url)
self.assertEqual(response.status_code, 404)
Tuy nhiên, những gì tôi nhận được thay vào đó là một lỗi ngoại lệ unhandled trong mã xem:
python projects/unittests/manage.py test
Creating test database for alias 'default'...
......ERROR:root:Unhandled Exception on request for http://testserver/foo/30afda98-b9d7-4e26-a59a-76ac1b6a001f/
Traceback (most recent call last):
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/core/handlers/base.py", line 111, in get_response
response = callback(request, *callback_args, **callback_kwargs)
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 39, in wrapped_view
resp = view_func(*args, **kwargs)
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 52, in wrapped_view
return view_func(*args, **kwargs)
File "/Users/lorin/django-myvenv/apps/myvenv_desktop/views.py", line 85, in foo_view
instance = get_object_or_404(Foo, uuid=foo_uuid)
File "/Users/lorin/.virtualenvs/myvenv/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 115, in get_object_or_404
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
Http404: No Foo matches the given query.
Theo Django 1.3 docs
The only exceptions that are not visible to the test client are Http404, PermissionDenied and SystemExit. Django catches these exceptions internally and converts them into the appropriate HTTP response codes. In these cases, you can check response.status_code in your test.
Tại sao Django không nhận ngoại lệ Http404 trong trường hợp này?
Lưu ý rằng (phù hợp với tài liệu), ngoại lệ là không phải được đưa vào ứng dụng khách thử nghiệm. Nếu tôi cố gắng nắm bắt những ngoại lệ trên các mặt hàng:
with self.assertRaises(django.http.Http404):
response = c.get(url)
tôi nhận được lỗi tương tự, cũng như một lỗi thêm:
AssertionError: Http404 not raised
Nhưng, theo câu trả lời của bạn, django phải trả lại mã phản hồi 404, đó là lỗi django, phải không? – AlejandroPerezLillo