From 72b29d687d90404688cb07423ea350f2e2fa2175 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; #2346 --- google/cloud/exceptions.py | 7 ++++++- unit_tests/test_exceptions.py | 31 +++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/google/cloud/exceptions.py b/google/cloud/exceptions.py index bc1349cb7d319..ae5e44dbe1fb7 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 3b99b30c1cdfe..dc7187377acb9 100644 --- a/unit_tests/test_exceptions.py +++ b/unit_tests/test_exceptions.py @@ -62,6 +62,37 @@ 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): + from google.cloud.exceptions import NotFound + _ERROR_MESSAGE = u'That\u2019s not found.' + _EXPECTED = (b'404 That\xe2\x80\x99s not found.', + '404 %s' % (_ERROR_MESSAGE,)) + + response = _Response(404) + content = u'{"error": {"message": "%s" }}' % (_ERROR_MESSAGE,) + + exception = self._callFUT(response, content) + self.assertIn(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\'s not found.' + + with _Monkey(six, PY2=False, PY3=True): + response = _Response(404) + content = u'{"error": {"message": "%s" }}' % (_ERROR_MESSAGE,) + + exception = self._callFUT(response, content) + self.assertEqual(str(exception), '404 %s' % (_ERROR_MESSAGE,)) + self.assertIsInstance(exception, NotFound) + self.assertEqual(exception.message, _ERROR_MESSAGE) + self.assertEqual(list(exception.errors), []) + def test_miss_w_content_as_dict(self): from google.cloud.exceptions import GoogleCloudError ERROR = {