From 9240117cf41b20ac7760e5e8998821261bf5f4e6 Mon Sep 17 00:00:00 2001 From: Thomas Schultz Date: Mon, 19 Sep 2016 12:44:29 -0400 Subject: [PATCH] Fix unicode message in exceptions; Fixes #2346 --- google/cloud/exceptions.py | 7 ++++++- unit_tests/test_exceptions.py | 38 +++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/google/cloud/exceptions.py b/google/cloud/exceptions.py index bc1349cb7d31..ae5e44dbe1fb 100644 --- a/google/cloud/exceptions.py +++ b/google/cloud/exceptions.py @@ -21,6 +21,8 @@ import json import six +from google.cloud._helpers import _to_bytes + _HTTP_CODE_TO_EXCEPTION = {} # populated at end of module @@ -41,7 +43,10 @@ def __init__(self, message, errors=()): self._errors = errors def __str__(self): - return '%d %s' % (self.code, self.message) + result = u'%d %s' % (self.code, self.message) + if six.PY2: + result = _to_bytes(result, 'utf-8') + return result @property def errors(self): diff --git a/unit_tests/test_exceptions.py b/unit_tests/test_exceptions.py index 3b99b30c1cdf..1ccabe4045c2 100644 --- a/unit_tests/test_exceptions.py +++ b/unit_tests/test_exceptions.py @@ -62,6 +62,44 @@ def test_hit_w_content_as_str(self): self.assertEqual(exception.message, 'Not Found') self.assertEqual(list(exception.errors), []) + def test_hit_w_content_as_unicode(self): + import six + from google.cloud._helpers import _to_bytes + from google.cloud.exceptions import NotFound + error_message = u'That\u2019s not found.' + expected = u'404 %s' % (error_message,) + + response = _Response(404) + content = u'{"error": {"message": "%s" }}' % (error_message,) + + exception = self._callFUT(response, content) + if six.PY2: + self.assertEqual(str(exception), + _to_bytes(expected, encoding='utf-8')) + else: # pragma: NO COVER + self.assertEqual(str(exception), expected) + + self.assertIsInstance(exception, NotFound) + self.assertEqual(exception.message, error_message) + self.assertEqual(list(exception.errors), []) + + def test_hit_w_content_as_unicode_as_py3(self): + import six + from unit_tests._testing import _Monkey + from google.cloud.exceptions import NotFound + error_message = u'That is not found.' + expected = u'404 %s' % (error_message,) + + with _Monkey(six, PY2=False): + response = _Response(404) + content = u'{"error": {"message": "%s" }}' % (error_message,) + exception = self._callFUT(response, content) + + self.assertIsInstance(exception, NotFound) + self.assertEqual(exception.message, error_message) + self.assertEqual(list(exception.errors), []) + self.assertEqual(str(exception), expected) + def test_miss_w_content_as_dict(self): from google.cloud.exceptions import GoogleCloudError ERROR = {