Skip to content
This repository was archived by the owner on Jan 13, 2021. It is now read-only.

Commit 1d8f94b

Browse files
author
Aviv Cohn
committed
Raising error in HTTP11Response if created with illegal attributes
An HTTP response must either specify a content-length header, specify 'close' for a connection header to signal that the connection will be closed after the response, or be a chunked response. If none of these conditions are true, we raise a detailed ValueError, instead of the plain assertion.
1 parent 065b539 commit 1d8f94b

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

hyper/http11/response.py

+4-5
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,10 @@ def __init__(self, code, reason, headers, sock, connection=None):
5858
b'chunked' in self.headers.get(b'transfer-encoding', [])
5959
)
6060

61-
# One of the following must be true: we must expect that the connection
62-
# will be closed following the body, or that a content-length was sent,
63-
# or that we're getting a chunked response.
64-
# FIXME: Remove naked assert, replace with something better.
65-
assert self._expect_close or self._length is not None or self._chunked
61+
if (not self._expect_close) and (not self._chunked) and (self._length is None):
62+
raise ValueError('A response must either specify a content-length, be a chunked response, '
63+
'or specify that the connection be closed after the response. '
64+
'None of these conditions were met.')
6665

6766
# This object is used for decompressing gzipped request bodies. Right
6867
# now we only support gzip because that's all the RFC mandates of us.

test/test_http11.py

+12
Original file line numberDiff line numberDiff line change
@@ -837,6 +837,18 @@ def test_closing_chunked_reads_dont_call_close_callback(self):
837837
assert r._sock is None
838838
assert connection.close.call_count == 1
839839

840+
def test_regular_response_with_no_content_length_and_no_connection_close_raises_error(self):
841+
headers = {}
842+
sock = DummySocket()
843+
connection = mock.MagicMock()
844+
845+
with pytest.raises(ValueError) as exc_info:
846+
HTTP11Response(200, 'OK', headers, sock, connection)
847+
assert 'A response must either specify a content-length, be a chunked response, ' \
848+
'or specify that the connection be closed after the response. ' \
849+
'None of these conditions were met.' \
850+
in str(exc_info)
851+
840852

841853
class DummySocket(object):
842854
def __init__(self):

0 commit comments

Comments
 (0)