blob: 8775ff4b79157df93156b142f08db4c36ed39499 [file] [log] [blame]
Serhiy Storchakabfe18242015-03-31 13:12:37 +03001from _compat_pickle import (IMPORT_MAPPING, REVERSE_IMPORT_MAPPING,
2 NAME_MAPPING, REVERSE_NAME_MAPPING)
3import builtins
Jeremy Hyltonbe467e52000-09-15 15:14:51 +00004import pickle
Guido van Rossumcfe5f202007-05-08 21:26:54 +00005import io
Antoine Pitrou8d3c2902012-03-04 18:31:48 +01006import collections
Serhiy Storchaka5bbd2312014-12-16 19:39:08 +02007import struct
8import sys
Miss Islington (bot)aa726682021-08-02 10:09:05 -07009import warnings
Serhiy Storchaka986375e2017-11-30 22:48:31 +020010import weakref
Tim Peters47a6b132003-01-28 22:34:11 +000011
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -070012import doctest
Serhiy Storchaka5bbd2312014-12-16 19:39:08 +020013import unittest
Benjamin Petersonee8712c2008-05-20 21:35:26 +000014from test import support
Hai Shi883bc632020-07-06 17:12:49 +080015from test.support import import_helper
Jeremy Hylton66426532001-10-15 21:38:56 +000016
Pierre Glaser289f1f82019-05-08 23:08:25 +020017from test.pickletester import AbstractHookTests
Serhiy Storchakac6b54b42015-09-29 15:33:24 +030018from test.pickletester import AbstractUnpickleTests
Tim Peters47a6b132003-01-28 22:34:11 +000019from test.pickletester import AbstractPickleTests
Tim Peters47a6b132003-01-28 22:34:11 +000020from test.pickletester import AbstractPickleModuleTests
21from test.pickletester import AbstractPersistentPicklerTests
Serhiy Storchakadec25af2016-07-17 11:24:17 +030022from test.pickletester import AbstractIdentityPersistentPicklerTests
Collin Winter771d8342009-04-16 03:18:06 +000023from test.pickletester import AbstractPicklerUnpicklerObjectTests
Antoine Pitrou8d3c2902012-03-04 18:31:48 +010024from test.pickletester import AbstractDispatchTableTests
Pierre Glaser289f1f82019-05-08 23:08:25 +020025from test.pickletester import AbstractCustomPicklerClass
Antoine Pitrou82be19f2011-08-29 23:09:33 +020026from test.pickletester import BigmemPickleTests
Tim Peters47a6b132003-01-28 22:34:11 +000027
Alexandre Vassalottica2d6102008-06-12 18:26:05 +000028try:
29 import _pickle
30 has_c_implementation = True
31except ImportError:
32 has_c_implementation = False
Jeremy Hylton66426532001-10-15 21:38:56 +000033
Guido van Rossum98297ee2007-11-06 21:34:58 +000034
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -070035class PyPickleTests(AbstractPickleModuleTests, unittest.TestCase):
Serhiy Storchaka65452562017-11-15 14:01:08 +020036 dump = staticmethod(pickle._dump)
37 dumps = staticmethod(pickle._dumps)
38 load = staticmethod(pickle._load)
39 loads = staticmethod(pickle._loads)
40 Pickler = pickle._Pickler
41 Unpickler = pickle._Unpickler
Guido van Rossum5d9113d2003-01-29 17:58:45 +000042
Tim Peterse0c446b2001-10-18 21:57:37 +000043
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -070044class PyUnpicklerTests(AbstractUnpickleTests, unittest.TestCase):
Serhiy Storchakac6b54b42015-09-29 15:33:24 +030045
46 unpickler = pickle._Unpickler
Serhiy Storchakae9b30742015-11-23 15:17:43 +020047 bad_stack_errors = (IndexError,)
Serhiy Storchaka7279bef2015-11-29 13:12:10 +020048 truncated_errors = (pickle.UnpicklingError, EOFError,
49 AttributeError, ValueError,
50 struct.error, IndexError, ImportError)
Serhiy Storchakac6b54b42015-09-29 15:33:24 +030051
52 def loads(self, buf, **kwds):
53 f = io.BytesIO(buf)
54 u = self.unpickler(f, **kwds)
55 return u.load()
56
57
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -070058class PyPicklerTests(AbstractPickleTests, unittest.TestCase):
Jeremy Hylton66426532001-10-15 21:38:56 +000059
Alexandre Vassalottica2d6102008-06-12 18:26:05 +000060 pickler = pickle._Pickler
61 unpickler = pickle._Unpickler
Jeremy Hylton66426532001-10-15 21:38:56 +000062
Antoine Pitrou91f43802019-05-26 17:10:09 +020063 def dumps(self, arg, proto=None, **kwargs):
Guido van Rossumcfe5f202007-05-08 21:26:54 +000064 f = io.BytesIO()
Antoine Pitrou91f43802019-05-26 17:10:09 +020065 p = self.pickler(f, proto, **kwargs)
Jeremy Hylton66426532001-10-15 21:38:56 +000066 p.dump(arg)
67 f.seek(0)
Guido van Rossumcfe5f202007-05-08 21:26:54 +000068 return bytes(f.read())
Jeremy Hylton66426532001-10-15 21:38:56 +000069
Alexander Belopolskyec8f0df2011-02-24 20:34:38 +000070 def loads(self, buf, **kwds):
Guido van Rossumcfe5f202007-05-08 21:26:54 +000071 f = io.BytesIO(buf)
Alexander Belopolskyec8f0df2011-02-24 20:34:38 +000072 u = self.unpickler(f, **kwds)
Jeremy Hylton66426532001-10-15 21:38:56 +000073 return u.load()
74
Alexandre Vassalottica2d6102008-06-12 18:26:05 +000075
Serhiy Storchakac6b54b42015-09-29 15:33:24 +030076class InMemoryPickleTests(AbstractPickleTests, AbstractUnpickleTests,
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -070077 BigmemPickleTests, unittest.TestCase):
Antoine Pitrouea99c5c2010-09-09 18:33:21 +000078
Serhiy Storchakae9b30742015-11-23 15:17:43 +020079 bad_stack_errors = (pickle.UnpicklingError, IndexError)
Serhiy Storchaka7279bef2015-11-29 13:12:10 +020080 truncated_errors = (pickle.UnpicklingError, EOFError,
81 AttributeError, ValueError,
82 struct.error, IndexError, ImportError)
Antoine Pitrouea99c5c2010-09-09 18:33:21 +000083
Antoine Pitrou91f43802019-05-26 17:10:09 +020084 def dumps(self, arg, protocol=None, **kwargs):
85 return pickle.dumps(arg, protocol, **kwargs)
Antoine Pitrouea99c5c2010-09-09 18:33:21 +000086
Alexander Belopolskyec8f0df2011-02-24 20:34:38 +000087 def loads(self, buf, **kwds):
88 return pickle.loads(buf, **kwds)
Antoine Pitrouea99c5c2010-09-09 18:33:21 +000089
Serhiy Storchaka0a2da502018-01-11 13:03:20 +020090 test_framed_write_sizes_with_delayed_writer = None
91
Antoine Pitrouea99c5c2010-09-09 18:33:21 +000092
Serhiy Storchakadec25af2016-07-17 11:24:17 +030093class PersistentPicklerUnpicklerMixin(object):
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +000094
Guido van Rossumf4169812008-03-17 22:56:06 +000095 def dumps(self, arg, proto=None):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +000096 class PersPickler(self.pickler):
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +000097 def persistent_id(subself, obj):
98 return self.persistent_id(obj)
Guido van Rossumcfe5f202007-05-08 21:26:54 +000099 f = io.BytesIO()
Guido van Rossum9d32bb12003-01-28 03:51:53 +0000100 p = PersPickler(f, proto)
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000101 p.dump(arg)
Serhiy Storchakadec25af2016-07-17 11:24:17 +0300102 return f.getvalue()
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000103
Alexander Belopolskyec8f0df2011-02-24 20:34:38 +0000104 def loads(self, buf, **kwds):
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000105 class PersUnpickler(self.unpickler):
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000106 def persistent_load(subself, obj):
107 return self.persistent_load(obj)
Guido van Rossumcfe5f202007-05-08 21:26:54 +0000108 f = io.BytesIO(buf)
Alexander Belopolskyec8f0df2011-02-24 20:34:38 +0000109 u = PersUnpickler(f, **kwds)
Jeremy Hylton5e0f4e72002-11-13 22:01:27 +0000110 return u.load()
111
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000112
Serhiy Storchakadec25af2016-07-17 11:24:17 +0300113class PyPersPicklerTests(AbstractPersistentPicklerTests,
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700114 PersistentPicklerUnpicklerMixin, unittest.TestCase):
Serhiy Storchakadec25af2016-07-17 11:24:17 +0300115
116 pickler = pickle._Pickler
117 unpickler = pickle._Unpickler
118
119
120class PyIdPersPicklerTests(AbstractIdentityPersistentPicklerTests,
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700121 PersistentPicklerUnpicklerMixin, unittest.TestCase):
Serhiy Storchakadec25af2016-07-17 11:24:17 +0300122
123 pickler = pickle._Pickler
124 unpickler = pickle._Unpickler
125
Serhiy Storchaka986375e2017-11-30 22:48:31 +0200126 @support.cpython_only
127 def test_pickler_reference_cycle(self):
128 def check(Pickler):
129 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
130 f = io.BytesIO()
131 pickler = Pickler(f, proto)
132 pickler.dump('abc')
133 self.assertEqual(self.loads(f.getvalue()), 'abc')
134 pickler = Pickler(io.BytesIO())
135 self.assertEqual(pickler.persistent_id('def'), 'def')
136 r = weakref.ref(pickler)
137 del pickler
138 self.assertIsNone(r())
139
140 class PersPickler(self.pickler):
141 def persistent_id(subself, obj):
142 return obj
143 check(PersPickler)
144
145 class PersPickler(self.pickler):
146 @classmethod
147 def persistent_id(cls, obj):
148 return obj
149 check(PersPickler)
150
151 class PersPickler(self.pickler):
152 @staticmethod
153 def persistent_id(obj):
154 return obj
155 check(PersPickler)
156
157 @support.cpython_only
158 def test_unpickler_reference_cycle(self):
159 def check(Unpickler):
160 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
161 unpickler = Unpickler(io.BytesIO(self.dumps('abc', proto)))
162 self.assertEqual(unpickler.load(), 'abc')
163 unpickler = Unpickler(io.BytesIO())
164 self.assertEqual(unpickler.persistent_load('def'), 'def')
165 r = weakref.ref(unpickler)
166 del unpickler
167 self.assertIsNone(r())
168
169 class PersUnpickler(self.unpickler):
170 def persistent_load(subself, pid):
171 return pid
172 check(PersUnpickler)
173
174 class PersUnpickler(self.unpickler):
175 @classmethod
176 def persistent_load(cls, pid):
177 return pid
178 check(PersUnpickler)
179
180 class PersUnpickler(self.unpickler):
181 @staticmethod
182 def persistent_load(pid):
183 return pid
184 check(PersUnpickler)
185
Serhiy Storchakadec25af2016-07-17 11:24:17 +0300186
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700187class PyPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests, unittest.TestCase):
Collin Winter771d8342009-04-16 03:18:06 +0000188
189 pickler_class = pickle._Pickler
190 unpickler_class = pickle._Unpickler
191
192
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700193class PyDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800194
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100195 pickler_class = pickle._Pickler
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800196
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100197 def get_dispatch_table(self):
198 return pickle.dispatch_table.copy()
199
200
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700201class PyChainDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800202
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100203 pickler_class = pickle._Pickler
Alexandre Vassalottid05c9ff2013-12-07 01:09:27 -0800204
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100205 def get_dispatch_table(self):
206 return collections.ChainMap({}, pickle.dispatch_table)
207
208
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700209class PyPicklerHookTests(AbstractHookTests, unittest.TestCase):
Victor Stinner63ab4ba2019-06-13 13:58:51 +0200210 class CustomPyPicklerClass(pickle._Pickler,
211 AbstractCustomPicklerClass):
212 pass
213 pickler_class = CustomPyPicklerClass
214
215
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000216if has_c_implementation:
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700217 class CPickleTests(AbstractPickleModuleTests, unittest.TestCase):
Serhiy Storchaka65452562017-11-15 14:01:08 +0200218 from _pickle import dump, dumps, load, loads, Pickler, Unpickler
219
Serhiy Storchakac6b54b42015-09-29 15:33:24 +0300220 class CUnpicklerTests(PyUnpicklerTests):
221 unpickler = _pickle.Unpickler
Serhiy Storchakae9b30742015-11-23 15:17:43 +0200222 bad_stack_errors = (pickle.UnpicklingError,)
Serhiy Storchaka90493ab2016-09-06 23:55:11 +0300223 truncated_errors = (pickle.UnpicklingError,)
Serhiy Storchakac6b54b42015-09-29 15:33:24 +0300224
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000225 class CPicklerTests(PyPicklerTests):
226 pickler = _pickle.Pickler
227 unpickler = _pickle.Unpickler
228
229 class CPersPicklerTests(PyPersPicklerTests):
230 pickler = _pickle.Pickler
231 unpickler = _pickle.Unpickler
232
Serhiy Storchakadec25af2016-07-17 11:24:17 +0300233 class CIdPersPicklerTests(PyIdPersPicklerTests):
234 pickler = _pickle.Pickler
235 unpickler = _pickle.Unpickler
236
Collin Winter771d8342009-04-16 03:18:06 +0000237 class CDumpPickle_LoadPickle(PyPicklerTests):
238 pickler = _pickle.Pickler
239 unpickler = pickle._Unpickler
240
241 class DumpPickle_CLoadPickle(PyPicklerTests):
242 pickler = pickle._Pickler
243 unpickler = _pickle.Unpickler
244
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700245 class CPicklerUnpicklerObjectTests(AbstractPicklerUnpicklerObjectTests, unittest.TestCase):
Collin Winter771d8342009-04-16 03:18:06 +0000246 pickler_class = _pickle.Pickler
247 unpickler_class = _pickle.Unpickler
248
Christian Heimesa24b4d22013-07-01 15:17:45 +0200249 def test_issue18339(self):
250 unpickler = self.unpickler_class(io.BytesIO())
Christian Heimes21782482013-07-01 23:00:13 +0200251 with self.assertRaises(TypeError):
252 unpickler.memo = object
Christian Heimesa24b4d22013-07-01 15:17:45 +0200253 # used to cause a segfault
Christian Heimes21782482013-07-01 23:00:13 +0200254 with self.assertRaises(ValueError):
255 unpickler.memo = {-1: None}
Christian Heimesa24b4d22013-07-01 15:17:45 +0200256 unpickler.memo = {1: None}
257
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700258 class CDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100259 pickler_class = pickle.Pickler
260 def get_dispatch_table(self):
261 return pickle.dispatch_table.copy()
262
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700263 class CChainDispatchTableTests(AbstractDispatchTableTests, unittest.TestCase):
Antoine Pitrou8d3c2902012-03-04 18:31:48 +0100264 pickler_class = pickle.Pickler
265 def get_dispatch_table(self):
266 return collections.ChainMap({}, pickle.dispatch_table)
267
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700268 class CPicklerHookTests(AbstractHookTests, unittest.TestCase):
Pierre Glaser289f1f82019-05-08 23:08:25 +0200269 class CustomCPicklerClass(_pickle.Pickler, AbstractCustomPicklerClass):
270 pass
271 pickler_class = CustomCPicklerClass
272
Serhiy Storchaka5bbd2312014-12-16 19:39:08 +0200273 @support.cpython_only
274 class SizeofTests(unittest.TestCase):
275 check_sizeof = support.check_sizeof
276
277 def test_pickler(self):
Antoine Pitrou91f43802019-05-26 17:10:09 +0200278 basesize = support.calcobjsize('7P2n3i2n3i2P')
Serhiy Storchaka5bbd2312014-12-16 19:39:08 +0200279 p = _pickle.Pickler(io.BytesIO())
280 self.assertEqual(object.__sizeof__(p), basesize)
281 MT_size = struct.calcsize('3nP0n')
282 ME_size = struct.calcsize('Pn0P')
283 check = self.check_sizeof
284 check(p, basesize +
285 MT_size + 8 * ME_size + # Minimal memo table size.
286 sys.getsizeof(b'x'*4096)) # Minimal write buffer size.
287 for i in range(6):
288 p.dump(chr(i))
289 check(p, basesize +
290 MT_size + 32 * ME_size + # Size of memo table required to
291 # save references to 6 objects.
292 0) # Write buffer is cleared after every dump().
293
294 def test_unpickler(self):
Antoine Pitrou91f43802019-05-26 17:10:09 +0200295 basesize = support.calcobjsize('2P2n2P 2P2n2i5P 2P3n8P2n2i')
Serhiy Storchaka5bbd2312014-12-16 19:39:08 +0200296 unpickler = _pickle.Unpickler
297 P = struct.calcsize('P') # Size of memo table entry.
298 n = struct.calcsize('n') # Size of mark table entry.
299 check = self.check_sizeof
300 for encoding in 'ASCII', 'UTF-16', 'latin-1':
301 for errors in 'strict', 'replace':
302 u = unpickler(io.BytesIO(),
303 encoding=encoding, errors=errors)
304 self.assertEqual(object.__sizeof__(u), basesize)
305 check(u, basesize +
306 32 * P + # Minimal memo table size.
307 len(encoding) + 1 + len(errors) + 1)
308
309 stdsize = basesize + len('ASCII') + 1 + len('strict') + 1
310 def check_unpickler(data, memo_size, marks_size):
311 dump = pickle.dumps(data)
312 u = unpickler(io.BytesIO(dump),
313 encoding='ASCII', errors='strict')
314 u.load()
315 check(u, stdsize + memo_size * P + marks_size * n)
316
317 check_unpickler(0, 32, 0)
318 # 20 is minimal non-empty mark stack size.
319 check_unpickler([0] * 100, 32, 20)
320 # 128 is memo table size required to save references to 100 objects.
321 check_unpickler([chr(i) for i in range(100)], 128, 20)
322 def recurse(deep):
323 data = 0
324 for i in range(deep):
325 data = [data, data]
326 return data
327 check_unpickler(recurse(0), 32, 0)
328 check_unpickler(recurse(1), 32, 20)
Sergey Fedoseev86b89912018-08-25 12:54:40 +0500329 check_unpickler(recurse(20), 32, 20)
330 check_unpickler(recurse(50), 64, 60)
331 check_unpickler(recurse(100), 128, 140)
Serhiy Storchaka5bbd2312014-12-16 19:39:08 +0200332
333 u = unpickler(io.BytesIO(pickle.dumps('a', 0)),
334 encoding='ASCII', errors='strict')
335 u.load()
336 check(u, stdsize + 32 * P + 2 + 1)
337
Alexandre Vassalottica2d6102008-06-12 18:26:05 +0000338
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300339ALT_IMPORT_MAPPING = {
340 ('_elementtree', 'xml.etree.ElementTree'),
341 ('cPickle', 'pickle'),
Serhiy Storchaka5c1d9d22016-01-18 22:33:44 +0200342 ('StringIO', 'io'),
343 ('cStringIO', 'io'),
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300344}
345
346ALT_NAME_MAPPING = {
347 ('__builtin__', 'basestring', 'builtins', 'str'),
348 ('exceptions', 'StandardError', 'builtins', 'Exception'),
349 ('UserDict', 'UserDict', 'collections', 'UserDict'),
350 ('socket', '_socketobject', 'socket', 'SocketType'),
351}
352
353def mapping(module, name):
354 if (module, name) in NAME_MAPPING:
355 module, name = NAME_MAPPING[(module, name)]
356 elif module in IMPORT_MAPPING:
357 module = IMPORT_MAPPING[module]
358 return module, name
359
360def reverse_mapping(module, name):
361 if (module, name) in REVERSE_NAME_MAPPING:
362 module, name = REVERSE_NAME_MAPPING[(module, name)]
363 elif module in REVERSE_IMPORT_MAPPING:
364 module = REVERSE_IMPORT_MAPPING[module]
365 return module, name
366
367def getmodule(module):
368 try:
369 return sys.modules[module]
370 except KeyError:
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300371 try:
Miss Islington (bot)aa726682021-08-02 10:09:05 -0700372 with warnings.catch_warnings():
373 action = 'always' if support.verbose else 'ignore'
374 warnings.simplefilter(action, DeprecationWarning)
375 __import__(module)
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300376 except AttributeError as exc:
377 if support.verbose:
378 print("Can't import module %r: %s" % (module, exc))
379 raise ImportError
380 except ImportError as exc:
381 if support.verbose:
382 print(exc)
383 raise
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300384 return sys.modules[module]
385
386def getattribute(module, name):
387 obj = getmodule(module)
388 for n in name.split('.'):
389 obj = getattr(obj, n)
390 return obj
391
392def get_exceptions(mod):
393 for name in dir(mod):
394 attr = getattr(mod, name)
395 if isinstance(attr, type) and issubclass(attr, BaseException):
396 yield name, attr
397
398class CompatPickleTests(unittest.TestCase):
399 def test_import(self):
400 modules = set(IMPORT_MAPPING.values())
401 modules |= set(REVERSE_IMPORT_MAPPING)
402 modules |= {module for module, name in REVERSE_NAME_MAPPING}
403 modules |= {module for module, name in NAME_MAPPING.values()}
404 for module in modules:
405 try:
406 getmodule(module)
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300407 except ImportError:
408 pass
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300409
410 def test_import_mapping(self):
411 for module3, module2 in REVERSE_IMPORT_MAPPING.items():
412 with self.subTest((module3, module2)):
413 try:
414 getmodule(module3)
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300415 except ImportError:
416 pass
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300417 if module3[:1] != '_':
418 self.assertIn(module2, IMPORT_MAPPING)
419 self.assertEqual(IMPORT_MAPPING[module2], module3)
420
421 def test_name_mapping(self):
422 for (module3, name3), (module2, name2) in REVERSE_NAME_MAPPING.items():
423 with self.subTest(((module3, name3), (module2, name2))):
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300424 if (module2, name2) == ('exceptions', 'OSError'):
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300425 attr = getattribute(module3, name3)
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300426 self.assertTrue(issubclass(attr, OSError))
Eric Snowc9432652016-09-07 15:42:32 -0700427 elif (module2, name2) == ('exceptions', 'ImportError'):
428 attr = getattribute(module3, name3)
429 self.assertTrue(issubclass(attr, ImportError))
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300430 else:
431 module, name = mapping(module2, name2)
432 if module3[:1] != '_':
433 self.assertEqual((module, name), (module3, name3))
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300434 try:
435 attr = getattribute(module3, name3)
436 except ImportError:
437 pass
438 else:
439 self.assertEqual(getattribute(module, name), attr)
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300440
441 def test_reverse_import_mapping(self):
442 for module2, module3 in IMPORT_MAPPING.items():
443 with self.subTest((module2, module3)):
444 try:
445 getmodule(module3)
446 except ImportError as exc:
447 if support.verbose:
448 print(exc)
449 if ((module2, module3) not in ALT_IMPORT_MAPPING and
450 REVERSE_IMPORT_MAPPING.get(module3, None) != module2):
451 for (m3, n3), (m2, n2) in REVERSE_NAME_MAPPING.items():
452 if (module3, module2) == (m3, m2):
453 break
454 else:
455 self.fail('No reverse mapping from %r to %r' %
456 (module3, module2))
457 module = REVERSE_IMPORT_MAPPING.get(module3, module3)
458 module = IMPORT_MAPPING.get(module, module)
459 self.assertEqual(module, module3)
460
461 def test_reverse_name_mapping(self):
462 for (module2, name2), (module3, name3) in NAME_MAPPING.items():
463 with self.subTest(((module2, name2), (module3, name3))):
Serhiy Storchakab9100e52015-03-31 16:49:26 +0300464 try:
465 attr = getattribute(module3, name3)
466 except ImportError:
467 pass
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300468 module, name = reverse_mapping(module3, name3)
469 if (module2, name2, module3, name3) not in ALT_NAME_MAPPING:
470 self.assertEqual((module, name), (module2, name2))
471 module, name = mapping(module, name)
472 self.assertEqual((module, name), (module3, name3))
473
474 def test_exceptions(self):
475 self.assertEqual(mapping('exceptions', 'StandardError'),
476 ('builtins', 'Exception'))
477 self.assertEqual(mapping('exceptions', 'Exception'),
478 ('builtins', 'Exception'))
479 self.assertEqual(reverse_mapping('builtins', 'Exception'),
480 ('exceptions', 'Exception'))
481 self.assertEqual(mapping('exceptions', 'OSError'),
482 ('builtins', 'OSError'))
483 self.assertEqual(reverse_mapping('builtins', 'OSError'),
484 ('exceptions', 'OSError'))
485
486 for name, exc in get_exceptions(builtins):
487 with self.subTest(name):
Yury Selivanov75445082015-05-11 22:57:16 -0400488 if exc in (BlockingIOError,
489 ResourceWarning,
Yury Selivanovf488fb42015-07-03 01:04:23 -0400490 StopAsyncIteration,
Inada Naoki48274832021-03-29 12:28:14 +0900491 RecursionError,
492 EncodingWarning):
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300493 continue
494 if exc is not OSError and issubclass(exc, OSError):
495 self.assertEqual(reverse_mapping('builtins', name),
496 ('exceptions', 'OSError'))
Eric Snowc9432652016-09-07 15:42:32 -0700497 elif exc is not ImportError and issubclass(exc, ImportError):
498 self.assertEqual(reverse_mapping('builtins', name),
499 ('exceptions', 'ImportError'))
500 self.assertEqual(mapping('exceptions', name),
501 ('exceptions', name))
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300502 else:
503 self.assertEqual(reverse_mapping('builtins', name),
504 ('exceptions', name))
505 self.assertEqual(mapping('exceptions', name),
506 ('builtins', name))
507
Serhiy Storchaka7b2cfc42015-10-10 20:10:07 +0300508 def test_multiprocessing_exceptions(self):
Hai Shi883bc632020-07-06 17:12:49 +0800509 module = import_helper.import_module('multiprocessing.context')
Serhiy Storchaka7b2cfc42015-10-10 20:10:07 +0300510 for name, exc in get_exceptions(module):
Serhiy Storchakabfe18242015-03-31 13:12:37 +0300511 with self.subTest(name):
512 self.assertEqual(reverse_mapping('multiprocessing.context', name),
513 ('multiprocessing', name))
514 self.assertEqual(mapping('multiprocessing', name),
515 ('multiprocessing.context', name))
516
517
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700518def load_tests(loader, tests, pattern):
519 tests.addTest(doctest.DocTestSuite())
520 return tests
521
Fred Drake694ed092001-12-19 16:42:15 +0000522
Jeremy Hylton66426532001-10-15 21:38:56 +0000523if __name__ == "__main__":
Miss Islington (bot)74c6acc2021-09-20 09:19:31 -0700524 unittest.main()