Debian Codegraph @

pypy/module/marshal/test/apptest_marshal.py

raw symbols SCIP
1 import marshal
2 import sys
3
4
5 # ---------------------------------------------------------------------------
6 # Helper
7 # ---------------------------------------------------------------------------
8
9 def marshal_check(case):
10 from io import BytesIO
11 s = marshal.dumps(case)
12 x = marshal.loads(s)
13 assert x == case and type(x) is type(case)
14
15 y = marshal.loads(memoryview(s))
16 assert y == case and type(y) is type(case)
17
18 if '__pypy__' in sys.builtin_module_names:
19 f = BytesIO()
20 marshal.dump(case, f)
21 f.seek(0)
22 x = marshal.load(f)
23 assert x == case and type(x) is type(case)
24 return x
25
26
27 # ---------------------------------------------------------------------------
28 # Basic scalars
29 # ---------------------------------------------------------------------------
30
31 def test_None():
32 marshal_check(None)
33
34 def test_False():
35 marshal_check(False)
36
37 def test_True():
38 marshal_check(True)
39
40 def test_StopIteration():
41 marshal_check(StopIteration)
42
43 def test_Ellipsis():
44 marshal_check(Ellipsis)
45
46 def test_42():
47 marshal_check(42)
48
49 def test_minus_17():
50 marshal_check(-17)
51
52 def test_sys_maxsize():
53 marshal_check(sys.maxsize)
54
55 def test_minus_1_dot_25():
56 marshal_check(-1.25)
57
58 def test_2_plus_5j():
59 marshal_check(2+5j)
60
61 def test_long():
62 marshal_check(-1234567890123456789012345678901234567890)
63
64
65 # ---------------------------------------------------------------------------
66 # Strings
67 # ---------------------------------------------------------------------------
68
69 def test_hello_not_interned():
70 hello = "he"
71 hello += "llo"
72 marshal_check(hello)
73
74 def test_hello_interned():
75 marshal_check("hello")
76
77 def test_bytes():
78 marshal_check(b'hello')
79
80 def test_unicode():
81 marshal_check('\uFFFF')
82 marshal_check('\ud800')
83 c = u"\ud800"
84 marshal_check(c + u'\udc00')
85 marshal_check(chr(sys.maxunicode))
86
87 def test_unmarshal_ascii():
88 s = marshal.loads(b"a\x04\x00\x00\x00abcd")
89 assert s == u"abcd"
90
91 def test_marshal_ascii():
92 s = marshal.dumps("a")
93 assert s.endswith(b"\x01a")
94 s = marshal.dumps("a" * 1000)
95 assert s == b"\xe1\xe8\x03\x00\x00" + b"a" * 1000
96 for x in ("?" * 255, "a" * 1000, "xyza"):
97 s = marshal.dumps(x)
98 s1 = marshal.dumps((x, x)) # check that sharing works
99 # The outer tuple is at ref index 0, the string at index 1.
100 assert s1 == b"\xa9\x02" + s + b"r\x01\x00\x00\x00"
101
102 def test_shared_string():
103 x = "hello, "
104 x += "world"
105 xl = 256
106 xl **= 100
107 for version in [2, 3]:
108 s = marshal.dumps((x, x), version)
109 assert s.count(b'hello, world') == 2 if version < 3 else 1
110 y = marshal.loads(s)
111 assert y == (x, x)
112 #
113 s = marshal.dumps((xl, xl), version)
114 if version < 3:
115 assert 200 < len(s) < 250
116 else:
117 assert 100 < len(s) < 125
118 yl = marshal.loads(s)
119 assert yl == (xl, xl)
120
121 def test_ascii_bug():
122 with raises(ValueError):
123 # TYPE_ASCII but not actually ascii
124 marshal.loads(b'a\x01\0\0\0\xff')
125
126
127 # ---------------------------------------------------------------------------
128 # Collections
129 # ---------------------------------------------------------------------------
130
131 def test_empty_tuple():
132 marshal_check(())
133
134 def test_tuple_1_2():
135 marshal_check((1, 2))
136
137 def test_empty_list():
138 marshal_check([])
139
140 def test_list_3_4():
141 marshal_check([3, 4])
142
143 def test_empty_dict():
144 marshal_check({})
145
146 def test_dict_5_6_7_8():
147 marshal_check({5: 6, 7: 8})
148
149 def test_empty_set():
150 marshal_check(set())
151
152 def test_set_1_2():
153 marshal_check(set([1, 2]))
154
155 def test_empty_frozenset():
156 marshal_check(frozenset())
157
158 def test_frozenset_3_4():
159 marshal_check(frozenset([3, 4]))
160
161 def test_list_recursive():
162 l = []
163 l.append(l)
164 b = marshal.dumps(l)
165 l2 = marshal.loads(b)
166 assert len(l2) == 1
167 assert l2[0] is l2
168
169
170 # ---------------------------------------------------------------------------
171 # Sharing / instancing (v3+)
172 # ---------------------------------------------------------------------------
173
174 def test_shared_tuple():
175 t = (1, "hello")
176 for version in [2, 3]:
177 s = marshal.dumps((t, t), version)
178 y = marshal.loads(s)
179 assert y == (t, t)
180
181 def test_tuple_sharing_identity():
182 # v3+: the same tuple object should be reused (not serialized twice)
183 t = (1, "hello")
184 for version in [3, 4]:
185 s = marshal.dumps((t, t), version)
186 y = marshal.loads(s)
187 assert y == (t, t)
188 assert y[0] is y[1]
189
190 def test_tuple_sharing_nested_in_list():
191 # A tuple appearing twice inside a list should share identity on load
192 inner = (42, "abc")
193 lst = [inner, inner]
194 for version in [3, 4]:
195 data = marshal.dumps(lst, version)
196 loaded = marshal.loads(data)
197 assert loaded[0] is loaded[1]
198
199 def test_tuple_sharing_nested_in_dict():
200 # A tuple appearing as two values in a dict should share identity on load
201 val = (42, "abc")
202 d = {"x": val, "y": val}
203 for version in [3, 4]:
204 data = marshal.dumps(d, version)
205 loaded = marshal.loads(data)
206 assert loaded["x"] is loaded["y"]
207
208
209 # ---------------------------------------------------------------------------
210 # Code objects
211 # ---------------------------------------------------------------------------
212
213 def test_code_object():
214 def foo(a, b):
215 pass
216 s = marshal.dumps(foo.__code__)
217 code2 = marshal.loads(s)
218 for attr_name in dir(code2):
219 if attr_name.startswith("co_"):
220 if callable(getattr(code2, attr_name)): # co_lines, co_positions
221 assert list(getattr(code2, attr_name)()) == list(getattr(foo.__code__, attr_name)())
222 else:
223 assert getattr(code2, attr_name) == getattr(foo.__code__, attr_name)
224
225 def test_code_positions():
226 def foo(a, b):
227 return (
228 a.x +
229 b.y
230 )
231 s = marshal.dumps(foo.__code__)
232 code2 = marshal.loads(s)
233 assert list(code2.co_positions()) == list(foo.__code__.co_positions())
234
235 def test_func_code():
236 def func(x):
237 return lambda y: x+y
238 marshal_check(func.__code__)
239
240 def test_scopefunc_code():
241 def func(x):
242 return lambda y: x+y
243 scopefunc = func(42)
244 marshal_check(scopefunc.__code__)
245
246 def test_co_filename_bug():
247 code = compile('pass', 'tmp-\udcff.py', "exec")
248 res = marshal.dumps(code) # must not crash
249 code2 = marshal.loads(res)
250 assert code.co_filename == code2.co_filename
251
252
253 # ---------------------------------------------------------------------------
254 # Buffer-like objects
255 # ---------------------------------------------------------------------------
256
257 def test_marshal_bufferlike_object():
258 s = marshal.dumps(memoryview(b'asd'))
259 t = marshal.loads(s)
260 assert type(t) is bytes and t == b'asd'
261
262 s = marshal.dumps(memoryview(bytearray(b'asd')))
263 t = marshal.loads(s)
264 assert type(t) is bytes and t == b'asd'
265
266
267 # ---------------------------------------------------------------------------
268 # Stream I/O
269 # ---------------------------------------------------------------------------
270
271 def test_stream_reader_writer():
272 import tempfile, os
273 obj1 = [4, ("hello", 7.5)]
274 obj2 = "foobar"
275 fd, tmpfile = tempfile.mkstemp()
276 os.close(fd)
277 try:
278 f = open(tmpfile, 'wb')
279 marshal.dump(obj1, f)
280 marshal.dump(obj2, f)
281 f.write(b'END')
282 f.close()
283 f = open(tmpfile, 'rb')
284 obj1b = marshal.load(f)
285 obj2b = marshal.load(f)
286 tail = f.read()
287 f.close()
288 assert obj1b == obj1
289 assert obj2b == obj2
290 assert tail == b'END'
291 finally:
292 os.unlink(tmpfile)
293
294
295 # ---------------------------------------------------------------------------
296 # Error / edge cases
297 # ---------------------------------------------------------------------------
298
299 def test_unmarshal_evil_long():
300 raises(ValueError, marshal.loads, b'l\x02\x00\x00\x00\x00\x00\x00\x00')
301
302 def test_int64():
303 assert marshal.loads(b'I\xff\xff\xff\xff\xff\xff\xff\x7f') == 0x7fffffffffffffff
304 assert marshal.loads(b'I\xfe\xdc\xba\x98\x76\x54\x32\x10') == 0x1032547698badcfe
305 assert marshal.loads(b'I\x01\x23\x45\x67\x89\xab\xcd\xef') == -0x1032547698badcff
306 assert marshal.loads(b'I\x08\x19\x2a\x3b\x4c\x5d\x6e\x7f') == 0x7f6e5d4c3b2a1908
307 assert marshal.loads(b'I\xf7\xe6\xd5\xc4\xb3\xa2\x91\x80') == -0x7f6e5d4c3b2a1909
308
309 def test_bad_typecode():
310 exc = raises(ValueError, marshal.loads, bytes([1]))
311 assert str(exc.value).startswith("bad marshal data (unknown type code")
312
313 def test_bad_reader():
314 import io
315 class BadReader(io.BytesIO):
316 def read(self, n=-1):
317 b = super().read(n)
318 if n is not None and n > 4:
319 b += b' ' * 10**6
320 return b
321 for value in (1.0, 1j, b'0123456789', '0123456789'):
322 raises(ValueError, marshal.load, BadReader(marshal.dumps(value)))
323
324 def test_reject_subtypes():
325 types = (float, complex, int, tuple, list, dict, set, frozenset)
326 for cls in types:
327 class subtype(cls):
328 pass
329 exc = raises(ValueError, marshal.dumps, subtype)
330 assert str(exc.value) == 'unmarshallable object'
331 exc = raises(ValueError, marshal.dumps, subtype())
332 assert str(exc.value) == 'unmarshallable object'
333 exc = raises(ValueError, marshal.dumps, (subtype(),))
334 assert str(exc.value) == 'unmarshallable object'
335
336 def test_valid_subtypes():
337 class subtype(bytearray):
338 pass
339 assert marshal.dumps(subtype(b'test')) == marshal.dumps(bytearray(b'test'))