Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix unicode message in exceptions #2348

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion google/cloud/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import json
import six

from google.cloud._helpers import _to_bytes

This comment was marked as spam.

_HTTP_CODE_TO_EXCEPTION = {} # populated at end of module


Expand All @@ -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):
Expand Down
38 changes: 38 additions & 0 deletions unit_tests/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down