Replace TypeError by ValueError in msgpackutils

There are some differences in the behaviour of json and msgpack
serializers. Msgpack throws TypeError when it doesn't know
how to handle an object. Json throws ValueError instead. Regarding
the fact that serialization should be configurable (in particular,
serializers should have similar behaviour; right now transition from
json to msgpack leads to errors and fails) this patch proposes to
raise ValueError instead of TypeError on failures so that libraries
already using jsonutils would be able to also work with msgpackutils.

Change-Id: I3d21b7d136e5a426a3c4a70a953c82ddcd6ef5af
This commit is contained in:
Gevorg Davoian 2016-05-20 15:00:12 +03:00
parent 8a4cac92bc
commit 4fdaeff758
4 changed files with 10 additions and 7 deletions

View File

@ -126,7 +126,7 @@ def to_primitive(value, convert_instances=False, convert_datetime=True,
return 'mock'
if level > max_depth:
return '?'
return None
# The try block may not be necessary after the class check above,
# but just in case ...

View File

@ -13,7 +13,7 @@
# under the License.
'''
Msgpack related utilities.
MessagePack related utilities.
This module provides a few things:
@ -388,8 +388,8 @@ class DateHandler(object):
def _serializer(registry, obj):
handler = registry.match(obj)
if handler is None:
raise TypeError("No serialization handler registered"
" for type '%s'" % (type(obj).__name__))
raise ValueError("No serialization handler registered"
" for type '%s'" % (type(obj).__name__))
return msgpack.ExtType(handler.identity, handler.serialize(obj))

View File

@ -288,9 +288,9 @@ class ToPrimitiveTestCase(test_base.BaseTestCase):
l4_obj = LevelsGenerator(4)
json_l2 = {0: {0: '?'}}
json_l3 = {0: {0: {0: '?'}}}
json_l4 = {0: {0: {0: {0: '?'}}}}
json_l2 = {0: {0: None}}
json_l3 = {0: {0: {0: None}}}
json_l4 = {0: {0: {0: {0: None}}}}
ret = jsonutils.to_primitive(l4_obj, max_depth=2)
self.assertEqual(ret, json_l2)

View File

@ -209,3 +209,6 @@ class MsgPackUtilsTest(test_base.BaseTestCase):
self.assertEqual(255, c.r)
self.assertEqual(254, c.g)
self.assertEqual(253, c.b)
def test_object(self):
self.assertRaises(ValueError, msgpackutils.dumps, object())