blob: 7e37f39c6a74d94a1bda3523d7730b72af6bb8ce [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):
27 # Test the full range of Python ints.
Christian Heimesa37d4c62007-12-04 23:02:19 +000028 n = sys.maxsize
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)
Skip Montanaroc1b41542003-08-02 15:02:33 +000032 n = n >> 1
Tim Peters82112372001-08-29 02:28:42 +000033
Skip Montanaroc1b41542003-08-02 15:02:33 +000034 def test_int64(self):
35 # Simulate int marshaling on a 64-bit box. This is most interesting if
36 # we're running the test on a 32-bit box, of course.
37
38 def to_little_endian_string(value, nbytes):
Guido van Rossum254348e2007-11-21 19:29:53 +000039 b = bytearray()
Skip Montanaroc1b41542003-08-02 15:02:33 +000040 for i in range(nbytes):
Guido van Rossume6d39042007-05-09 00:01:30 +000041 b.append(value & 0xff)
Skip Montanaroc1b41542003-08-02 15:02:33 +000042 value >>= 8
Guido van Rossume6d39042007-05-09 00:01:30 +000043 return b
Skip Montanaroc1b41542003-08-02 15:02:33 +000044
Guido van Rossume2a383d2007-01-15 16:59:06 +000045 maxint64 = (1 << 63) - 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000046 minint64 = -maxint64-1
47
48 for base in maxint64, minint64, -maxint64, -(minint64 >> 1):
49 while base:
Guido van Rossume6d39042007-05-09 00:01:30 +000050 s = b'I' + to_little_endian_string(base, 8)
Skip Montanaroc1b41542003-08-02 15:02:33 +000051 got = marshal.loads(s)
52 self.assertEqual(base, got)
53 if base == -1: # a fixed-point for shifting right 1
54 base = 0
55 else:
56 base >>= 1
57
58 def test_bool(self):
59 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000060 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000061
Guido van Rossum47f17d02007-07-10 11:37:44 +000062class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000063 def test_floats(self):
64 # Test a few floats
65 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000066 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000067 while n > small:
68 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000069 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000070 n /= 123.4567
71
72 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000073 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000074 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000075 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000076 # and with version <= 1 (floats marshalled differently then)
77 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000078 got = marshal.loads(s)
79 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000080
Christian Heimesa37d4c62007-12-04 23:02:19 +000081 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000082 while n < small:
83 for expected in (-n, n):
84 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000085 self.helper(f)
86 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000087 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000088
Guido van Rossum47f17d02007-07-10 11:37:44 +000089class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000090 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000091 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
92 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000093
Skip Montanaroc1b41542003-08-02 15:02:33 +000094 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000095 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
96 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000097
Guido van Rossumbae07c92007-10-08 02:46:15 +000098 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +000099 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +0000100 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +0000101
Skip Montanaroc1b41542003-08-02 15:02:33 +0000102class ExceptionTestCase(unittest.TestCase):
103 def test_exceptions(self):
104 new = marshal.loads(marshal.dumps(StopIteration))
105 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +0000106
Skip Montanaroc1b41542003-08-02 15:02:33 +0000107class CodeTestCase(unittest.TestCase):
108 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +0000109 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +0000110 new = marshal.loads(marshal.dumps(co))
111 self.assertEqual(co, new)
112
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +0000113 def test_many_codeobjects(self):
114 # Issue2957: bad recursion count on code objects
115 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
116 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
117 marshal.loads(marshal.dumps(codes))
118
Benjamin Peterson43b06862011-05-27 09:08:01 -0500119 def test_different_filenames(self):
120 co1 = compile("x", "f1", "exec")
121 co2 = compile("y", "f2", "exec")
122 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
123 self.assertEqual(co1.co_filename, "f1")
124 self.assertEqual(co2.co_filename, "f2")
125
126 @support.cpython_only
127 def test_same_filename_used(self):
128 s = """def f(): pass\ndef g(): pass"""
129 co = compile(s, "myfile", "exec")
130 co = marshal.loads(marshal.dumps(co))
131 for obj in co.co_consts:
132 if isinstance(obj, types.CodeType):
133 self.assertIs(co.co_filename, obj.co_filename)
134
Guido van Rossum47f17d02007-07-10 11:37:44 +0000135class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000136 d = {'astring': 'foo@bar.baz.spam',
137 'afloat': 7283.43,
138 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000139 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000140 'alist': ['.zyx.41'],
141 'atuple': ('.zyx.41',)*10,
142 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000143 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000144 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000145
Skip Montanaroc1b41542003-08-02 15:02:33 +0000146 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000147 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000148
Skip Montanaroc1b41542003-08-02 15:02:33 +0000149 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000150 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000151
152 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000153 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000154
Raymond Hettingera422c342005-01-11 03:03:27 +0000155 def test_sets(self):
156 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000157 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000158
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100159
160class BufferTestCase(unittest.TestCase, HelperMixin):
161
162 def test_bytearray(self):
163 b = bytearray(b"abc")
164 self.helper(b)
165 new = marshal.loads(marshal.dumps(b))
166 self.assertEqual(type(new), bytes)
167
168 def test_memoryview(self):
169 b = memoryview(b"abc")
170 self.helper(b)
171 new = marshal.loads(marshal.dumps(b))
172 self.assertEqual(type(new), bytes)
173
174 def test_array(self):
175 a = array.array('B', b"abc")
176 new = marshal.loads(marshal.dumps(a))
177 self.assertEqual(new, b"abc")
178
179
Skip Montanaroc1b41542003-08-02 15:02:33 +0000180class BugsTestCase(unittest.TestCase):
181 def test_bug_5888452(self):
182 # Simple-minded check for SF 588452: Debug build crashes
183 marshal.dumps([128] * 1000)
184
Armin Rigo01ab2792004-03-26 15:09:27 +0000185 def test_patch_873224(self):
186 self.assertRaises(Exception, marshal.loads, '0')
187 self.assertRaises(Exception, marshal.loads, 'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000188 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000189
Armin Rigo2ccea172004-12-20 12:25:57 +0000190 def test_version_argument(self):
191 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000192 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
193 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000194
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000195 def test_fuzz(self):
196 # simple test that it's at least not *totally* trivial to
197 # crash from bad marshal data
198 for c in [chr(i) for i in range(256)]:
199 try:
200 marshal.loads(c)
201 except Exception:
202 pass
203
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000204 def test_loads_recursion(self):
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100205 s = b'c' + (b'X' * 4*4) + b'{' * 2**20
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000206 self.assertRaises(ValueError, marshal.loads, s)
207
208 def test_recursion_limit(self):
209 # Create a deeply nested structure.
210 head = last = []
211 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000212 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
213 MAX_MARSHAL_STACK_DEPTH = 1500
214 else:
215 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000216 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
217 last.append([0])
218 last = last[-1]
219
220 # Verify we don't blow out the stack with dumps/load.
221 data = marshal.dumps(head)
222 new_head = marshal.loads(data)
223 # Don't use == to compare objects, it can exceed the recursion limit.
224 self.assertEqual(len(new_head), len(head))
225 self.assertEqual(len(new_head[0]), len(head[0]))
226 self.assertEqual(len(new_head[-1]), len(head[-1]))
227
228 last.append([0])
229 self.assertRaises(ValueError, marshal.dumps, head)
230
Guido van Rossum58da9312007-11-10 23:39:45 +0000231 def test_exact_type_match(self):
232 # Former bug:
233 # >>> class Int(int): pass
234 # >>> type(loads(dumps(Int())))
235 # <type 'int'>
236 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200237 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000238 # by marshal's routines for objects supporting the buffer API.
239 subtyp = type('subtyp', (typ,), {})
240 self.assertRaises(ValueError, marshal.dumps, subtyp())
241
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000242 # Issue #1792 introduced a change in how marshal increases the size of its
243 # internal buffer; this test ensures that the new code is exercised.
244 def test_large_marshal(self):
245 size = int(1e6)
246 testString = 'abc' * size
247 marshal.dumps(testString)
248
Mark Dickinson2683ab02009-09-29 19:21:35 +0000249 def test_invalid_longs(self):
250 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
251 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
252 self.assertRaises(ValueError, marshal.loads, invalid_string)
253
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100254 def test_multiple_dumps_and_loads(self):
255 # Issue 12291: marshal.load() should be callable multiple times
256 # with interleaved data written by non-marshal code
257 # Adapted from a patch by Engelbert Gruber.
258 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
259 for interleaved in (b'', b'0123'):
260 ilen = len(interleaved)
261 positions = []
262 try:
263 with open(support.TESTFN, 'wb') as f:
264 for d in data:
265 marshal.dump(d, f)
266 if ilen:
267 f.write(interleaved)
268 positions.append(f.tell())
269 with open(support.TESTFN, 'rb') as f:
270 for i, d in enumerate(data):
271 self.assertEqual(d, marshal.load(f))
272 if ilen:
273 f.read(ilen)
274 self.assertEqual(positions[i], f.tell())
275 finally:
276 support.unlink(support.TESTFN)
277
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100278 def test_loads_reject_unicode_strings(self):
279 # Issue #14177: marshal.loads() should not accept unicode strings
280 unicode_string = 'T'
281 self.assertRaises(TypeError, marshal.loads, unicode_string)
282
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300283 def test_bad_reader(self):
284 class BadReader(io.BytesIO):
285 def read(self, n=-1):
286 b = super().read(n)
287 if n is not None and n > 4:
288 b += b' ' * 10**6
289 return b
290 for value in (1.0, 1j, b'0123456789', '0123456789'):
291 self.assertRaises(ValueError, marshal.load,
292 BadReader(marshal.dumps(value)))
293
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200294LARGE_SIZE = 2**31
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200295pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
296
297class NullWriter:
298 def write(self, s):
299 pass
300
301@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
302class LargeValuesTestCase(unittest.TestCase):
303 def check_unmarshallable(self, data):
304 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
305
306 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
307 def test_bytes(self, size):
308 self.check_unmarshallable(b'x' * size)
309
Serhiy Storchaka40f42d92013-02-13 12:32:24 +0200310 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200311 def test_str(self, size):
312 self.check_unmarshallable('x' * size)
313
314 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
315 def test_tuple(self, size):
316 self.check_unmarshallable((None,) * size)
317
318 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size, dry_run=False)
319 def test_list(self, size):
320 self.check_unmarshallable([None] * size)
321
322 @support.bigmemtest(size=LARGE_SIZE,
323 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
324 dry_run=False)
325 def test_set(self, size):
326 self.check_unmarshallable(set(range(size)))
327
328 @support.bigmemtest(size=LARGE_SIZE,
329 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
330 dry_run=False)
331 def test_frozenset(self, size):
332 self.check_unmarshallable(frozenset(range(size)))
333
334 @support.bigmemtest(size=LARGE_SIZE, memuse=1, dry_run=False)
335 def test_bytearray(self, size):
336 self.check_unmarshallable(bytearray(size))
337
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000338
Skip Montanaroc1b41542003-08-02 15:02:33 +0000339def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000340 support.run_unittest(IntTestCase,
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200341 FloatTestCase,
342 StringTestCase,
343 CodeTestCase,
344 ContainerTestCase,
345 ExceptionTestCase,
346 BufferTestCase,
347 BugsTestCase,
348 LargeValuesTestCase,
349 )
Skip Montanaroc1b41542003-08-02 15:02:33 +0000350
351if __name__ == "__main__":
352 test_main()