Skip to content

Commit

Permalink
Merge pull request #2348 from daspecster/fix-google-cloud-error-excep…
Browse files Browse the repository at this point in the history
…tion-message

Fix unicode message in exceptions
  • Loading branch information
daspecster authored Sep 22, 2016
2 parents b60d498 + 9240117 commit e9660a8
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
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

_HTTP_CODE_TO_EXCEPTION = {} # populated at end of module

try:
Expand Down Expand Up @@ -52,7 +54,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

0 comments on commit e9660a8

Please sign in to comment.