Debian Codegraph @

test/test_obj.py

raw
1 #!/usr/bin/env python
2
3 from pytest import raises
4
5 from msgpack import packb, unpackb
6
7
8 def _decode_complex(obj):
9 if b"__complex__" in obj:
10 return complex(obj[b"real"], obj[b"imag"])
11 return obj
12
13
14 def _encode_complex(obj):
15 if isinstance(obj, complex):
16 return {b"__complex__": True, b"real": 1, b"imag": 2}
17 return obj
18
19
20 def test_encode_hook():
21 packed = packb([3, 1 + 2j], default=_encode_complex)
22 unpacked = unpackb(packed, use_list=1)
23 assert unpacked[1] == {b"__complex__": True, b"real": 1, b"imag": 2}
24
25
26 def test_decode_hook():
27 packed = packb([3, {b"__complex__": True, b"real": 1, b"imag": 2}])
28 unpacked = unpackb(packed, object_hook=_decode_complex, use_list=1)
29 assert unpacked[1] == 1 + 2j
30
31
32 def test_decode_pairs_hook():
33 packed = packb([3, {1: 2, 3: 4}])
34 prod_sum = 1 * 2 + 3 * 4
35 unpacked = unpackb(
36 packed,
37 object_pairs_hook=lambda lst: sum(k * v for k, v in lst),
38 use_list=1,
39 strict_map_key=False,
40 )
41 assert unpacked[1] == prod_sum
42
43
44 def test_only_one_obj_hook():
45 with raises(TypeError):
46 unpackb(b"", object_hook=lambda x: x, object_pairs_hook=lambda x: x)
47
48
49 def test_bad_hook():
50 with raises(TypeError):
51 packed = packb([3, 1 + 2j], default=lambda o: o)
52 unpackb(packed, use_list=1)
53
54
55 def _arr_to_str(arr):
56 return "".join(str(c) for c in arr)
57
58
59 def test_array_hook():
60 packed = packb([1, 2, 3])
61 unpacked = unpackb(packed, list_hook=_arr_to_str, use_list=1)
62 assert unpacked == "123"
63
64
65 class DecodeError(Exception):
66 pass
67
68
69 def bad_complex_decoder(o):
70 raise DecodeError("Ooops!")
71
72
73 def test_an_exception_in_objecthook1():
74 with raises(DecodeError):
75 packed = packb({1: {"__complex__": True, "real": 1, "imag": 2}})
76 unpackb(packed, object_hook=bad_complex_decoder, strict_map_key=False)
77
78
79 def test_an_exception_in_objecthook2():
80 with raises(DecodeError):
81 packed = packb({1: [{"__complex__": True, "real": 1, "imag": 2}]})
82 unpackb(packed, list_hook=bad_complex_decoder, use_list=1, strict_map_key=False)