Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid KeyError if no Content-Type header; don't perform unnecessary checks in can_minify_response #87

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions htmlmin/middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,21 @@ def can_minify_response(self, request, response):
req_ok = request._hit_htmlmin
except AttributeError:
return False
else:
if not req_ok:
raise ValueError("`request._hit_htmlmin` was set to False, when should only be True or not set.")

if hasattr(settings, 'EXCLUDE_FROM_MINIFYING'):
for url_pattern in settings.EXCLUDE_FROM_MINIFYING:
regex = re.compile(url_pattern)
if regex.match(request.path.lstrip('/')):
req_ok = False
break
return False

resp_ok = response.status_code == 200
resp_ok = resp_ok and 'text/html' in response['Content-Type']
resp_ok = resp_ok and 'text/html' in response.get('Content-Type', '')
if hasattr(response, 'minify_response'):
resp_ok = resp_ok and response.minify_response
return req_ok and resp_ok
return resp_ok

def process_response(self, request, response):
minify = getattr(settings, "HTML_MINIFY", not settings.DEBUG)
Expand Down
23 changes: 23 additions & 0 deletions htmlmin/tests/test_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,29 @@ def test_should_set_flag_when_request_hits_middleware(self):
MarkRequestMiddleware().process_request(request_mock)
self.assertTrue(request_mock._hit_htmlmin)

def test_should_never_set_flag_to_false(self):
request_mock = RequestBareMock()
request_mock._hit_htmlmin = False

def process():
response = HtmlMinifyMiddleware().process_response(
request_mock, ResponseMock(),
)

self.assertRaises(ValueError, process)

def test_does_not_throw_error_when_no_content_type_set(self):
response_mock = ResponseMock()
if 'Content-Type' in response_mock:
del response_mock['Content-Type']

# no self.assertNotRaises exists, but failing test would raise
# a KeyError
response = HtmlMinifyMiddleware().process_response(
RequestMock(), response_mock,
)


def test_should_not_minify_when_request_did_not_hit_middleware(self):
expected_output = "<html> <body>some text here</body> </html>"

Expand Down