Search code examples
djangotestingcontent-type

Django: Checking content type of response in tests


I have Django view that returns a HTTPResponse with content type 'application/json'. In my tests, I want to verify the expected content type was set.

From the docs, I see that a HTTPResponse I can pass the content_type has a parameter, put not get it as an attribute. Why is that?

In my views.py, I build and send out a HTTPResponse like this:

j = json.dumps(j)
return HttpResponse(j, content_type='application/json')

In my tests.py, I would like to do something like

self.assertEqual(response.content_type, 'application/json')

But without the attribute on the HTTPResponse object, that of course fails with AttributeError: 'HttpResponse' object has no attribute 'content_type'

How can I get the content type of the response in Django? Am misunderstanding something about the workings of HTTP?


Solution

  • The easiest way would be response['content-type'] which would return 'application/json' in your case. So to test you would use:

    self.assertEqual(response['content-type'], 'application/json')