From 6b2f1c73713039b3aa9cc62da343549be8d86c33 Mon Sep 17 00:00:00 2001 From: David Avsajanishvili Date: Mon, 3 Jun 2013 14:19:40 +0400 Subject: [PATCH] Test HTTP 422 --- rest_framework/tests/test_generics.py | 48 +++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/rest_framework/tests/test_generics.py b/rest_framework/tests/test_generics.py index 37734195a..75dc4a36f 100644 --- a/rest_framework/tests/test_generics.py +++ b/rest_framework/tests/test_generics.py @@ -158,6 +158,21 @@ class TestRootView(TestCase): created = self.objects.get(id=4) self.assertEqual(created.text, 'foobar') + def test_post_unprocessable_entity(self): + """ + POST requests with wrong JSON data should raise HTTP 422 + (UNPROCESSABLE ENTITY) + """ + content = {'id': 999, 'wrongtext': 'foobar'} + request = factory.post('/', json.dumps(content), + content_type='application/json') + with self.assertNumQueries(0): + response = self.view(request, pk=1).render() + self.assertEqual(response.status_code, + status.HTTP_422_UNPROCESSABLE_ENTITY) + self.assertIn('text', response.data) + self.assertEqual(response.data['text'], ['This field is required.']) + class TestInstanceView(TestCase): def setUp(self): @@ -303,6 +318,39 @@ class TestInstanceView(TestCase): updated = self.objects.get(id=1) self.assertEqual(updated.text, 'foobar') + def test_put_unprocessable_entity(self): + """ + PUT requests with wrong JSON data should raise HTTP 422 + (UNPROCESSABLE ENTITY) + """ + content = {'id': 999, 'wrongtext': 'foobar'} + request = factory.put('/1', json.dumps(content), + content_type='application/json') + with self.assertNumQueries(1): + response = self.view(request, pk=1).render() + self.assertEqual(response.status_code, + status.HTTP_422_UNPROCESSABLE_ENTITY) + self.assertIn('text', response.data) + self.assertEqual(response.data['text'], ['This field is required.']) + + def test_patch_unprocessable_entity(self): + """ + PATCH requests with wrong JSON data should raise HTTP 422 + (UNPROCESSABLE ENTITY) + """ + content = {'text': 'foobar' * 20} # too long + request = factory.patch('/1', json.dumps(content), + content_type='application/json') + + with self.assertNumQueries(1): + response = self.view(request, pk=1).render() + self.assertEqual(response.status_code, + status.HTTP_422_UNPROCESSABLE_ENTITY) + self.assertIn('text', response.data) + self.assertEqual( + response.data['text'], + [u'Ensure this value has at most 100 characters (it has 120).']) + def test_put_to_deleted_instance(self): """ PUT requests to RetrieveUpdateDestroyAPIView should create an object