Search code examples
pythondjangounit-testingdjango-rest-frameworktdd

How to write test for API views which create multiple DB objects on single request?


There is transaction table in my database, i've API which create multiple transaction rows in database on single request,

i've write code to test the API but somehow it fails following is my code

Here is my serializer:

class TransactionSerializer(serializers.ModelSerializer):
    """Transaction Serializer"""
    class Meta:
        """meta class"""
        model = Transaction
        fields = '__all__'
        read_only_fields = ['id', 'user']
        extra_kwargs = {'staff': {'required': True}}

Here is my View:

 class CreateMultipleTransactionAPIView(APIView):
    """create multiple transactions"""
    def post(self, request):
        """handling post request"""
        serializer = TransactionSerializer(data=request.data,
                                           many=True)
        if serializer.is_valid():
            serializer.save(user=self.request.user)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

here is my test code which is failing:

    def test_create_multiple_transactions_errors(self):
        url = reverse('transaction_apis:create_multiple')
        request_data = {'items': [{}]}
        response = self.client.post(url, request_data)
        print(response.content_type)
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

Ouput after running test:

self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
AssertionError: 201 != 400


Solution

  • while requesting API just use format=json with list of object like below code

        def test_create_multiple_transactions_errors(self):
            url = reverse('sa_transaction_apis:create_multiple')
            request_data = {
                'service_name': 'S2',
                'service_price': 321,
                'payment_type': 'W'
            }
            response = self.client.post(url, request_data)
            self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
    
        def test_create_multiple_transactions_success(self):
            url = reverse('sa_transaction_apis:create_multiple')
            datas = list()
            datas.append({
                'service_name': 'S2',
                'service_price': 321,
                'staff': self.staff.pk,
                'created_at': "2016-10-12T12:31:08.553139",
                'payment_type': 'W'
            })
            response = self.client.post(url, datas, format='json')
            self.assertEqual(response.status_code, status.HTTP_201_CREATED)
    
    

    test is now working with 100% cc