Home > database >  Response.status_code 400 for a simple view test
Response.status_code 400 for a simple view test

Time:03-29

I'm passing a simple json body to my view but I'm getting a 400 instead of a 200. It should be a really straightforward test but I can't quite figure out what is wrong. Thanks.

Url:

        "api/v2/ada/send",
        views.sendView.as_view(),
        name="ada-send",
    ),

View:

class sendView(generics.GenericAPIView):
    permission_classes = (permissions.IsAuthenticated,)
    
    def post(self, request, *args, **kwargs):
        body = request.data
        return Response(body, status=status.HTTP_200_OK)

View Test:

class AdaSendGet(APITestCase):
    url = reverse("ada-send")
    def test_choice_type_valid(
        self,):
        user = get_user_model().objects.create_user("test")
        self.client.force_authenticate(user)
        response = self.client.post(
            self.url,
                {
                    "contact_uuid": "49548747-48888043",
                    "choices": 3,
                    "message": (
                        "What is the issue?\n\nAbdominal pain"
                        "\nHeadache\nNone of these\n\n"
                        "Choose the option that matches your answer. "
                        "Eg, 1 for Abdominal pain\n\nEnter *back* to go to "
                        "the previous question or *abort* to "
                        "end the assessment"
                    ),
                    "step": 6,
                    "value": 2,
                    "optionId": 0,
                    "path": "/assessments/assessment-id/dialog/next",
                    "cardType": "CHOICE",
                    "title": "SYMPTOM"
                },
            content_type="application/json",
        )
        self.assertEqual(response.status_code, status.HTTP_200_OK)

Error:

self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 400 != 200

response.json() returns:

{'detail': 'JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)'}

CodePudding user response:

Weird one here. I solved it by removing

content_type="application/json",

from the payload.

CodePudding user response:

As they mentioned in the documentation here https://www.django-rest-framework.org/api-guide/testing/#api-test-cases

When you want to specify the format you should use format argument.

Methods which create a request body, such as post, put and patch, include a format argument, which make it easy to generate requests using a content type other than multipart form data.

  • Related