blob: 068c4713e1824e90a930e69324858e08b1caa9f5 [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Antoine Pitrou679e9d32012-03-02 18:12:43 +01002import array
Serhiy Storchaka3641a742013-07-11 22:20:47 +03003import io
Tim Peters82112372001-08-29 02:28:42 +00004import marshal
5import sys
Skip Montanaroc1b41542003-08-02 15:02:33 +00006import unittest
7import os
Benjamin Peterson43b06862011-05-27 09:08:01 -05008import types
Tim Peters82112372001-08-29 02:28:42 +00009
Guido van Rossum47f17d02007-07-10 11:37:44 +000010class HelperMixin:
11 def helper(self, sample, *extra):
12 new = marshal.loads(marshal.dumps(sample, *extra))
13 self.assertEqual(sample, new)
14 try:
Brian Curtin2c3563f2010-10-13 02:40:26 +000015 with open(support.TESTFN, "wb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000016 marshal.dump(sample, f, *extra)
Brian Curtin2c3563f2010-10-13 02:40:26 +000017 with open(support.TESTFN, "rb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000018 new = marshal.load(f)
Guido van Rossum47f17d02007-07-10 11:37:44 +000019 self.assertEqual(sample, new)
20 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +000021 support.unlink(support.TESTFN)
Guido van Rossum47f17d02007-07-10 11:37:44 +000022
23class IntTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000024 def test_ints(self):
Antoine Pitroue9bbe8b2013-04-13 22:41:09 +020025 # Test a range of Python ints larger than the machine word size.
26 n = sys.maxsize ** 2
Skip Montanaroc1b41542003-08-02 15:02:33 +000027 while n:
28 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000029 self.helper(expected)
Antoine Pitrouc1ab0bd2013-04-13 22:46:33 +020030 n = n >> 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000031
32 def test_bool(self):
33 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000034 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000035
Guido van Rossum47f17d02007-07-10 11:37:44 +000036class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000037 def test_floats(self):
38 # Test a few floats
39 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000040 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000041 while n > small:
42 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000043 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000044 n /= 123.4567
45
46 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000047 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000048 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000049 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000050 # and with version <= 1 (floats marshalled differently then)
51 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000052 got = marshal.loads(s)
53 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000054
Christian Heimesa37d4c62007-12-04 23:02:19 +000055 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000056 while n < small:
57 for expected in (-n, n):
58 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000059 self.helper(f)
60 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000061 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000062
Guido van Rossum47f17d02007-07-10 11:37:44 +000063class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000064 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000065 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
66 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000067
Skip Montanaroc1b41542003-08-02 15:02:33 +000068 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000069 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
70 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000071
Guido van Rossumbae07c92007-10-08 02:46:15 +000072 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +000073 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +000074 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +000075
Skip Montanaroc1b41542003-08-02 15:02:33 +000076class ExceptionTestCase(unittest.TestCase):
77 def test_exceptions(self):
78 new = marshal.loads(marshal.dumps(StopIteration))
79 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +000080
Skip Montanaroc1b41542003-08-02 15:02:33 +000081class CodeTestCase(unittest.TestCase):
82 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +000083 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +000084 new = marshal.loads(marshal.dumps(co))
85 self.assertEqual(co, new)
86
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +000087 def test_many_codeobjects(self):
88 # Issue2957: bad recursion count on code objects
89 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
90 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
91 marshal.loads(marshal.dumps(codes))
92
Benjamin Peterson43b06862011-05-27 09:08:01 -050093 def test_different_filenames(self):
94 co1 = compile("x", "f1", "exec")
95 co2 = compile("y", "f2", "exec")
96 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
97 self.assertEqual(co1.co_filename, "f1")
98 self.assertEqual(co2.co_filename, "f2")
99
100 @support.cpython_only
101 def test_same_filename_used(self):
102 s = """def f(): pass\ndef g(): pass"""
103 co = compile(s, "myfile", "exec")
104 co = marshal.loads(marshal.dumps(co))
105 for obj in co.co_consts:
106 if isinstance(obj, types.CodeType):
107 self.assertIs(co.co_filename, obj.co_filename)
108
Guido van Rossum47f17d02007-07-10 11:37:44 +0000109class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000110 d = {'astring': 'foo@bar.baz.spam',
111 'afloat': 7283.43,
112 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000113 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000114 'alist': ['.zyx.41'],
115 'atuple': ('.zyx.41',)*10,
116 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000117 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000118 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000119
Skip Montanaroc1b41542003-08-02 15:02:33 +0000120 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000121 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000122
Skip Montanaroc1b41542003-08-02 15:02:33 +0000123 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000124 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000125
126 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000127 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000128
Raymond Hettingera422c342005-01-11 03:03:27 +0000129 def test_sets(self):
130 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000131 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000132
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100133
134class BufferTestCase(unittest.TestCase, HelperMixin):
135
136 def test_bytearray(self):
137 b = bytearray(b"abc")
138 self.helper(b)
139 new = marshal.loads(marshal.dumps(b))
140 self.assertEqual(type(new), bytes)
141
142 def test_memoryview(self):
143 b = memoryview(b"abc")
144 self.helper(b)
145 new = marshal.loads(marshal.dumps(b))
146 self.assertEqual(type(new), bytes)
147
148 def test_array(self):
149 a = array.array('B', b"abc")
150 new = marshal.loads(marshal.dumps(a))
151 self.assertEqual(new, b"abc")
152
153
Skip Montanaroc1b41542003-08-02 15:02:33 +0000154class BugsTestCase(unittest.TestCase):
155 def test_bug_5888452(self):
156 # Simple-minded check for SF 588452: Debug build crashes
157 marshal.dumps([128] * 1000)
158
Armin Rigo01ab2792004-03-26 15:09:27 +0000159 def test_patch_873224(self):
160 self.assertRaises(Exception, marshal.loads, '0')
161 self.assertRaises(Exception, marshal.loads, 'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000162 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000163
Armin Rigo2ccea172004-12-20 12:25:57 +0000164 def test_version_argument(self):
165 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000166 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
167 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000168
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000169 def test_fuzz(self):
170 # simple test that it's at least not *totally* trivial to
171 # crash from bad marshal data
172 for c in [chr(i) for i in range(256)]:
173 try:
174 marshal.loads(c)
175 except Exception:
176 pass
177
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700178 def test_loads_2x_code(self):
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100179 s = b'c' + (b'X' * 4*4) + b'{' * 2**20
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000180 self.assertRaises(ValueError, marshal.loads, s)
181
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700182 def test_loads_recursion(self):
183 s = b'c' + (b'X' * 4*5) + b'{' * 2**20
184 self.assertRaises(ValueError, marshal.loads, s)
185
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000186 def test_recursion_limit(self):
187 # Create a deeply nested structure.
188 head = last = []
189 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000190 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
191 MAX_MARSHAL_STACK_DEPTH = 1500
192 else:
193 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000194 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
195 last.append([0])
196 last = last[-1]
197
198 # Verify we don't blow out the stack with dumps/load.
199 data = marshal.dumps(head)
200 new_head = marshal.loads(data)
201 # Don't use == to compare objects, it can exceed the recursion limit.
202 self.assertEqual(len(new_head), len(head))
203 self.assertEqual(len(new_head[0]), len(head[0]))
204 self.assertEqual(len(new_head[-1]), len(head[-1]))
205
206 last.append([0])
207 self.assertRaises(ValueError, marshal.dumps, head)
208
Guido van Rossum58da9312007-11-10 23:39:45 +0000209 def test_exact_type_match(self):
210 # Former bug:
211 # >>> class Int(int): pass
212 # >>> type(loads(dumps(Int())))
213 # <type 'int'>
214 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200215 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000216 # by marshal's routines for objects supporting the buffer API.
217 subtyp = type('subtyp', (typ,), {})
218 self.assertRaises(ValueError, marshal.dumps, subtyp())
219
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000220 # Issue #1792 introduced a change in how marshal increases the size of its
221 # internal buffer; this test ensures that the new code is exercised.
222 def test_large_marshal(self):
223 size = int(1e6)
224 testString = 'abc' * size
225 marshal.dumps(testString)
226
Mark Dickinson2683ab02009-09-29 19:21:35 +0000227 def test_invalid_longs(self):
228 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
229 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
230 self.assertRaises(ValueError, marshal.loads, invalid_string)
231
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100232 def test_multiple_dumps_and_loads(self):
233 # Issue 12291: marshal.load() should be callable multiple times
234 # with interleaved data written by non-marshal code
235 # Adapted from a patch by Engelbert Gruber.
236 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
237 for interleaved in (b'', b'0123'):
238 ilen = len(interleaved)
239 positions = []
240 try:
241 with open(support.TESTFN, 'wb') as f:
242 for d in data:
243 marshal.dump(d, f)
244 if ilen:
245 f.write(interleaved)
246 positions.append(f.tell())
247 with open(support.TESTFN, 'rb') as f:
248 for i, d in enumerate(data):
249 self.assertEqual(d, marshal.load(f))
250 if ilen:
251 f.read(ilen)
252 self.assertEqual(positions[i], f.tell())
253 finally:
254 support.unlink(support.TESTFN)
255
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100256 def test_loads_reject_unicode_strings(self):
257 # Issue #14177: marshal.loads() should not accept unicode strings
258 unicode_string = 'T'
259 self.assertRaises(TypeError, marshal.loads, unicode_string)
260
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300261 def test_bad_reader(self):
262 class BadReader(io.BytesIO):
Antoine Pitrou1164dfc2013-10-12 22:25:39 +0200263 def readinto(self, buf):
264 n = super().readinto(buf)
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300265 if n is not None and n > 4:
Antoine Pitrou1164dfc2013-10-12 22:25:39 +0200266 n += 10**6
267 return n
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300268 for value in (1.0, 1j, b'0123456789', '0123456789'):
269 self.assertRaises(ValueError, marshal.load,
270 BadReader(marshal.dumps(value)))
271
Kristján Valur Jónsson61683622013-03-20 14:26:33 -0700272 def _test_eof(self):
273 data = marshal.dumps(("hello", "dolly", None))
274 for i in range(len(data)):
275 self.assertRaises(EOFError, marshal.loads, data[0: i])
276
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200277LARGE_SIZE = 2**31
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200278pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
279
280class NullWriter:
281 def write(self, s):
282 pass
283
284@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
285class LargeValuesTestCase(unittest.TestCase):
286 def check_unmarshallable(self, data):
287 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
288
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200289 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200290 def test_bytes(self, size):
291 self.check_unmarshallable(b'x' * size)
292
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200293 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200294 def test_str(self, size):
295 self.check_unmarshallable('x' * size)
296
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200297 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200298 def test_tuple(self, size):
299 self.check_unmarshallable((None,) * size)
300
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200301 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200302 def test_list(self, size):
303 self.check_unmarshallable([None] * size)
304
305 @support.bigmemtest(size=LARGE_SIZE,
306 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
307 dry_run=False)
308 def test_set(self, size):
309 self.check_unmarshallable(set(range(size)))
310
311 @support.bigmemtest(size=LARGE_SIZE,
312 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
313 dry_run=False)
314 def test_frozenset(self, size):
315 self.check_unmarshallable(frozenset(range(size)))
316
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200317 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200318 def test_bytearray(self, size):
319 self.check_unmarshallable(bytearray(size))
320
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700321def CollectObjectIDs(ids, obj):
322 """Collect object ids seen in a structure"""
323 if id(obj) in ids:
324 return
325 ids.add(id(obj))
326 if isinstance(obj, (list, tuple, set, frozenset)):
327 for e in obj:
328 CollectObjectIDs(ids, e)
329 elif isinstance(obj, dict):
330 for k, v in obj.items():
331 CollectObjectIDs(ids, k)
332 CollectObjectIDs(ids, v)
333 return len(ids)
334
335class InstancingTestCase(unittest.TestCase, HelperMixin):
336 intobj = 123321
337 floatobj = 1.2345
338 strobj = "abcde"*3
339 dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"}
340
341 def helper3(self, rsample, recursive=False, simple=False):
342 #we have two instances
343 sample = (rsample, rsample)
344
345 n0 = CollectObjectIDs(set(), sample)
346
347 s3 = marshal.dumps(sample, 3)
348 n3 = CollectObjectIDs(set(), marshal.loads(s3))
349
350 #same number of instances generated
351 self.assertEqual(n3, n0)
352
353 if not recursive:
354 #can compare with version 2
355 s2 = marshal.dumps(sample, 2)
356 n2 = CollectObjectIDs(set(), marshal.loads(s2))
357 #old format generated more instances
358 self.assertGreater(n2, n0)
359
360 #if complex objects are in there, old format is larger
361 if not simple:
362 self.assertGreater(len(s2), len(s3))
363 else:
364 self.assertGreaterEqual(len(s2), len(s3))
365
366 def testInt(self):
367 self.helper(self.intobj)
368 self.helper3(self.intobj, simple=True)
369
370 def testFloat(self):
371 self.helper(self.floatobj)
372 self.helper3(self.floatobj)
373
374 def testStr(self):
375 self.helper(self.strobj)
376 self.helper3(self.strobj)
377
378 def testDict(self):
379 self.helper(self.dictobj)
380 self.helper3(self.dictobj)
381
382 def testModule(self):
383 with open(__file__, "rb") as f:
384 code = f.read()
385 if __file__.endswith(".py"):
386 code = compile(code, __file__, "exec")
387 self.helper(code)
388 self.helper3(code)
389
390 def testRecursion(self):
391 d = dict(self.dictobj)
392 d["self"] = d
393 self.helper3(d, recursive=True)
394 l = [self.dictobj]
395 l.append(l)
396 self.helper3(l, recursive=True)
397
398class CompatibilityTestCase(unittest.TestCase):
399 def _test(self, version):
400 with open(__file__, "rb") as f:
401 code = f.read()
402 if __file__.endswith(".py"):
403 code = compile(code, __file__, "exec")
404 data = marshal.dumps(code, version)
405 marshal.loads(data)
406
407 def test0To3(self):
408 self._test(0)
409
410 def test1To3(self):
411 self._test(1)
412
413 def test2To3(self):
414 self._test(2)
415
416 def test3To3(self):
417 self._test(3)
418
419class InterningTestCase(unittest.TestCase, HelperMixin):
420 strobj = "this is an interned string"
421 strobj = sys.intern(strobj)
422
423 def testIntern(self):
424 s = marshal.loads(marshal.dumps(self.strobj))
425 self.assertEqual(s, self.strobj)
426 self.assertEqual(id(s), id(self.strobj))
427 s2 = sys.intern(s)
428 self.assertEqual(id(s2), id(s))
429
430 def testNoIntern(self):
431 s = marshal.loads(marshal.dumps(self.strobj, 2))
432 self.assertEqual(s, self.strobj)
433 self.assertNotEqual(id(s), id(self.strobj))
434 s2 = sys.intern(s)
435 self.assertNotEqual(id(s2), id(s))
436
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000437
Skip Montanaroc1b41542003-08-02 15:02:33 +0000438def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000439 support.run_unittest(IntTestCase,
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200440 FloatTestCase,
441 StringTestCase,
442 CodeTestCase,
443 ContainerTestCase,
444 ExceptionTestCase,
445 BufferTestCase,
446 BugsTestCase,
447 LargeValuesTestCase,
448 )
Skip Montanaroc1b41542003-08-02 15:02:33 +0000449
450if __name__ == "__main__":
451 test_main()