Home > Net >  Django api update/create request from test case never fired the related methods in serializer
Django api update/create request from test case never fired the related methods in serializer

Time:10-30

How i can send the UPDATE or CREATE request from my test case? When i run my test case the create/update methods never fired in serializer.. What i misunderstand in Django philosophy? Can someone suggest what i have to do?

For example:

#View
class  filesPairView (viewsets.ModelViewSet):
    serializer_class = filesPairViewSerializer
    
    def create(self, request):
    ...
        return Response(status=status.HTTP_201_CREATED)


#Serializer
class filesPairViewSerializer(serializers.ModelSerializer):

    class Meta:
        ...
    
    def create(self, validated_data):
        print ("filesPairViewSerializer CREATE")
        

    def update(self, validated_data):
        print ("filesPairViewSerializer UPDATE")
        


#Test case
class filesPairViewTestCase(APITestCase):

    def test_barmi(self):
        print("test_barmi")
        url = ('http://127.0.0.1:8000/api/filesPairView/')
        data ={
        #some valid data
        }

        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)


#urls
router.register(r'filesPairView', views.filesPairView )

CodePudding user response:

Do the following:

#Test case
from django.urls import reverse

class filesPairViewTestCase(APITestCase):

    def test_barmi(self):
        print("test_barmi")
        url = reverse('filespairview-list')
        data ={
            #some valid data
        }
        response = self.client.post(url, data)
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)


#urls
router.register(r'filesPairView', views.filesPairView, basename='filespairview')

Notice that the trick here is use the basename which is normally in singular and has the following result based on REST:

  • reverse('filespairview-list') -> /filesPairView/ - GET - List all
  • reverse('filespairview-list') -> /filesPairView/ - POST - Create
  • reverse('filespairview-detail') -> /filesPairView/{int:pk}/ - GET - Get one
  • reverse('filespairview-detail') -> /filesPairView/{int:pk}/ - POST - Update one
  • reverse('filespairview-detail') -> /filesPairView/{int:pk}/ - PATCH - Update partial
  • Related