From f05878d90fb7894d93d1a7b40952e702e2539161 Mon Sep 17 00:00:00 2001 From: sneakypete81 Date: Fri, 31 Jan 2014 19:34:01 +0000 Subject: [PATCH] Fix repr unicode handling Python2 requires utf-8 encoded bytestring Python3 requires unicode string --- tests/unit/test_photos.py | 5 +++++ trovebox/objects/trovebox_object.py | 16 +++++++++++++--- 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/tests/unit/test_photos.py b/tests/unit/test_photos.py index 9b10a77..5d77849 100644 --- a/tests/unit/test_photos.py +++ b/tests/unit/test_photos.py @@ -606,6 +606,11 @@ class TestPhotoObject(TestPhotos): "name": "Test Name"}) self.assertEqual(repr(photo), "") + def test_photo_object_repr_with_unicode_id(self): + """ Ensure that a unicode id is correctly represented """ + photo = trovebox.objects.photo.Photo(self.client, {"id": "\xfcmlaut"}) + self.assertIn(repr(photo), [b"", ""]) + @mock.patch.object(trovebox.Trovebox, 'post') def test_photo_object_create_attribute(self, _): """ diff --git a/trovebox/objects/trovebox_object.py b/trovebox/objects/trovebox_object.py index 2e02eca..bd52582 100644 --- a/trovebox/objects/trovebox_object.py +++ b/trovebox/objects/trovebox_object.py @@ -1,6 +1,10 @@ """ Base object supporting the storage of custom fields as attributes """ + +from __future__ import unicode_literals +import sys + class TroveboxObject(object): """ Base object supporting the storage of custom fields as attributes """ _type = "None" @@ -41,11 +45,17 @@ class TroveboxObject(object): def __repr__(self): if self.name is not None: - return "<%s name='%s'>" % (self.__class__.__name__, self.name) + value = "<%s name='%s'>" % (self.__class__.__name__, self.name) elif self.id is not None: - return "<%s id='%s'>" % (self.__class__.__name__, self.id) + value = "<%s id='%s'>" % (self.__class__.__name__, self.id) else: - return "<%s>" % (self.__class__.__name__) + value = "<%s>" % (self.__class__.__name__) + + # Python2 requires a bytestring + if sys.version < '3': + return value.encode('utf-8') + else: # pragma: no cover + return value def get_fields(self): """ Returns this object's attributes """