DRF Viewset test method

Viewed 574

I have added a method to my viewset as follows:

class CustomImageViewSet(viewsets.ModelViewSet):
    queryset = CustomImage.objects.all()
    serializer_class = CustomImageSerializer
    lookup_field = 'id'

    @action(detail=True, methods=['get'], url_path='sepia/')
    def sepia(self, request, id):
        # do something
        data = image_to_string(image)
        return HttpResponse(data, content_type="image/png", status=status.HTTP_200_OK)

Since it is not a default or overridden request method, I am not sure how can I proceed writing a test for it. Any suggestions?

2 Answers

You're not clear on what the test should test but you can test the response status_code for example like this:

def test_sepia_api():
    api_client = APIClient()
    response = api_client.get(path="{path_to_your_api}/sepia/")
    assert response.status_code == 200

I noticed you were using pytest. I'll assume you've got pytest-django too then (it really does make everything easier). I like using request factory since it's generally faster if you've got authentication needs.

def test_me(self, user, rf):
    view = CustomImageViewSet()
    request = rf.get("")
    request.user = user  # If you need authentication 

    view.request = request

    response = view.sepia(request, 123)

    assert response.data == BLAH
Related