From deeda31a8840cee334f05f15bd2308af13dc9c64 Mon Sep 17 00:00:00 2001 From: Lorenzo Bolla Date: Sat, 30 Sep 2017 08:23:55 +0100 Subject: 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 --- msgpack/fallback.py | 2 +- test/test_stricttype.py | 49 ++++++++++++++++++++++++++++++++++++++++++++++++- 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 -- cgit v1.2.1