blob: 96a70ecc2abc5272ad67ddd373e9ed8960be4c5c [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
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):
25 # Test the full range of Python ints.
Christian Heimesa37d4c62007-12-04 23:02:19 +000026 n = sys.maxsize
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)
Skip Montanaroc1b41542003-08-02 15:02:33 +000030 n = n >> 1
Tim Peters82112372001-08-29 02:28:42 +000031
Skip Montanaroc1b41542003-08-02 15:02:33 +000032 def test_int64(self):
33 # Simulate int marshaling on a 64-bit box. This is most interesting if
34 # we're running the test on a 32-bit box, of course.
35
36 def to_little_endian_string(value, nbytes):
Guido van Rossum254348e2007-11-21 19:29:53 +000037 b = bytearray()
Skip Montanaroc1b41542003-08-02 15:02:33 +000038 for i in range(nbytes):
Guido van Rossume6d39042007-05-09 00:01:30 +000039 b.append(value & 0xff)
Skip Montanaroc1b41542003-08-02 15:02:33 +000040 value >>= 8
Guido van Rossume6d39042007-05-09 00:01:30 +000041 return b
Skip Montanaroc1b41542003-08-02 15:02:33 +000042
Guido van Rossume2a383d2007-01-15 16:59:06 +000043 maxint64 = (1 << 63) - 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000044 minint64 = -maxint64-1
45
46 for base in maxint64, minint64, -maxint64, -(minint64 >> 1):
47 while base:
Guido van Rossume6d39042007-05-09 00:01:30 +000048 s = b'I' + to_little_endian_string(base, 8)
Skip Montanaroc1b41542003-08-02 15:02:33 +000049 got = marshal.loads(s)
50 self.assertEqual(base, got)
51 if base == -1: # a fixed-point for shifting right 1
52 base = 0
53 else:
54 base >>= 1
55
56 def test_bool(self):
57 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000058 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000059
Guido van Rossum47f17d02007-07-10 11:37:44 +000060class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000061 def test_floats(self):
62 # Test a few floats
63 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000064 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000065 while n > small:
66 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000067 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000068 n /= 123.4567
69
70 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000071 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000072 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000073 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000074 # and with version <= 1 (floats marshalled differently then)
75 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000076 got = marshal.loads(s)
77 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000078
Christian Heimesa37d4c62007-12-04 23:02:19 +000079 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000080 while n < small:
81 for expected in (-n, n):
82 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000083 self.helper(f)
84 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000085 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000086
Guido van Rossum47f17d02007-07-10 11:37:44 +000087class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000088 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000089 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
90 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000091
Skip Montanaroc1b41542003-08-02 15:02:33 +000092 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000093 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
94 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000095
Guido van Rossumbae07c92007-10-08 02:46:15 +000096 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +000097 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +000098 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +000099
Skip Montanaroc1b41542003-08-02 15:02:33 +0000100class ExceptionTestCase(unittest.TestCase):
101 def test_exceptions(self):
102 new = marshal.loads(marshal.dumps(StopIteration))
103 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +0000104
Skip Montanaroc1b41542003-08-02 15:02:33 +0000105class CodeTestCase(unittest.TestCase):
106 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +0000107 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +0000108 new = marshal.loads(marshal.dumps(co))
109 self.assertEqual(co, new)
110
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +0000111 def test_many_codeobjects(self):
112 # Issue2957: bad recursion count on code objects
113 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
114 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
115 marshal.loads(marshal.dumps(codes))
116
Guido van Rossum47f17d02007-07-10 11:37:44 +0000117class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000118 d = {'astring': 'foo@bar.baz.spam',
119 'afloat': 7283.43,
120 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000121 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000122 'alist': ['.zyx.41'],
123 'atuple': ('.zyx.41',)*10,
124 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000125 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000126 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000127
Skip Montanaroc1b41542003-08-02 15:02:33 +0000128 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000129 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000130
Skip Montanaroc1b41542003-08-02 15:02:33 +0000131 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000132 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000133
134 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000135 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000136
Raymond Hettingera422c342005-01-11 03:03:27 +0000137 def test_sets(self):
138 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000139 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000140
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100141
142class BufferTestCase(unittest.TestCase, HelperMixin):
143
144 def test_bytearray(self):
145 b = bytearray(b"abc")
146 self.helper(b)
147 new = marshal.loads(marshal.dumps(b))
148 self.assertEqual(type(new), bytes)
149
150 def test_memoryview(self):
151 b = memoryview(b"abc")
152 self.helper(b)
153 new = marshal.loads(marshal.dumps(b))
154 self.assertEqual(type(new), bytes)
155
156 def test_array(self):
157 a = array.array('B', b"abc")
158 new = marshal.loads(marshal.dumps(a))
159 self.assertEqual(new, b"abc")
160
161
Skip Montanaroc1b41542003-08-02 15:02:33 +0000162class BugsTestCase(unittest.TestCase):
163 def test_bug_5888452(self):
164 # Simple-minded check for SF 588452: Debug build crashes
165 marshal.dumps([128] * 1000)
166
Armin Rigo01ab2792004-03-26 15:09:27 +0000167 def test_patch_873224(self):
168 self.assertRaises(Exception, marshal.loads, '0')
169 self.assertRaises(Exception, marshal.loads, 'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000170 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000171
Armin Rigo2ccea172004-12-20 12:25:57 +0000172 def test_version_argument(self):
173 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000174 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
175 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000176
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000177 def test_fuzz(self):
178 # simple test that it's at least not *totally* trivial to
179 # crash from bad marshal data
180 for c in [chr(i) for i in range(256)]:
181 try:
182 marshal.loads(c)
183 except Exception:
184 pass
185
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000186 def test_loads_recursion(self):
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100187 s = b'c' + (b'X' * 4*4) + b'{' * 2**20
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000188 self.assertRaises(ValueError, marshal.loads, s)
189
190 def test_recursion_limit(self):
191 # Create a deeply nested structure.
192 head = last = []
193 # The max stack depth should match the value in Python/marshal.c.
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000194 if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
195 MAX_MARSHAL_STACK_DEPTH = 1500
196 else:
197 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000198 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
199 last.append([0])
200 last = last[-1]
201
202 # Verify we don't blow out the stack with dumps/load.
203 data = marshal.dumps(head)
204 new_head = marshal.loads(data)
205 # Don't use == to compare objects, it can exceed the recursion limit.
206 self.assertEqual(len(new_head), len(head))
207 self.assertEqual(len(new_head[0]), len(head[0]))
208 self.assertEqual(len(new_head[-1]), len(head[-1]))
209
210 last.append([0])
211 self.assertRaises(ValueError, marshal.dumps, head)
212
Guido van Rossum58da9312007-11-10 23:39:45 +0000213 def test_exact_type_match(self):
214 # Former bug:
215 # >>> class Int(int): pass
216 # >>> type(loads(dumps(Int())))
217 # <type 'int'>
218 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200219 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000220 # by marshal's routines for objects supporting the buffer API.
221 subtyp = type('subtyp', (typ,), {})
222 self.assertRaises(ValueError, marshal.dumps, subtyp())
223
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000224 # Issue #1792 introduced a change in how marshal increases the size of its
225 # internal buffer; this test ensures that the new code is exercised.
226 def test_large_marshal(self):
227 size = int(1e6)
228 testString = 'abc' * size
229 marshal.dumps(testString)
230
Mark Dickinson2683ab02009-09-29 19:21:35 +0000231 def test_invalid_longs(self):
232 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
233 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
234 self.assertRaises(ValueError, marshal.loads, invalid_string)
235
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100236 def test_multiple_dumps_and_loads(self):
237 # Issue 12291: marshal.load() should be callable multiple times
238 # with interleaved data written by non-marshal code
239 # Adapted from a patch by Engelbert Gruber.
240 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
241 for interleaved in (b'', b'0123'):
242 ilen = len(interleaved)
243 positions = []
244 try:
245 with open(support.TESTFN, 'wb') as f:
246 for d in data:
247 marshal.dump(d, f)
248 if ilen:
249 f.write(interleaved)
250 positions.append(f.tell())
251 with open(support.TESTFN, 'rb') as f:
252 for i, d in enumerate(data):
253 self.assertEqual(d, marshal.load(f))
254 if ilen:
255 f.read(ilen)
256 self.assertEqual(positions[i], f.tell())
257 finally:
258 support.unlink(support.TESTFN)
259
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100260 def test_loads_reject_unicode_strings(self):
261 # Issue #14177: marshal.loads() should not accept unicode strings
262 unicode_string = 'T'
263 self.assertRaises(TypeError, marshal.loads, unicode_string)
264
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000265
Skip Montanaroc1b41542003-08-02 15:02:33 +0000266def test_main():
Benjamin Petersonee8712c2008-05-20 21:35:26 +0000267 support.run_unittest(IntTestCase,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000268 FloatTestCase,
269 StringTestCase,
270 CodeTestCase,
271 ContainerTestCase,
272 ExceptionTestCase,
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100273 BufferTestCase,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000274 BugsTestCase)
275
276if __name__ == "__main__":
277 test_main()