DRF Response content-type set to None during tests

Viewed 4215

I'm using Django Rest Framework (version 3.6.2) to create REST API. I've defined my viewset that inherits from GenericViewSet and have overriden retrieve method to implement custom behaviour.

class FooViewSet(viewsets.GenericViewSet):
    serializer_class = FooSerializer

    def retrieve(self, request, *args, **kwargs):
        ... 
        serializer = self.get_serializer(data)
        return Response(serializer.data)

I want to have BrowsableAPI while accessing this endpoint from the browser and receive json response when accessing this endpoint e.g. from the code. I've configured DRF with the following settings:

    REST_FRAMEWORK = {
    'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        'rest_framework.renderers.BrowsableAPIRenderer',
    ),
    'TEST_REQUEST_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
    ),
    'TEST_REQUEST_DEFAULT_FORMAT':'json'
}

Everything works as expected, I can access the browsable API from the browser and when making request with the Postman tool I get json response. Unfortunately, I can't achieve the same result during tests.

class GetFooDetailViewTest(APITestCase):

    def test_get_should_return_json(self):
        response = self.client.get(self.VIEW_URL)
        self.assertEqual(response.content_type, "application/json")

I expect the response to have content_type set to application/json (this is the header that I can see in the responses from browser and Postman). But this test fails - response.content_type is set to None. While debugging this test, I've discovered that response._headers dictionary looks like this

{
    'vary': ('Vary', 'Cookie'),
    'x-frame-options': ('X-Frame-Options', 'SAMEORIGIN'),
    'content-type': ('Content-Type', 'application/json'),
    'allow': ('Allow', 'GET, PUT, DELETE, OPTIONS')
}

So it seems like the correct header is being set, but it's not getting populated to the content_type attribute. Am I missing something?

2 Answers

I ran into something similar and this worked for me:

response = self.client.get(self.VIEW_URL, HTTP_ACCEPT='application/json')

Related