Home > Software engineering >  Django Unable to test API patch method with query parameters other than pk MultiValueDictKeyError
Django Unable to test API patch method with query parameters other than pk MultiValueDictKeyError

Time:09-29

I have an APIView implementing patch for an entity (lets say money). I can send a request from axios and the money gets updated but I cannot make the test to work. The request.query_params are empty when I send them via self.client.patch inside the test case. Then it throuws MultiValueDictKeyError('money_code') Here is the code:

class UpdateMoneyQuantity(APIView):
    def patch(self, request):
        try:
            money_code = request.query_params["money_code"]
            money_object = Money.objects.get(money_code=money_code)
            # set partial=True to update a data partially
            serializer = MoneySerializer(
                money_object, data=request.data, partial=True
            )
            if serializer.is_valid():
                serializer.save()
                return Response(data=serializer.data, status=HTTP_200_OK)
            return Response(data=serializer.errors, status=HTTP_400_BAD_REQUEST)
        except Money.DoesNotExist as err:
            return Response(
                data={
                    "error": "Unable to find the desired code."
                },
                status=HTTP_400_BAD_REQUEST,
            )
        except Exception as err:
            logger.exception(
                f"Unable to perform patch on money quantity. \n Exception: {str(err)}"
            )
            return Response(data=str(err), status=HTTP_500_INTERNAL_SERVER_ERROR)

Here is the url:

path(
    "update-money-quantity/",
    UpdateMoneyQuantity.as_view(),
    name="update-money-quantity",
),

Here is the test case I am trying to write but couldn't make it work.

class MoneyUpdateTest(APITestCase):
        def test_update_quantity(self):
            """
            Ensure we can update the quantity.
            """
            obj = Money.objects.create(
                money_code="RG100TEST1",
                supplier="Test supplier",
            )
            params = {"money_code": "RG100TEST1"}
            url = reverse("update-money-quantity")
            data = {
                "saving": 110,
                "actual_saving": 105,
            }
            response = self.client.patch(url, data=data, query_params=params)
            self.assertEqual(response.status_code, HTTP_200_OK)
            self.assertEqual(
                Money.objects.get(money_code="RG100TEST1").saving, 110
            )
            self.assertEqual(
                Money.objects.get(money_code="RG100TEST1").actual_saving, 105
            )

CodePudding user response:

You must send money_code to your view:

change this line

 url = reverse("update-money-quantity")

to

 url = f'{reverse("update-money-quantity")}?money_code={obj.money_code}'

to send money_code as query param

  • Related