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?
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')
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With