blob: 83c348c393d70f025da1f2de8d650e11334cc2a9 [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
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000203 def test_loads_recursion(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
207 def test_recursion_limit(self):
208 # Create a deeply nested structure.
209 head = last = []
210 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000211 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
212 MAX_MARSHAL_STACK_DEPTH = 1500
213 else:
214 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000215 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
216 last.append([0])
217 last = last[-1]
218
219 # Verify we don't blow out the stack with dumps/load.
220 data = marshal.dumps(head)
221 new_head = marshal.loads(data)
222 # Don't use == to compare objects, it can exceed the recursion limit.
223 self.assertEqual(len(new_head), len(head))
224 self.assertEqual(len(new_head[0]), len(head[0]))
225 self.assertEqual(len(new_head[-1]), len(head[-1]))
226
227 last.append([0])
228 self.assertRaises(ValueError, marshal.dumps, head)
229
Guido van Rossum58da9312007-11-10 23:39:45 +0000230 def test_exact_type_match(self):
231 # Former bug:
232 # >>> class Int(int): pass
233 # >>> type(loads(dumps(Int())))
234 # <type 'int'>
235 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200236 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000237 # by marshal's routines for objects supporting the buffer API.
238 subtyp = type('subtyp', (typ,), {})
239 self.assertRaises(ValueError, marshal.dumps, subtyp())
240
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000241 # Issue #1792 introduced a change in how marshal increases the size of its
242 # internal buffer; this test ensures that the new code is exercised.
243 def test_large_marshal(self):
244 size = int(1e6)
245 testString = 'abc' * size
246 marshal.dumps(testString)
247
Mark Dickinson2683ab02009-09-29 19:21:35 +0000248 def test_invalid_longs(self):
249 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
250 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
251 self.assertRaises(ValueError, marshal.loads, invalid_string)
252
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100253 def test_multiple_dumps_and_loads(self):
254 # Issue 12291: marshal.load() should be callable multiple times
255 # with interleaved data written by non-marshal code
256 # Adapted from a patch by Engelbert Gruber.
257 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
258 for interleaved in (b'', b'0123'):
259 ilen = len(interleaved)
260 positions = []
261 try:
262 with open(support.TESTFN, 'wb') as f:
263 for d in data:
264 marshal.dump(d, f)
265 if ilen:
266 f.write(interleaved)
267 positions.append(f.tell())
268 with open(support.TESTFN, 'rb') as f:
269 for i, d in enumerate(data):
270 self.assertEqual(d, marshal.load(f))
271 if ilen:
272 f.read(ilen)
273 self.assertEqual(positions[i], f.tell())
274 finally:
275 support.unlink(support.TESTFN)
276
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100277 def test_loads_reject_unicode_strings(self):
278 # Issue #14177: marshal.loads() should not accept unicode strings
279 unicode_string = 'T'
280 self.assertRaises(TypeError, marshal.loads, unicode_string)
281
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000282
Skip Montanaroc1b41542003-08-02 15:02:33 +0000283def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000284 support.run_unittest(IntTestCase,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000285 FloatTestCase,
286 StringTestCase,
287 CodeTestCase,
288 ContainerTestCase,
289 ExceptionTestCase,
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100290 BufferTestCase,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000291 BugsTestCase)
292
293if __name__ == "__main__":
294 test_main()