From b926765a7c04e88a85f2360a238efde9ffe98244 Mon Sep 17 00:00:00 2001 From: Jannis Leidel Date: Thu, 9 Feb 2012 18:57:13 +0000 Subject: [PATCH] Fixed #16035 -- Appended the Etag response header if the GZipMiddleware is in use to follow RFC2616 better. Thanks, ext and dracos2. git-svn-id: http://code.djangoproject.com/svn/django/trunk@17471 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --- django/middleware/gzip.py | 3 +++ tests/regressiontests/middleware/tests.py | 33 +++++++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/django/middleware/gzip.py b/django/middleware/gzip.py index 39ec624851..69f938cf0a 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 50cb81d9a1..3adb10964a 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)