PageRenderTime 59ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/kbe/src/lib/python/Lib/importlib/test/source/test_abc_loader.py

https://bitbucket.org/kbengine/kbengine
Python | 876 lines | 805 code | 41 blank | 30 comment | 7 complexity | a0124ebd011098b3cdcba585d1d77cb6 MD5 | raw file
  1. import importlib
  2. from importlib import abc
  3. from .. import abc as testing_abc
  4. from .. import util
  5. from . import util as source_util
  6. import imp
  7. import inspect
  8. import io
  9. import marshal
  10. import os
  11. import sys
  12. import types
  13. import unittest
  14. import warnings
  15. class SourceOnlyLoaderMock(abc.SourceLoader):
  16. # Globals that should be defined for all modules.
  17. source = (b"_ = '::'.join([__name__, __file__, __cached__, __package__, "
  18. b"repr(__loader__)])")
  19. def __init__(self, path):
  20. self.path = path
  21. def get_data(self, path):
  22. assert self.path == path
  23. return self.source
  24. def get_filename(self, fullname):
  25. return self.path
  26. class SourceLoaderMock(SourceOnlyLoaderMock):
  27. source_mtime = 1
  28. def __init__(self, path, magic=imp.get_magic()):
  29. super().__init__(path)
  30. self.bytecode_path = imp.cache_from_source(self.path)
  31. data = bytearray(magic)
  32. data.extend(marshal._w_long(self.source_mtime))
  33. code_object = compile(self.source, self.path, 'exec',
  34. dont_inherit=True)
  35. data.extend(marshal.dumps(code_object))
  36. self.bytecode = bytes(data)
  37. self.written = {}
  38. def get_data(self, path):
  39. if path == self.path:
  40. return super().get_data(path)
  41. elif path == self.bytecode_path:
  42. return self.bytecode
  43. else:
  44. raise IOError
  45. def path_mtime(self, path):
  46. assert path == self.path
  47. return self.source_mtime
  48. def set_data(self, path, data):
  49. self.written[path] = bytes(data)
  50. return path == self.bytecode_path
  51. class PyLoaderMock(abc.PyLoader):
  52. # Globals that should be defined for all modules.
  53. source = (b"_ = '::'.join([__name__, __file__, __package__, "
  54. b"repr(__loader__)])")
  55. def __init__(self, data):
  56. """Take a dict of 'module_name: path' pairings.
  57. Paths should have no file extension, allowing packages to be denoted by
  58. ending in '__init__'.
  59. """
  60. self.module_paths = data
  61. self.path_to_module = {val:key for key,val in data.items()}
  62. def get_data(self, path):
  63. if path not in self.path_to_module:
  64. raise IOError
  65. return self.source
  66. def is_package(self, name):
  67. filename = os.path.basename(self.get_filename(name))
  68. return os.path.splitext(filename)[0] == '__init__'
  69. def source_path(self, name):
  70. try:
  71. return self.module_paths[name]
  72. except KeyError:
  73. raise ImportError
  74. def get_filename(self, name):
  75. """Silence deprecation warning."""
  76. with warnings.catch_warnings(record=True) as w:
  77. warnings.simplefilter("always")
  78. path = super().get_filename(name)
  79. assert len(w) == 1
  80. assert issubclass(w[0].category, PendingDeprecationWarning)
  81. return path
  82. class PyLoaderCompatMock(PyLoaderMock):
  83. """Mock that matches what is suggested to have a loader that is compatible
  84. from Python 3.1 onwards."""
  85. def get_filename(self, fullname):
  86. try:
  87. return self.module_paths[fullname]
  88. except KeyError:
  89. raise ImportError
  90. def source_path(self, fullname):
  91. try:
  92. return self.get_filename(fullname)
  93. except ImportError:
  94. return None
  95. class PyPycLoaderMock(abc.PyPycLoader, PyLoaderMock):
  96. default_mtime = 1
  97. def __init__(self, source, bc={}):
  98. """Initialize mock.
  99. 'bc' is a dict keyed on a module's name. The value is dict with
  100. possible keys of 'path', 'mtime', 'magic', and 'bc'. Except for 'path',
  101. each of those keys control if any part of created bytecode is to
  102. deviate from default values.
  103. """
  104. super().__init__(source)
  105. self.module_bytecode = {}
  106. self.path_to_bytecode = {}
  107. self.bytecode_to_path = {}
  108. for name, data in bc.items():
  109. self.path_to_bytecode[data['path']] = name
  110. self.bytecode_to_path[name] = data['path']
  111. magic = data.get('magic', imp.get_magic())
  112. mtime = importlib._w_long(data.get('mtime', self.default_mtime))
  113. if 'bc' in data:
  114. bc = data['bc']
  115. else:
  116. bc = self.compile_bc(name)
  117. self.module_bytecode[name] = magic + mtime + bc
  118. def compile_bc(self, name):
  119. source_path = self.module_paths.get(name, '<test>') or '<test>'
  120. code = compile(self.source, source_path, 'exec')
  121. return marshal.dumps(code)
  122. def source_mtime(self, name):
  123. if name in self.module_paths:
  124. return self.default_mtime
  125. elif name in self.module_bytecode:
  126. return None
  127. else:
  128. raise ImportError
  129. def bytecode_path(self, name):
  130. try:
  131. return self.bytecode_to_path[name]
  132. except KeyError:
  133. if name in self.module_paths:
  134. return None
  135. else:
  136. raise ImportError
  137. def write_bytecode(self, name, bytecode):
  138. self.module_bytecode[name] = bytecode
  139. return True
  140. def get_data(self, path):
  141. if path in self.path_to_module:
  142. return super().get_data(path)
  143. elif path in self.path_to_bytecode:
  144. name = self.path_to_bytecode[path]
  145. return self.module_bytecode[name]
  146. else:
  147. raise IOError
  148. def is_package(self, name):
  149. try:
  150. return super().is_package(name)
  151. except TypeError:
  152. return '__init__' in self.bytecode_to_path[name]
  153. def get_code(self, name):
  154. with warnings.catch_warnings(record=True) as w:
  155. warnings.simplefilter("always")
  156. code_object = super().get_code(name)
  157. assert len(w) == 1
  158. assert issubclass(w[0].category, PendingDeprecationWarning)
  159. return code_object
  160. class PyLoaderTests(testing_abc.LoaderTests):
  161. """Tests for importlib.abc.PyLoader."""
  162. mocker = PyLoaderMock
  163. def eq_attrs(self, ob, **kwargs):
  164. for attr, val in kwargs.items():
  165. found = getattr(ob, attr)
  166. self.assertEqual(found, val,
  167. "{} attribute: {} != {}".format(attr, found, val))
  168. def test_module(self):
  169. name = '<module>'
  170. path = os.path.join('', 'path', 'to', 'module')
  171. mock = self.mocker({name: path})
  172. with util.uncache(name):
  173. module = mock.load_module(name)
  174. self.assertTrue(name in sys.modules)
  175. self.eq_attrs(module, __name__=name, __file__=path, __package__='',
  176. __loader__=mock)
  177. self.assertTrue(not hasattr(module, '__path__'))
  178. return mock, name
  179. def test_package(self):
  180. name = '<pkg>'
  181. path = os.path.join('path', 'to', name, '__init__')
  182. mock = self.mocker({name: path})
  183. with util.uncache(name):
  184. module = mock.load_module(name)
  185. self.assertTrue(name in sys.modules)
  186. self.eq_attrs(module, __name__=name, __file__=path,
  187. __path__=[os.path.dirname(path)], __package__=name,
  188. __loader__=mock)
  189. return mock, name
  190. def test_lacking_parent(self):
  191. name = 'pkg.mod'
  192. path = os.path.join('path', 'to', 'pkg', 'mod')
  193. mock = self.mocker({name: path})
  194. with util.uncache(name):
  195. module = mock.load_module(name)
  196. self.assertIn(name, sys.modules)
  197. self.eq_attrs(module, __name__=name, __file__=path, __package__='pkg',
  198. __loader__=mock)
  199. self.assertFalse(hasattr(module, '__path__'))
  200. return mock, name
  201. def test_module_reuse(self):
  202. name = 'mod'
  203. path = os.path.join('path', 'to', 'mod')
  204. module = imp.new_module(name)
  205. mock = self.mocker({name: path})
  206. with util.uncache(name):
  207. sys.modules[name] = module
  208. loaded_module = mock.load_module(name)
  209. self.assertTrue(loaded_module is module)
  210. self.assertTrue(sys.modules[name] is module)
  211. return mock, name
  212. def test_state_after_failure(self):
  213. name = "mod"
  214. module = imp.new_module(name)
  215. module.blah = None
  216. mock = self.mocker({name: os.path.join('path', 'to', 'mod')})
  217. mock.source = b"1/0"
  218. with util.uncache(name):
  219. sys.modules[name] = module
  220. with self.assertRaises(ZeroDivisionError):
  221. mock.load_module(name)
  222. self.assertTrue(sys.modules[name] is module)
  223. self.assertTrue(hasattr(module, 'blah'))
  224. return mock
  225. def test_unloadable(self):
  226. name = "mod"
  227. mock = self.mocker({name: os.path.join('path', 'to', 'mod')})
  228. mock.source = b"1/0"
  229. with util.uncache(name):
  230. with self.assertRaises(ZeroDivisionError):
  231. mock.load_module(name)
  232. self.assertTrue(name not in sys.modules)
  233. return mock
  234. class PyLoaderCompatTests(PyLoaderTests):
  235. """Test that the suggested code to make a loader that is compatible from
  236. Python 3.1 forward works."""
  237. mocker = PyLoaderCompatMock
  238. class PyLoaderInterfaceTests(unittest.TestCase):
  239. """Tests for importlib.abc.PyLoader to make sure that when source_path()
  240. doesn't return a path everything works as expected."""
  241. def test_no_source_path(self):
  242. # No source path should lead to ImportError.
  243. name = 'mod'
  244. mock = PyLoaderMock({})
  245. with util.uncache(name), self.assertRaises(ImportError):
  246. mock.load_module(name)
  247. def test_source_path_is_None(self):
  248. name = 'mod'
  249. mock = PyLoaderMock({name: None})
  250. with util.uncache(name), self.assertRaises(ImportError):
  251. mock.load_module(name)
  252. def test_get_filename_with_source_path(self):
  253. # get_filename() should return what source_path() returns.
  254. name = 'mod'
  255. path = os.path.join('path', 'to', 'source')
  256. mock = PyLoaderMock({name: path})
  257. with util.uncache(name):
  258. self.assertEqual(mock.get_filename(name), path)
  259. def test_get_filename_no_source_path(self):
  260. # get_filename() should raise ImportError if source_path returns None.
  261. name = 'mod'
  262. mock = PyLoaderMock({name: None})
  263. with util.uncache(name), self.assertRaises(ImportError):
  264. mock.get_filename(name)
  265. class PyPycLoaderTests(PyLoaderTests):
  266. """Tests for importlib.abc.PyPycLoader."""
  267. mocker = PyPycLoaderMock
  268. @source_util.writes_bytecode_files
  269. def verify_bytecode(self, mock, name):
  270. assert name in mock.module_paths
  271. self.assertIn(name, mock.module_bytecode)
  272. magic = mock.module_bytecode[name][:4]
  273. self.assertEqual(magic, imp.get_magic())
  274. mtime = importlib._r_long(mock.module_bytecode[name][4:8])
  275. self.assertEqual(mtime, 1)
  276. bc = mock.module_bytecode[name][8:]
  277. self.assertEqual(bc, mock.compile_bc(name))
  278. def test_module(self):
  279. mock, name = super().test_module()
  280. self.verify_bytecode(mock, name)
  281. def test_package(self):
  282. mock, name = super().test_package()
  283. self.verify_bytecode(mock, name)
  284. def test_lacking_parent(self):
  285. mock, name = super().test_lacking_parent()
  286. self.verify_bytecode(mock, name)
  287. def test_module_reuse(self):
  288. mock, name = super().test_module_reuse()
  289. self.verify_bytecode(mock, name)
  290. def test_state_after_failure(self):
  291. super().test_state_after_failure()
  292. def test_unloadable(self):
  293. super().test_unloadable()
  294. class PyPycLoaderInterfaceTests(unittest.TestCase):
  295. """Test for the interface of importlib.abc.PyPycLoader."""
  296. def get_filename_check(self, src_path, bc_path, expect):
  297. name = 'mod'
  298. mock = PyPycLoaderMock({name: src_path}, {name: {'path': bc_path}})
  299. with util.uncache(name):
  300. assert mock.source_path(name) == src_path
  301. assert mock.bytecode_path(name) == bc_path
  302. self.assertEqual(mock.get_filename(name), expect)
  303. def test_filename_with_source_bc(self):
  304. # When source and bytecode paths present, return the source path.
  305. self.get_filename_check('source_path', 'bc_path', 'source_path')
  306. def test_filename_with_source_no_bc(self):
  307. # With source but no bc, return source path.
  308. self.get_filename_check('source_path', None, 'source_path')
  309. def test_filename_with_no_source_bc(self):
  310. # With not source but bc, return the bc path.
  311. self.get_filename_check(None, 'bc_path', 'bc_path')
  312. def test_filename_with_no_source_or_bc(self):
  313. # With no source or bc, raise ImportError.
  314. name = 'mod'
  315. mock = PyPycLoaderMock({name: None}, {name: {'path': None}})
  316. with util.uncache(name), self.assertRaises(ImportError):
  317. mock.get_filename(name)
  318. class SkipWritingBytecodeTests(unittest.TestCase):
  319. """Test that bytecode is properly handled based on
  320. sys.dont_write_bytecode."""
  321. @source_util.writes_bytecode_files
  322. def run_test(self, dont_write_bytecode):
  323. name = 'mod'
  324. mock = PyPycLoaderMock({name: os.path.join('path', 'to', 'mod')})
  325. sys.dont_write_bytecode = dont_write_bytecode
  326. with util.uncache(name):
  327. mock.load_module(name)
  328. self.assertTrue((name in mock.module_bytecode) is not
  329. dont_write_bytecode)
  330. def test_no_bytecode_written(self):
  331. self.run_test(True)
  332. def test_bytecode_written(self):
  333. self.run_test(False)
  334. class RegeneratedBytecodeTests(unittest.TestCase):
  335. """Test that bytecode is regenerated as expected."""
  336. @source_util.writes_bytecode_files
  337. def test_different_magic(self):
  338. # A different magic number should lead to new bytecode.
  339. name = 'mod'
  340. bad_magic = b'\x00\x00\x00\x00'
  341. assert bad_magic != imp.get_magic()
  342. mock = PyPycLoaderMock({name: os.path.join('path', 'to', 'mod')},
  343. {name: {'path': os.path.join('path', 'to',
  344. 'mod.bytecode'),
  345. 'magic': bad_magic}})
  346. with util.uncache(name):
  347. mock.load_module(name)
  348. self.assertTrue(name in mock.module_bytecode)
  349. magic = mock.module_bytecode[name][:4]
  350. self.assertEqual(magic, imp.get_magic())
  351. @source_util.writes_bytecode_files
  352. def test_old_mtime(self):
  353. # Bytecode with an older mtime should be regenerated.
  354. name = 'mod'
  355. old_mtime = PyPycLoaderMock.default_mtime - 1
  356. mock = PyPycLoaderMock({name: os.path.join('path', 'to', 'mod')},
  357. {name: {'path': 'path/to/mod.bytecode', 'mtime': old_mtime}})
  358. with util.uncache(name):
  359. mock.load_module(name)
  360. self.assertTrue(name in mock.module_bytecode)
  361. mtime = importlib._r_long(mock.module_bytecode[name][4:8])
  362. self.assertEqual(mtime, PyPycLoaderMock.default_mtime)
  363. class BadBytecodeFailureTests(unittest.TestCase):
  364. """Test import failures when there is no source and parts of the bytecode
  365. is bad."""
  366. def test_bad_magic(self):
  367. # A bad magic number should lead to an ImportError.
  368. name = 'mod'
  369. bad_magic = b'\x00\x00\x00\x00'
  370. bc = {name:
  371. {'path': os.path.join('path', 'to', 'mod'),
  372. 'magic': bad_magic}}
  373. mock = PyPycLoaderMock({name: None}, bc)
  374. with util.uncache(name), self.assertRaises(ImportError):
  375. mock.load_module(name)
  376. def test_no_bytecode(self):
  377. # Missing code object bytecode should lead to an EOFError.
  378. name = 'mod'
  379. bc = {name: {'path': os.path.join('path', 'to', 'mod'), 'bc': b''}}
  380. mock = PyPycLoaderMock({name: None}, bc)
  381. with util.uncache(name), self.assertRaises(EOFError):
  382. mock.load_module(name)
  383. def test_bad_bytecode(self):
  384. # Malformed code object bytecode should lead to a ValueError.
  385. name = 'mod'
  386. bc = {name: {'path': os.path.join('path', 'to', 'mod'), 'bc': b'1234'}}
  387. mock = PyPycLoaderMock({name: None}, bc)
  388. with util.uncache(name), self.assertRaises(ValueError):
  389. mock.load_module(name)
  390. def raise_ImportError(*args, **kwargs):
  391. raise ImportError
  392. class MissingPathsTests(unittest.TestCase):
  393. """Test what happens when a source or bytecode path does not exist (either
  394. from *_path returning None or raising ImportError)."""
  395. def test_source_path_None(self):
  396. # Bytecode should be used when source_path returns None, along with
  397. # __file__ being set to the bytecode path.
  398. name = 'mod'
  399. bytecode_path = 'path/to/mod'
  400. mock = PyPycLoaderMock({name: None}, {name: {'path': bytecode_path}})
  401. with util.uncache(name):
  402. module = mock.load_module(name)
  403. self.assertEqual(module.__file__, bytecode_path)
  404. # Testing for bytecode_path returning None handled by all tests where no
  405. # bytecode initially exists.
  406. def test_all_paths_None(self):
  407. # If all *_path methods return None, raise ImportError.
  408. name = 'mod'
  409. mock = PyPycLoaderMock({name: None})
  410. with util.uncache(name), self.assertRaises(ImportError):
  411. mock.load_module(name)
  412. def test_source_path_ImportError(self):
  413. # An ImportError from source_path should trigger an ImportError.
  414. name = 'mod'
  415. mock = PyPycLoaderMock({}, {name: {'path': os.path.join('path', 'to',
  416. 'mod')}})
  417. with util.uncache(name), self.assertRaises(ImportError):
  418. mock.load_module(name)
  419. def test_bytecode_path_ImportError(self):
  420. # An ImportError from bytecode_path should trigger an ImportError.
  421. name = 'mod'
  422. mock = PyPycLoaderMock({name: os.path.join('path', 'to', 'mod')})
  423. bad_meth = types.MethodType(raise_ImportError, mock)
  424. mock.bytecode_path = bad_meth
  425. with util.uncache(name), self.assertRaises(ImportError):
  426. mock.load_module(name)
  427. class SourceLoaderTestHarness(unittest.TestCase):
  428. def setUp(self, *, is_package=True, **kwargs):
  429. self.package = 'pkg'
  430. if is_package:
  431. self.path = os.path.join(self.package, '__init__.py')
  432. self.name = self.package
  433. else:
  434. module_name = 'mod'
  435. self.path = os.path.join(self.package, '.'.join(['mod', 'py']))
  436. self.name = '.'.join([self.package, module_name])
  437. self.cached = imp.cache_from_source(self.path)
  438. self.loader = self.loader_mock(self.path, **kwargs)
  439. def verify_module(self, module):
  440. self.assertEqual(module.__name__, self.name)
  441. self.assertEqual(module.__file__, self.path)
  442. self.assertEqual(module.__cached__, self.cached)
  443. self.assertEqual(module.__package__, self.package)
  444. self.assertEqual(module.__loader__, self.loader)
  445. values = module._.split('::')
  446. self.assertEqual(values[0], self.name)
  447. self.assertEqual(values[1], self.path)
  448. self.assertEqual(values[2], self.cached)
  449. self.assertEqual(values[3], self.package)
  450. self.assertEqual(values[4], repr(self.loader))
  451. def verify_code(self, code_object):
  452. module = imp.new_module(self.name)
  453. module.__file__ = self.path
  454. module.__cached__ = self.cached
  455. module.__package__ = self.package
  456. module.__loader__ = self.loader
  457. module.__path__ = []
  458. exec(code_object, module.__dict__)
  459. self.verify_module(module)
  460. class SourceOnlyLoaderTests(SourceLoaderTestHarness):
  461. """Test importlib.abc.SourceLoader for source-only loading.
  462. Reload testing is subsumed by the tests for
  463. importlib.util.module_for_loader.
  464. """
  465. loader_mock = SourceOnlyLoaderMock
  466. def test_get_source(self):
  467. # Verify the source code is returned as a string.
  468. # If an IOError is raised by get_data then raise ImportError.
  469. expected_source = self.loader.source.decode('utf-8')
  470. self.assertEqual(self.loader.get_source(self.name), expected_source)
  471. def raise_IOError(path):
  472. raise IOError
  473. self.loader.get_data = raise_IOError
  474. with self.assertRaises(ImportError):
  475. self.loader.get_source(self.name)
  476. def test_is_package(self):
  477. # Properly detect when loading a package.
  478. self.setUp(is_package=True)
  479. self.assertTrue(self.loader.is_package(self.name))
  480. self.setUp(is_package=False)
  481. self.assertFalse(self.loader.is_package(self.name))
  482. def test_get_code(self):
  483. # Verify the code object is created.
  484. code_object = self.loader.get_code(self.name)
  485. self.verify_code(code_object)
  486. def test_load_module(self):
  487. # Loading a module should set __name__, __loader__, __package__,
  488. # __path__ (for packages), __file__, and __cached__.
  489. # The module should also be put into sys.modules.
  490. with util.uncache(self.name):
  491. module = self.loader.load_module(self.name)
  492. self.verify_module(module)
  493. self.assertEqual(module.__path__, [os.path.dirname(self.path)])
  494. self.assertTrue(self.name in sys.modules)
  495. def test_package_settings(self):
  496. # __package__ needs to be set, while __path__ is set on if the module
  497. # is a package.
  498. # Testing the values for a package are covered by test_load_module.
  499. self.setUp(is_package=False)
  500. with util.uncache(self.name):
  501. module = self.loader.load_module(self.name)
  502. self.verify_module(module)
  503. self.assertTrue(not hasattr(module, '__path__'))
  504. def test_get_source_encoding(self):
  505. # Source is considered encoded in UTF-8 by default unless otherwise
  506. # specified by an encoding line.
  507. source = "_ = 'ü'"
  508. self.loader.source = source.encode('utf-8')
  509. returned_source = self.loader.get_source(self.name)
  510. self.assertEqual(returned_source, source)
  511. source = "# coding: latin-1\n_ = ü"
  512. self.loader.source = source.encode('latin-1')
  513. returned_source = self.loader.get_source(self.name)
  514. self.assertEqual(returned_source, source)
  515. @unittest.skipIf(sys.dont_write_bytecode, "sys.dont_write_bytecode is true")
  516. class SourceLoaderBytecodeTests(SourceLoaderTestHarness):
  517. """Test importlib.abc.SourceLoader's use of bytecode.
  518. Source-only testing handled by SourceOnlyLoaderTests.
  519. """
  520. loader_mock = SourceLoaderMock
  521. def verify_code(self, code_object, *, bytecode_written=False):
  522. super().verify_code(code_object)
  523. if bytecode_written:
  524. self.assertIn(self.cached, self.loader.written)
  525. data = bytearray(imp.get_magic())
  526. data.extend(marshal._w_long(self.loader.source_mtime))
  527. data.extend(marshal.dumps(code_object))
  528. self.assertEqual(self.loader.written[self.cached], bytes(data))
  529. def test_code_with_everything(self):
  530. # When everything should work.
  531. code_object = self.loader.get_code(self.name)
  532. self.verify_code(code_object)
  533. def test_no_bytecode(self):
  534. # If no bytecode exists then move on to the source.
  535. self.loader.bytecode_path = "<does not exist>"
  536. # Sanity check
  537. with self.assertRaises(IOError):
  538. bytecode_path = imp.cache_from_source(self.path)
  539. self.loader.get_data(bytecode_path)
  540. code_object = self.loader.get_code(self.name)
  541. self.verify_code(code_object, bytecode_written=True)
  542. def test_code_bad_timestamp(self):
  543. # Bytecode is only used when the timestamp matches the source EXACTLY.
  544. for source_mtime in (0, 2):
  545. assert source_mtime != self.loader.source_mtime
  546. original = self.loader.source_mtime
  547. self.loader.source_mtime = source_mtime
  548. # If bytecode is used then EOFError would be raised by marshal.
  549. self.loader.bytecode = self.loader.bytecode[8:]
  550. code_object = self.loader.get_code(self.name)
  551. self.verify_code(code_object, bytecode_written=True)
  552. self.loader.source_mtime = original
  553. def test_code_bad_magic(self):
  554. # Skip over bytecode with a bad magic number.
  555. self.setUp(magic=b'0000')
  556. # If bytecode is used then EOFError would be raised by marshal.
  557. self.loader.bytecode = self.loader.bytecode[8:]
  558. code_object = self.loader.get_code(self.name)
  559. self.verify_code(code_object, bytecode_written=True)
  560. def test_dont_write_bytecode(self):
  561. # Bytecode is not written if sys.dont_write_bytecode is true.
  562. # Can assume it is false already thanks to the skipIf class decorator.
  563. try:
  564. sys.dont_write_bytecode = True
  565. self.loader.bytecode_path = "<does not exist>"
  566. code_object = self.loader.get_code(self.name)
  567. self.assertNotIn(self.cached, self.loader.written)
  568. finally:
  569. sys.dont_write_bytecode = False
  570. def test_no_set_data(self):
  571. # If set_data is not defined, one can still read bytecode.
  572. self.setUp(magic=b'0000')
  573. original_set_data = self.loader.__class__.set_data
  574. try:
  575. del self.loader.__class__.set_data
  576. code_object = self.loader.get_code(self.name)
  577. self.verify_code(code_object)
  578. finally:
  579. self.loader.__class__.set_data = original_set_data
  580. def test_set_data_raises_exceptions(self):
  581. # Raising NotImplementedError or IOError is okay for set_data.
  582. def raise_exception(exc):
  583. def closure(*args, **kwargs):
  584. raise exc
  585. return closure
  586. self.setUp(magic=b'0000')
  587. self.loader.set_data = raise_exception(NotImplementedError)
  588. code_object = self.loader.get_code(self.name)
  589. self.verify_code(code_object)
  590. class SourceLoaderGetSourceTests(unittest.TestCase):
  591. """Tests for importlib.abc.SourceLoader.get_source()."""
  592. def test_default_encoding(self):
  593. # Should have no problems with UTF-8 text.
  594. name = 'mod'
  595. mock = SourceOnlyLoaderMock('mod.file')
  596. source = 'x = "ü"'
  597. mock.source = source.encode('utf-8')
  598. returned_source = mock.get_source(name)
  599. self.assertEqual(returned_source, source)
  600. def test_decoded_source(self):
  601. # Decoding should work.
  602. name = 'mod'
  603. mock = SourceOnlyLoaderMock("mod.file")
  604. source = "# coding: Latin-1\nx='ü'"
  605. assert source.encode('latin-1') != source.encode('utf-8')
  606. mock.source = source.encode('latin-1')
  607. returned_source = mock.get_source(name)
  608. self.assertEqual(returned_source, source)
  609. def test_universal_newlines(self):
  610. # PEP 302 says universal newlines should be used.
  611. name = 'mod'
  612. mock = SourceOnlyLoaderMock('mod.file')
  613. source = "x = 42\r\ny = -13\r\n"
  614. mock.source = source.encode('utf-8')
  615. expect = io.IncrementalNewlineDecoder(None, True).decode(source)
  616. self.assertEqual(mock.get_source(name), expect)
  617. class AbstractMethodImplTests(unittest.TestCase):
  618. """Test the concrete abstractmethod implementations."""
  619. class Loader(abc.Loader):
  620. def load_module(self, fullname):
  621. super().load_module(fullname)
  622. class Finder(abc.Finder):
  623. def find_module(self, _):
  624. super().find_module(_)
  625. class ResourceLoader(Loader, abc.ResourceLoader):
  626. def get_data(self, _):
  627. super().get_data(_)
  628. class InspectLoader(Loader, abc.InspectLoader):
  629. def is_package(self, _):
  630. super().is_package(_)
  631. def get_code(self, _):
  632. super().get_code(_)
  633. def get_source(self, _):
  634. super().get_source(_)
  635. class ExecutionLoader(InspectLoader, abc.ExecutionLoader):
  636. def get_filename(self, _):
  637. super().get_filename(_)
  638. class SourceLoader(ResourceLoader, ExecutionLoader, abc.SourceLoader):
  639. pass
  640. class PyLoader(ResourceLoader, InspectLoader, abc.PyLoader):
  641. def source_path(self, _):
  642. super().source_path(_)
  643. class PyPycLoader(PyLoader, abc.PyPycLoader):
  644. def bytecode_path(self, _):
  645. super().bytecode_path(_)
  646. def source_mtime(self, _):
  647. super().source_mtime(_)
  648. def write_bytecode(self, _, _2):
  649. super().write_bytecode(_, _2)
  650. def raises_NotImplementedError(self, ins, *args):
  651. for method_name in args:
  652. method = getattr(ins, method_name)
  653. arg_count = len(inspect.getfullargspec(method)[0]) - 1
  654. args = [''] * arg_count
  655. try:
  656. method(*args)
  657. except NotImplementedError:
  658. pass
  659. else:
  660. msg = "{}.{} did not raise NotImplementedError"
  661. self.fail(msg.format(ins.__class__.__name__, method_name))
  662. def test_Loader(self):
  663. self.raises_NotImplementedError(self.Loader(), 'load_module')
  664. # XXX misplaced; should be somewhere else
  665. def test_Finder(self):
  666. self.raises_NotImplementedError(self.Finder(), 'find_module')
  667. def test_ResourceLoader(self):
  668. self.raises_NotImplementedError(self.ResourceLoader(), 'load_module',
  669. 'get_data')
  670. def test_InspectLoader(self):
  671. self.raises_NotImplementedError(self.InspectLoader(), 'load_module',
  672. 'is_package', 'get_code', 'get_source')
  673. def test_ExecutionLoader(self):
  674. self.raises_NotImplementedError(self.ExecutionLoader(), 'load_module',
  675. 'is_package', 'get_code', 'get_source',
  676. 'get_filename')
  677. def test_SourceLoader(self):
  678. ins = self.SourceLoader()
  679. # Required abstractmethods.
  680. self.raises_NotImplementedError(ins, 'get_filename', 'get_data')
  681. # Optional abstractmethods.
  682. self.raises_NotImplementedError(ins,'path_mtime', 'set_data')
  683. def test_PyLoader(self):
  684. self.raises_NotImplementedError(self.PyLoader(), 'source_path',
  685. 'get_data', 'is_package')
  686. def test_PyPycLoader(self):
  687. self.raises_NotImplementedError(self.PyPycLoader(), 'source_path',
  688. 'source_mtime', 'bytecode_path',
  689. 'write_bytecode')
  690. def test_main():
  691. from test.support import run_unittest
  692. run_unittest(PyLoaderTests, PyLoaderCompatTests,
  693. PyLoaderInterfaceTests,
  694. PyPycLoaderTests, PyPycLoaderInterfaceTests,
  695. SkipWritingBytecodeTests, RegeneratedBytecodeTests,
  696. BadBytecodeFailureTests, MissingPathsTests,
  697. SourceOnlyLoaderTests,
  698. SourceLoaderBytecodeTests,
  699. SourceLoaderGetSourceTests,
  700. AbstractMethodImplTests)
  701. if __name__ == '__main__':
  702. test_main()