blob: b7f4dbb98e36d4c4af8db00cee89dc8bc511f1ab [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
Serhiy Storchakab5181342015-02-06 08:58:56 +020010try:
11 import _testcapi
12except ImportError:
13 _testcapi = None
14
Guido van Rossum47f17d02007-07-10 11:37:44 +000015class HelperMixin:
16 def helper(self, sample, *extra):
17 new = marshal.loads(marshal.dumps(sample, *extra))
18 self.assertEqual(sample, new)
19 try:
Brian Curtin2c3563f2010-10-13 02:40:26 +000020 with open(support.TESTFN, "wb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000021 marshal.dump(sample, f, *extra)
Brian Curtin2c3563f2010-10-13 02:40:26 +000022 with open(support.TESTFN, "rb") as f:
Guido van Rossum47f17d02007-07-10 11:37:44 +000023 new = marshal.load(f)
Guido van Rossum47f17d02007-07-10 11:37:44 +000024 self.assertEqual(sample, new)
25 finally:
Benjamin Petersonee8712c2008-05-20 21:35:26 +000026 support.unlink(support.TESTFN)
Guido van Rossum47f17d02007-07-10 11:37:44 +000027
28class IntTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000029 def test_ints(self):
Antoine Pitroue9bbe8b2013-04-13 22:41:09 +020030 # Test a range of Python ints larger than the machine word size.
31 n = sys.maxsize ** 2
Skip Montanaroc1b41542003-08-02 15:02:33 +000032 while n:
33 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000034 self.helper(expected)
Antoine Pitrouc1ab0bd2013-04-13 22:46:33 +020035 n = n >> 1
Skip Montanaroc1b41542003-08-02 15:02:33 +000036
Serhiy Storchaka00987f62017-11-15 17:41:05 +020037 def test_int64(self):
38 # Simulate int marshaling with TYPE_INT64.
39 maxint64 = (1 << 63) - 1
40 minint64 = -maxint64-1
41 for base in maxint64, minint64, -maxint64, -(minint64 >> 1):
42 while base:
43 s = b'I' + int.to_bytes(base, 8, 'little', signed=True)
44 got = marshal.loads(s)
45 self.assertEqual(base, got)
46 if base == -1: # a fixed-point for shifting right 1
47 base = 0
48 else:
49 base >>= 1
50
51 got = marshal.loads(b'I\xfe\xdc\xba\x98\x76\x54\x32\x10')
52 self.assertEqual(got, 0x1032547698badcfe)
53 got = marshal.loads(b'I\x01\x23\x45\x67\x89\xab\xcd\xef')
54 self.assertEqual(got, -0x1032547698badcff)
55 got = marshal.loads(b'I\x08\x19\x2a\x3b\x4c\x5d\x6e\x7f')
56 self.assertEqual(got, 0x7f6e5d4c3b2a1908)
57 got = marshal.loads(b'I\xf7\xe6\xd5\xc4\xb3\xa2\x91\x80')
58 self.assertEqual(got, -0x7f6e5d4c3b2a1909)
59
Skip Montanaroc1b41542003-08-02 15:02:33 +000060 def test_bool(self):
61 for b in (True, False):
Guido van Rossum47f17d02007-07-10 11:37:44 +000062 self.helper(b)
Tim Peters58eb11c2004-01-18 20:29:55 +000063
Guido van Rossum47f17d02007-07-10 11:37:44 +000064class FloatTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000065 def test_floats(self):
66 # Test a few floats
67 small = 1e-25
Christian Heimesa37d4c62007-12-04 23:02:19 +000068 n = sys.maxsize * 3.7e250
Skip Montanaroc1b41542003-08-02 15:02:33 +000069 while n > small:
70 for expected in (-n, n):
Guido van Rossum47f17d02007-07-10 11:37:44 +000071 self.helper(float(expected))
Skip Montanaroc1b41542003-08-02 15:02:33 +000072 n /= 123.4567
73
74 f = 0.0
Michael W. Hudsondf888462005-06-03 14:41:55 +000075 s = marshal.dumps(f, 2)
Tim Peters82112372001-08-29 02:28:42 +000076 got = marshal.loads(s)
Skip Montanaroc1b41542003-08-02 15:02:33 +000077 self.assertEqual(f, got)
Michael W. Hudsondf888462005-06-03 14:41:55 +000078 # and with version <= 1 (floats marshalled differently then)
79 s = marshal.dumps(f, 1)
Tim Peters5d36a552005-06-03 22:40:27 +000080 got = marshal.loads(s)
81 self.assertEqual(f, got)
Tim Peters82112372001-08-29 02:28:42 +000082
Christian Heimesa37d4c62007-12-04 23:02:19 +000083 n = sys.maxsize * 3.7e-250
Skip Montanaroc1b41542003-08-02 15:02:33 +000084 while n < small:
85 for expected in (-n, n):
86 f = float(expected)
Guido van Rossum47f17d02007-07-10 11:37:44 +000087 self.helper(f)
88 self.helper(f, 1)
Skip Montanaroc1b41542003-08-02 15:02:33 +000089 n *= 123.4567
Tim Peters82112372001-08-29 02:28:42 +000090
Guido van Rossum47f17d02007-07-10 11:37:44 +000091class StringTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +000092 def test_unicode(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000093 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
94 self.helper(marshal.loads(marshal.dumps(s)))
Tim Peters82112372001-08-29 02:28:42 +000095
Skip Montanaroc1b41542003-08-02 15:02:33 +000096 def test_string(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +000097 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
98 self.helper(s)
Tim Peters82112372001-08-29 02:28:42 +000099
Guido van Rossumbae07c92007-10-08 02:46:15 +0000100 def test_bytes(self):
Guido van Rossume6d39042007-05-09 00:01:30 +0000101 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
Guido van Rossumbae07c92007-10-08 02:46:15 +0000102 self.helper(s)
Tim Peters58eb11c2004-01-18 20:29:55 +0000103
Skip Montanaroc1b41542003-08-02 15:02:33 +0000104class ExceptionTestCase(unittest.TestCase):
105 def test_exceptions(self):
106 new = marshal.loads(marshal.dumps(StopIteration))
107 self.assertEqual(StopIteration, new)
Thomas Heller3e1c18a2002-07-30 11:40:57 +0000108
Skip Montanaroc1b41542003-08-02 15:02:33 +0000109class CodeTestCase(unittest.TestCase):
110 def test_code(self):
Neal Norwitz221085d2007-02-25 20:55:47 +0000111 co = ExceptionTestCase.test_exceptions.__code__
Skip Montanaroc1b41542003-08-02 15:02:33 +0000112 new = marshal.loads(marshal.dumps(co))
113 self.assertEqual(co, new)
114
Amaury Forgeot d'Arc74c71f52008-05-26 21:41:42 +0000115 def test_many_codeobjects(self):
116 # Issue2957: bad recursion count on code objects
117 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
118 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
119 marshal.loads(marshal.dumps(codes))
120
Benjamin Peterson43b06862011-05-27 09:08:01 -0500121 def test_different_filenames(self):
122 co1 = compile("x", "f1", "exec")
123 co2 = compile("y", "f2", "exec")
124 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
125 self.assertEqual(co1.co_filename, "f1")
126 self.assertEqual(co2.co_filename, "f2")
127
128 @support.cpython_only
129 def test_same_filename_used(self):
130 s = """def f(): pass\ndef g(): pass"""
131 co = compile(s, "myfile", "exec")
132 co = marshal.loads(marshal.dumps(co))
133 for obj in co.co_consts:
134 if isinstance(obj, types.CodeType):
135 self.assertIs(co.co_filename, obj.co_filename)
136
Guido van Rossum47f17d02007-07-10 11:37:44 +0000137class ContainerTestCase(unittest.TestCase, HelperMixin):
Skip Montanaroc1b41542003-08-02 15:02:33 +0000138 d = {'astring': 'foo@bar.baz.spam',
139 'afloat': 7283.43,
140 'anint': 2**20,
Guido van Rossume2a383d2007-01-15 16:59:06 +0000141 'ashortlong': 2,
Skip Montanaroc1b41542003-08-02 15:02:33 +0000142 'alist': ['.zyx.41'],
143 'atuple': ('.zyx.41',)*10,
144 'aboolean': False,
Guido van Rossum47f17d02007-07-10 11:37:44 +0000145 'aunicode': "Andr\xe8 Previn"
Skip Montanaroc1b41542003-08-02 15:02:33 +0000146 }
Guido van Rossum47f17d02007-07-10 11:37:44 +0000147
Skip Montanaroc1b41542003-08-02 15:02:33 +0000148 def test_dict(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000149 self.helper(self.d)
Tim Peters58eb11c2004-01-18 20:29:55 +0000150
Skip Montanaroc1b41542003-08-02 15:02:33 +0000151 def test_list(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000152 self.helper(list(self.d.items()))
Skip Montanaroc1b41542003-08-02 15:02:33 +0000153
154 def test_tuple(self):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000155 self.helper(tuple(self.d.keys()))
Tim Peters58eb11c2004-01-18 20:29:55 +0000156
Raymond Hettingera422c342005-01-11 03:03:27 +0000157 def test_sets(self):
158 for constructor in (set, frozenset):
Guido van Rossum47f17d02007-07-10 11:37:44 +0000159 self.helper(constructor(self.d.keys()))
Raymond Hettingera422c342005-01-11 03:03:27 +0000160
Antoine Pitrou679e9d32012-03-02 18:12:43 +0100161
162class BufferTestCase(unittest.TestCase, HelperMixin):
163
164 def test_bytearray(self):
165 b = bytearray(b"abc")
166 self.helper(b)
167 new = marshal.loads(marshal.dumps(b))
168 self.assertEqual(type(new), bytes)
169
170 def test_memoryview(self):
171 b = memoryview(b"abc")
172 self.helper(b)
173 new = marshal.loads(marshal.dumps(b))
174 self.assertEqual(type(new), bytes)
175
176 def test_array(self):
177 a = array.array('B', b"abc")
178 new = marshal.loads(marshal.dumps(a))
179 self.assertEqual(new, b"abc")
180
181
Skip Montanaroc1b41542003-08-02 15:02:33 +0000182class BugsTestCase(unittest.TestCase):
183 def test_bug_5888452(self):
184 # Simple-minded check for SF 588452: Debug build crashes
185 marshal.dumps([128] * 1000)
186
Armin Rigo01ab2792004-03-26 15:09:27 +0000187 def test_patch_873224(self):
Serhiy Storchaka09bb9182018-07-05 12:19:19 +0300188 self.assertRaises(Exception, marshal.loads, b'0')
189 self.assertRaises(Exception, marshal.loads, b'f')
Guido van Rossume2a383d2007-01-15 16:59:06 +0000190 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
Armin Rigo01ab2792004-03-26 15:09:27 +0000191
Armin Rigo2ccea172004-12-20 12:25:57 +0000192 def test_version_argument(self):
193 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
Ezio Melottib3aedd42010-11-20 19:04:17 +0000194 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
195 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
Armin Rigo2ccea172004-12-20 12:25:57 +0000196
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000197 def test_fuzz(self):
198 # simple test that it's at least not *totally* trivial to
199 # crash from bad marshal data
Serhiy Storchaka09bb9182018-07-05 12:19:19 +0300200 for i in range(256):
201 c = bytes([i])
Michael W. Hudsonf2ca5af2005-06-13 18:28:46 +0000202 try:
203 marshal.loads(c)
204 except Exception:
205 pass
206
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700207 def test_loads_recursion(self):
Serhiy Storchakafc05e682018-07-05 11:17:20 +0300208 def run_tests(N, check):
209 # (((...None...),),)
210 check(b')\x01' * N + b'N')
211 check(b'(\x01\x00\x00\x00' * N + b'N')
212 # [[[...None...]]]
213 check(b'[\x01\x00\x00\x00' * N + b'N')
214 # {None: {None: {None: ...None...}}}
215 check(b'{N' * N + b'N' + b'0' * N)
216 # frozenset([frozenset([frozenset([...None...])])])
217 check(b'>\x01\x00\x00\x00' * N + b'N')
218 # Check that the generated marshal data is valid and marshal.loads()
219 # works for moderately deep nesting
220 run_tests(100, marshal.loads)
221 # Very deeply nested structure shouldn't blow the stack
222 def check(s):
223 self.assertRaises(ValueError, marshal.loads, s)
224 run_tests(2**20, check)
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700225
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000226 def test_recursion_limit(self):
227 # Create a deeply nested structure.
228 head = last = []
229 # The max stack depth should match the value in Python/marshal.c.
Steve Dower2a4a62b2018-06-04 13:25:00 -0700230 # BUG: https://bugs.python.org/issue33720
231 # Windows always limits the maximum depth on release and debug builds
232 #if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
233 if os.name == 'nt':
Steve Dowerf6c69e62014-11-01 15:15:16 -0700234 MAX_MARSHAL_STACK_DEPTH = 1000
Guido van Rossum991bf5d2007-08-29 18:44:54 +0000235 else:
236 MAX_MARSHAL_STACK_DEPTH = 2000
Guido van Rossumd59da4b2007-05-22 18:11:13 +0000237 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
238 last.append([0])
239 last = last[-1]
240
241 # Verify we don't blow out the stack with dumps/load.
242 data = marshal.dumps(head)
243 new_head = marshal.loads(data)
244 # Don't use == to compare objects, it can exceed the recursion limit.
245 self.assertEqual(len(new_head), len(head))
246 self.assertEqual(len(new_head[0]), len(head[0]))
247 self.assertEqual(len(new_head[-1]), len(head[-1]))
248
249 last.append([0])
250 self.assertRaises(ValueError, marshal.dumps, head)
251
Guido van Rossum58da9312007-11-10 23:39:45 +0000252 def test_exact_type_match(self):
253 # Former bug:
254 # >>> class Int(int): pass
255 # >>> type(loads(dumps(Int())))
256 # <type 'int'>
257 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
Ezio Melotti13925002011-03-16 11:05:33 +0200258 # Note: str subclasses are not tested because they get handled
Guido van Rossum58da9312007-11-10 23:39:45 +0000259 # by marshal's routines for objects supporting the buffer API.
260 subtyp = type('subtyp', (typ,), {})
261 self.assertRaises(ValueError, marshal.dumps, subtyp())
262
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000263 # Issue #1792 introduced a change in how marshal increases the size of its
264 # internal buffer; this test ensures that the new code is exercised.
265 def test_large_marshal(self):
266 size = int(1e6)
267 testString = 'abc' * size
268 marshal.dumps(testString)
269
Mark Dickinson2683ab02009-09-29 19:21:35 +0000270 def test_invalid_longs(self):
271 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
272 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
273 self.assertRaises(ValueError, marshal.loads, invalid_string)
274
Vinay Sajip5bdae3b2011-07-02 16:42:47 +0100275 def test_multiple_dumps_and_loads(self):
276 # Issue 12291: marshal.load() should be callable multiple times
277 # with interleaved data written by non-marshal code
278 # Adapted from a patch by Engelbert Gruber.
279 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
280 for interleaved in (b'', b'0123'):
281 ilen = len(interleaved)
282 positions = []
283 try:
284 with open(support.TESTFN, 'wb') as f:
285 for d in data:
286 marshal.dump(d, f)
287 if ilen:
288 f.write(interleaved)
289 positions.append(f.tell())
290 with open(support.TESTFN, 'rb') as f:
291 for i, d in enumerate(data):
292 self.assertEqual(d, marshal.load(f))
293 if ilen:
294 f.read(ilen)
295 self.assertEqual(positions[i], f.tell())
296 finally:
297 support.unlink(support.TESTFN)
298
Antoine Pitrou4a90ef02012-03-03 02:35:32 +0100299 def test_loads_reject_unicode_strings(self):
300 # Issue #14177: marshal.loads() should not accept unicode strings
301 unicode_string = 'T'
302 self.assertRaises(TypeError, marshal.loads, unicode_string)
303
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300304 def test_bad_reader(self):
305 class BadReader(io.BytesIO):
Antoine Pitrou1164dfc2013-10-12 22:25:39 +0200306 def readinto(self, buf):
307 n = super().readinto(buf)
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300308 if n is not None and n > 4:
Antoine Pitrou1164dfc2013-10-12 22:25:39 +0200309 n += 10**6
310 return n
Serhiy Storchaka3641a742013-07-11 22:20:47 +0300311 for value in (1.0, 1j, b'0123456789', '0123456789'):
312 self.assertRaises(ValueError, marshal.load,
313 BadReader(marshal.dumps(value)))
314
Serhiy Storchaka09bb9182018-07-05 12:19:19 +0300315 def test_eof(self):
Kristján Valur Jónsson61683622013-03-20 14:26:33 -0700316 data = marshal.dumps(("hello", "dolly", None))
317 for i in range(len(data)):
318 self.assertRaises(EOFError, marshal.loads, data[0: i])
319
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200320LARGE_SIZE = 2**31
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200321pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
322
323class NullWriter:
324 def write(self, s):
325 pass
326
327@unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
328class LargeValuesTestCase(unittest.TestCase):
329 def check_unmarshallable(self, data):
330 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
331
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200332 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200333 def test_bytes(self, size):
334 self.check_unmarshallable(b'x' * size)
335
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200336 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200337 def test_str(self, size):
338 self.check_unmarshallable('x' * size)
339
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200340 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200341 def test_tuple(self, size):
342 self.check_unmarshallable((None,) * size)
343
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200344 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200345 def test_list(self, size):
346 self.check_unmarshallable([None] * size)
347
348 @support.bigmemtest(size=LARGE_SIZE,
349 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
350 dry_run=False)
351 def test_set(self, size):
352 self.check_unmarshallable(set(range(size)))
353
354 @support.bigmemtest(size=LARGE_SIZE,
355 memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
356 dry_run=False)
357 def test_frozenset(self, size):
358 self.check_unmarshallable(frozenset(range(size)))
359
Serhiy Storchaka4847e4e2014-01-10 13:37:54 +0200360 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
Serhiy Storchaka7e019112013-02-13 12:08:15 +0200361 def test_bytearray(self, size):
362 self.check_unmarshallable(bytearray(size))
363
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700364def CollectObjectIDs(ids, obj):
365 """Collect object ids seen in a structure"""
366 if id(obj) in ids:
367 return
368 ids.add(id(obj))
369 if isinstance(obj, (list, tuple, set, frozenset)):
370 for e in obj:
371 CollectObjectIDs(ids, e)
372 elif isinstance(obj, dict):
373 for k, v in obj.items():
374 CollectObjectIDs(ids, k)
375 CollectObjectIDs(ids, v)
376 return len(ids)
377
378class InstancingTestCase(unittest.TestCase, HelperMixin):
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300379 keys = (123, 1.2345, 'abc', (123, 'abc'), frozenset({123, 'abc'}))
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700380
381 def helper3(self, rsample, recursive=False, simple=False):
382 #we have two instances
383 sample = (rsample, rsample)
384
385 n0 = CollectObjectIDs(set(), sample)
386
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300387 for v in range(3, marshal.version + 1):
388 s3 = marshal.dumps(sample, v)
389 n3 = CollectObjectIDs(set(), marshal.loads(s3))
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700390
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300391 #same number of instances generated
392 self.assertEqual(n3, n0)
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700393
394 if not recursive:
395 #can compare with version 2
396 s2 = marshal.dumps(sample, 2)
397 n2 = CollectObjectIDs(set(), marshal.loads(s2))
398 #old format generated more instances
399 self.assertGreater(n2, n0)
400
401 #if complex objects are in there, old format is larger
402 if not simple:
403 self.assertGreater(len(s2), len(s3))
404 else:
405 self.assertGreaterEqual(len(s2), len(s3))
406
407 def testInt(self):
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300408 intobj = 123321
409 self.helper(intobj)
410 self.helper3(intobj, simple=True)
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700411
412 def testFloat(self):
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300413 floatobj = 1.2345
414 self.helper(floatobj)
415 self.helper3(floatobj)
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700416
417 def testStr(self):
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300418 strobj = "abcde"*3
419 self.helper(strobj)
420 self.helper3(strobj)
421
422 def testBytes(self):
423 bytesobj = b"abcde"*3
424 self.helper(bytesobj)
425 self.helper3(bytesobj)
426
427 def testList(self):
428 for obj in self.keys:
429 listobj = [obj, obj]
430 self.helper(listobj)
431 self.helper3(listobj)
432
433 def testTuple(self):
434 for obj in self.keys:
435 tupleobj = (obj, obj)
436 self.helper(tupleobj)
437 self.helper3(tupleobj)
438
439 def testSet(self):
440 for obj in self.keys:
441 setobj = {(obj, 1), (obj, 2)}
442 self.helper(setobj)
443 self.helper3(setobj)
444
445 def testFrozenSet(self):
446 for obj in self.keys:
447 frozensetobj = frozenset({(obj, 1), (obj, 2)})
448 self.helper(frozensetobj)
449 self.helper3(frozensetobj)
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700450
451 def testDict(self):
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300452 for obj in self.keys:
453 dictobj = {"hello": obj, "goodbye": obj, obj: "hello"}
454 self.helper(dictobj)
455 self.helper3(dictobj)
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700456
457 def testModule(self):
458 with open(__file__, "rb") as f:
459 code = f.read()
460 if __file__.endswith(".py"):
461 code = compile(code, __file__, "exec")
462 self.helper(code)
463 self.helper3(code)
464
465 def testRecursion(self):
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300466 obj = 1.2345
467 d = {"hello": obj, "goodbye": obj, obj: "hello"}
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700468 d["self"] = d
469 self.helper3(d, recursive=True)
Serhiy Storchakad71f3172019-06-02 09:03:59 +0300470 l = [obj, obj]
Kristján Valur Jónssond7009c62013-03-19 18:02:10 -0700471 l.append(l)
472 self.helper3(l, recursive=True)
473
474class CompatibilityTestCase(unittest.TestCase):
475 def _test(self, version):
476 with open(__file__, "rb") as f:
477 code = f.read()
478 if __file__.endswith(".py"):
479 code = compile(code, __file__, "exec")
480 data = marshal.dumps(code, version)
481 marshal.loads(data)
482
483 def test0To3(self):
484 self._test(0)
485
486 def test1To3(self):
487 self._test(1)
488
489 def test2To3(self):
490 self._test(2)
491
492 def test3To3(self):
493 self._test(3)
494
495class InterningTestCase(unittest.TestCase, HelperMixin):
496 strobj = "this is an interned string"
497 strobj = sys.intern(strobj)
498
499 def testIntern(self):
500 s = marshal.loads(marshal.dumps(self.strobj))
501 self.assertEqual(s, self.strobj)
502 self.assertEqual(id(s), id(self.strobj))
503 s2 = sys.intern(s)
504 self.assertEqual(id(s2), id(s))
505
506 def testNoIntern(self):
507 s = marshal.loads(marshal.dumps(self.strobj, 2))
508 self.assertEqual(s, self.strobj)
509 self.assertNotEqual(id(s), id(self.strobj))
510 s2 = sys.intern(s)
511 self.assertNotEqual(id(s2), id(s))
512
Serhiy Storchakab5181342015-02-06 08:58:56 +0200513@support.cpython_only
514@unittest.skipUnless(_testcapi, 'requires _testcapi')
515class CAPI_TestCase(unittest.TestCase, HelperMixin):
Alexandre Vassalotti5f8ced22008-05-16 00:03:33 +0000516
Serhiy Storchakab5181342015-02-06 08:58:56 +0200517 def test_write_long_to_file(self):
518 for v in range(marshal.version + 1):
519 _testcapi.pymarshal_write_long_to_file(0x12345678, support.TESTFN, v)
520 with open(support.TESTFN, 'rb') as f:
521 data = f.read()
522 support.unlink(support.TESTFN)
523 self.assertEqual(data, b'\x78\x56\x34\x12')
524
525 def test_write_object_to_file(self):
526 obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000)
527 for v in range(marshal.version + 1):
528 _testcapi.pymarshal_write_object_to_file(obj, support.TESTFN, v)
529 with open(support.TESTFN, 'rb') as f:
530 data = f.read()
531 support.unlink(support.TESTFN)
532 self.assertEqual(marshal.loads(data), obj)
533
534 def test_read_short_from_file(self):
535 with open(support.TESTFN, 'wb') as f:
536 f.write(b'\x34\x12xxxx')
537 r, p = _testcapi.pymarshal_read_short_from_file(support.TESTFN)
538 support.unlink(support.TESTFN)
539 self.assertEqual(r, 0x1234)
540 self.assertEqual(p, 2)
541
542 with open(support.TESTFN, 'wb') as f:
543 f.write(b'\x12')
544 with self.assertRaises(EOFError):
545 _testcapi.pymarshal_read_short_from_file(support.TESTFN)
546 support.unlink(support.TESTFN)
547
548 def test_read_long_from_file(self):
549 with open(support.TESTFN, 'wb') as f:
550 f.write(b'\x78\x56\x34\x12xxxx')
551 r, p = _testcapi.pymarshal_read_long_from_file(support.TESTFN)
552 support.unlink(support.TESTFN)
553 self.assertEqual(r, 0x12345678)
554 self.assertEqual(p, 4)
555
556 with open(support.TESTFN, 'wb') as f:
557 f.write(b'\x56\x34\x12')
558 with self.assertRaises(EOFError):
559 _testcapi.pymarshal_read_long_from_file(support.TESTFN)
560 support.unlink(support.TESTFN)
561
562 def test_read_last_object_from_file(self):
563 obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
564 for v in range(marshal.version + 1):
565 data = marshal.dumps(obj, v)
566 with open(support.TESTFN, 'wb') as f:
567 f.write(data + b'xxxx')
568 r, p = _testcapi.pymarshal_read_last_object_from_file(support.TESTFN)
569 support.unlink(support.TESTFN)
570 self.assertEqual(r, obj)
571
572 with open(support.TESTFN, 'wb') as f:
573 f.write(data[:1])
574 with self.assertRaises(EOFError):
575 _testcapi.pymarshal_read_last_object_from_file(support.TESTFN)
576 support.unlink(support.TESTFN)
577
578 def test_read_object_from_file(self):
579 obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
580 for v in range(marshal.version + 1):
581 data = marshal.dumps(obj, v)
582 with open(support.TESTFN, 'wb') as f:
583 f.write(data + b'xxxx')
584 r, p = _testcapi.pymarshal_read_object_from_file(support.TESTFN)
585 support.unlink(support.TESTFN)
586 self.assertEqual(r, obj)
587 self.assertEqual(p, len(data))
588
589 with open(support.TESTFN, 'wb') as f:
590 f.write(data[:1])
591 with self.assertRaises(EOFError):
592 _testcapi.pymarshal_read_object_from_file(support.TESTFN)
593 support.unlink(support.TESTFN)
594
Skip Montanaroc1b41542003-08-02 15:02:33 +0000595
596if __name__ == "__main__":
Serhiy Storchakab5181342015-02-06 08:58:56 +0200597 unittest.main()