summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLorenzo Bolla <lbolla@gmail.com>2017-09-30 08:23:55 +0100
committerINADA Naoki <methane@users.noreply.github.com>2017-09-30 16:23:55 +0900
commitdeeda31a8840cee334f05f15bd2308af13dc9c64 (patch)
tree947c87be0e7923151265a558c5be8554468e689a
parentf0f2c0b39703e0129d2352c71ec9811a8f275cc8 (diff)
downloadmsgpack-python-deeda31a8840cee334f05f15bd2308af13dc9c64.tar.gz
Add unittests to document serialisation of tuples (#246)
Also, fix formatting of error message in case of tuple. See https://github.com/msgpack/msgpack-python/issues/245
-rw-r--r--msgpack/fallback.py2
-rw-r--r--test/test_stricttype.py49
2 files changed, 49 insertions, 2 deletions
diff --git a/msgpack/fallback.py b/msgpack/fallback.py
index a02cbe1..28478ca 100644
--- a/msgpack/fallback.py
+++ b/msgpack/fallback.py
@@ -795,7 +795,7 @@ class Packer(object):
obj = self._default(obj)
default_used = 1
continue
- raise TypeError("Cannot serialize %r" % obj)
+ raise TypeError("Cannot serialize %r" % (obj, ))
def pack(self, obj):
self._pack(obj)
diff --git a/test/test_stricttype.py b/test/test_stricttype.py
index a20b5eb..0f865c8 100644
--- a/test/test_stricttype.py
+++ b/test/test_stricttype.py
@@ -1,7 +1,7 @@
# coding: utf-8
from collections import namedtuple
-from msgpack import packb, unpackb
+from msgpack import packb, unpackb, ExtType
def test_namedtuple():
@@ -13,3 +13,50 @@ def test_namedtuple():
packed = packb(T(1, 42), strict_types=True, use_bin_type=True, default=default)
unpacked = unpackb(packed, encoding='utf-8')
assert unpacked == {'foo': 1, 'bar': 42}
+
+
+def test_tuple():
+ t = ('one', 2, b'three', (4, ))
+
+ def default(o):
+ if isinstance(o, tuple):
+ return {
+ '__type__': 'tuple',
+ 'value': list(o),
+ }
+ raise TypeError('Unsupported type %s' % (type(o),))
+
+ def convert(o):
+ if o.get('__type__') == 'tuple':
+ return tuple(o['value'])
+ return o
+
+ data = packb(t, strict_types=True, use_bin_type=True, default=default)
+ expected = unpackb(data, encoding='utf-8', object_hook=convert)
+
+ assert expected == t
+
+
+def test_tuple_ext():
+ t = ('one', 2, b'three', (4, ))
+
+ MSGPACK_EXT_TYPE_TUPLE = 0
+
+ def default(o):
+ if isinstance(o, tuple):
+ # Convert to list and pack
+ payload = packb(
+ list(o), strict_types=True, use_bin_type=True, default=default)
+ return ExtType(MSGPACK_EXT_TYPE_TUPLE, payload)
+ raise TypeError(repr(o))
+
+ def convert(code, payload):
+ if code == MSGPACK_EXT_TYPE_TUPLE:
+ # Unpack and convert to tuple
+ return tuple(unpackb(payload, encoding='utf-8', ext_hook=convert))
+ raise ValueError('Unknown Ext code {}'.format(code))
+
+ data = packb(t, strict_types=True, use_bin_type=True, default=default)
+ expected = unpackb(data, encoding='utf-8', ext_hook=convert)
+
+ assert expected == t