From 6e2ddad05937c78749cc87890a3d24138e2bfb13 Mon Sep 17 00:00:00 2001 From: JasonHomeWorkstationUbuntu Date: Wed, 21 Oct 2020 16:05:45 +1100 Subject: [PATCH] Added POST --- src/puppies/tests/test_views.py | 39 +++++++++++++++++++++++++++++++++ src/puppies/views.py | 15 +++++++++---- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/src/puppies/tests/test_views.py b/src/puppies/tests/test_views.py index 9ab318c..7ef686d 100644 --- a/src/puppies/tests/test_views.py +++ b/src/puppies/tests/test_views.py @@ -58,3 +58,42 @@ class GetSinglePuppyTest(TestCase): response = client.get( reverse('get_delete_update_puppy', kwargs={'pk': 30})) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) + + +class CreateNewPuppyTest(TestCase): + """ + Test module for inserting a new puppy + 1. inserting a valid puppy + 2. inserting a invalid puppy + """ + + def setUp(self): + self.valid_payload = { + 'name': 'Muffin', + 'age': 4, + 'breed': 'Pamerion', + 'color': 'White' + } + # Why this syntax works? + self.invalid_payload = { + 'name': '', + 'age': 4, + 'breed': 'Pamerion', + 'color': 'White' + } + + def test_create_valid_puppy(self): + response = client.post( + reverse('get_post_puppies'), + data=json.dumps(self.valid_payload), + content_type='application/json' + ) + self.assertEqual(response.status_code, status.HTTP_201_CREATED) + + def test_create_invalid_puppy(self): + response = client.post( + reverse('get_post_puppies'), + data=json.dumps(self.invalid_payload), + content_type='application/json' + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) diff --git a/src/puppies/views.py b/src/puppies/views.py index 53847b9..0c65b57 100644 --- a/src/puppies/views.py +++ b/src/puppies/views.py @@ -35,7 +35,14 @@ def get_post_puppies(request): return Response(serializer.data) # insert a new record for a puppy elif request.method == 'POST': - return Response({}) - # insert a new record for a puppy - elif request.method == 'POST': - return Response({}) \ No newline at end of file + data = { + 'name': request.data.get('name'), + 'age': int(request.data.get('age')), + 'breed': request.data.get('breed'), + 'color': request.data.get('color') + } + serializer = PuppySerializer(data=data) + if serializer.is_valid(): + serializer.save() + return Response(serializer.data, status=status.HTTP_201_CREATED) + return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) \ No newline at end of file