From b9fca76dbd9d8acbb2537224510638d380d53fe6 Mon Sep 17 00:00:00 2001 From: allfro Date: Tue, 24 Jul 2018 10:11:55 -0400 Subject: [PATCH 1/2] Fixed message truncation bug The length of the utf-8 encoded body may be different than the unicode length of the string. This causes message truncation on the response. This patch fixes the issue. --- chalice/local.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chalice/local.py b/chalice/local.py index 5deb86d23..61df58605 100644 --- a/chalice/local.py +++ b/chalice/local.py @@ -576,6 +576,8 @@ def _send_http_response(self, code, headers, body): def _send_http_response_with_body(self, code, headers, body): # type: (int, HeaderType, Union[str,bytes]) -> None self.send_response(code) + if not isinstance(body, bytes): + body = body.encode('utf-8') self.send_header('Content-Length', str(len(body))) content_type = headers.pop( 'Content-Type', 'application/json') @@ -583,8 +585,6 @@ def _send_http_response_with_body(self, code, headers, body): for header_name, header_value in headers.items(): self.send_header(header_name, header_value) self.end_headers() - if not isinstance(body, bytes): - body = body.encode('utf-8') self.wfile.write(body) do_GET = do_PUT = do_POST = do_HEAD = do_DELETE = do_PATCH = do_OPTIONS = \ From e484eb10c51e02c0004d02c169705437f26834de Mon Sep 17 00:00:00 2001 From: stealthycoin Date: Fri, 27 Jul 2018 13:56:52 -0700 Subject: [PATCH 2/2] Add test for local mode unicode content-length --- CHANGELOG.rst | 6 ++++++ tests/functional/test_local.py | 13 +++++++++++++ 2 files changed, 19 insertions(+) diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 0ecc7a775..7c5884e61 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -2,6 +2,12 @@ CHANGELOG ========= +Next Release (TBD) +================== + +* Fix local mode issue with unicode responses and Content-Length + (`#910 `__) + 1.6.0 ===== diff --git a/tests/functional/test_local.py b/tests/functional/test_local.py index ff228ea2d..78cb70f7e 100644 --- a/tests/functional/test_local.py +++ b/tests/functional/test_local.py @@ -159,6 +159,19 @@ def test_can_accept_get_request(config, sample_app, local_server_factory): assert response.text == '{"hello": "world"}' +def test_can_get_unicode_string_content_length( + config, local_server_factory): + demo = app.Chalice('app-name') + + @demo.route('/') + def index_view(): + return u'\u2713' + + local_server, port = local_server_factory(demo, config) + response = local_server.make_call(requests.get, '/', port) + assert response.headers['Content-Length'] == '3' + + def test_can_accept_options_request(config, sample_app, local_server_factory): local_server, port = local_server_factory(sample_app, config) response = local_server.make_call(requests.options, '/test-cors', port)