Search code examples
djangodjango-rest-frameworkpython-unittestdjango-testingdjango-tests

Coverage show test get_serializer_class as untested


Use coverage to show what have to be covered by tests drf views. And coverage show that all view is tested ok (cover by unittest + dango client API)

But coverage shows that this part need to be covered:

def get_serializer_class(self): 
    return self.serializer_class ` 

I think that that code possible to delete as it useless (it is not my code):)

Any idea how to cover that past of code in GenericAPIView? Thx for any help


Solution

  • There are two approaches to specify the serializer class:

    1. First approach is to set the serializer_class attribute in your class.
    2. Second approach is to override the get_serializer_class()method.

    If you already added the serializer_class attribute in your class (first approach) then the get_serializer_class() is definitely useless.

    This is the example:

    from django.contrib.auth.models import User
    from myapp.serializers import UserSerializer
    from rest_framework import generics
    
    class UserList(generics.GenericAPIView):
        queryset = User.objects.all()
        serializer_class = UserSerializer
    

    In most situations you should use the first approach because usually you will need only one serializer for your API view. Second approach is useful for dynamic behavior, such as using different serializers for read and write operations, or providing different serializers to different types of users.

    Example:

    def get_serializer_class(self):
        if self.request.user.is_staff:
            return StaffSerializer
        return BasicSerializer