From 36539df232e8493c1c9633ef970634bdcbc24f76 Mon Sep 17 00:00:00 2001 From: "ChangBo Guo(gcb)" Date: Tue, 27 Jun 2017 14:05:30 +0800 Subject: [PATCH] Add unit test for unicode in object __repr__ This adds a unit test for the behavior when an object has a unicode string field. If on python 2, the repr is encoded to the default encoding (ascii) before being returned. This is to ensure calls like str(obj_repr) will work under python 2. This patch also adjusts logic to make the code compatbile for Python 4. [1] http://astrofrog.github.io/blog/2016/01/12/stop-writing-python-4-incompatible-code/ Co-Authored-By: melanie witt Change-Id: I65dd271ac2198b384d201349607e74992c447f75 --- oslo_versionedobjects/base.py | 2 +- oslo_versionedobjects/tests/test_objects.py | 14 ++++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/oslo_versionedobjects/base.py b/oslo_versionedobjects/base.py index 7df5e52..5e73017 100644 --- a/oslo_versionedobjects/base.py +++ b/oslo_versionedobjects/base.py @@ -314,7 +314,7 @@ class VersionedObject(object): field.stringify(getattr(self, name)) or '')) for name, field in sorted(self.fields.items())])) - if not six.PY3: + if six.PY2: repr_str = encodeutils.safe_encode(repr_str, incoming='utf-8') return repr_str diff --git a/oslo_versionedobjects/tests/test_objects.py b/oslo_versionedobjects/tests/test_objects.py index edd0083..30a1168 100644 --- a/oslo_versionedobjects/tests/test_objects.py +++ b/oslo_versionedobjects/tests/test_objects.py @@ -1200,6 +1200,20 @@ class _TestObject(object): obj2 = MySensitiveObj() self.assertEqual('MySensitiveObj(data=)', repr(obj2)) + def test_obj_repr_unicode(self): + obj = MyObj(bar=u'\u0191\u01A1\u01A1') + # verify the unicode string has been encoded as ASCII if on python 2 + if six.PY2: + self.assertEqual("MyObj(bar='\xc6\x91\xc6\xa1\xc6\xa1',foo=," + "missing=,mutable_default=,readonly=," + "rel_object=,rel_objects=,timestamp=)", + repr(obj)) + else: + self.assertEqual("MyObj(bar='\u0191\u01A1\u01A1',foo=," + "missing=,mutable_default=,readonly=," + "rel_object=,rel_objects=,timestamp=)", + repr(obj)) + def test_obj_make_obj_compatible_with_relationships(self): subobj = MyOwnedObject(baz=1) obj = MyObj(rel_object=subobj) -- GitLab