Debian Codegraph @

test/test_case.py

raw
1 #!/usr/bin/env python
2 from msgpack import packb, unpackb
3
4
5 def check(length, obj, use_bin_type=True):
6 v = packb(obj, use_bin_type=use_bin_type)
7 assert len(v) == length, f"{obj!r} length should be {length!r} but get {len(v)!r}"
8 assert unpackb(v, use_list=0, raw=not use_bin_type) == obj
9
10
11 def test_1():
12 for o in [
13 None,
14 True,
15 False,
16 0,
17 1,
18 (1 << 6),
19 (1 << 7) - 1,
20 -1,
21 -((1 << 5) - 1),
22 -(1 << 5),
23 ]:
24 check(1, o)
25
26
27 def test_2():
28 for o in [1 << 7, (1 << 8) - 1, -((1 << 5) + 1), -(1 << 7)]:
29 check(2, o)
30
31
32 def test_3():
33 for o in [1 << 8, (1 << 16) - 1, -((1 << 7) + 1), -(1 << 15)]:
34 check(3, o)
35
36
37 def test_5():
38 for o in [1 << 16, (1 << 32) - 1, -((1 << 15) + 1), -(1 << 31)]:
39 check(5, o)
40
41
42 def test_9():
43 for o in [
44 1 << 32,
45 (1 << 64) - 1,
46 -((1 << 31) + 1),
47 -(1 << 63),
48 1.0,
49 0.1,
50 -0.1,
51 -1.0,
52 ]:
53 check(9, o)
54
55
56 def check_raw(overhead, num):
57 check(num + overhead, b" " * num, use_bin_type=False)
58
59
60 def test_fixraw():
61 check_raw(1, 0)
62 check_raw(1, (1 << 5) - 1)
63
64
65 def test_raw16():
66 check_raw(3, 1 << 5)
67 check_raw(3, (1 << 16) - 1)
68
69
70 def test_raw32():
71 check_raw(5, 1 << 16)
72
73
74 def check_array(overhead, num):
75 check(num + overhead, (None,) * num)
76
77
78 def test_fixarray():
79 check_array(1, 0)
80 check_array(1, (1 << 4) - 1)
81
82
83 def test_array16():
84 check_array(3, 1 << 4)
85 check_array(3, (1 << 16) - 1)
86
87
88 def test_array32():
89 check_array(5, (1 << 16))
90
91
92 def match(obj, buf):
93 assert packb(obj) == buf
94 assert unpackb(buf, use_list=0, strict_map_key=False) == obj
95
96
97 def test_match():
98 cases = [
99 (None, b"\xc0"),
100 (False, b"\xc2"),
101 (True, b"\xc3"),
102 (0, b"\x00"),
103 (127, b"\x7f"),
104 (128, b"\xcc\x80"),
105 (256, b"\xcd\x01\x00"),
106 (-1, b"\xff"),
107 (-33, b"\xd0\xdf"),
108 (-129, b"\xd1\xff\x7f"),
109 ({1: 1}, b"\x81\x01\x01"),
110 (1.0, b"\xcb\x3f\xf0\x00\x00\x00\x00\x00\x00"),
111 ((), b"\x90"),
112 (
113 tuple(range(15)),
114 b"\x9f\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e",
115 ),
116 (
117 tuple(range(16)),
118 b"\xdc\x00\x10\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
119 ),
120 ({}, b"\x80"),
121 (
122 {x: x for x in range(15)},
123 b"\x8f\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06\x06\x07\x07\x08\x08\t\t\n\n\x0b\x0b\x0c\x0c\r\r\x0e\x0e",
124 ),
125 (
126 {x: x for x in range(16)},
127 b"\xde\x00\x10\x00\x00\x01\x01\x02\x02\x03\x03\x04\x04\x05\x05\x06\x06\x07\x07\x08\x08\t\t\n\n\x0b\x0b\x0c\x0c\r\r\x0e\x0e\x0f\x0f",
128 ),
129 ]
130
131 for v, p in cases:
132 match(v, p)
133
134
135 def test_unicode():
136 assert unpackb(packb("foobar"), use_list=1) == "foobar"