blob: 292746bd58cd51fc35a4b85bff2d308f1868b075 [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
Tim Peters82112372001-08-29 02:28:42 +00005import marshal
6import sys
Skip Montanaroc1b41542003-08-02 15:02:33 +00007import unittest
8import os
Benjamin Peterson43b06862011-05-27 09:08:01 -05009import types
Tim Peters82112372001-08-29 02:28:42 +000010
Guido van Rossum47f17d02007-07-10 11:37:44 +000011class HelperMixin:
12 def helper(self, sample, *extra):
13 new = marshal.loads(marshal.dumps(sample, *extra))
14 self.assertEqual(sample, new)
15 try:
Brian Curtin2c3563f2010-10-13 02:40:26 +000016 with open(support.TESTFN, "wb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000017 marshal.dump(sample, f, *extra)
Brian Curtin2c3563f2010-10-13 02:40:26 +000018 with open(support.TESTFN, "rb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000019 new = marshal.load(f)
Guido van Rossum47f17d02007-07-10 11:37:44 +000020 self.assertEqual(sample, new)
21 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +000022 support.unlink(support.TESTFN)
Guido van Rossum47f17d02007-07-10 11:37:44 +000023
24class IntTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000025 def test_ints(self):
Antoine Pitroue9bbe8b2013-04-13 22:41:09 +020026 # Test a range of Python ints larger than the machine word size.
27 n = sys.maxsize ** 2
Skip Montanaroc1b41542003-08-02 15:02:33 +000028 while n:
29 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000030 self.helper(expected)
Antoine Pitrouc1ab0bd2013-04-13 22:46:33 +020031 n = n >> 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000032
33 def test_bool(self):
34 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000035 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000036
Guido van Rossum47f17d02007-07-10 11:37:44 +000037class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000038 def test_floats(self):
39 # Test a few floats
40 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000041 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000042 while n > small:
43 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000044 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000045 n /= 123.4567
46
47 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000048 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000049 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000050 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000051 # and with version <= 1 (floats marshalled differently then)
52 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000053 got = marshal.loads(s)
54 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000055
Christian Heimesa37d4c62007-12-04 23:02:19 +000056 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000057 while n < small:
58 for expected in (-n, n):
59 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000060 self.helper(f)
61 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000062 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000063
Guido van Rossum47f17d02007-07-10 11:37:44 +000064class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000065 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000066 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
67 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000068
Skip Montanaroc1b41542003-08-02 15:02:33 +000069 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000070 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
71 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000072
Guido van Rossumbae07c92007-10-08 02:46:15 +000073 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +000074 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +000075 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +000076
Skip Montanaroc1b41542003-08-02 15:02:33 +000077class ExceptionTestCase(unittest.TestCase):
78 def test_exceptions(self):
79 new = marshal.loads(marshal.dumps(StopIteration))
80 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +000081
Skip Montanaroc1b41542003-08-02 15:02:33 +000082class CodeTestCase(unittest.TestCase):
83 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +000084 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +000085 new = marshal.loads(marshal.dumps(co))
86 self.assertEqual(co, new)
87
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +000088 def test_many_codeobjects(self):
89 # Issue2957: bad recursion count on code objects
90 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
91 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
92 marshal.loads(marshal.dumps(codes))
93
Benjamin Peterson43b06862011-05-27 09:08:01 -050094 def test_different_filenames(self):
95 co1 = compile("x", "f1", "exec")
96 co2 = compile("y", "f2", "exec")
97 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
98 self.assertEqual(co1.co_filename, "f1")
99 self.assertEqual(co2.co_filename, "f2")
100
101 @support.cpython_only
102 def test_same_filename_used(self):
103 s = """def f(): pass\ndef g(): pass"""
104 co = compile(s, "myfile", "exec")
105 co = marshal.loads(marshal.dumps(co))
106 for obj in co.co_consts:
107 if isinstance(obj, types.CodeType):
108 self.assertIs(co.co_filename, obj.co_filename)
109
Guido van Rossum47f17d02007-07-10 11:37:44 +0000110class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000111 d = {'astring': 'foo@bar.baz.spam',
112 'afloat': 7283.43,
113 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000114 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000115 'alist': ['.zyx.41'],
116 'atuple': ('.zyx.41',)*10,
117 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000118 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000119 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000120
Skip Montanaroc1b41542003-08-02 15:02:33 +0000121 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000122 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000123
Skip Montanaroc1b41542003-08-02 15:02:33 +0000124 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000125 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000126
127 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000128 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000129
Raymond Hettingera422c342005-01-11 03:03:27 +0000130 def test_sets(self):
131 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000132 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000133
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100134
135class BufferTestCase(unittest.TestCase, HelperMixin):
136
137 def test_bytearray(self):
138 b = bytearray(b"abc")
139 self.helper(b)
140 new = marshal.loads(marshal.dumps(b))
141 self.assertEqual(type(new), bytes)
142
143 def test_memoryview(self):
144 b = memoryview(b"abc")
145 self.helper(b)
146 new = marshal.loads(marshal.dumps(b))
147 self.assertEqual(type(new), bytes)
148
149 def test_array(self):
150 a = array.array('B', b"abc")
151 new = marshal.loads(marshal.dumps(a))
152 self.assertEqual(new, b"abc")
153
154
Skip Montanaroc1b41542003-08-02 15:02:33 +0000155class BugsTestCase(unittest.TestCase):
156 def test_bug_5888452(self):
157 # Simple-minded check for SF 588452: Debug build crashes
158 marshal.dumps([128] * 1000)
159
Armin Rigo01ab2792004-03-26 15:09:27 +0000160 def test_patch_873224(self):
161 self.assertRaises(Exception, marshal.loads, '0')
162 self.assertRaises(Exception, marshal.loads, 'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000163 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000164
Armin Rigo2ccea172004-12-20 12:25:57 +0000165 def test_version_argument(self):
166 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000167 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
168 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000169
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000170 def test_fuzz(self):
171 # simple test that it's at least not *totally* trivial to
172 # crash from bad marshal data
173 for c in [chr(i) for i in range(256)]:
174 try:
175 marshal.loads(c)
176 except Exception:
177 pass
178
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700179 def test_loads_2x_code(self):
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100180 s = b'c' + (b'X' * 4*4) + b'{' * 2**20
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000181 self.assertRaises(ValueError, marshal.loads, s)
182
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700183 def test_loads_recursion(self):
184 s = b'c' + (b'X' * 4*5) + b'{' * 2**20
185 self.assertRaises(ValueError, marshal.loads, s)
186
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000187 def test_recursion_limit(self):
188 # Create a deeply nested structure.
189 head = last = []
190 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000191 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
192 MAX_MARSHAL_STACK_DEPTH = 1500
193 else:
194 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000195 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
196 last.append([0])
197 last = last[-1]
198
199 # Verify we don't blow out the stack with dumps/load.
200 data = marshal.dumps(head)
201 new_head = marshal.loads(data)
202 # Don't use == to compare objects, it can exceed the recursion limit.
203 self.assertEqual(len(new_head), len(head))
204 self.assertEqual(len(new_head[0]), len(head[0]))
205 self.assertEqual(len(new_head[-1]), len(head[-1]))
206
207 last.append([0])
208 self.assertRaises(ValueError, marshal.dumps, head)
209
Guido van Rossum58da9312007-11-10 23:39:45 +0000210 def test_exact_type_match(self):
211 # Former bug:
212 # >>> class Int(int): pass
213 # >>> type(loads(dumps(Int())))
214 # <type 'int'>
215 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200216 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000217 # by marshal's routines for objects supporting the buffer API.
218 subtyp = type('subtyp', (typ,), {})
219 self.assertRaises(ValueError, marshal.dumps, subtyp())
220
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000221 # Issue #1792 introduced a change in how marshal increases the size of its
222 # internal buffer; this test ensures that the new code is exercised.
223 def test_large_marshal(self):
224 size = int(1e6)
225 testString = 'abc' * size
226 marshal.dumps(testString)
227
Mark Dickinson2683ab02009-09-29 19:21:35 +0000228 def test_invalid_longs(self):
229 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
230 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
231 self.assertRaises(ValueError, marshal.loads, invalid_string)
232
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100233 def test_multiple_dumps_and_loads(self):
234 # Issue 12291: marshal.load() should be callable multiple times
235 # with interleaved data written by non-marshal code
236 # Adapted from a patch by Engelbert Gruber.
237 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
238 for interleaved in (b'', b'0123'):
239 ilen = len(interleaved)
240 positions = []
241 try:
242 with open(support.TESTFN, 'wb') as f:
243 for d in data:
244 marshal.dump(d, f)
245 if ilen:
246 f.write(interleaved)
247 positions.append(f.tell())
248 with open(support.TESTFN, 'rb') as f:
249 for i, d in enumerate(data):
250 self.assertEqual(d, marshal.load(f))
251 if ilen:
252 f.read(ilen)
253 self.assertEqual(positions[i], f.tell())
254 finally:
255 support.unlink(support.TESTFN)
256
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100257 def test_loads_reject_unicode_strings(self):
258 # Issue #14177: marshal.loads() should not accept unicode strings
259 unicode_string = 'T'
260 self.assertRaises(TypeError, marshal.loads, unicode_string)
261
Kristján Valur Jónsson61683622013-03-20 14:26:33 -0700262 def _test_eof(self):
263 data = marshal.dumps(("hello", "dolly", None))
264 for i in range(len(data)):
265 self.assertRaises(EOFError, marshal.loads, data[0: i])
266
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200267LARGE_SIZE = 2**31
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200268pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
269
270class NullWriter:
271 def write(self, s):
272 pass
273
274@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
275class LargeValuesTestCase(unittest.TestCase):
276 def check_unmarshallable(self, data):
277 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
278
279 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
280 def test_bytes(self, size):
281 self.check_unmarshallable(b'x' * size)
282
Serhiy Storchaka40f42d92013-02-13 12:32:24 +0200283 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200284 def test_str(self, size):
285 self.check_unmarshallable('x' * size)
286
287 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
288 def test_tuple(self, size):
289 self.check_unmarshallable((None,) * size)
290
291 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
292 def test_list(self, size):
293 self.check_unmarshallable([None] * size)
294
295 @support.bigmemtest(size=LARGE_SIZE,
296 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
297 dry_run=False)
298 def test_set(self, size):
299 self.check_unmarshallable(set(range(size)))
300
301 @support.bigmemtest(size=LARGE_SIZE,
302 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
303 dry_run=False)
304 def test_frozenset(self, size):
305 self.check_unmarshallable(frozenset(range(size)))
306
307 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
308 def test_bytearray(self, size):
309 self.check_unmarshallable(bytearray(size))
310
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700311def CollectObjectIDs(ids, obj):
312 """Collect object ids seen in a structure"""
313 if id(obj) in ids:
314 return
315 ids.add(id(obj))
316 if isinstance(obj, (list, tuple, set, frozenset)):
317 for e in obj:
318 CollectObjectIDs(ids, e)
319 elif isinstance(obj, dict):
320 for k, v in obj.items():
321 CollectObjectIDs(ids, k)
322 CollectObjectIDs(ids, v)
323 return len(ids)
324
325class InstancingTestCase(unittest.TestCase, HelperMixin):
326 intobj = 123321
327 floatobj = 1.2345
328 strobj = "abcde"*3
329 dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"}
330
331 def helper3(self, rsample, recursive=False, simple=False):
332 #we have two instances
333 sample = (rsample, rsample)
334
335 n0 = CollectObjectIDs(set(), sample)
336
337 s3 = marshal.dumps(sample, 3)
338 n3 = CollectObjectIDs(set(), marshal.loads(s3))
339
340 #same number of instances generated
341 self.assertEqual(n3, n0)
342
343 if not recursive:
344 #can compare with version 2
345 s2 = marshal.dumps(sample, 2)
346 n2 = CollectObjectIDs(set(), marshal.loads(s2))
347 #old format generated more instances
348 self.assertGreater(n2, n0)
349
350 #if complex objects are in there, old format is larger
351 if not simple:
352 self.assertGreater(len(s2), len(s3))
353 else:
354 self.assertGreaterEqual(len(s2), len(s3))
355
356 def testInt(self):
357 self.helper(self.intobj)
358 self.helper3(self.intobj, simple=True)
359
360 def testFloat(self):
361 self.helper(self.floatobj)
362 self.helper3(self.floatobj)
363
364 def testStr(self):
365 self.helper(self.strobj)
366 self.helper3(self.strobj)
367
368 def testDict(self):
369 self.helper(self.dictobj)
370 self.helper3(self.dictobj)
371
372 def testModule(self):
373 with open(__file__, "rb") as f:
374 code = f.read()
375 if __file__.endswith(".py"):
376 code = compile(code, __file__, "exec")
377 self.helper(code)
378 self.helper3(code)
379
380 def testRecursion(self):
381 d = dict(self.dictobj)
382 d["self"] = d
383 self.helper3(d, recursive=True)
384 l = [self.dictobj]
385 l.append(l)
386 self.helper3(l, recursive=True)
387
388class CompatibilityTestCase(unittest.TestCase):
389 def _test(self, version):
390 with open(__file__, "rb") as f:
391 code = f.read()
392 if __file__.endswith(".py"):
393 code = compile(code, __file__, "exec")
394 data = marshal.dumps(code, version)
395 marshal.loads(data)
396
397 def test0To3(self):
398 self._test(0)
399
400 def test1To3(self):
401 self._test(1)
402
403 def test2To3(self):
404 self._test(2)
405
406 def test3To3(self):
407 self._test(3)
408
409class InterningTestCase(unittest.TestCase, HelperMixin):
410 strobj = "this is an interned string"
411 strobj = sys.intern(strobj)
412
413 def testIntern(self):
414 s = marshal.loads(marshal.dumps(self.strobj))
415 self.assertEqual(s, self.strobj)
416 self.assertEqual(id(s), id(self.strobj))
417 s2 = sys.intern(s)
418 self.assertEqual(id(s2), id(s))
419
420 def testNoIntern(self):
421 s = marshal.loads(marshal.dumps(self.strobj, 2))
422 self.assertEqual(s, self.strobj)
423 self.assertNotEqual(id(s), id(self.strobj))
424 s2 = sys.intern(s)
425 self.assertNotEqual(id(s2), id(s))
426
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000427
Skip Montanaroc1b41542003-08-02 15:02:33 +0000428def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000429 support.run_unittest(IntTestCase,
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200430 FloatTestCase,
431 StringTestCase,
432 CodeTestCase,
433 ContainerTestCase,
434 ExceptionTestCase,
435 BufferTestCase,
436 BugsTestCase,
437 LargeValuesTestCase,
438 )
Skip Montanaroc1b41542003-08-02 15:02:33 +0000439
440if __name__ == "__main__":
441 test_main()