Search code examples
pythondjangounit-testingdjango-rest-frameworkdrf-yasg

AssertionError: 400 != 201 Unit Test Django REST Framework with drf-yasg


i am creating an unittest for a endpoint POST that i created:

Endpoint:

class AddJokeAPI(generics.ListAPIView):
    serializer_class = JokeSerializer
    queryset = Joke.objects.all()
    query_param = openapi.Parameter('text', openapi.IN_QUERY,
                             description="Nuevo chiste",
                             type=openapi.TYPE_STRING)

    @swagger_auto_schema(
        operation_description="Guarda en una base de datos el chiste el texto pasado por parámetro",
        manual_parameters=[query_param]
    )
    def post(self, request):
        serializer = self.get_serializer(data={"joke": self.request.GET.get('text')})
        serializer.is_valid(raise_exception=True)
        joke = serializer.save()
        return Response({
            "joke": JokeSerializer(joke, context=self.get_serializer_context()).data,
            "message": "New joke added",
            "success": True
        }, status=status.HTTP_201_CREATED)

If you can see, in the POST method i have to send a POST query param called "text" to register it in the model "Joke" and receive a 201 HTTP Status.

This is my test.py method to call that endpoint:

class JokesTestCase(TestCase):

    def setUp(self):
        self.client = APIClient()

    def test_post_joke(self):
        payload = {
            'text': 'Test Joke'
        }
        response = self.client.post('/api/jokes/add', payload)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

the error that i am getting is:

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

as you can see the error is that i am making a bad request, but i dont know exactly why i am getting that error.

If i try to make a request with this path, the test will pass as i expect:

response = self.client.post('/api/jokes/add?text=Test%20Joke')

UPDATE: This is my serializers.py

class JokeSerializer(serializers.ModelSerializer):
    class Meta:
        model = Joke
        fields = ('id', 'joke')

    def create(self, validated_data):
        joke = Joke.objects.create(**validated_data)
        return joke

Anyone can help me with this? Thank you


Solution

  • The error is caused because you are sending "payload" in your request body instead of query params.

    response = self.client.post('/api/jokes/add', payload)
    

    You are trying to get text from request.GET which is non existent and will return None.

    serializer = self.get_serializer(data={"joke": self.request.GET.get('text')})
    

    And when you instantiate your serializer when passing data which will have value None for key joke, it will not be valid and will raise exception which will be a validationError i.e. 400 BAD Request.

    serializer.is_valid(raise_exception=True)
    

    Your function will be returned from this line.

    Hence, your assertion will fail. 400 != 201

    To solve this, send joke as a query param instead of a request body.

    response = self.client.post('/api/jokes/', params={'text': 'Test Joke'})