Skip to content

Commit

Permalink
Fix unicode message in exceptions; #2346
Browse files Browse the repository at this point in the history
  • Loading branch information
daspecster committed Sep 21, 2016
1 parent 5f1cda9 commit 72b29d6
Show file tree
Hide file tree
Showing 2 changed files with 37 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


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

0 comments on commit 72b29d6

Please sign in to comment.