Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/test/pickletester.py

    r2 r391  
    33import cPickle
    44import StringIO
     5import cStringIO
    56import pickletools
    67import copy_reg
    78
    8 from test.test_support import TestFailed, have_unicode, TESTFN, \
    9                               run_with_locale
     9from test.test_support import TestFailed, verbose, have_unicode, TESTFN
     10try:
     11    from test.test_support import _2G, _1M, precisionbigmemtest
     12except ImportError:
     13    # this import might fail when run on older Python versions by test_xpickle
     14    _2G = _1M = 0
     15    def precisionbigmemtest(*args, **kwargs):
     16        return lambda self: None
    1017
    1118# Tests that try a number of pickle protocols should have a
     
    1421assert pickle.HIGHEST_PROTOCOL == cPickle.HIGHEST_PROTOCOL == 2
    1522protocols = range(pickle.HIGHEST_PROTOCOL + 1)
     23
     24# Copy of test.test_support.run_with_locale. This is needed to support Python
     25# 2.4, which didn't include it. This is all to support test_xpickle, which
     26# bounces pickled objects through older Python versions to test backwards
     27# compatibility.
     28def run_with_locale(catstr, *locales):
     29    def decorator(func):
     30        def inner(*args, **kwds):
     31            try:
     32                import locale
     33                category = getattr(locale, catstr)
     34                orig_locale = locale.setlocale(category)
     35            except AttributeError:
     36                # if the test author gives us an invalid category string
     37                raise
     38            except:
     39                # cannot retrieve original locale, so do nothing
     40                locale = orig_locale = None
     41            else:
     42                for loc in locales:
     43                    try:
     44                        locale.setlocale(category, loc)
     45                        break
     46                    except:
     47                        pass
     48
     49            # now run the function, resetting the locale on exceptions
     50            try:
     51                return func(*args, **kwds)
     52            finally:
     53                if locale and orig_locale:
     54                    locale.setlocale(category, orig_locale)
     55        inner.func_name = func.func_name
     56        inner.__doc__ = func.__doc__
     57        return inner
     58    return decorator
    1659
    1760
     
    88131class use_metaclass(object):
    89132    __metaclass__ = metaclass
     133
     134class pickling_metaclass(type):
     135    def __eq__(self, other):
     136        return (type(self) == type(other) and
     137                self.reduce_args == other.reduce_args)
     138
     139    def __reduce__(self):
     140        return (create_dynamic_class, self.reduce_args)
     141
     142    __hash__ = None
     143
     144def create_dynamic_class(name, bases):
     145    result = pickling_metaclass(name, bases, dict())
     146    result.reduce_args = (name, bases)
     147    return result
    90148
    91149# DATA0 .. DATA2 are the pickles we expect under the various protocols, for
     
    411469    # of 1.
    412470    def dont_test_disassembly(self):
    413         from cStringIO import StringIO
    414471        from pickletools import dis
    415472
    416473        for proto, expected in (0, DATA0_DIS), (1, DATA1_DIS):
    417474            s = self.dumps(self._testdata, proto)
    418             filelike = StringIO()
     475            filelike = cStringIO.StringIO()
    419476            dis(s, out=filelike)
    420477            got = filelike.getvalue()
     
    428485            x = self.loads(s)
    429486            self.assertEqual(len(x), 1)
    430             self.assert_(x is x[0])
     487            self.assertTrue(x is x[0])
    431488
    432489    def test_recursive_tuple(self):
     
    438495            self.assertEqual(len(x), 1)
    439496            self.assertEqual(len(x[0]), 1)
    440             self.assert_(x is x[0][0])
     497            self.assertTrue(x is x[0][0])
    441498
    442499    def test_recursive_dict(self):
     
    447504            x = self.loads(s)
    448505            self.assertEqual(x.keys(), [1])
    449             self.assert_(x[1] is x)
     506            self.assertTrue(x[1] is x)
    450507
    451508    def test_recursive_inst(self):
     
    453510        i.attr = i
    454511        for proto in protocols:
    455             s = self.dumps(i, 2)
     512            s = self.dumps(i, proto)
    456513            x = self.loads(s)
    457514            self.assertEqual(dir(x), dir(i))
    458             self.assert_(x.attr is x)
     515            self.assertIs(x.attr, x)
    459516
    460517    def test_recursive_multi(self):
     
    470527            self.assertEqual(dir(x[0]), dir(i))
    471528            self.assertEqual(x[0].attr.keys(), [1])
    472             self.assert_(x[0].attr[1] is x)
     529            self.assertTrue(x[0].attr[1] is x)
    473530
    474531    def test_garyp(self):
     
    482539                    "'abc'   ?", # junk after close quote
    483540                    "'\\'", # trailing backslash
     541                    "'",    # issue #17710
     542                    "' ",   # issue #17710
    484543                    # some tests of the quoting rules
    485544                    #"'abc\"\''",
     
    575634            self.assertEqual(a.__class__, b.__class__)
    576635
     636    def test_dynamic_class(self):
     637        a = create_dynamic_class("my_dynamic_class", (object,))
     638        copy_reg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
     639        for proto in protocols:
     640            s = self.dumps(a, proto)
     641            b = self.loads(s)
     642            self.assertEqual(a, b)
     643
    577644    def test_structseq(self):
    578645        import time
     
    611678            self.loads(badpickle)
    612679        except ValueError, detail:
    613             self.failUnless(str(detail).startswith(
     680            self.assertTrue(str(detail).startswith(
    614681                                            "unsupported pickle protocol"))
    615682        else:
     
    683750                s = self.dumps(x, proto)
    684751                y = self.loads(s)
    685                 self.assert_(x is y, (proto, x, s, y))
     752                self.assertTrue(x is y, (proto, x, s, y))
    686753                expected = expected_opcode[proto, x]
    687754                self.assertEqual(opcode_in_pickle(expected, s), True)
     
    733800            # Dump using protocol 1 for comparison.
    734801            s1 = self.dumps(x, 1)
    735             self.assert_(__name__ in s1)
    736             self.assert_("MyList" in s1)
     802            self.assertIn(__name__, s1)
     803            self.assertIn("MyList", s1)
    737804            self.assertEqual(opcode_in_pickle(opcode, s1), False)
    738805
     
    743810            # Dump using protocol 2 for test.
    744811            s2 = self.dumps(x, 2)
    745             self.assert_(__name__ not in s2)
    746             self.assert_("MyList" not in s2)
     812            self.assertNotIn(__name__, s2)
     813            self.assertNotIn("MyList", s2)
    747814            self.assertEqual(opcode_in_pickle(opcode, s2), True)
    748815
     
    788855                self.assertEqual(num_appends, 0)
    789856            else:
    790                 self.failUnless(num_appends >= 2)
     857                self.assertTrue(num_appends >= 2)
    791858
    792859    def test_dict_chunking(self):
     
    810877                self.assertEqual(num_setitems, 0)
    811878            else:
    812                 self.failUnless(num_setitems >= 2)
     879                self.assertTrue(num_setitems >= 2)
    813880
    814881    def test_simple_newobj(self):
     
    834901
    835902    def test_reduce_overrides_default_reduce_ex(self):
    836         for proto in 0, 1, 2:
     903        for proto in protocols:
    837904            x = REX_one()
    838905            self.assertEqual(x._reduce_called, 0)
     
    843910
    844911    def test_reduce_ex_called(self):
    845         for proto in 0, 1, 2:
     912        for proto in protocols:
    846913            x = REX_two()
    847914            self.assertEqual(x._proto, None)
     
    852919
    853920    def test_reduce_ex_overrides_reduce(self):
    854         for proto in 0, 1, 2:
     921        for proto in protocols:
    855922            x = REX_three()
    856923            self.assertEqual(x._proto, None)
     
    861928
    862929    def test_reduce_ex_calls_base(self):
    863         for proto in 0, 1, 2:
     930        for proto in protocols:
    864931            x = REX_four()
    865932            self.assertEqual(x._proto, None)
     
    870937
    871938    def test_reduce_calls_base(self):
    872         for proto in 0, 1, 2:
     939        for proto in protocols:
    873940            x = REX_five()
    874941            self.assertEqual(x._reduce_called, 0)
     
    891958
    892959        # Protocol 0 is less strict and also accept iterables.
    893         for proto in 0, 1, 2:
     960        for proto in protocols:
    894961            try:
    895962                self.dumps(C(), proto)
     
    901968                pass
    902969
     970    def test_many_puts_and_gets(self):
     971        # Test that internal data structures correctly deal with lots of
     972        # puts/gets.
     973        keys = ("aaa" + str(i) for i in xrange(100))
     974        large_dict = dict((k, [4, 5, 6]) for k in keys)
     975        obj = [dict(large_dict), dict(large_dict), dict(large_dict)]
     976
     977        for proto in protocols:
     978            dumped = self.dumps(obj, proto)
     979            loaded = self.loads(dumped)
     980            self.assertEqual(loaded, obj,
     981                             "Failed protocol %d: %r != %r"
     982                             % (proto, obj, loaded))
     983
     984    def test_attribute_name_interning(self):
     985        # Test that attribute names of pickled objects are interned when
     986        # unpickling.
     987        for proto in protocols:
     988            x = C()
     989            x.foo = 42
     990            x.bar = "hello"
     991            s = self.dumps(x, proto)
     992            y = self.loads(s)
     993            x_keys = sorted(x.__dict__)
     994            y_keys = sorted(y.__dict__)
     995            for x_key, y_key in zip(x_keys, y_keys):
     996                self.assertIs(x_key, y_key)
     997
     998
    903999# Test classes for reduce_ex
    9041000
     
    10021098            os.remove(TESTFN)
    10031099
     1100    def test_load_from_and_dump_to_file(self):
     1101        stream = cStringIO.StringIO()
     1102        data = [123, {}, 124]
     1103        self.module.dump(data, stream)
     1104        stream.seek(0)
     1105        unpickled = self.module.load(stream)
     1106        self.assertEqual(unpickled, data)
     1107
    10041108    def test_highest_protocol(self):
    10051109        # Of course this needs to be changed when HIGHEST_PROTOCOL changes.
     
    10071111
    10081112    def test_callapi(self):
    1009         from cStringIO import StringIO
    1010         f = StringIO()
     1113        f = cStringIO.StringIO()
    10111114        # With and without keyword arguments
    10121115        self.module.dump(123, f, -1)
     
    10741177        self.assertEqual(self.id_count, 5)
    10751178        self.assertEqual(self.load_count, 5)
     1179
     1180class AbstractPicklerUnpicklerObjectTests(unittest.TestCase):
     1181
     1182    pickler_class = None
     1183    unpickler_class = None
     1184
     1185    def setUp(self):
     1186        assert self.pickler_class
     1187        assert self.unpickler_class
     1188
     1189    def test_clear_pickler_memo(self):
     1190        # To test whether clear_memo() has any effect, we pickle an object,
     1191        # then pickle it again without clearing the memo; the two serialized
     1192        # forms should be different. If we clear_memo() and then pickle the
     1193        # object again, the third serialized form should be identical to the
     1194        # first one we obtained.
     1195        data = ["abcdefg", "abcdefg", 44]
     1196        f = cStringIO.StringIO()
     1197        pickler = self.pickler_class(f)
     1198
     1199        pickler.dump(data)
     1200        first_pickled = f.getvalue()
     1201
     1202        # Reset StringIO object.
     1203        f.seek(0)
     1204        f.truncate()
     1205
     1206        pickler.dump(data)
     1207        second_pickled = f.getvalue()
     1208
     1209        # Reset the Pickler and StringIO objects.
     1210        pickler.clear_memo()
     1211        f.seek(0)
     1212        f.truncate()
     1213
     1214        pickler.dump(data)
     1215        third_pickled = f.getvalue()
     1216
     1217        self.assertNotEqual(first_pickled, second_pickled)
     1218        self.assertEqual(first_pickled, third_pickled)
     1219
     1220    def test_priming_pickler_memo(self):
     1221        # Verify that we can set the Pickler's memo attribute.
     1222        data = ["abcdefg", "abcdefg", 44]
     1223        f = cStringIO.StringIO()
     1224        pickler = self.pickler_class(f)
     1225
     1226        pickler.dump(data)
     1227        first_pickled = f.getvalue()
     1228
     1229        f = cStringIO.StringIO()
     1230        primed = self.pickler_class(f)
     1231        primed.memo = pickler.memo
     1232
     1233        primed.dump(data)
     1234        primed_pickled = f.getvalue()
     1235
     1236        self.assertNotEqual(first_pickled, primed_pickled)
     1237
     1238    def test_priming_unpickler_memo(self):
     1239        # Verify that we can set the Unpickler's memo attribute.
     1240        data = ["abcdefg", "abcdefg", 44]
     1241        f = cStringIO.StringIO()
     1242        pickler = self.pickler_class(f)
     1243
     1244        pickler.dump(data)
     1245        first_pickled = f.getvalue()
     1246
     1247        f = cStringIO.StringIO()
     1248        primed = self.pickler_class(f)
     1249        primed.memo = pickler.memo
     1250
     1251        primed.dump(data)
     1252        primed_pickled = f.getvalue()
     1253
     1254        unpickler = self.unpickler_class(cStringIO.StringIO(first_pickled))
     1255        unpickled_data1 = unpickler.load()
     1256
     1257        self.assertEqual(unpickled_data1, data)
     1258
     1259        primed = self.unpickler_class(cStringIO.StringIO(primed_pickled))
     1260        primed.memo = unpickler.memo
     1261        unpickled_data2 = primed.load()
     1262
     1263        primed.memo.clear()
     1264
     1265        self.assertEqual(unpickled_data2, data)
     1266        self.assertTrue(unpickled_data2 is unpickled_data1)
     1267
     1268    def test_reusing_unpickler_objects(self):
     1269        data1 = ["abcdefg", "abcdefg", 44]
     1270        f = cStringIO.StringIO()
     1271        pickler = self.pickler_class(f)
     1272        pickler.dump(data1)
     1273        pickled1 = f.getvalue()
     1274
     1275        data2 = ["abcdefg", 44, 44]
     1276        f = cStringIO.StringIO()
     1277        pickler = self.pickler_class(f)
     1278        pickler.dump(data2)
     1279        pickled2 = f.getvalue()
     1280
     1281        f = cStringIO.StringIO()
     1282        f.write(pickled1)
     1283        f.seek(0)
     1284        unpickler = self.unpickler_class(f)
     1285        self.assertEqual(unpickler.load(), data1)
     1286
     1287        f.seek(0)
     1288        f.truncate()
     1289        f.write(pickled2)
     1290        f.seek(0)
     1291        self.assertEqual(unpickler.load(), data2)
     1292
     1293class BigmemPickleTests(unittest.TestCase):
     1294
     1295    # Memory requirements: 1 byte per character for input strings, 1 byte
     1296    # for pickled data, 1 byte for unpickled strings, 1 byte for internal
     1297    # buffer and 1 byte of free space for resizing of internal buffer.
     1298
     1299    @precisionbigmemtest(size=_2G + 100*_1M, memuse=5)
     1300    def test_huge_strlist(self, size):
     1301        chunksize = 2**20
     1302        data = []
     1303        while size > chunksize:
     1304            data.append('x' * chunksize)
     1305            size -= chunksize
     1306            chunksize += 1
     1307        data.append('y' * size)
     1308
     1309        try:
     1310            for proto in protocols:
     1311                try:
     1312                    pickled = self.dumps(data, proto)
     1313                    res = self.loads(pickled)
     1314                    self.assertEqual(res, data)
     1315                finally:
     1316                    res = None
     1317                    pickled = None
     1318        finally:
     1319            data = None
Note: See TracChangeset for help on using the changeset viewer.