Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 441
Thore Avatar asked Dec 31 '22 22:12

Thore


2 Answers

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')

like image 92
DHerls Avatar answered Jan 10 '23 06:01

DHerls


The doc for the Django HttpResponse mentions:

HttpResponse.__getitem__(header)
Returns the value for the given header name. Case-insensitive.

This MDN doc mentions that in a HTTP response the Content Type is a header with name Content-Type.

So the following code returns the Content Type of a Django HttpResponse:

response.__getitem__('Content-Type')

This could be used in a Django test to assert that the Content Type has a certain value, for example to assert that the Content Type of the HttpResponse is application/json:

self.assertEqual(response.__getitem__('content-type'), 'application/json')
like image 23
hgolding Avatar answered Jan 10 '23 05:01

hgolding