diff --git a/django/middleware/gzip.py b/django/middleware/gzip.py index 39ec6248514..69f938cf0a4 100644 --- a/django/middleware/gzip.py +++ b/django/middleware/gzip.py @@ -37,6 +37,9 @@ class GZipMiddleware(object): if len(compressed_content) >= len(response.content): return response + if response.has_header('ETag'): + response['ETag'] = re.sub('"$', ';gzip"', response['ETag']) + response.content = compressed_content response['Content-Encoding'] = 'gzip' response['Content-Length'] = str(len(response.content)) diff --git a/tests/regressiontests/middleware/tests.py b/tests/regressiontests/middleware/tests.py index 50cb81d9a10..3adb10964af 100644 --- a/tests/regressiontests/middleware/tests.py +++ b/tests/regressiontests/middleware/tests.py @@ -13,8 +13,8 @@ from django.middleware.clickjacking import XFrameOptionsMiddleware from django.middleware.common import CommonMiddleware from django.middleware.http import ConditionalGetMiddleware from django.middleware.gzip import GZipMiddleware -from django.test import TestCase - +from django.test import TestCase, RequestFactory +from django.test.utils import override_settings class CommonMiddlewareTest(TestCase): def setUp(self): @@ -582,3 +582,32 @@ class GZipMiddlewareTest(TestCase): r = GZipMiddleware().process_response(self.req, self.resp) self.assertEqual(r.content, self.uncompressible_string) self.assertEqual(r.get('Content-Encoding'), None) + + +@override_settings(USE_ETAGS=True) +class ETagGZipMiddlewareTest(TestCase): + """ + Tests if the ETag middleware behaves correctly with GZip middleware. + """ + compressible_string = 'a' * 500 + + def setUp(self): + self.rf = RequestFactory() + + def test_compress_response(self): + """ + Tests that ETag is changed after gzip compression is performed. + """ + request = self.rf.get('/', HTTP_ACCEPT_ENCODING='gzip, deflate') + response = GZipMiddleware().process_response(request, + CommonMiddleware().process_response(request, + HttpResponse(self.compressible_string))) + gzip_etag = response.get('ETag') + + request = self.rf.get('/', HTTP_ACCEPT_ENCODING='') + response = GZipMiddleware().process_response(request, + CommonMiddleware().process_response(request, + HttpResponse(self.compressible_string))) + nogzip_etag = response.get('ETag') + + self.assertNotEqual(gzip_etag, nogzip_etag)