2012-10-21 20:40:31 +00:00
|
|
|
from __future__ import unicode_literals
|
|
|
|
|
2013-05-20 22:41:23 +00:00
|
|
|
import gzip
|
2015-01-28 12:35:27 +00:00
|
|
|
import io
|
2013-05-20 22:41:23 +00:00
|
|
|
|
2015-03-13 22:40:14 +00:00
|
|
|
from django.http import HttpRequest, HttpResponse, StreamingHttpResponse
|
|
|
|
from django.http.utils import conditional_content_removal
|
2015-04-17 21:38:20 +00:00
|
|
|
from django.test import SimpleTestCase
|
2012-10-21 20:40:31 +00:00
|
|
|
|
|
|
|
|
2013-05-20 22:41:23 +00:00
|
|
|
# based on Python 3.3's gzip.compress
|
|
|
|
def gzip_compress(data):
|
|
|
|
buf = io.BytesIO()
|
2013-05-21 11:18:53 +00:00
|
|
|
f = gzip.GzipFile(fileobj=buf, mode='wb', compresslevel=0)
|
|
|
|
try:
|
2013-05-20 22:41:23 +00:00
|
|
|
f.write(data)
|
2013-05-21 11:18:53 +00:00
|
|
|
finally:
|
|
|
|
f.close()
|
2013-05-20 22:41:23 +00:00
|
|
|
return buf.getvalue()
|
|
|
|
|
|
|
|
|
2015-04-17 21:38:20 +00:00
|
|
|
class HttpUtilTests(SimpleTestCase):
|
2012-10-21 20:40:31 +00:00
|
|
|
|
|
|
|
def test_conditional_content_removal(self):
|
|
|
|
"""
|
|
|
|
Tests that content is removed from regular and streaming responses with
|
|
|
|
a status_code of 100-199, 204, 304 or a method of "HEAD".
|
|
|
|
"""
|
|
|
|
req = HttpRequest()
|
|
|
|
|
|
|
|
# Do nothing for 200 responses.
|
|
|
|
res = HttpResponse('abc')
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(res.content, b'abc')
|
|
|
|
|
|
|
|
res = StreamingHttpResponse(['abc'])
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(b''.join(res), b'abc')
|
|
|
|
|
|
|
|
# Strip content for some status codes.
|
|
|
|
for status_code in (100, 150, 199, 204, 304):
|
|
|
|
res = HttpResponse('abc', status=status_code)
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(res.content, b'')
|
|
|
|
|
|
|
|
res = StreamingHttpResponse(['abc'], status=status_code)
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(b''.join(res), b'')
|
|
|
|
|
2013-10-10 20:42:30 +00:00
|
|
|
# Issue #20472
|
2013-05-20 22:41:23 +00:00
|
|
|
abc = gzip_compress(b'abc')
|
|
|
|
res = HttpResponse(abc, status=304)
|
|
|
|
res['Content-Encoding'] = 'gzip'
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(res.content, b'')
|
|
|
|
|
|
|
|
res = StreamingHttpResponse([abc], status=304)
|
|
|
|
res['Content-Encoding'] = 'gzip'
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(b''.join(res), b'')
|
|
|
|
|
2012-10-21 20:40:31 +00:00
|
|
|
# Strip content for HEAD requests.
|
|
|
|
req.method = 'HEAD'
|
|
|
|
|
|
|
|
res = HttpResponse('abc')
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(res.content, b'')
|
|
|
|
|
|
|
|
res = StreamingHttpResponse(['abc'])
|
|
|
|
conditional_content_removal(req, res)
|
|
|
|
self.assertEqual(b''.join(res), b'')
|