Debian Codegraph @

lib-python/3/test/test_marshal.py

raw symbols SCIP
1 from test import support
2 from test.support import os_helper, requires_debug_ranges
3 from test.support.script_helper import assert_python_ok
4 import array
5 import io
6 import marshal
7 import sys
8 import unittest
9 import os
10 import types
11 import textwrap
12
13 try:
14 import _testcapi
15 except ImportError:
16 _testcapi = None
17
18 class HelperMixin:
19 def helper(self, sample, *extra):
20 new = marshal.loads(marshal.dumps(sample, *extra))
21 self.assertEqual(sample, new)
22 try:
23 with open(os_helper.TESTFN, "wb") as f:
24 marshal.dump(sample, f, *extra)
25 with open(os_helper.TESTFN, "rb") as f:
26 new = marshal.load(f)
27 self.assertEqual(sample, new)
28 finally:
29 os_helper.unlink(os_helper.TESTFN)
30
31 class IntTestCase(unittest.TestCase, HelperMixin):
32 def test_ints(self):
33 # Test a range of Python ints larger than the machine word size.
34 n = sys.maxsize ** 2
35 while n:
36 for expected in (-n, n):
37 self.helper(expected)
38 n = n >> 1
39
40 def test_int64(self):
41 # Simulate int marshaling with TYPE_INT64.
42 maxint64 = (1 << 63) - 1
43 minint64 = -maxint64-1
44 for base in maxint64, minint64, -maxint64, -(minint64 >> 1):
45 while base:
46 s = b'I' + int.to_bytes(base, 8, 'little', signed=True)
47 got = marshal.loads(s)
48 self.assertEqual(base, got)
49 if base == -1: # a fixed-point for shifting right 1
50 base = 0
51 else:
52 base >>= 1
53
54 got = marshal.loads(b'I\xfe\xdc\xba\x98\x76\x54\x32\x10')
55 self.assertEqual(got, 0x1032547698badcfe)
56 got = marshal.loads(b'I\x01\x23\x45\x67\x89\xab\xcd\xef')
57 self.assertEqual(got, -0x1032547698badcff)
58 got = marshal.loads(b'I\x08\x19\x2a\x3b\x4c\x5d\x6e\x7f')
59 self.assertEqual(got, 0x7f6e5d4c3b2a1908)
60 got = marshal.loads(b'I\xf7\xe6\xd5\xc4\xb3\xa2\x91\x80')
61 self.assertEqual(got, -0x7f6e5d4c3b2a1909)
62
63 def test_bool(self):
64 for b in (True, False):
65 self.helper(b)
66
67 class FloatTestCase(unittest.TestCase, HelperMixin):
68 def test_floats(self):
69 # Test a few floats
70 small = 1e-25
71 n = sys.maxsize * 3.7e250
72 while n > small:
73 for expected in (-n, n):
74 self.helper(float(expected))
75 n /= 123.4567
76
77 f = 0.0
78 s = marshal.dumps(f, 2)
79 got = marshal.loads(s)
80 self.assertEqual(f, got)
81 # and with version <= 1 (floats marshalled differently then)
82 s = marshal.dumps(f, 1)
83 got = marshal.loads(s)
84 self.assertEqual(f, got)
85
86 n = sys.maxsize * 3.7e-250
87 while n < small:
88 for expected in (-n, n):
89 f = float(expected)
90 self.helper(f)
91 self.helper(f, 1)
92 n *= 123.4567
93
94 class StringTestCase(unittest.TestCase, HelperMixin):
95 def test_unicode(self):
96 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
97 self.helper(marshal.loads(marshal.dumps(s)))
98
99 def test_string(self):
100 for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
101 self.helper(s)
102
103 def test_bytes(self):
104 for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
105 self.helper(s)
106
107 class ExceptionTestCase(unittest.TestCase):
108 def test_exceptions(self):
109 new = marshal.loads(marshal.dumps(StopIteration))
110 self.assertEqual(StopIteration, new)
111
112 class CodeTestCase(unittest.TestCase):
113 def test_code(self):
114 co = ExceptionTestCase.test_exceptions.__code__
115 new = marshal.loads(marshal.dumps(co))
116 self.assertEqual(co, new)
117
118 def test_many_codeobjects(self):
119 # Issue2957: bad recursion count on code objects
120 count = 5000 # more than MAX_MARSHAL_STACK_DEPTH
121 codes = (ExceptionTestCase.test_exceptions.__code__,) * count
122 marshal.loads(marshal.dumps(codes))
123
124 def test_different_filenames(self):
125 co1 = compile("x", "f1", "exec")
126 co2 = compile("y", "f2", "exec")
127 co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
128 self.assertEqual(co1.co_filename, "f1")
129 self.assertEqual(co2.co_filename, "f2")
130
131 @requires_debug_ranges()
132 @support.impl_detail("PyPy does not implement -X no_debug_ranges", cpython=True)
133 def test_minimal_linetable_with_no_debug_ranges(self):
134 # Make sure when demarshalling objects with `-X no_debug_ranges`
135 # that the columns are None.
136 co = ExceptionTestCase.test_exceptions.__code__
137 code = textwrap.dedent("""
138 import sys
139 import marshal
140 with open(sys.argv[1], 'rb') as f:
141 co = marshal.load(f)
142 positions = list(co.co_positions())
143 assert positions[0][2] is None
144 assert positions[0][3] is None
145 """)
146
147 try:
148 with open(os_helper.TESTFN, 'wb') as f:
149 marshal.dump(co, f)
150
151 assert_python_ok('-X', 'no_debug_ranges',
152 '-c', code, os_helper.TESTFN)
153 finally:
154 os_helper.unlink(os_helper.TESTFN)
155
156 @support.cpython_only
157 def test_same_filename_used(self):
158 s = """def f(): pass\ndef g(): pass"""
159 co = compile(s, "myfile", "exec")
160 co = marshal.loads(marshal.dumps(co))
161 for obj in co.co_consts:
162 if isinstance(obj, types.CodeType):
163 self.assertIs(co.co_filename, obj.co_filename)
164
165 class ContainerTestCase(unittest.TestCase, HelperMixin):
166 d = {'astring': '[email protected]',
167 'afloat': 7283.43,
168 'anint': 2**20,
169 'ashortlong': 2,
170 'alist': ['.zyx.41'],
171 'atuple': ('.zyx.41',)*10,
172 'aboolean': False,
173 'aunicode': "Andr\xe8 Previn"
174 }
175
176 def test_dict(self):
177 self.helper(self.d)
178
179 def test_list(self):
180 self.helper(list(self.d.items()))
181
182 def test_tuple(self):
183 self.helper(tuple(self.d.keys()))
184
185 def test_sets(self):
186 for constructor in (set, frozenset):
187 self.helper(constructor(self.d.keys()))
188
189
190 class BufferTestCase(unittest.TestCase, HelperMixin):
191
192 def test_bytearray(self):
193 b = bytearray(b"abc")
194 self.helper(b)
195 new = marshal.loads(marshal.dumps(b))
196 self.assertEqual(type(new), bytes)
197
198 def test_memoryview(self):
199 b = memoryview(b"abc")
200 self.helper(b)
201 new = marshal.loads(marshal.dumps(b))
202 self.assertEqual(type(new), bytes)
203
204 def test_array(self):
205 a = array.array('B', b"abc")
206 new = marshal.loads(marshal.dumps(a))
207 self.assertEqual(new, b"abc")
208
209
210 class BugsTestCase(unittest.TestCase):
211 def test_bug_5888452(self):
212 # Simple-minded check for SF 588452: Debug build crashes
213 marshal.dumps([128] * 1000)
214
215 def test_patch_873224(self):
216 self.assertRaises(Exception, marshal.loads, b'0')
217 self.assertRaises(Exception, marshal.loads, b'f')
218 self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
219
220 def test_version_argument(self):
221 # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
222 self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
223 self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
224
225 def test_fuzz(self):
226 # simple test that it's at least not *totally* trivial to
227 # crash from bad marshal data
228 for i in range(256):
229 c = bytes([i])
230 try:
231 marshal.loads(c)
232 except Exception:
233 pass
234
235 def test_loads_recursion(self):
236 def run_tests(N, check):
237 # (((...None...),),)
238 check(b')\x01' * N + b'N')
239 check(b'(\x01\x00\x00\x00' * N + b'N')
240 # [[[...None...]]]
241 check(b'[\x01\x00\x00\x00' * N + b'N')
242 # {None: {None: {None: ...None...}}}
243 check(b'{N' * N + b'N' + b'0' * N)
244 # frozenset([frozenset([frozenset([...None...])])])
245 check(b'>\x01\x00\x00\x00' * N + b'N')
246 # Check that the generated marshal data is valid and marshal.loads()
247 # works for moderately deep nesting
248 run_tests(100, marshal.loads)
249 # Very deeply nested structure shouldn't blow the stack
250 def check(s):
251 self.assertRaises(ValueError, marshal.loads, s)
252 run_tests(2**20, check)
253
254 @support.impl_detail('specific recursion check')
255 def test_recursion_limit(self):
256 # Create a deeply nested structure.
257 head = last = []
258 # The max stack depth should match the value in Python/marshal.c.
259 # BUG: https://bugs.python.org/issue33720
260 # Windows always limits the maximum depth on release and debug builds
261 #if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
262 if os.name == 'nt':
263 MAX_MARSHAL_STACK_DEPTH = 1000
264 elif sys.platform == 'wasi':
265 MAX_MARSHAL_STACK_DEPTH = 1500
266 else:
267 MAX_MARSHAL_STACK_DEPTH = 2000
268 for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
269 last.append([0])
270 last = last[-1]
271
272 # Verify we don't blow out the stack with dumps/load.
273 data = marshal.dumps(head)
274 new_head = marshal.loads(data)
275 # Don't use == to compare objects, it can exceed the recursion limit.
276 self.assertEqual(len(new_head), len(head))
277 self.assertEqual(len(new_head[0]), len(head[0]))
278 self.assertEqual(len(new_head[-1]), len(head[-1]))
279
280 last.append([0])
281 self.assertRaises(ValueError, marshal.dumps, head)
282
283 def test_exact_type_match(self):
284 # Former bug:
285 # >>> class Int(int): pass
286 # >>> type(loads(dumps(Int())))
287 # <type 'int'>
288 for typ in (int, float, complex, tuple, list, dict, set, frozenset):
289 # Note: str subclasses are not tested because they get handled
290 # by marshal's routines for objects supporting the buffer API.
291 subtyp = type('subtyp', (typ,), {})
292 self.assertRaises(ValueError, marshal.dumps, subtyp())
293
294 # Issue #1792 introduced a change in how marshal increases the size of its
295 # internal buffer; this test ensures that the new code is exercised.
296 def test_large_marshal(self):
297 size = int(1e6)
298 testString = 'abc' * size
299 marshal.dumps(testString)
300
301 def test_invalid_longs(self):
302 # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
303 invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
304 self.assertRaises(ValueError, marshal.loads, invalid_string)
305
306 def test_multiple_dumps_and_loads(self):
307 # Issue 12291: marshal.load() should be callable multiple times
308 # with interleaved data written by non-marshal code
309 # Adapted from a patch by Engelbert Gruber.
310 data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
311 for interleaved in (b'', b'0123'):
312 ilen = len(interleaved)
313 positions = []
314 try:
315 with open(os_helper.TESTFN, 'wb') as f:
316 for d in data:
317 marshal.dump(d, f)
318 if ilen:
319 f.write(interleaved)
320 positions.append(f.tell())
321 with open(os_helper.TESTFN, 'rb') as f:
322 for i, d in enumerate(data):
323 self.assertEqual(d, marshal.load(f))
324 if ilen:
325 f.read(ilen)
326 self.assertEqual(positions[i], f.tell())
327 finally:
328 os_helper.unlink(os_helper.TESTFN)
329
330 def test_loads_reject_unicode_strings(self):
331 # Issue #14177: marshal.loads() should not accept unicode strings
332 unicode_string = 'T'
333 self.assertRaises(TypeError, marshal.loads, unicode_string)
334
335 def test_bad_reader(self):
336 class BadReader(io.BytesIO):
337 def readinto(self, buf):
338 n = super().readinto(buf)
339 if n is not None and n > 4:
340 n += 10**6
341 return n
342 def read(self, n): # PyPy calls read(), not readinto()
343 result = super().read(n)
344 if len(result) > 4:
345 result += b'\x00' * (10**6)
346 return result
347 for value in (1.0, 1j, b'0123456789', '0123456789'):
348 self.assertRaises(ValueError, marshal.load,
349 BadReader(marshal.dumps(value)))
350
351 def test_eof(self):
352 data = marshal.dumps(("hello", "dolly", None))
353 for i in range(len(data)):
354 self.assertRaises(EOFError, marshal.loads, data[0: i])
355
356 def test_deterministic_sets(self):
357 # bpo-37596: To support reproducible builds, sets and frozensets need to
358 # have their elements serialized in a consistent order (even when they
359 # have been scrambled by hash randomization):
360 for kind in ("set", "frozenset"):
361 for elements in (
362 "float('nan'), b'a', b'b', b'c', 'x', 'y', 'z'",
363 # Also test for bad interactions with backreferencing:
364 "('Spam', 0), ('Spam', 1), ('Spam', 2), ('Spam', 3), ('Spam', 4), ('Spam', 5)",
365 ):
366 s = f"{kind}([{elements}])"
367 with self.subTest(s):
368 # First, make sure that our test case still has different
369 # orders under hash seeds 0 and 1. If this check fails, we
370 # need to update this test with different elements. Skip
371 # this part if we are configured to use any other hash
372 # algorithm (for example, using Py_HASH_EXTERNAL):
373 if sys.hash_info.algorithm in {"fnv", "siphash24"}:
374 args = ["-c", f"print({s})"]
375 _, repr_0, _ = assert_python_ok(*args, PYTHONHASHSEED="0")
376 _, repr_1, _ = assert_python_ok(*args, PYTHONHASHSEED="1")
377 if sys.implementation.name != 'pypy':
378 self.assertNotEqual(repr_0, repr_1)
379 # Then, perform the actual test:
380 args = ["-c", f"import marshal; print(marshal.dumps({s}))"]
381 _, dump_0, _ = assert_python_ok(*args, PYTHONHASHSEED="0")
382 _, dump_1, _ = assert_python_ok(*args, PYTHONHASHSEED="1")
383 self.assertEqual(dump_0, dump_1)
384
385 LARGE_SIZE = 2**31
386 pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
387 if support.check_impl_detail(pypy=False):
388 sizeof_large_size = sys.getsizeof(LARGE_SIZE-1)
389 else:
390 sizeof_large_size = 32 # Some value for PyPy
391
392 class NullWriter:
393 def write(self, s):
394 pass
395
396 @unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
397 class LargeValuesTestCase(unittest.TestCase):
398 def check_unmarshallable(self, data):
399 self.assertRaises(ValueError, marshal.dump, data, NullWriter())
400
401 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
402 def test_bytes(self, size):
403 self.check_unmarshallable(b'x' * size)
404
405 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
406 def test_str(self, size):
407 self.check_unmarshallable('x' * size)
408
409 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
410 def test_tuple(self, size):
411 self.check_unmarshallable((None,) * size)
412
413 @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
414 def test_list(self, size):
415 self.check_unmarshallable([None] * size)
416
417 @support.bigmemtest(size=LARGE_SIZE,
418 memuse=pointer_size*12 + sizeof_large_size,
419 dry_run=False)
420 def test_set(self, size):
421 self.check_unmarshallable(set(range(size)))
422
423 @support.bigmemtest(size=LARGE_SIZE,
424 memuse=pointer_size*12 + sizeof_large_size,
425 dry_run=False)
426 def test_frozenset(self, size):
427 self.check_unmarshallable(frozenset(range(size)))
428
429 @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
430 def test_bytearray(self, size):
431 self.check_unmarshallable(bytearray(size))
432
433 def CollectObjectIDs(ids, obj):
434 """Collect object ids seen in a structure"""
435 if id(obj) in ids:
436 return
437 ids.add(id(obj))
438 if isinstance(obj, (list, tuple, set, frozenset)):
439 for e in obj:
440 CollectObjectIDs(ids, e)
441 elif isinstance(obj, dict):
442 for k, v in obj.items():
443 CollectObjectIDs(ids, k)
444 CollectObjectIDs(ids, v)
445 return len(ids)
446
447 class InstancingTestCase(unittest.TestCase, HelperMixin):
448 keys = (123, 1.2345, 'abc', (123, 'abc'), frozenset({123, 'abc'}))
449
450 def helper3(self, rsample, recursive=False, simple=False):
451 #we have two instances
452 sample = (rsample, rsample)
453
454 n0 = CollectObjectIDs(set(), sample)
455
456 for v in range(3, marshal.version + 1):
457 s3 = marshal.dumps(sample, v)
458 n3 = CollectObjectIDs(set(), marshal.loads(s3))
459
460 #same number of instances generated
461 self.assertEqual(n3, n0)
462
463 if not recursive:
464 #can compare with version 2
465 s2 = marshal.dumps(sample, 2)
466 n2 = CollectObjectIDs(set(), marshal.loads(s2))
467 #old format generated more instances
468 # PyPy: same-valued scalars (int, float) share id(); skip this check
469 if sys.implementation.name != 'pypy':
470 self.assertGreater(n2, n0)
471
472 #if complex objects are in there, old format is larger
473 if not simple:
474 self.assertGreater(len(s2), len(s3))
475 else:
476 self.assertGreaterEqual(len(s2), len(s3))
477
478 def testInt(self):
479 intobj = 123321
480 self.helper(intobj)
481 self.helper3(intobj, simple=True)
482
483 def testFloat(self):
484 floatobj = 1.2345
485 self.helper(floatobj)
486 self.helper3(floatobj)
487
488 def testStr(self):
489 strobj = "abcde"*3
490 self.helper(strobj)
491 self.helper3(strobj)
492
493 def testBytes(self):
494 bytesobj = b"abcde"*3
495 self.helper(bytesobj)
496 self.helper3(bytesobj)
497
498 def testList(self):
499 for obj in self.keys:
500 listobj = [obj, obj]
501 self.helper(listobj)
502 self.helper3(listobj)
503
504 def testTuple(self):
505 for obj in self.keys:
506 tupleobj = (obj, obj)
507 self.helper(tupleobj)
508 self.helper3(tupleobj)
509
510 def testSet(self):
511 for obj in self.keys:
512 setobj = {(obj, 1), (obj, 2)}
513 self.helper(setobj)
514 self.helper3(setobj)
515
516 def testFrozenSet(self):
517 for obj in self.keys:
518 frozensetobj = frozenset({(obj, 1), (obj, 2)})
519 self.helper(frozensetobj)
520 self.helper3(frozensetobj)
521
522 def testDict(self):
523 for obj in self.keys:
524 dictobj = {"hello": obj, "goodbye": obj, obj: "hello"}
525 self.helper(dictobj)
526 self.helper3(dictobj)
527
528 def testModule(self):
529 with open(__file__, "rb") as f:
530 code = f.read()
531 if __file__.endswith(".py"):
532 code = compile(code, __file__, "exec")
533 self.helper(code)
534 self.helper3(code)
535
536 def testRecursion(self):
537 obj = 1.2345
538 d = {"hello": obj, "goodbye": obj, obj: "hello"}
539 d["self"] = d
540 self.helper3(d, recursive=True)
541 l = [obj, obj]
542 l.append(l)
543 self.helper3(l, recursive=True)
544
545 class CompatibilityTestCase(unittest.TestCase):
546 def _test(self, version):
547 with open(__file__, "rb") as f:
548 code = f.read()
549 if __file__.endswith(".py"):
550 code = compile(code, __file__, "exec")
551 data = marshal.dumps(code, version)
552 marshal.loads(data)
553
554 def test0To3(self):
555 self._test(0)
556
557 def test1To3(self):
558 self._test(1)
559
560 def test2To3(self):
561 self._test(2)
562
563 def test3To3(self):
564 self._test(3)
565
566 class InterningTestCase(unittest.TestCase, HelperMixin):
567 strobj = "this is an interned string"
568 strobj = sys.intern(strobj)
569
570 def testIntern(self):
571 s = marshal.loads(marshal.dumps(self.strobj))
572 self.assertEqual(s, self.strobj)
573 self.assertEqual(id(s), id(self.strobj))
574 s2 = sys.intern(s)
575 self.assertEqual(id(s2), id(s))
576
577 def testNoIntern(self):
578 s = marshal.loads(marshal.dumps(self.strobj, 2))
579 self.assertEqual(s, self.strobj)
580 self.assertNotEqual(id(s), id(self.strobj))
581 s2 = sys.intern(s)
582 self.assertNotEqual(id(s2), id(s))
583
584 @support.cpython_only
585 @unittest.skipUnless(_testcapi, 'requires _testcapi')
586 class CAPI_TestCase(unittest.TestCase, HelperMixin):
587
588 def test_write_long_to_file(self):
589 for v in range(marshal.version + 1):
590 _testcapi.pymarshal_write_long_to_file(0x12345678, os_helper.TESTFN, v)
591 with open(os_helper.TESTFN, 'rb') as f:
592 data = f.read()
593 os_helper.unlink(os_helper.TESTFN)
594 self.assertEqual(data, b'\x78\x56\x34\x12')
595
596 def test_write_object_to_file(self):
597 obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000)
598 for v in range(marshal.version + 1):
599 _testcapi.pymarshal_write_object_to_file(obj, os_helper.TESTFN, v)
600 with open(os_helper.TESTFN, 'rb') as f:
601 data = f.read()
602 os_helper.unlink(os_helper.TESTFN)
603 self.assertEqual(marshal.loads(data), obj)
604
605 def test_read_short_from_file(self):
606 with open(os_helper.TESTFN, 'wb') as f:
607 f.write(b'\x34\x12xxxx')
608 r, p = _testcapi.pymarshal_read_short_from_file(os_helper.TESTFN)
609 os_helper.unlink(os_helper.TESTFN)
610 self.assertEqual(r, 0x1234)
611 self.assertEqual(p, 2)
612
613 with open(os_helper.TESTFN, 'wb') as f:
614 f.write(b'\x12')
615 with self.assertRaises(EOFError):
616 _testcapi.pymarshal_read_short_from_file(os_helper.TESTFN)
617 os_helper.unlink(os_helper.TESTFN)
618
619 def test_read_long_from_file(self):
620 with open(os_helper.TESTFN, 'wb') as f:
621 f.write(b'\x78\x56\x34\x12xxxx')
622 r, p = _testcapi.pymarshal_read_long_from_file(os_helper.TESTFN)
623 os_helper.unlink(os_helper.TESTFN)
624 self.assertEqual(r, 0x12345678)
625 self.assertEqual(p, 4)
626
627 with open(os_helper.TESTFN, 'wb') as f:
628 f.write(b'\x56\x34\x12')
629 with self.assertRaises(EOFError):
630 _testcapi.pymarshal_read_long_from_file(os_helper.TESTFN)
631 os_helper.unlink(os_helper.TESTFN)
632
633 def test_read_last_object_from_file(self):
634 obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
635 for v in range(marshal.version + 1):
636 data = marshal.dumps(obj, v)
637 with open(os_helper.TESTFN, 'wb') as f:
638 f.write(data + b'xxxx')
639 r, p = _testcapi.pymarshal_read_last_object_from_file(os_helper.TESTFN)
640 os_helper.unlink(os_helper.TESTFN)
641 self.assertEqual(r, obj)
642
643 with open(os_helper.TESTFN, 'wb') as f:
644 f.write(data[:1])
645 with self.assertRaises(EOFError):
646 _testcapi.pymarshal_read_last_object_from_file(os_helper.TESTFN)
647 os_helper.unlink(os_helper.TESTFN)
648
649 def test_read_object_from_file(self):
650 obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
651 for v in range(marshal.version + 1):
652 data = marshal.dumps(obj, v)
653 with open(os_helper.TESTFN, 'wb') as f:
654 f.write(data + b'xxxx')
655 r, p = _testcapi.pymarshal_read_object_from_file(os_helper.TESTFN)
656 os_helper.unlink(os_helper.TESTFN)
657 self.assertEqual(r, obj)
658 self.assertEqual(p, len(data))
659
660 with open(os_helper.TESTFN, 'wb') as f:
661 f.write(data[:1])
662 with self.assertRaises(EOFError):
663 _testcapi.pymarshal_read_object_from_file(os_helper.TESTFN)
664 os_helper.unlink(os_helper.TESTFN)
665
666
667 if __name__ == "__main__":
668 unittest.main()