1
1
# coding: utf-8
2
2
3
3
from collections import namedtuple
4
- from msgpack import packb , unpackb
4
+ from msgpack import packb , unpackb , ExtType
5
5
6
6
7
7
def test_namedtuple ():
@@ -13,3 +13,50 @@ def default(o):
13
13
packed = packb (T (1 , 42 ), strict_types = True , use_bin_type = True , default = default )
14
14
unpacked = unpackb (packed , encoding = 'utf-8' )
15
15
assert unpacked == {'foo' : 1 , 'bar' : 42 }
16
+
17
+
18
+ def test_tuple ():
19
+ t = ('one' , 2 , b'three' , (4 , ))
20
+
21
+ def default (o ):
22
+ if isinstance (o , tuple ):
23
+ return {
24
+ '__type__' : 'tuple' ,
25
+ 'value' : list (o ),
26
+ }
27
+ raise TypeError ('Unsupported type %s' % (type (o ),))
28
+
29
+ def convert (o ):
30
+ if o .get ('__type__' ) == 'tuple' :
31
+ return tuple (o ['value' ])
32
+ return o
33
+
34
+ data = packb (t , strict_types = True , use_bin_type = True , default = default )
35
+ expected = unpackb (data , encoding = 'utf-8' , object_hook = convert )
36
+
37
+ assert expected == t
38
+
39
+
40
+ def test_tuple_ext ():
41
+ t = ('one' , 2 , b'three' , (4 , ))
42
+
43
+ MSGPACK_EXT_TYPE_TUPLE = 0
<
A135
code> 44
+
45
+ def default (o ):
46
+ if isinstance (o , tuple ):
47
+ # Convert to list and pack
48
+ payload = packb (
49
+ list (o ), strict_types = True , use_bin_type = True , default = default )
50
+ return ExtType (MSGPACK_EXT_TYPE_TUPLE , payload )
51
+ raise TypeError (repr (o ))
52
+
53
+ def convert (code , payload ):
54
+ if code == MSGPACK_EXT_TYPE_TUPLE :
55
+ # Unpack and convert to tuple
56
+ return tuple (unpackb (payload , encoding = 'utf-8' , ext_hook = convert ))
57
+ raise ValueError ('Unknown Ext code {}' .format (code ))
58
+
59
+ data = packb (t , strict_types = True , use_bin_type = True , default = default )
60
+ expected = unpackb (data , encoding = 'utf-8' , ext_hook = convert )
61
+
62
+ assert expected == t
0 commit comments