blob: 16e6d817fbcab7f1199f3ffdf77bc5d37aae986a [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):
26 # Test the full range of Python ints.
Christian Heimesa37d4c62007-12-04 23:02:19 +000027 n = sys.maxsize
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)
Skip Montanaroc1b41542003-08-02 15:02:33 +000031 n = n >> 1
Tim Peters82112372001-08-29 02:28:42 +000032
Skip Montanaroc1b41542003-08-02 15:02:33 +000033 def test_int64(self):
34 # Simulate int marshaling on a 64-bit box. This is most interesting if
35 # we're running the test on a 32-bit box, of course.
36
37 def to_little_endian_string(value, nbytes):
Guido van Rossum254348e2007-11-21 19:29:53 +000038 b = bytearray()
Skip Montanaroc1b41542003-08-02 15:02:33 +000039 for i in range(nbytes):
Guido van Rossume6d39042007-05-09 00:01:30 +000040 b.append(value & 0xff)
Skip Montanaroc1b41542003-08-02 15:02:33 +000041 value >>= 8
Guido van Rossume6d39042007-05-09 00:01:30 +000042 return b
Skip Montanaroc1b41542003-08-02 15:02:33 +000043
Guido van Rossume2a383d2007-01-15 16:59:06 +000044 maxint64 = (1 << 63) - 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000045 minint64 = -maxint64-1
46
47 for base in maxint64, minint64, -maxint64, -(minint64 >> 1):
48 while base:
Guido van Rossume6d39042007-05-09 00:01:30 +000049 s = b'I' + to_little_endian_string(base, 8)
Skip Montanaroc1b41542003-08-02 15:02:33 +000050 got = marshal.loads(s)
51 self.assertEqual(base, got)
52 if base == -1: # a fixed-point for shifting right 1
53 base = 0
54 else:
55 base >>= 1
56
57 def test_bool(self):
58 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000059 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000060
Guido van Rossum47f17d02007-07-10 11:37:44 +000061class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000062 def test_floats(self):
63 # Test a few floats
64 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000065 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000066 while n > small:
67 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000068 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000069 n /= 123.4567
70
71 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000072 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000073 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000074 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000075 # and with version <= 1 (floats marshalled differently then)
76 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000077 got = marshal.loads(s)
78 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000079
Christian Heimesa37d4c62007-12-04 23:02:19 +000080 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000081 while n < small:
82 for expected in (-n, n):
83 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000084 self.helper(f)
85 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000086 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000087
Guido van Rossum47f17d02007-07-10 11:37:44 +000088class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000089 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000090 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
91 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000092
Skip Montanaroc1b41542003-08-02 15:02:33 +000093 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000094 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
95 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000096
Guido van Rossumbae07c92007-10-08 02:46:15 +000097 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +000098 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +000099 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +0000100
Skip Montanaroc1b41542003-08-02 15:02:33 +0000101class ExceptionTestCase(unittest.TestCase):
102 def test_exceptions(self):
103 new = marshal.loads(marshal.dumps(StopIteration))
104 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +0000105
Skip Montanaroc1b41542003-08-02 15:02:33 +0000106class CodeTestCase(unittest.TestCase):
107 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +0000108 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +0000109 new = marshal.loads(marshal.dumps(co))
110 self.assertEqual(co, new)
111
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +0000112 def test_many_codeobjects(self):
113 # Issue2957: bad recursion count on code objects
114 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
115 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
116 marshal.loads(marshal.dumps(codes))
117
Benjamin Peterson43b06862011-05-27 09:08:01 -0500118 def test_different_filenames(self):
119 co1 = compile("x", "f1", "exec")
120 co2 = compile("y", "f2", "exec")
121 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
122 self.assertEqual(co1.co_filename, "f1")
123 self.assertEqual(co2.co_filename, "f2")
124
125 @support.cpython_only
126 def test_same_filename_used(self):
127 s = """def f(): pass\ndef g(): pass"""
128 co = compile(s, "myfile", "exec")
129 co = marshal.loads(marshal.dumps(co))
130 for obj in co.co_consts:
131 if isinstance(obj, types.CodeType):
132 self.assertIs(co.co_filename, obj.co_filename)
133
Guido van Rossum47f17d02007-07-10 11:37:44 +0000134class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000135 d = {'astring': 'foo@bar.baz.spam',
136 'afloat': 7283.43,
137 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000138 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000139 'alist': ['.zyx.41'],
140 'atuple': ('.zyx.41',)*10,
141 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000142 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000143 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000144
Skip Montanaroc1b41542003-08-02 15:02:33 +0000145 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000146 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000147
Skip Montanaroc1b41542003-08-02 15:02:33 +0000148 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000149 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000150
151 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000152 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000153
Raymond Hettingera422c342005-01-11 03:03:27 +0000154 def test_sets(self):
155 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000156 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000157
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100158
159class BufferTestCase(unittest.TestCase, HelperMixin):
160
161 def test_bytearray(self):
162 b = bytearray(b"abc")
163 self.helper(b)
164 new = marshal.loads(marshal.dumps(b))
165 self.assertEqual(type(new), bytes)
166
167 def test_memoryview(self):
168 b = memoryview(b"abc")
169 self.helper(b)
170 new = marshal.loads(marshal.dumps(b))
171 self.assertEqual(type(new), bytes)
172
173 def test_array(self):
174 a = array.array('B', b"abc")
175 new = marshal.loads(marshal.dumps(a))
176 self.assertEqual(new, b"abc")
177
178
Skip Montanaroc1b41542003-08-02 15:02:33 +0000179class BugsTestCase(unittest.TestCase):
180 def test_bug_5888452(self):
181 # Simple-minded check for SF 588452: Debug build crashes
182 marshal.dumps([128] * 1000)
183
Armin Rigo01ab2792004-03-26 15:09:27 +0000184 def test_patch_873224(self):
185 self.assertRaises(Exception, marshal.loads, '0')
186 self.assertRaises(Exception, marshal.loads, 'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000187 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000188
Armin Rigo2ccea172004-12-20 12:25:57 +0000189 def test_version_argument(self):
190 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000191 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
192 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000193
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000194 def test_fuzz(self):
195 # simple test that it's at least not *totally* trivial to
196 # crash from bad marshal data
197 for c in [chr(i) for i in range(256)]:
198 try:
199 marshal.loads(c)
200 except Exception:
201 pass
202
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700203 def test_loads_2x_code(self):
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100204 s = b'c' + (b'X' * 4*4) + b'{' * 2**20
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000205 self.assertRaises(ValueError, marshal.loads, s)
206
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700207 def test_loads_recursion(self):
208 s = b'c' + (b'X' * 4*5) + b'{' * 2**20
209 self.assertRaises(ValueError, marshal.loads, s)
210
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000211 def test_recursion_limit(self):
212 # Create a deeply nested structure.
213 head = last = []
214 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000215 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
216 MAX_MARSHAL_STACK_DEPTH = 1500
217 else:
218 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000219 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
220 last.append([0])
221 last = last[-1]
222
223 # Verify we don't blow out the stack with dumps/load.
224 data = marshal.dumps(head)
225 new_head = marshal.loads(data)
226 # Don't use == to compare objects, it can exceed the recursion limit.
227 self.assertEqual(len(new_head), len(head))
228 self.assertEqual(len(new_head[0]), len(head[0]))
229 self.assertEqual(len(new_head[-1]), len(head[-1]))
230
231 last.append([0])
232 self.assertRaises(ValueError, marshal.dumps, head)
233
Guido van Rossum58da9312007-11-10 23:39:45 +0000234 def test_exact_type_match(self):
235 # Former bug:
236 # >>> class Int(int): pass
237 # >>> type(loads(dumps(Int())))
238 # <type 'int'>
239 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200240 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000241 # by marshal's routines for objects supporting the buffer API.
242 subtyp = type('subtyp', (typ,), {})
243 self.assertRaises(ValueError, marshal.dumps, subtyp())
244
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000245 # Issue #1792 introduced a change in how marshal increases the size of its
246 # internal buffer; this test ensures that the new code is exercised.
247 def test_large_marshal(self):
248 size = int(1e6)
249 testString = 'abc' * size
250 marshal.dumps(testString)
251
Mark Dickinson2683ab02009-09-29 19:21:35 +0000252 def test_invalid_longs(self):
253 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
254 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
255 self.assertRaises(ValueError, marshal.loads, invalid_string)
256
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100257 def test_multiple_dumps_and_loads(self):
258 # Issue 12291: marshal.load() should be callable multiple times
259 # with interleaved data written by non-marshal code
260 # Adapted from a patch by Engelbert Gruber.
261 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
262 for interleaved in (b'', b'0123'):
263 ilen = len(interleaved)
264 positions = []
265 try:
266 with open(support.TESTFN, 'wb') as f:
267 for d in data:
268 marshal.dump(d, f)
269 if ilen:
270 f.write(interleaved)
271 positions.append(f.tell())
272 with open(support.TESTFN, 'rb') as f:
273 for i, d in enumerate(data):
274 self.assertEqual(d, marshal.load(f))
275 if ilen:
276 f.read(ilen)
277 self.assertEqual(positions[i], f.tell())
278 finally:
279 support.unlink(support.TESTFN)
280
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100281 def test_loads_reject_unicode_strings(self):
282 # Issue #14177: marshal.loads() should not accept unicode strings
283 unicode_string = 'T'
284 self.assertRaises(TypeError, marshal.loads, unicode_string)
285
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200286LARGE_SIZE = 2**31
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200287pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
288
289class NullWriter:
290 def write(self, s):
291 pass
292
293@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
294class LargeValuesTestCase(unittest.TestCase):
295 def check_unmarshallable(self, data):
296 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
297
298 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
299 def test_bytes(self, size):
300 self.check_unmarshallable(b'x' * size)
301
Serhiy Storchaka40f42d92013-02-13 12:32:24 +0200302 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200303 def test_str(self, size):
304 self.check_unmarshallable('x' * size)
305
306 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
307 def test_tuple(self, size):
308 self.check_unmarshallable((None,) * size)
309
310 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
311 def test_list(self, size):
312 self.check_unmarshallable([None] * size)
313
314 @support.bigmemtest(size=LARGE_SIZE,
315 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
316 dry_run=False)
317 def test_set(self, size):
318 self.check_unmarshallable(set(range(size)))
319
320 @support.bigmemtest(size=LARGE_SIZE,
321 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
322 dry_run=False)
323 def test_frozenset(self, size):
324 self.check_unmarshallable(frozenset(range(size)))
325
326 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
327 def test_bytearray(self, size):
328 self.check_unmarshallable(bytearray(size))
329
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700330def CollectObjectIDs(ids, obj):
331 """Collect object ids seen in a structure"""
332 if id(obj) in ids:
333 return
334 ids.add(id(obj))
335 if isinstance(obj, (list, tuple, set, frozenset)):
336 for e in obj:
337 CollectObjectIDs(ids, e)
338 elif isinstance(obj, dict):
339 for k, v in obj.items():
340 CollectObjectIDs(ids, k)
341 CollectObjectIDs(ids, v)
342 return len(ids)
343
344class InstancingTestCase(unittest.TestCase, HelperMixin):
345 intobj = 123321
346 floatobj = 1.2345
347 strobj = "abcde"*3
348 dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"}
349
350 def helper3(self, rsample, recursive=False, simple=False):
351 #we have two instances
352 sample = (rsample, rsample)
353
354 n0 = CollectObjectIDs(set(), sample)
355
356 s3 = marshal.dumps(sample, 3)
357 n3 = CollectObjectIDs(set(), marshal.loads(s3))
358
359 #same number of instances generated
360 self.assertEqual(n3, n0)
361
362 if not recursive:
363 #can compare with version 2
364 s2 = marshal.dumps(sample, 2)
365 n2 = CollectObjectIDs(set(), marshal.loads(s2))
366 #old format generated more instances
367 self.assertGreater(n2, n0)
368
369 #if complex objects are in there, old format is larger
370 if not simple:
371 self.assertGreater(len(s2), len(s3))
372 else:
373 self.assertGreaterEqual(len(s2), len(s3))
374
375 def testInt(self):
376 self.helper(self.intobj)
377 self.helper3(self.intobj, simple=True)
378
379 def testFloat(self):
380 self.helper(self.floatobj)
381 self.helper3(self.floatobj)
382
383 def testStr(self):
384 self.helper(self.strobj)
385 self.helper3(self.strobj)
386
387 def testDict(self):
388 self.helper(self.dictobj)
389 self.helper3(self.dictobj)
390
391 def testModule(self):
392 with open(__file__, "rb") as f:
393 code = f.read()
394 if __file__.endswith(".py"):
395 code = compile(code, __file__, "exec")
396 self.helper(code)
397 self.helper3(code)
398
399 def testRecursion(self):
400 d = dict(self.dictobj)
401 d["self"] = d
402 self.helper3(d, recursive=True)
403 l = [self.dictobj]
404 l.append(l)
405 self.helper3(l, recursive=True)
406
407class CompatibilityTestCase(unittest.TestCase):
408 def _test(self, version):
409 with open(__file__, "rb") as f:
410 code = f.read()
411 if __file__.endswith(".py"):
412 code = compile(code, __file__, "exec")
413 data = marshal.dumps(code, version)
414 marshal.loads(data)
415
416 def test0To3(self):
417 self._test(0)
418
419 def test1To3(self):
420 self._test(1)
421
422 def test2To3(self):
423 self._test(2)
424
425 def test3To3(self):
426 self._test(3)
427
428class InterningTestCase(unittest.TestCase, HelperMixin):
429 strobj = "this is an interned string"
430 strobj = sys.intern(strobj)
431
432 def testIntern(self):
433 s = marshal.loads(marshal.dumps(self.strobj))
434 self.assertEqual(s, self.strobj)
435 self.assertEqual(id(s), id(self.strobj))
436 s2 = sys.intern(s)
437 self.assertEqual(id(s2), id(s))
438
439 def testNoIntern(self):
440 s = marshal.loads(marshal.dumps(self.strobj, 2))
441 self.assertEqual(s, self.strobj)
442 self.assertNotEqual(id(s), id(self.strobj))
443 s2 = sys.intern(s)
444 self.assertNotEqual(id(s2), id(s))
445
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000446
Skip Montanaroc1b41542003-08-02 15:02:33 +0000447def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000448 support.run_unittest(IntTestCase,
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200449 FloatTestCase,
450 StringTestCase,
451 CodeTestCase,
452 ContainerTestCase,
453 ExceptionTestCase,
454 BufferTestCase,
455 BugsTestCase,
456 LargeValuesTestCase,
457 )
Skip Montanaroc1b41542003-08-02 15:02:33 +0000458
459if __name__ == "__main__":
460 test_main()