From a064de88dbc7c2382ad52a4b2b0a24201522335a Mon Sep 17 00:00:00 2001 From: Julien Duponchelle Date: Thu, 1 Jun 2017 15:19:41 +0200 Subject: [PATCH] Raise RuntimeError is you try to set the Content Length and enable chunked encoding at the same time --- CHANGES.rst | 2 +- aiohttp/web_response.py | 8 +++++++- tests/test_web_response.py | 16 ++++++++++++++++ 3 files changed, 24 insertions(+), 2 deletions(-) diff --git a/CHANGES.rst b/CHANGES.rst index 131bd02999c..f1f62a0bff7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -23,7 +23,7 @@ Changes - -- +- Raise RuntimeError is you try to set the Content Length and enable chunked encoding at the same time 2.1.0 (2017-05-26) ------------------ diff --git a/aiohttp/web_response.py b/aiohttp/web_response.py index f096c86556a..013edb6d76d 100644 --- a/aiohttp/web_response.py +++ b/aiohttp/web_response.py @@ -111,6 +111,10 @@ def output_length(self): def enable_chunked_encoding(self, chunk_size=None): """Enables automatic chunked transfer encoding.""" self._chunked = True + + if hdrs.CONTENT_LENGTH in self._headers: + raise RuntimeError("You can't enable chunked encoding when " + "a content length is set") if chunk_size is not None: warnings.warn('Chunk size is deprecated #1615', DeprecationWarning) @@ -194,7 +198,9 @@ def content_length(self): def content_length(self, value): if value is not None: value = int(value) - # TODO: raise error if chunked enabled + if self._chunked: + raise RuntimeError("You can't set content length when " + "chunked encoding is enable") self._headers[hdrs.CONTENT_LENGTH] = str(value) else: self._headers.pop(hdrs.CONTENT_LENGTH, None) diff --git a/tests/test_web_response.py b/tests/test_web_response.py index 6a407cbdcd1..f8338c136f9 100644 --- a/tests/test_web_response.py +++ b/tests/test_web_response.py @@ -86,6 +86,14 @@ def test_content_length_setter(): assert 234 == resp.content_length +def test_content_length_setter_with_enable_chunked_encoding(): + resp = StreamResponse() + + resp.enable_chunked_encoding() + with pytest.raises(RuntimeError): + resp.content_length = 234 + + def test_drop_content_length_header_on_setting_len_to_None(): resp = StreamResponse() @@ -223,6 +231,14 @@ def test_chunked_encoding(): assert msg.chunked +def test_enable_chunked_encoding_with_content_length(): + resp = StreamResponse() + + resp.content_length = 234 + with pytest.raises(RuntimeError): + resp.enable_chunked_encoding() + + @asyncio.coroutine def test_chunk_size(): req = make_request('GET', '/', payload_writer=mock.Mock())