diff --git a/hyper/http11/response.py b/hyper/http11/response.py index 8f3eb985..31d2266d 100644 --- a/hyper/http11/response.py +++ b/hyper/http11/response.py @@ -53,10 +53,13 @@ def __init__(self, code, reason, headers, sock, connection=None, self._expect_close = True # The expected length of the body. - try: - self._length = int(self.headers[b'content-length'][0]) - except KeyError: - self._length = None + if request_method != b'HEAD': + try: + self._length = int(self.headers[b'content-length'][0]) + except KeyError: + self._length = None + else: + self._length = 0 # Whether we expect a chunked response. self._chunked = ( diff --git a/test/test_http11.py b/test/test_http11.py index 954bacd0..4a9280c9 100644 --- a/test/test_http11.py +++ b/test/test_http11.py @@ -941,6 +941,18 @@ def test_response_version(self): r = HTTP11Response(200, 'OK', headers, d) assert r.version is HTTPVersion.http11 + def test_response_body_length(self): + methods = [b'HEAD', b'GET'] + headers = {b'content-length': [b'15']} + d = DummySocket() + for method in methods: + d.queue = [] + r = HTTP11Response(200, 'OK', headers, d, request_method=method) + if method == b'HEAD': + assert r._length == 0 + else: + assert r._length == int(r.headers[b'content-length'][0]) + class DummySocket(object): def __init__(self): diff --git a/test_release.py b/test_release.py index 07c8c9df..38138657 100644 --- a/test_release.py +++ b/test_release.py @@ -168,3 +168,27 @@ def test_hitting_nghttp2_org_via_h2c_upgrade(self): assert response.status == 200 assert response.read() assert response.version == HTTPVersion.http20 + + def test_http11_response_body_length(self): + """ + This test function uses check the expected length of the HTTP/1.1-response-body. + """ + c = HTTP11Connection('httpbin.org:443') + + # Make some HTTP/1.1 requests. + methods = ['GET', 'HEAD'] + for method in methods: + c.request(method, '/') + resp = c.get_response() + + # Check the expected length of the body. + if method == 'HEAD': + assert resp._length == 0 + assert resp.read() == b'' + else: + try: + content_length = int(resp.headers[b'Content-Length'][0]) + except KeyError: + continue + assert resp._length == content_length + assert resp.read()