Home | History | Annotate | Download | only in test
      1 from test import support
      2 import array
      3 import io
      4 import marshal
      5 import sys
      6 import unittest
      7 import os
      8 import types
      9 
     10 try:
     11     import _testcapi
     12 except ImportError:
     13     _testcapi = None
     14 
     15 class HelperMixin:
     16     def helper(self, sample, *extra):
     17         new = marshal.loads(marshal.dumps(sample, *extra))
     18         self.assertEqual(sample, new)
     19         try:
     20             with open(support.TESTFN, "wb") as f:
     21                 marshal.dump(sample, f, *extra)
     22             with open(support.TESTFN, "rb") as f:
     23                 new = marshal.load(f)
     24             self.assertEqual(sample, new)
     25         finally:
     26             support.unlink(support.TESTFN)
     27 
     28 class IntTestCase(unittest.TestCase, HelperMixin):
     29     def test_ints(self):
     30         # Test a range of Python ints larger than the machine word size.
     31         n = sys.maxsize ** 2
     32         while n:
     33             for expected in (-n, n):
     34                 self.helper(expected)
     35             n = n >> 1
     36 
     37     def test_bool(self):
     38         for b in (True, False):
     39             self.helper(b)
     40 
     41 class FloatTestCase(unittest.TestCase, HelperMixin):
     42     def test_floats(self):
     43         # Test a few floats
     44         small = 1e-25
     45         n = sys.maxsize * 3.7e250
     46         while n > small:
     47             for expected in (-n, n):
     48                 self.helper(float(expected))
     49             n /= 123.4567
     50 
     51         f = 0.0
     52         s = marshal.dumps(f, 2)
     53         got = marshal.loads(s)
     54         self.assertEqual(f, got)
     55         # and with version <= 1 (floats marshalled differently then)
     56         s = marshal.dumps(f, 1)
     57         got = marshal.loads(s)
     58         self.assertEqual(f, got)
     59 
     60         n = sys.maxsize * 3.7e-250
     61         while n < small:
     62             for expected in (-n, n):
     63                 f = float(expected)
     64                 self.helper(f)
     65                 self.helper(f, 1)
     66             n *= 123.4567
     67 
     68 class StringTestCase(unittest.TestCase, HelperMixin):
     69     def test_unicode(self):
     70         for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
     71             self.helper(marshal.loads(marshal.dumps(s)))
     72 
     73     def test_string(self):
     74         for s in ["", "Andr\xe8 Previn", "abc", " "*10000]:
     75             self.helper(s)
     76 
     77     def test_bytes(self):
     78         for s in [b"", b"Andr\xe8 Previn", b"abc", b" "*10000]:
     79             self.helper(s)
     80 
     81 class ExceptionTestCase(unittest.TestCase):
     82     def test_exceptions(self):
     83         new = marshal.loads(marshal.dumps(StopIteration))
     84         self.assertEqual(StopIteration, new)
     85 
     86 class CodeTestCase(unittest.TestCase):
     87     def test_code(self):
     88         co = ExceptionTestCase.test_exceptions.__code__
     89         new = marshal.loads(marshal.dumps(co))
     90         self.assertEqual(co, new)
     91 
     92     def test_many_codeobjects(self):
     93         # Issue2957: bad recursion count on code objects
     94         count = 5000    # more than MAX_MARSHAL_STACK_DEPTH
     95         codes = (ExceptionTestCase.test_exceptions.__code__,) * count
     96         marshal.loads(marshal.dumps(codes))
     97 
     98     def test_different_filenames(self):
     99         co1 = compile("x", "f1", "exec")
    100         co2 = compile("y", "f2", "exec")
    101         co1, co2 = marshal.loads(marshal.dumps((co1, co2)))
    102         self.assertEqual(co1.co_filename, "f1")
    103         self.assertEqual(co2.co_filename, "f2")
    104 
    105     @support.cpython_only
    106     def test_same_filename_used(self):
    107         s = """def f(): pass\ndef g(): pass"""
    108         co = compile(s, "myfile", "exec")
    109         co = marshal.loads(marshal.dumps(co))
    110         for obj in co.co_consts:
    111             if isinstance(obj, types.CodeType):
    112                 self.assertIs(co.co_filename, obj.co_filename)
    113 
    114 class ContainerTestCase(unittest.TestCase, HelperMixin):
    115     d = {'astring': 'foo (at] bar.baz.spam',
    116          'afloat': 7283.43,
    117          'anint': 2**20,
    118          'ashortlong': 2,
    119          'alist': ['.zyx.41'],
    120          'atuple': ('.zyx.41',)*10,
    121          'aboolean': False,
    122          'aunicode': "Andr\xe8 Previn"
    123          }
    124 
    125     def test_dict(self):
    126         self.helper(self.d)
    127 
    128     def test_list(self):
    129         self.helper(list(self.d.items()))
    130 
    131     def test_tuple(self):
    132         self.helper(tuple(self.d.keys()))
    133 
    134     def test_sets(self):
    135         for constructor in (set, frozenset):
    136             self.helper(constructor(self.d.keys()))
    137 
    138     @support.cpython_only
    139     def test_empty_frozenset_singleton(self):
    140         # marshal.loads() must reuse the empty frozenset singleton
    141         obj = frozenset()
    142         obj2 = marshal.loads(marshal.dumps(obj))
    143         self.assertIs(obj2, obj)
    144 
    145 
    146 class BufferTestCase(unittest.TestCase, HelperMixin):
    147 
    148     def test_bytearray(self):
    149         b = bytearray(b"abc")
    150         self.helper(b)
    151         new = marshal.loads(marshal.dumps(b))
    152         self.assertEqual(type(new), bytes)
    153 
    154     def test_memoryview(self):
    155         b = memoryview(b"abc")
    156         self.helper(b)
    157         new = marshal.loads(marshal.dumps(b))
    158         self.assertEqual(type(new), bytes)
    159 
    160     def test_array(self):
    161         a = array.array('B', b"abc")
    162         new = marshal.loads(marshal.dumps(a))
    163         self.assertEqual(new, b"abc")
    164 
    165 
    166 class BugsTestCase(unittest.TestCase):
    167     def test_bug_5888452(self):
    168         # Simple-minded check for SF 588452: Debug build crashes
    169         marshal.dumps([128] * 1000)
    170 
    171     def test_patch_873224(self):
    172         self.assertRaises(Exception, marshal.loads, '0')
    173         self.assertRaises(Exception, marshal.loads, 'f')
    174         self.assertRaises(Exception, marshal.loads, marshal.dumps(2**65)[:-1])
    175 
    176     def test_version_argument(self):
    177         # Python 2.4.0 crashes for any call to marshal.dumps(x, y)
    178         self.assertEqual(marshal.loads(marshal.dumps(5, 0)), 5)
    179         self.assertEqual(marshal.loads(marshal.dumps(5, 1)), 5)
    180 
    181     def test_fuzz(self):
    182         # simple test that it's at least not *totally* trivial to
    183         # crash from bad marshal data
    184         for c in [chr(i) for i in range(256)]:
    185             try:
    186                 marshal.loads(c)
    187             except Exception:
    188                 pass
    189 
    190     def test_loads_2x_code(self):
    191         s = b'c' + (b'X' * 4*4) + b'{' * 2**20
    192         self.assertRaises(ValueError, marshal.loads, s)
    193 
    194     def test_loads_recursion(self):
    195         s = b'c' + (b'X' * 4*5) + b'{' * 2**20
    196         self.assertRaises(ValueError, marshal.loads, s)
    197 
    198     def test_recursion_limit(self):
    199         # Create a deeply nested structure.
    200         head = last = []
    201         # The max stack depth should match the value in Python/marshal.c.
    202         if os.name == 'nt' and hasattr(sys, 'gettotalrefcount'):
    203             MAX_MARSHAL_STACK_DEPTH = 1000
    204         else:
    205             MAX_MARSHAL_STACK_DEPTH = 2000
    206         for i in range(MAX_MARSHAL_STACK_DEPTH - 2):
    207             last.append([0])
    208             last = last[-1]
    209 
    210         # Verify we don't blow out the stack with dumps/load.
    211         data = marshal.dumps(head)
    212         new_head = marshal.loads(data)
    213         # Don't use == to compare objects, it can exceed the recursion limit.
    214         self.assertEqual(len(new_head), len(head))
    215         self.assertEqual(len(new_head[0]), len(head[0]))
    216         self.assertEqual(len(new_head[-1]), len(head[-1]))
    217 
    218         last.append([0])
    219         self.assertRaises(ValueError, marshal.dumps, head)
    220 
    221     def test_exact_type_match(self):
    222         # Former bug:
    223         #   >>> class Int(int): pass
    224         #   >>> type(loads(dumps(Int())))
    225         #   <type 'int'>
    226         for typ in (int, float, complex, tuple, list, dict, set, frozenset):
    227             # Note: str subclasses are not tested because they get handled
    228             # by marshal's routines for objects supporting the buffer API.
    229             subtyp = type('subtyp', (typ,), {})
    230             self.assertRaises(ValueError, marshal.dumps, subtyp())
    231 
    232     # Issue #1792 introduced a change in how marshal increases the size of its
    233     # internal buffer; this test ensures that the new code is exercised.
    234     def test_large_marshal(self):
    235         size = int(1e6)
    236         testString = 'abc' * size
    237         marshal.dumps(testString)
    238 
    239     def test_invalid_longs(self):
    240         # Issue #7019: marshal.loads shouldn't produce unnormalized PyLongs
    241         invalid_string = b'l\x02\x00\x00\x00\x00\x00\x00\x00'
    242         self.assertRaises(ValueError, marshal.loads, invalid_string)
    243 
    244     def test_multiple_dumps_and_loads(self):
    245         # Issue 12291: marshal.load() should be callable multiple times
    246         # with interleaved data written by non-marshal code
    247         # Adapted from a patch by Engelbert Gruber.
    248         data = (1, 'abc', b'def', 1.0, (2, 'a', ['b', b'c']))
    249         for interleaved in (b'', b'0123'):
    250             ilen = len(interleaved)
    251             positions = []
    252             try:
    253                 with open(support.TESTFN, 'wb') as f:
    254                     for d in data:
    255                         marshal.dump(d, f)
    256                         if ilen:
    257                             f.write(interleaved)
    258                         positions.append(f.tell())
    259                 with open(support.TESTFN, 'rb') as f:
    260                     for i, d in enumerate(data):
    261                         self.assertEqual(d, marshal.load(f))
    262                         if ilen:
    263                             f.read(ilen)
    264                         self.assertEqual(positions[i], f.tell())
    265             finally:
    266                 support.unlink(support.TESTFN)
    267 
    268     def test_loads_reject_unicode_strings(self):
    269         # Issue #14177: marshal.loads() should not accept unicode strings
    270         unicode_string = 'T'
    271         self.assertRaises(TypeError, marshal.loads, unicode_string)
    272 
    273     def test_bad_reader(self):
    274         class BadReader(io.BytesIO):
    275             def readinto(self, buf):
    276                 n = super().readinto(buf)
    277                 if n is not None and n > 4:
    278                     n += 10**6
    279                 return n
    280         for value in (1.0, 1j, b'0123456789', '0123456789'):
    281             self.assertRaises(ValueError, marshal.load,
    282                               BadReader(marshal.dumps(value)))
    283 
    284     def _test_eof(self):
    285         data = marshal.dumps(("hello", "dolly", None))
    286         for i in range(len(data)):
    287             self.assertRaises(EOFError, marshal.loads, data[0: i])
    288 
    289 LARGE_SIZE = 2**31
    290 pointer_size = 8 if sys.maxsize > 0xFFFFFFFF else 4
    291 
    292 class NullWriter:
    293     def write(self, s):
    294         pass
    295 
    296 @unittest.skipIf(LARGE_SIZE > sys.maxsize, "test cannot run on 32-bit systems")
    297 class LargeValuesTestCase(unittest.TestCase):
    298     def check_unmarshallable(self, data):
    299         self.assertRaises(ValueError, marshal.dump, data, NullWriter())
    300 
    301     @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
    302     def test_bytes(self, size):
    303         self.check_unmarshallable(b'x' * size)
    304 
    305     @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
    306     def test_str(self, size):
    307         self.check_unmarshallable('x' * size)
    308 
    309     @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
    310     def test_tuple(self, size):
    311         self.check_unmarshallable((None,) * size)
    312 
    313     @support.bigmemtest(size=LARGE_SIZE, memuse=pointer_size + 1, dry_run=False)
    314     def test_list(self, size):
    315         self.check_unmarshallable([None] * size)
    316 
    317     @support.bigmemtest(size=LARGE_SIZE,
    318             memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
    319             dry_run=False)
    320     def test_set(self, size):
    321         self.check_unmarshallable(set(range(size)))
    322 
    323     @support.bigmemtest(size=LARGE_SIZE,
    324             memuse=pointer_size*12 + sys.getsizeof(LARGE_SIZE-1),
    325             dry_run=False)
    326     def test_frozenset(self, size):
    327         self.check_unmarshallable(frozenset(range(size)))
    328 
    329     @support.bigmemtest(size=LARGE_SIZE, memuse=2, dry_run=False)
    330     def test_bytearray(self, size):
    331         self.check_unmarshallable(bytearray(size))
    332 
    333 def CollectObjectIDs(ids, obj):
    334     """Collect object ids seen in a structure"""
    335     if id(obj) in ids:
    336         return
    337     ids.add(id(obj))
    338     if isinstance(obj, (list, tuple, set, frozenset)):
    339         for e in obj:
    340             CollectObjectIDs(ids, e)
    341     elif isinstance(obj, dict):
    342         for k, v in obj.items():
    343             CollectObjectIDs(ids, k)
    344             CollectObjectIDs(ids, v)
    345     return len(ids)
    346 
    347 class InstancingTestCase(unittest.TestCase, HelperMixin):
    348     intobj = 123321
    349     floatobj = 1.2345
    350     strobj = "abcde"*3
    351     dictobj = {"hello":floatobj, "goodbye":floatobj, floatobj:"hello"}
    352 
    353     def helper3(self, rsample, recursive=False, simple=False):
    354         #we have two instances
    355         sample = (rsample, rsample)
    356 
    357         n0 = CollectObjectIDs(set(), sample)
    358 
    359         s3 = marshal.dumps(sample, 3)
    360         n3 = CollectObjectIDs(set(), marshal.loads(s3))
    361 
    362         #same number of instances generated
    363         self.assertEqual(n3, n0)
    364 
    365         if not recursive:
    366             #can compare with version 2
    367             s2 = marshal.dumps(sample, 2)
    368             n2 = CollectObjectIDs(set(), marshal.loads(s2))
    369             #old format generated more instances
    370             self.assertGreater(n2, n0)
    371 
    372             #if complex objects are in there, old format is larger
    373             if not simple:
    374                 self.assertGreater(len(s2), len(s3))
    375             else:
    376                 self.assertGreaterEqual(len(s2), len(s3))
    377 
    378     def testInt(self):
    379         self.helper(self.intobj)
    380         self.helper3(self.intobj, simple=True)
    381 
    382     def testFloat(self):
    383         self.helper(self.floatobj)
    384         self.helper3(self.floatobj)
    385 
    386     def testStr(self):
    387         self.helper(self.strobj)
    388         self.helper3(self.strobj)
    389 
    390     def testDict(self):
    391         self.helper(self.dictobj)
    392         self.helper3(self.dictobj)
    393 
    394     def testModule(self):
    395         with open(__file__, "rb") as f:
    396             code = f.read()
    397         if __file__.endswith(".py"):
    398             code = compile(code, __file__, "exec")
    399         self.helper(code)
    400         self.helper3(code)
    401 
    402     def testRecursion(self):
    403         d = dict(self.dictobj)
    404         d["self"] = d
    405         self.helper3(d, recursive=True)
    406         l = [self.dictobj]
    407         l.append(l)
    408         self.helper3(l, recursive=True)
    409 
    410 class CompatibilityTestCase(unittest.TestCase):
    411     def _test(self, version):
    412         with open(__file__, "rb") as f:
    413             code = f.read()
    414         if __file__.endswith(".py"):
    415             code = compile(code, __file__, "exec")
    416         data = marshal.dumps(code, version)
    417         marshal.loads(data)
    418 
    419     def test0To3(self):
    420         self._test(0)
    421 
    422     def test1To3(self):
    423         self._test(1)
    424 
    425     def test2To3(self):
    426         self._test(2)
    427 
    428     def test3To3(self):
    429         self._test(3)
    430 
    431 class InterningTestCase(unittest.TestCase, HelperMixin):
    432     strobj = "this is an interned string"
    433     strobj = sys.intern(strobj)
    434 
    435     def testIntern(self):
    436         s = marshal.loads(marshal.dumps(self.strobj))
    437         self.assertEqual(s, self.strobj)
    438         self.assertEqual(id(s), id(self.strobj))
    439         s2 = sys.intern(s)
    440         self.assertEqual(id(s2), id(s))
    441 
    442     def testNoIntern(self):
    443         s = marshal.loads(marshal.dumps(self.strobj, 2))
    444         self.assertEqual(s, self.strobj)
    445         self.assertNotEqual(id(s), id(self.strobj))
    446         s2 = sys.intern(s)
    447         self.assertNotEqual(id(s2), id(s))
    448 
    449 @support.cpython_only
    450 @unittest.skipUnless(_testcapi, 'requires _testcapi')
    451 class CAPI_TestCase(unittest.TestCase, HelperMixin):
    452 
    453     def test_write_long_to_file(self):
    454         for v in range(marshal.version + 1):
    455             _testcapi.pymarshal_write_long_to_file(0x12345678, support.TESTFN, v)
    456             with open(support.TESTFN, 'rb') as f:
    457                 data = f.read()
    458             support.unlink(support.TESTFN)
    459             self.assertEqual(data, b'\x78\x56\x34\x12')
    460 
    461     def test_write_object_to_file(self):
    462         obj = ('\u20ac', b'abc', 123, 45.6, 7+8j, 'long line '*1000)
    463         for v in range(marshal.version + 1):
    464             _testcapi.pymarshal_write_object_to_file(obj, support.TESTFN, v)
    465             with open(support.TESTFN, 'rb') as f:
    466                 data = f.read()
    467             support.unlink(support.TESTFN)
    468             self.assertEqual(marshal.loads(data), obj)
    469 
    470     def test_read_short_from_file(self):
    471         with open(support.TESTFN, 'wb') as f:
    472             f.write(b'\x34\x12xxxx')
    473         r, p = _testcapi.pymarshal_read_short_from_file(support.TESTFN)
    474         support.unlink(support.TESTFN)
    475         self.assertEqual(r, 0x1234)
    476         self.assertEqual(p, 2)
    477 
    478         with open(support.TESTFN, 'wb') as f:
    479             f.write(b'\x12')
    480         with self.assertRaises(EOFError):
    481             _testcapi.pymarshal_read_short_from_file(support.TESTFN)
    482         support.unlink(support.TESTFN)
    483 
    484     def test_read_long_from_file(self):
    485         with open(support.TESTFN, 'wb') as f:
    486             f.write(b'\x78\x56\x34\x12xxxx')
    487         r, p = _testcapi.pymarshal_read_long_from_file(support.TESTFN)
    488         support.unlink(support.TESTFN)
    489         self.assertEqual(r, 0x12345678)
    490         self.assertEqual(p, 4)
    491 
    492         with open(support.TESTFN, 'wb') as f:
    493             f.write(b'\x56\x34\x12')
    494         with self.assertRaises(EOFError):
    495             _testcapi.pymarshal_read_long_from_file(support.TESTFN)
    496         support.unlink(support.TESTFN)
    497 
    498     def test_read_last_object_from_file(self):
    499         obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
    500         for v in range(marshal.version + 1):
    501             data = marshal.dumps(obj, v)
    502             with open(support.TESTFN, 'wb') as f:
    503                 f.write(data + b'xxxx')
    504             r, p = _testcapi.pymarshal_read_last_object_from_file(support.TESTFN)
    505             support.unlink(support.TESTFN)
    506             self.assertEqual(r, obj)
    507 
    508             with open(support.TESTFN, 'wb') as f:
    509                 f.write(data[:1])
    510             with self.assertRaises(EOFError):
    511                 _testcapi.pymarshal_read_last_object_from_file(support.TESTFN)
    512             support.unlink(support.TESTFN)
    513 
    514     def test_read_object_from_file(self):
    515         obj = ('\u20ac', b'abc', 123, 45.6, 7+8j)
    516         for v in range(marshal.version + 1):
    517             data = marshal.dumps(obj, v)
    518             with open(support.TESTFN, 'wb') as f:
    519                 f.write(data + b'xxxx')
    520             r, p = _testcapi.pymarshal_read_object_from_file(support.TESTFN)
    521             support.unlink(support.TESTFN)
    522             self.assertEqual(r, obj)
    523             self.assertEqual(p, len(data))
    524 
    525             with open(support.TESTFN, 'wb') as f:
    526                 f.write(data[:1])
    527             with self.assertRaises(EOFError):
    528                 _testcapi.pymarshal_read_object_from_file(support.TESTFN)
    529             support.unlink(support.TESTFN)
    530 
    531 
    532 if __name__ == "__main__":
    533     unittest.main()
    534