test_pickle.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. from _compat_pickle import (IMPORT_MAPPING, REVERSE_IMPORT_MAPPING,
  2. NAME_MAPPING, REVERSE_NAME_MAPPING)
  3. import builtins
  4. import pickle
  5. import io
  6. import collections
  7. import struct
  8. import sys
  9. import warnings
  10. import weakref
  11. import doctest
  12. import unittest
  13. from test import support
  14. from test.support import import_helper
  15. from test.pickletester import AbstractHookTests
  16. from test.pickletester import AbstractUnpickleTests
  17. from test.pickletester import AbstractPickleTests
  18. from test.pickletester import AbstractPickleModuleTests
  19. from test.pickletester import AbstractPersistentPicklerTests
  20. from test.pickletester import AbstractIdentityPersistentPicklerTests
  21. from test.pickletester import AbstractPicklerUnpicklerObjectTests
  22. from test.pickletester import AbstractDispatchTableTests
  23. from test.pickletester import AbstractCustomPicklerClass
  24. from test.pickletester import BigmemPickleTests
  25. try:
  26. import _pickle
  27. has_c_implementation = True
  28. except ImportError:
  29. has_c_implementation = False
  30. class PyPickleTests(AbstractPickleModuleTests, unittest.TestCase):
  31. dump = staticmethod(pickle._dump)
  32. dumps = staticmethod(pickle._dumps)
  33. load = staticmethod(pickle._load)
  34. loads = staticmethod(pickle._loads)
  35. Pickler = pickle._Pickler
  36. Unpickler = pickle._Unpickler
  37. class PyUnpicklerTests(AbstractUnpickleTests, unittest.TestCase):
  38. unpickler = pickle._Unpickler
  39. bad_stack_errors = (IndexError,)
  40. truncated_errors = (pickle.UnpicklingError, EOFError,
  41. AttributeError, ValueError,
  42. struct.error, IndexError, ImportError)
  43. def loads(self, buf, **kwds):
  44. f = io.BytesIO(buf)
  45. u = self.unpickler(f, **kwds)
  46. return u.load()
  47. class PyPicklerTests(AbstractPickleTests, unittest.TestCase):
  48. pickler = pickle._Pickler
  49. unpickler = pickle._Unpickler
  50. def dumps(self, arg, proto=None, **kwargs):
  51. f = io.BytesIO()
  52. p = self.pickler(f, proto, **kwargs)
  53. p.dump(arg)
  54. f.seek(0)
  55. return bytes(f.read())
  56. def loads(self, buf, **kwds):
  57. f = io.BytesIO(buf)
  58. u = self.unpickler(f, **kwds)
  59. return u.load()
  60. class InMemoryPickleTests(AbstractPickleTests, AbstractUnpickleTests,
  61. BigmemPickleTests, unittest.TestCase):
  62. bad_stack_errors = (pickle.UnpicklingError, IndexError)
  63. truncated_errors = (pickle.UnpicklingError, EOFError,
  64. AttributeError, ValueError,
  65. struct.error, IndexError, ImportError)
  66. def dumps(self, arg, protocol=None, **kwargs):
  67. return pickle.dumps(arg, protocol, **kwargs)
  68. def loads(self, buf, **kwds):
  69. return pickle.loads(buf, **kwds)
  70. test_framed_write_sizes_with_delayed_writer = None
  71. class PersistentPicklerUnpicklerMixin(object):
  72. def dumps(self, arg, proto=None):
  73. class PersPickler(self.pickler):
  74. def persistent_id(subself, obj):
  75. return self.persistent_id(obj)
  76. f = io.BytesIO()
  77. p = PersPickler(f, proto)
  78. p.dump(arg)
  79. return f.getvalue()
  80. def loads(self, buf, **kwds):
  81. class PersUnpickler(self.unpickler):
  82. def persistent_load(subself, obj):
  83. return self.persistent_load(obj)
  84. f = io.BytesIO(buf)
  85. u = PersUnpickler(f, **kwds)
  86. return u.load()
  87. class PyPersPicklerTests(AbstractPersistentPicklerTests,
  88. PersistentPicklerUnpicklerMixin, unittest.TestCase):
  89. pickler = pickle._Pickler
  90. unpickler = pickle._Unpickler
  91. class PyIdPersPicklerTests(AbstractIdentityPersistentPicklerTests,
  92. PersistentPicklerUnpicklerMixin, unittest.TestCase):
  93. pickler = pickle._Pickler
  94. unpickler = pickle._Unpickler
  95. @support.cpython_only
  96. def test_pickler_reference_cycle(self):
  97. def check(Pickler):
  98. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  99. f = io.BytesIO()
  100. pickler = Pickler(f, proto)
  101. pickler.dump('abc')
  102. self.assertEqual(self.loads(f.getvalue()), 'abc')
  103. pickler = Pickler(io.BytesIO())
  104. self.assertEqual(pickler.persistent_id('def'), 'def')
  105. r = weakref.ref(pickler)
  106. del pickler
  107. self.assertIsNone(r())
  108. class PersPickler(self.pickler):
  109. def persistent_id(subself, obj):
  110. return obj
  111. check(PersPickler)
  112. class PersPickler(self.pickler):
  113. @classmethod
  114. def persistent_id(cls, obj):
  115. return obj
  116. check(PersPickler)
  117. class PersPickler(self.pickler):
  118. @staticmethod
  119. def persistent_id(obj):
  120. return obj
  121. check(PersPickler)
  122. @support.cpython_only
  123. def test_custom_pickler_dispatch_table_memleak(self):
  124. # See https://github.com/python/cpython/issues/89988
  125. class Pickler(self.pickler):
  126. def __init__(self, *args, **kwargs):
  127. self.dispatch_table = table
  128. super().__init__(*args, **kwargs)
  129. class DispatchTable:
  130. pass
  131. table = DispatchTable()
  132. pickler = Pickler(io.BytesIO())
  133. self.assertIs(pickler.dispatch_table, table)
  134. table_ref = weakref.ref(table)
  135. self.assertIsNotNone(table_ref())
  136. del pickler
  137. del table
  138. support.gc_collect()
  139. self.assertIsNone(table_ref())
  140. @support.cpython_only
  141. def test_unpickler_reference_cycle(self):
  142. def check(Unpickler):
  143. for proto in range(pickle.HIGHEST_PROTOCOL + 1):
  144. unpickler = Unpickler(io.BytesIO(self.dumps('abc', proto)))
  145. self.assertEqual(unpickler.load(), 'abc')
  146. unpickler = Unpickler(io.BytesIO())
  147. self.assertEqual(unpickler.persistent_load('def'), 'def')
  148. r = weakref.ref(unpickler)
  149. del unpickler
  150. self.assertIsNone(r())
  151. class PersUnpickler(self.unpickler):
  152. def persistent_load(subself, pid):
  153. return pid
  154. check(PersUnpickler)
  155. class PersUnpickler(self.unpickler):
  156. @classmethod
  157. def persistent_load(cls, pid):
  158. return pid
  159. check(PersUnpickler)
  160. class PersUnpickler(self.unpickler):
  161. @staticmethod
  162. def persistent_load(pid):
  163. return pid
  164. check(PersUnpickler)
  165. class PyPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests, unittest.TestCase):
  166. pickler_class = pickle._Pickler
  167. unpickler_class = pickle._Unpickler
  168. class PyDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
  169. pickler_class = pickle._Pickler
  170. def get_dispatch_table(self):
  171. return pickle.dispatch_table.copy()
  172. class PyChainDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
  173. pickler_class = pickle._Pickler
  174. def get_dispatch_table(self):
  175. return collections.ChainMap({}, pickle.dispatch_table)
  176. class PyPicklerHookTests(AbstractHookTests, unittest.TestCase):
  177. class CustomPyPicklerClass(pickle._Pickler,
  178. AbstractCustomPicklerClass):
  179. pass
  180. pickler_class = CustomPyPicklerClass
  181. if has_c_implementation:
  182. class CPickleTests(AbstractPickleModuleTests, unittest.TestCase):
  183. from _pickle import dump, dumps, load, loads, Pickler, Unpickler
  184. class CUnpicklerTests(PyUnpicklerTests):
  185. unpickler = _pickle.Unpickler
  186. bad_stack_errors = (pickle.UnpicklingError,)
  187. truncated_errors = (pickle.UnpicklingError,)
  188. class CPicklerTests(PyPicklerTests):
  189. pickler = _pickle.Pickler
  190. unpickler = _pickle.Unpickler
  191. class CPersPicklerTests(PyPersPicklerTests):
  192. pickler = _pickle.Pickler
  193. unpickler = _pickle.Unpickler
  194. class CIdPersPicklerTests(PyIdPersPicklerTests):
  195. pickler = _pickle.Pickler
  196. unpickler = _pickle.Unpickler
  197. class CDumpPickle_LoadPickle(PyPicklerTests):
  198. pickler = _pickle.Pickler
  199. unpickler = pickle._Unpickler
  200. class DumpPickle_CLoadPickle(PyPicklerTests):
  201. pickler = pickle._Pickler
  202. unpickler = _pickle.Unpickler
  203. class CPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests, unittest.TestCase):
  204. pickler_class = _pickle.Pickler
  205. unpickler_class = _pickle.Unpickler
  206. def test_issue18339(self):
  207. unpickler = self.unpickler_class(io.BytesIO())
  208. with self.assertRaises(TypeError):
  209. unpickler.memo = object
  210. # used to cause a segfault
  211. with self.assertRaises(ValueError):
  212. unpickler.memo = {-1: None}
  213. unpickler.memo = {1: None}
  214. class CDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
  215. pickler_class = pickle.Pickler
  216. def get_dispatch_table(self):
  217. return pickle.dispatch_table.copy()
  218. class CChainDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
  219. pickler_class = pickle.Pickler
  220. def get_dispatch_table(self):
  221. return collections.ChainMap({}, pickle.dispatch_table)
  222. class CPicklerHookTests(AbstractHookTests, unittest.TestCase):
  223. class CustomCPicklerClass(_pickle.Pickler, AbstractCustomPicklerClass):
  224. pass
  225. pickler_class = CustomCPicklerClass
  226. @support.cpython_only
  227. class SizeofTests(unittest.TestCase):
  228. check_sizeof = support.check_sizeof
  229. def test_pickler(self):
  230. basesize = support.calcobjsize('7P2n3i2n3i2P')
  231. p = _pickle.Pickler(io.BytesIO())
  232. self.assertEqual(object.__sizeof__(p), basesize)
  233. MT_size = struct.calcsize('3nP0n')
  234. ME_size = struct.calcsize('Pn0P')
  235. check = self.check_sizeof
  236. check(p, basesize +
  237. MT_size + 8 * ME_size + # Minimal memo table size.
  238. sys.getsizeof(b'x'*4096)) # Minimal write buffer size.
  239. for i in range(6):
  240. p.dump(chr(i))
  241. check(p, basesize +
  242. MT_size + 32 * ME_size + # Size of memo table required to
  243. # save references to 6 objects.
  244. 0) # Write buffer is cleared after every dump().
  245. def test_unpickler(self):
  246. basesize = support.calcobjsize('2P2n2P 2P2n2i5P 2P3n8P2n2i')
  247. unpickler = _pickle.Unpickler
  248. P = struct.calcsize('P') # Size of memo table entry.
  249. n = struct.calcsize('n') # Size of mark table entry.
  250. check = self.check_sizeof
  251. for encoding in 'ASCII', 'UTF-16', 'latin-1':
  252. for errors in 'strict', 'replace':
  253. u = unpickler(io.BytesIO(),
  254. encoding=encoding, errors=errors)
  255. self.assertEqual(object.__sizeof__(u), basesize)
  256. check(u, basesize +
  257. 32 * P + # Minimal memo table size.
  258. len(encoding) + 1 + len(errors) + 1)
  259. stdsize = basesize + len('ASCII') + 1 + len('strict') + 1
  260. def check_unpickler(data, memo_size, marks_size):
  261. dump = pickle.dumps(data)
  262. u = unpickler(io.BytesIO(dump),
  263. encoding='ASCII', errors='strict')
  264. u.load()
  265. check(u, stdsize + memo_size * P + marks_size * n)
  266. check_unpickler(0, 32, 0)
  267. # 20 is minimal non-empty mark stack size.
  268. check_unpickler([0] * 100, 32, 20)
  269. # 128 is memo table size required to save references to 100 objects.
  270. check_unpickler([chr(i) for i in range(100)], 128, 20)
  271. def recurse(deep):
  272. data = 0
  273. for i in range(deep):
  274. data = [data, data]
  275. return data
  276. check_unpickler(recurse(0), 32, 0)
  277. check_unpickler(recurse(1), 32, 20)
  278. check_unpickler(recurse(20), 32, 20)
  279. check_unpickler(recurse(50), 64, 60)
  280. check_unpickler(recurse(100), 128, 140)
  281. u = unpickler(io.BytesIO(pickle.dumps('a', 0)),
  282. encoding='ASCII', errors='strict')
  283. u.load()
  284. check(u, stdsize + 32 * P + 2 + 1)
  285. ALT_IMPORT_MAPPING = {
  286. ('_elementtree', 'xml.etree.ElementTree'),
  287. ('cPickle', 'pickle'),
  288. ('StringIO', 'io'),
  289. ('cStringIO', 'io'),
  290. }
  291. ALT_NAME_MAPPING = {
  292. ('__builtin__', 'basestring', 'builtins', 'str'),
  293. ('exceptions', 'StandardError', 'builtins', 'Exception'),
  294. ('UserDict', 'UserDict', 'collections', 'UserDict'),
  295. ('socket', '_socketobject', 'socket', 'SocketType'),
  296. }
  297. def mapping(module, name):
  298. if (module, name) in NAME_MAPPING:
  299. module, name = NAME_MAPPING[(module, name)]
  300. elif module in IMPORT_MAPPING:
  301. module = IMPORT_MAPPING[module]
  302. return module, name
  303. def reverse_mapping(module, name):
  304. if (module, name) in REVERSE_NAME_MAPPING:
  305. module, name = REVERSE_NAME_MAPPING[(module, name)]
  306. elif module in REVERSE_IMPORT_MAPPING:
  307. module = REVERSE_IMPORT_MAPPING[module]
  308. return module, name
  309. def getmodule(module):
  310. try:
  311. return sys.modules[module]
  312. except KeyError:
  313. try:
  314. with warnings.catch_warnings():
  315. action = 'always' if support.verbose else 'ignore'
  316. warnings.simplefilter(action, DeprecationWarning)
  317. __import__(module)
  318. except AttributeError as exc:
  319. if support.verbose:
  320. print("Can't import module %r: %s" % (module, exc))
  321. raise ImportError
  322. except ImportError as exc:
  323. if support.verbose:
  324. print(exc)
  325. raise
  326. return sys.modules[module]
  327. def getattribute(module, name):
  328. obj = getmodule(module)
  329. for n in name.split('.'):
  330. obj = getattr(obj, n)
  331. return obj
  332. def get_exceptions(mod):
  333. for name in dir(mod):
  334. attr = getattr(mod, name)
  335. if isinstance(attr, type) and issubclass(attr, BaseException):
  336. yield name, attr
  337. class CompatPickleTests(unittest.TestCase):
  338. def test_import(self):
  339. modules = set(IMPORT_MAPPING.values())
  340. modules |= set(REVERSE_IMPORT_MAPPING)
  341. modules |= {module for module, name in REVERSE_NAME_MAPPING}
  342. modules |= {module for module, name in NAME_MAPPING.values()}
  343. for module in modules:
  344. try:
  345. getmodule(module)
  346. except ImportError:
  347. pass
  348. def test_import_mapping(self):
  349. for module3, module2 in REVERSE_IMPORT_MAPPING.items():
  350. with self.subTest((module3, module2)):
  351. try:
  352. getmodule(module3)
  353. except ImportError:
  354. pass
  355. if module3[:1] != '_':
  356. self.assertIn(module2, IMPORT_MAPPING)
  357. self.assertEqual(IMPORT_MAPPING[module2], module3)
  358. def test_name_mapping(self):
  359. for (module3, name3), (module2, name2) in REVERSE_NAME_MAPPING.items():
  360. with self.subTest(((module3, name3), (module2, name2))):
  361. if (module2, name2) == ('exceptions', 'OSError'):
  362. attr = getattribute(module3, name3)
  363. self.assertTrue(issubclass(attr, OSError))
  364. elif (module2, name2) == ('exceptions', 'ImportError'):
  365. attr = getattribute(module3, name3)
  366. self.assertTrue(issubclass(attr, ImportError))
  367. else:
  368. module, name = mapping(module2, name2)
  369. if module3[:1] != '_':
  370. self.assertEqual((module, name), (module3, name3))
  371. try:
  372. attr = getattribute(module3, name3)
  373. except ImportError:
  374. pass
  375. else:
  376. self.assertEqual(getattribute(module, name), attr)
  377. def test_reverse_import_mapping(self):
  378. for module2, module3 in IMPORT_MAPPING.items():
  379. with self.subTest((module2, module3)):
  380. try:
  381. getmodule(module3)
  382. except ImportError as exc:
  383. if support.verbose:
  384. print(exc)
  385. if ((module2, module3) not in ALT_IMPORT_MAPPING and
  386. REVERSE_IMPORT_MAPPING.get(module3, None) != module2):
  387. for (m3, n3), (m2, n2) in REVERSE_NAME_MAPPING.items():
  388. if (module3, module2) == (m3, m2):
  389. break
  390. else:
  391. self.fail('No reverse mapping from %r to %r' %
  392. (module3, module2))
  393. module = REVERSE_IMPORT_MAPPING.get(module3, module3)
  394. module = IMPORT_MAPPING.get(module, module)
  395. self.assertEqual(module, module3)
  396. def test_reverse_name_mapping(self):
  397. for (module2, name2), (module3, name3) in NAME_MAPPING.items():
  398. with self.subTest(((module2, name2), (module3, name3))):
  399. try:
  400. attr = getattribute(module3, name3)
  401. except ImportError:
  402. pass
  403. module, name = reverse_mapping(module3, name3)
  404. if (module2, name2, module3, name3) not in ALT_NAME_MAPPING:
  405. self.assertEqual((module, name), (module2, name2))
  406. module, name = mapping(module, name)
  407. self.assertEqual((module, name), (module3, name3))
  408. def test_exceptions(self):
  409. self.assertEqual(mapping('exceptions', 'StandardError'),
  410. ('builtins', 'Exception'))
  411. self.assertEqual(mapping('exceptions', 'Exception'),
  412. ('builtins', 'Exception'))
  413. self.assertEqual(reverse_mapping('builtins', 'Exception'),
  414. ('exceptions', 'Exception'))
  415. self.assertEqual(mapping('exceptions', 'OSError'),
  416. ('builtins', 'OSError'))
  417. self.assertEqual(reverse_mapping('builtins', 'OSError'),
  418. ('exceptions', 'OSError'))
  419. for name, exc in get_exceptions(builtins):
  420. with self.subTest(name):
  421. if exc in (BlockingIOError,
  422. ResourceWarning,
  423. StopAsyncIteration,
  424. RecursionError,
  425. EncodingWarning,
  426. BaseExceptionGroup,
  427. ExceptionGroup):
  428. continue
  429. if exc is not OSError and issubclass(exc, OSError):
  430. self.assertEqual(reverse_mapping('builtins', name),
  431. ('exceptions', 'OSError'))
  432. elif exc is not ImportError and issubclass(exc, ImportError):
  433. self.assertEqual(reverse_mapping('builtins', name),
  434. ('exceptions', 'ImportError'))
  435. self.assertEqual(mapping('exceptions', name),
  436. ('exceptions', name))
  437. else:
  438. self.assertEqual(reverse_mapping('builtins', name),
  439. ('exceptions', name))
  440. self.assertEqual(mapping('exceptions', name),
  441. ('builtins', name))
  442. def test_multiprocessing_exceptions(self):
  443. module = import_helper.import_module('multiprocessing.context')
  444. for name, exc in get_exceptions(module):
  445. with self.subTest(name):
  446. self.assertEqual(reverse_mapping('multiprocessing.context', name),
  447. ('multiprocessing', name))
  448. self.assertEqual(mapping('multiprocessing', name),
  449. ('multiprocessing.context', name))
  450. def load_tests(loader, tests, pattern):
  451. tests.addTest(doctest.DocTestSuite())
  452. return tests
  453. if __name__ == "__main__":
  454. unittest.main()