blob: ab062370641d0ea0cc8ce74dcb822e823a0c3444 [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#!/usr/bin/env python3
Skip Montanaroc1b41542003-08-02 15:02:33 +00002
Benjamin Petersonee8712c2008-05-20 21:35:26 +00003from test import support
Antoine Pitrou679e9d32012-03-02 18:12:43 +01004import array
Serhiy Storchaka3641a742013-07-11 22:20:47 +03005import io
Tim Peters82112372001-08-29 02:28:42 +00006import marshal
7import sys
Skip Montanaroc1b41542003-08-02 15:02:33 +00008import unittest
9import os
Benjamin Peterson43b06862011-05-27 09:08:01 -050010import types
Tim Peters82112372001-08-29 02:28:42 +000011
Guido van Rossum47f17d02007-07-10 11:37:44 +000012class HelperMixin:
13 def helper(self, sample, *extra):
14 new = marshal.loads(marshal.dumps(sample, *extra))
15 self.assertEqual(sample, new)
16 try:
Brian Curtin2c3563f2010-10-13 02:40:26 +000017 with open(support.TESTFN, "wb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000018 marshal.dump(sample, f, *extra)
Brian Curtin2c3563f2010-10-13 02:40:26 +000019 with open(support.TESTFN, "rb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000020 new = marshal.load(f)
Guido van Rossum47f17d02007-07-10 11:37:44 +000021 self.assertEqual(sample, new)
22 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +000023 support.unlink(support.TESTFN)
Guido van Rossum47f17d02007-07-10 11:37:44 +000024
25class IntTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000026 def test_ints(self):
Antoine Pitroue9bbe8b2013-04-13 22:41:09 +020027 # Test a range of Python ints larger than the machine word size.
28 n = sys.maxsize ** 2
Skip Montanaroc1b41542003-08-02 15:02:33 +000029 while n:
30 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000031 self.helper(expected)
Antoine Pitrouc1ab0bd2013-04-13 22:46:33 +020032 n = n >> 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000033
34 def test_bool(self):
35 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000036 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000037
Guido van Rossum47f17d02007-07-10 11:37:44 +000038class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000039 def test_floats(self):
40 # Test a few floats
41 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000042 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000043 while n > small:
44 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000045 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000046 n /= 123.4567
47
48 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000049 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000050 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000051 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000052 # and with version <= 1 (floats marshalled differently then)
53 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000054 got = marshal.loads(s)
55 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000056
Christian Heimesa37d4c62007-12-04 23:02:19 +000057 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000058 while n < small:
59 for expected in (-n, n):
60 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000061 self.helper(f)
62 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000063 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000064
Guido van Rossum47f17d02007-07-10 11:37:44 +000065class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000066 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000067 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
68 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000069
Skip Montanaroc1b41542003-08-02 15:02:33 +000070 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000071 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
72 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000073
Guido van Rossumbae07c92007-10-08 02:46:15 +000074 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +000075 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +000076 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +000077
Skip Montanaroc1b41542003-08-02 15:02:33 +000078class ExceptionTestCase(unittest.TestCase):
79 def test_exceptions(self):
80 new = marshal.loads(marshal.dumps(StopIteration))
81 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +000082
Skip Montanaroc1b41542003-08-02 15:02:33 +000083class CodeTestCase(unittest.TestCase):
84 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +000085 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +000086 new = marshal.loads(marshal.dumps(co))
87 self.assertEqual(co, new)
88
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +000089 def test_many_codeobjects(self):
90 # Issue2957: bad recursion count on code objects
91 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
92 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
93 marshal.loads(marshal.dumps(codes))
94
Benjamin Peterson43b06862011-05-27 09:08:01 -050095 def test_different_filenames(self):
96 co1 = compile("x", "f1", "exec")
97 co2 = compile("y", "f2", "exec")
98 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
99 self.assertEqual(co1.co_filename, "f1")
100 self.assertEqual(co2.co_filename, "f2")
101
102 @support.cpython_only
103 def test_same_filename_used(self):
104 s = """def f(): pass\ndef g(): pass"""
105 co = compile(s, "myfile", "exec")
106 co = marshal.loads(marshal.dumps(co))
107 for obj in co.co_consts:
108 if isinstance(obj, types.CodeType):
109 self.assertIs(co.co_filename, obj.co_filename)
110
Guido van Rossum47f17d02007-07-10 11:37:44 +0000111class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000112 d = {'astring': 'foo@bar.baz.spam',
113 'afloat': 7283.43,
114 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000115 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000116 'alist': ['.zyx.41'],
117 'atuple': ('.zyx.41',)*10,
118 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000119 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000120 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000121
Skip Montanaroc1b41542003-08-02 15:02:33 +0000122 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000123 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000124
Skip Montanaroc1b41542003-08-02 15:02:33 +0000125 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000126 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000127
128 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000129 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000130
Raymond Hettingera422c342005-01-11 03:03:27 +0000131 def test_sets(self):
132 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000133 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000134
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100135
136class BufferTestCase(unittest.TestCase, HelperMixin):
137
138 def test_bytearray(self):
139 b = bytearray(b"abc")
140 self.helper(b)
141 new = marshal.loads(marshal.dumps(b))
142 self.assertEqual(type(new), bytes)
143
144 def test_memoryview(self):
145 b = memoryview(b"abc")
146 self.helper(b)
147 new = marshal.loads(marshal.dumps(b))
148 self.assertEqual(type(new), bytes)
149
150 def test_array(self):
151 a = array.array('B', b"abc")
152 new = marshal.loads(marshal.dumps(a))
153 self.assertEqual(new, b"abc")
154
155
Skip Montanaroc1b41542003-08-02 15:02:33 +0000156class BugsTestCase(unittest.TestCase):
157 def test_bug_5888452(self):
158 # Simple-minded check for SF 588452: Debug build crashes
159 marshal.dumps([128] * 1000)
160
Armin Rigo01ab2792004-03-26 15:09:27 +0000161 def test_patch_873224(self):
162 self.assertRaises(Exception, marshal.loads, '0')
163 self.assertRaises(Exception, marshal.loads, 'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000164 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000165
Armin Rigo2ccea172004-12-20 12:25:57 +0000166 def test_version_argument(self):
167 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000168 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
169 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000170
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000171 def test_fuzz(self):
172 # simple test that it's at least not *totally* trivial to
173 # crash from bad marshal data
174 for c in [chr(i) for i in range(256)]:
175 try:
176 marshal.loads(c)
177 except Exception:
178 pass
179
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700180 def test_loads_2x_code(self):
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100181 s = b'c' + (b'X' * 4*4) + b'{' * 2**20
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000182 self.assertRaises(ValueError, marshal.loads, s)
183
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700184 def test_loads_recursion(self):
185 s = b'c' + (b'X' * 4*5) + b'{' * 2**20
186 self.assertRaises(ValueError, marshal.loads, s)
187
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000188 def test_recursion_limit(self):
189 # Create a deeply nested structure.
190 head = last = []
191 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000192 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
193 MAX_MARSHAL_STACK_DEPTH = 1500
194 else:
195 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000196 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
197 last.append([0])
198 last = last[-1]
199
200 # Verify we don't blow out the stack with dumps/load.
201 data = marshal.dumps(head)
202 new_head = marshal.loads(data)
203 # Don't use == to compare objects, it can exceed the recursion limit.
204 self.assertEqual(len(new_head), len(head))
205 self.assertEqual(len(new_head[0]), len(head[0]))
206 self.assertEqual(len(new_head[-1]), len(head[-1]))
207
208 last.append([0])
209 self.assertRaises(ValueError, marshal.dumps, head)
210
Guido van Rossum58da9312007-11-10 23:39:45 +0000211 def test_exact_type_match(self):
212 # Former bug:
213 # >>> class Int(int): pass
214 # >>> type(loads(dumps(Int())))
215 # <type 'int'>
216 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200217 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000218 # by marshal's routines for objects supporting the buffer API.
219 subtyp = type('subtyp', (typ,), {})
220 self.assertRaises(ValueError, marshal.dumps, subtyp())
221
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000222 # Issue #1792 introduced a change in how marshal increases the size of its
223 # internal buffer; this test ensures that the new code is exercised.
224 def test_large_marshal(self):
225 size = int(1e6)
226 testString = 'abc' * size
227 marshal.dumps(testString)
228
Mark Dickinson2683ab02009-09-29 19:21:35 +0000229 def test_invalid_longs(self):
230 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
231 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
232 self.assertRaises(ValueError, marshal.loads, invalid_string)
233
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100234 def test_multiple_dumps_and_loads(self):
235 # Issue 12291: marshal.load() should be callable multiple times
236 # with interleaved data written by non-marshal code
237 # Adapted from a patch by Engelbert Gruber.
238 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
239 for interleaved in (b'', b'0123'):
240 ilen = len(interleaved)
241 positions = []
242 try:
243 with open(support.TESTFN, 'wb') as f:
244 for d in data:
245 marshal.dump(d, f)
246 if ilen:
247 f.write(interleaved)
248 positions.append(f.tell())
249 with open(support.TESTFN, 'rb') as f:
250 for i, d in enumerate(data):
251 self.assertEqual(d, marshal.load(f))
252 if ilen:
253 f.read(ilen)
254 self.assertEqual(positions[i], f.tell())
255 finally:
256 support.unlink(support.TESTFN)
257
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100258 def test_loads_reject_unicode_strings(self):
259 # Issue #14177: marshal.loads() should not accept unicode strings
260 unicode_string = 'T'
261 self.assertRaises(TypeError, marshal.loads, unicode_string)
262
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300263 def test_bad_reader(self):
264 class BadReader(io.BytesIO):
265 def read(self, n=-1):
266 b = super().read(n)
267 if n is not None and n > 4:
268 b += b' ' * 10**6
269 return b
270 for value in (1.0, 1j, b'0123456789', '0123456789'):
271 self.assertRaises(ValueError, marshal.load,
272 BadReader(marshal.dumps(value)))
273
Kristján Valur Jónsson61683622013-03-20 14:26:33 -0700274 def _test_eof(self):
275 data = marshal.dumps(("hello", "dolly", None))
276 for i in range(len(data)):
277 self.assertRaises(EOFError, marshal.loads, data[0: i])
278
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200279LARGE_SIZE = 2**31
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200280pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
281
282class NullWriter:
283 def write(self, s):
284 pass
285
286@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
287class LargeValuesTestCase(unittest.TestCase):
288 def check_unmarshallable(self, data):
289 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
290
291 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
292 def test_bytes(self, size):
293 self.check_unmarshallable(b'x' * size)
294
Serhiy Storchaka40f42d92013-02-13 12:32:24 +0200295 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200296 def test_str(self, size):
297 self.check_unmarshallable('x' * size)
298
299 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
300 def test_tuple(self, size):
301 self.check_unmarshallable((None,) * size)
302
303 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
304 def test_list(self, size):
305 self.check_unmarshallable([None] * size)
306
307 @support.bigmemtest(size=LARGE_SIZE,
308 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
309 dry_run=False)
310 def test_set(self, size):
311 self.check_unmarshallable(set(range(size)))
312
313 @support.bigmemtest(size=LARGE_SIZE,
314 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
315 dry_run=False)
316 def test_frozenset(self, size):
317 self.check_unmarshallable(frozenset(range(size)))
318
319 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
320 def test_bytearray(self, size):
321 self.check_unmarshallable(bytearray(size))
322
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700323def CollectObjectIDs(ids, obj):
324 """Collect object ids seen in a structure"""
325 if id(obj) in ids:
326 return
327 ids.add(id(obj))
328 if isinstance(obj, (list, tuple, set, frozenset)):
329 for e in obj:
330 CollectObjectIDs(ids, e)
331 elif isinstance(obj, dict):
332 for k, v in obj.items():
333 CollectObjectIDs(ids, k)
334 CollectObjectIDs(ids, v)
335 return len(ids)
336
337class InstancingTestCase(unittest.TestCase, HelperMixin):
338 intobj = 123321
339 floatobj = 1.2345
340 strobj = "abcde"*3
341 dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"}
342
343 def helper3(self, rsample, recursive=False, simple=False):
344 #we have two instances
345 sample = (rsample, rsample)
346
347 n0 = CollectObjectIDs(set(), sample)
348
349 s3 = marshal.dumps(sample, 3)
350 n3 = CollectObjectIDs(set(), marshal.loads(s3))
351
352 #same number of instances generated
353 self.assertEqual(n3, n0)
354
355 if not recursive:
356 #can compare with version 2
357 s2 = marshal.dumps(sample, 2)
358 n2 = CollectObjectIDs(set(), marshal.loads(s2))
359 #old format generated more instances
360 self.assertGreater(n2, n0)
361
362 #if complex objects are in there, old format is larger
363 if not simple:
364 self.assertGreater(len(s2), len(s3))
365 else:
366 self.assertGreaterEqual(len(s2), len(s3))
367
368 def testInt(self):
369 self.helper(self.intobj)
370 self.helper3(self.intobj, simple=True)
371
372 def testFloat(self):
373 self.helper(self.floatobj)
374 self.helper3(self.floatobj)
375
376 def testStr(self):
377 self.helper(self.strobj)
378 self.helper3(self.strobj)
379
380 def testDict(self):
381 self.helper(self.dictobj)
382 self.helper3(self.dictobj)
383
384 def testModule(self):
385 with open(__file__, "rb") as f:
386 code = f.read()
387 if __file__.endswith(".py"):
388 code = compile(code, __file__, "exec")
389 self.helper(code)
390 self.helper3(code)
391
392 def testRecursion(self):
393 d = dict(self.dictobj)
394 d["self"] = d
395 self.helper3(d, recursive=True)
396 l = [self.dictobj]
397 l.append(l)
398 self.helper3(l, recursive=True)
399
400class CompatibilityTestCase(unittest.TestCase):
401 def _test(self, version):
402 with open(__file__, "rb") as f:
403 code = f.read()
404 if __file__.endswith(".py"):
405 code = compile(code, __file__, "exec")
406 data = marshal.dumps(code, version)
407 marshal.loads(data)
408
409 def test0To3(self):
410 self._test(0)
411
412 def test1To3(self):
413 self._test(1)
414
415 def test2To3(self):
416 self._test(2)
417
418 def test3To3(self):
419 self._test(3)
420
421class InterningTestCase(unittest.TestCase, HelperMixin):
422 strobj = "this is an interned string"
423 strobj = sys.intern(strobj)
424
425 def testIntern(self):
426 s = marshal.loads(marshal.dumps(self.strobj))
427 self.assertEqual(s, self.strobj)
428 self.assertEqual(id(s), id(self.strobj))
429 s2 = sys.intern(s)
430 self.assertEqual(id(s2), id(s))
431
432 def testNoIntern(self):
433 s = marshal.loads(marshal.dumps(self.strobj, 2))
434 self.assertEqual(s, self.strobj)
435 self.assertNotEqual(id(s), id(self.strobj))
436 s2 = sys.intern(s)
437 self.assertNotEqual(id(s2), id(s))
438
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000439
Skip Montanaroc1b41542003-08-02 15:02:33 +0000440def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000441 support.run_unittest(IntTestCase,
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200442 FloatTestCase,
443 StringTestCase,
444 CodeTestCase,
445 ContainerTestCase,
446 ExceptionTestCase,
447 BufferTestCase,
448 BugsTestCase,
449 LargeValuesTestCase,
450 )
Skip Montanaroc1b41542003-08-02 15:02:33 +0000451
452if __name__ == "__main__":
453 test_main()