mirror of
https://github.com/python/cpython.git
synced 2024-12-25 09:44:37 +08:00
f416981691
for bytes. This is the default protocol. It intentionally cannot be unpickled by Python 2.x. - When a pickle written by Python 2.x contains an (8-bit) str instance, this is now decoded to a (Unicode) str instance. The encoding used to do this defaults to ASCII, but can be overridden via two new keyword arguments to the Unpickler class. Previously this would create bytes instances, which is usually wrong: str instances are often used to pickle attribute names etc., and text is more common than binary data anyway.
67 lines
1.6 KiB
Python
67 lines
1.6 KiB
Python
import pickle
|
|
import io
|
|
|
|
from test import test_support
|
|
|
|
from test.pickletester import AbstractPickleTests
|
|
from test.pickletester import AbstractPickleModuleTests
|
|
from test.pickletester import AbstractPersistentPicklerTests
|
|
|
|
class PickleTests(AbstractPickleTests, AbstractPickleModuleTests):
|
|
|
|
module = pickle
|
|
error = KeyError
|
|
|
|
def dumps(self, arg, proto=None):
|
|
return pickle.dumps(arg, proto)
|
|
|
|
def loads(self, buf):
|
|
return pickle.loads(buf)
|
|
|
|
class PicklerTests(AbstractPickleTests):
|
|
|
|
error = KeyError
|
|
|
|
def dumps(self, arg, proto=None):
|
|
f = io.BytesIO()
|
|
p = pickle.Pickler(f, proto)
|
|
p.dump(arg)
|
|
f.seek(0)
|
|
return bytes(f.read())
|
|
|
|
def loads(self, buf):
|
|
f = io.BytesIO(buf)
|
|
u = pickle.Unpickler(f)
|
|
return u.load()
|
|
|
|
class PersPicklerTests(AbstractPersistentPicklerTests):
|
|
|
|
def dumps(self, arg, proto=None):
|
|
class PersPickler(pickle.Pickler):
|
|
def persistent_id(subself, obj):
|
|
return self.persistent_id(obj)
|
|
f = io.BytesIO()
|
|
p = PersPickler(f, proto)
|
|
p.dump(arg)
|
|
f.seek(0)
|
|
return f.read()
|
|
|
|
def loads(self, buf):
|
|
class PersUnpickler(pickle.Unpickler):
|
|
def persistent_load(subself, obj):
|
|
return self.persistent_load(obj)
|
|
f = io.BytesIO(buf)
|
|
u = PersUnpickler(f)
|
|
return u.load()
|
|
|
|
def test_main():
|
|
test_support.run_unittest(
|
|
PickleTests,
|
|
PicklerTests,
|
|
PersPicklerTests
|
|
)
|
|
test_support.run_doctest(pickle)
|
|
|
|
if __name__ == "__main__":
|
|
test_main()
|