PageRenderTime 52ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/test/test_importlib/test_util.py

https://github.com/albertz/CPython
Python | 811 lines | 737 code | 48 blank | 26 comment | 28 complexity | b72e0be0634a4cb63060a9db6be907f7 MD5 | raw file
  1. from . import util
  2. abc = util.import_importlib('importlib.abc')
  3. init = util.import_importlib('importlib')
  4. machinery = util.import_importlib('importlib.machinery')
  5. importlib_util = util.import_importlib('importlib.util')
  6. import importlib.util
  7. import os
  8. import pathlib
  9. import string
  10. import sys
  11. from test import support
  12. import types
  13. import unittest
  14. import warnings
  15. class DecodeSourceBytesTests:
  16. source = "string ='ΓΌ'"
  17. def test_ut8_default(self):
  18. source_bytes = self.source.encode('utf-8')
  19. self.assertEqual(self.util.decode_source(source_bytes), self.source)
  20. def test_specified_encoding(self):
  21. source = '# coding=latin-1\n' + self.source
  22. source_bytes = source.encode('latin-1')
  23. assert source_bytes != source.encode('utf-8')
  24. self.assertEqual(self.util.decode_source(source_bytes), source)
  25. def test_universal_newlines(self):
  26. source = '\r\n'.join([self.source, self.source])
  27. source_bytes = source.encode('utf-8')
  28. self.assertEqual(self.util.decode_source(source_bytes),
  29. '\n'.join([self.source, self.source]))
  30. (Frozen_DecodeSourceBytesTests,
  31. Source_DecodeSourceBytesTests
  32. ) = util.test_both(DecodeSourceBytesTests, util=importlib_util)
  33. class ModuleFromSpecTests:
  34. def test_no_create_module(self):
  35. class Loader:
  36. def exec_module(self, module):
  37. pass
  38. spec = self.machinery.ModuleSpec('test', Loader())
  39. with self.assertRaises(ImportError):
  40. module = self.util.module_from_spec(spec)
  41. def test_create_module_returns_None(self):
  42. class Loader(self.abc.Loader):
  43. def create_module(self, spec):
  44. return None
  45. spec = self.machinery.ModuleSpec('test', Loader())
  46. module = self.util.module_from_spec(spec)
  47. self.assertIsInstance(module, types.ModuleType)
  48. self.assertEqual(module.__name__, spec.name)
  49. def test_create_module(self):
  50. name = 'already set'
  51. class CustomModule(types.ModuleType):
  52. pass
  53. class Loader(self.abc.Loader):
  54. def create_module(self, spec):
  55. module = CustomModule(spec.name)
  56. module.__name__ = name
  57. return module
  58. spec = self.machinery.ModuleSpec('test', Loader())
  59. module = self.util.module_from_spec(spec)
  60. self.assertIsInstance(module, CustomModule)
  61. self.assertEqual(module.__name__, name)
  62. def test___name__(self):
  63. spec = self.machinery.ModuleSpec('test', object())
  64. module = self.util.module_from_spec(spec)
  65. self.assertEqual(module.__name__, spec.name)
  66. def test___spec__(self):
  67. spec = self.machinery.ModuleSpec('test', object())
  68. module = self.util.module_from_spec(spec)
  69. self.assertEqual(module.__spec__, spec)
  70. def test___loader__(self):
  71. loader = object()
  72. spec = self.machinery.ModuleSpec('test', loader)
  73. module = self.util.module_from_spec(spec)
  74. self.assertIs(module.__loader__, loader)
  75. def test___package__(self):
  76. spec = self.machinery.ModuleSpec('test.pkg', object())
  77. module = self.util.module_from_spec(spec)
  78. self.assertEqual(module.__package__, spec.parent)
  79. def test___path__(self):
  80. spec = self.machinery.ModuleSpec('test', object(), is_package=True)
  81. module = self.util.module_from_spec(spec)
  82. self.assertEqual(module.__path__, spec.submodule_search_locations)
  83. def test___file__(self):
  84. spec = self.machinery.ModuleSpec('test', object(), origin='some/path')
  85. spec.has_location = True
  86. module = self.util.module_from_spec(spec)
  87. self.assertEqual(module.__file__, spec.origin)
  88. def test___cached__(self):
  89. spec = self.machinery.ModuleSpec('test', object())
  90. spec.cached = 'some/path'
  91. spec.has_location = True
  92. module = self.util.module_from_spec(spec)
  93. self.assertEqual(module.__cached__, spec.cached)
  94. (Frozen_ModuleFromSpecTests,
  95. Source_ModuleFromSpecTests
  96. ) = util.test_both(ModuleFromSpecTests, abc=abc, machinery=machinery,
  97. util=importlib_util)
  98. class ModuleForLoaderTests:
  99. """Tests for importlib.util.module_for_loader."""
  100. @classmethod
  101. def module_for_loader(cls, func):
  102. with warnings.catch_warnings():
  103. warnings.simplefilter('ignore', DeprecationWarning)
  104. return cls.util.module_for_loader(func)
  105. def test_warning(self):
  106. # Should raise a PendingDeprecationWarning when used.
  107. with warnings.catch_warnings():
  108. warnings.simplefilter('error', DeprecationWarning)
  109. with self.assertRaises(DeprecationWarning):
  110. func = self.util.module_for_loader(lambda x: x)
  111. def return_module(self, name):
  112. fxn = self.module_for_loader(lambda self, module: module)
  113. return fxn(self, name)
  114. def raise_exception(self, name):
  115. def to_wrap(self, module):
  116. raise ImportError
  117. fxn = self.module_for_loader(to_wrap)
  118. try:
  119. fxn(self, name)
  120. except ImportError:
  121. pass
  122. def test_new_module(self):
  123. # Test that when no module exists in sys.modules a new module is
  124. # created.
  125. module_name = 'a.b.c'
  126. with util.uncache(module_name):
  127. module = self.return_module(module_name)
  128. self.assertIn(module_name, sys.modules)
  129. self.assertIsInstance(module, types.ModuleType)
  130. self.assertEqual(module.__name__, module_name)
  131. def test_reload(self):
  132. # Test that a module is reused if already in sys.modules.
  133. class FakeLoader:
  134. def is_package(self, name):
  135. return True
  136. @self.module_for_loader
  137. def load_module(self, module):
  138. return module
  139. name = 'a.b.c'
  140. module = types.ModuleType('a.b.c')
  141. module.__loader__ = 42
  142. module.__package__ = 42
  143. with util.uncache(name):
  144. sys.modules[name] = module
  145. loader = FakeLoader()
  146. returned_module = loader.load_module(name)
  147. self.assertIs(returned_module, sys.modules[name])
  148. self.assertEqual(module.__loader__, loader)
  149. self.assertEqual(module.__package__, name)
  150. def test_new_module_failure(self):
  151. # Test that a module is removed from sys.modules if added but an
  152. # exception is raised.
  153. name = 'a.b.c'
  154. with util.uncache(name):
  155. self.raise_exception(name)
  156. self.assertNotIn(name, sys.modules)
  157. def test_reload_failure(self):
  158. # Test that a failure on reload leaves the module in-place.
  159. name = 'a.b.c'
  160. module = types.ModuleType(name)
  161. with util.uncache(name):
  162. sys.modules[name] = module
  163. self.raise_exception(name)
  164. self.assertIs(module, sys.modules[name])
  165. def test_decorator_attrs(self):
  166. def fxn(self, module): pass
  167. wrapped = self.module_for_loader(fxn)
  168. self.assertEqual(wrapped.__name__, fxn.__name__)
  169. self.assertEqual(wrapped.__qualname__, fxn.__qualname__)
  170. def test_false_module(self):
  171. # If for some odd reason a module is considered false, still return it
  172. # from sys.modules.
  173. class FalseModule(types.ModuleType):
  174. def __bool__(self): return False
  175. name = 'mod'
  176. module = FalseModule(name)
  177. with util.uncache(name):
  178. self.assertFalse(module)
  179. sys.modules[name] = module
  180. given = self.return_module(name)
  181. self.assertIs(given, module)
  182. def test_attributes_set(self):
  183. # __name__, __loader__, and __package__ should be set (when
  184. # is_package() is defined; undefined implicitly tested elsewhere).
  185. class FakeLoader:
  186. def __init__(self, is_package):
  187. self._pkg = is_package
  188. def is_package(self, name):
  189. return self._pkg
  190. @self.module_for_loader
  191. def load_module(self, module):
  192. return module
  193. name = 'pkg.mod'
  194. with util.uncache(name):
  195. loader = FakeLoader(False)
  196. module = loader.load_module(name)
  197. self.assertEqual(module.__name__, name)
  198. self.assertIs(module.__loader__, loader)
  199. self.assertEqual(module.__package__, 'pkg')
  200. name = 'pkg.sub'
  201. with util.uncache(name):
  202. loader = FakeLoader(True)
  203. module = loader.load_module(name)
  204. self.assertEqual(module.__name__, name)
  205. self.assertIs(module.__loader__, loader)
  206. self.assertEqual(module.__package__, name)
  207. (Frozen_ModuleForLoaderTests,
  208. Source_ModuleForLoaderTests
  209. ) = util.test_both(ModuleForLoaderTests, util=importlib_util)
  210. class SetPackageTests:
  211. """Tests for importlib.util.set_package."""
  212. def verify(self, module, expect):
  213. """Verify the module has the expected value for __package__ after
  214. passing through set_package."""
  215. fxn = lambda: module
  216. wrapped = self.util.set_package(fxn)
  217. with warnings.catch_warnings():
  218. warnings.simplefilter('ignore', DeprecationWarning)
  219. wrapped()
  220. self.assertTrue(hasattr(module, '__package__'))
  221. self.assertEqual(expect, module.__package__)
  222. def test_top_level(self):
  223. # __package__ should be set to the empty string if a top-level module.
  224. # Implicitly tests when package is set to None.
  225. module = types.ModuleType('module')
  226. module.__package__ = None
  227. self.verify(module, '')
  228. def test_package(self):
  229. # Test setting __package__ for a package.
  230. module = types.ModuleType('pkg')
  231. module.__path__ = ['<path>']
  232. module.__package__ = None
  233. self.verify(module, 'pkg')
  234. def test_submodule(self):
  235. # Test __package__ for a module in a package.
  236. module = types.ModuleType('pkg.mod')
  237. module.__package__ = None
  238. self.verify(module, 'pkg')
  239. def test_setting_if_missing(self):
  240. # __package__ should be set if it is missing.
  241. module = types.ModuleType('mod')
  242. if hasattr(module, '__package__'):
  243. delattr(module, '__package__')
  244. self.verify(module, '')
  245. def test_leaving_alone(self):
  246. # If __package__ is set and not None then leave it alone.
  247. for value in (True, False):
  248. module = types.ModuleType('mod')
  249. module.__package__ = value
  250. self.verify(module, value)
  251. def test_decorator_attrs(self):
  252. def fxn(module): pass
  253. with warnings.catch_warnings():
  254. warnings.simplefilter('ignore', DeprecationWarning)
  255. wrapped = self.util.set_package(fxn)
  256. self.assertEqual(wrapped.__name__, fxn.__name__)
  257. self.assertEqual(wrapped.__qualname__, fxn.__qualname__)
  258. (Frozen_SetPackageTests,
  259. Source_SetPackageTests
  260. ) = util.test_both(SetPackageTests, util=importlib_util)
  261. class SetLoaderTests:
  262. """Tests importlib.util.set_loader()."""
  263. @property
  264. def DummyLoader(self):
  265. # Set DummyLoader on the class lazily.
  266. class DummyLoader:
  267. @self.util.set_loader
  268. def load_module(self, module):
  269. return self.module
  270. self.__class__.DummyLoader = DummyLoader
  271. return DummyLoader
  272. def test_no_attribute(self):
  273. loader = self.DummyLoader()
  274. loader.module = types.ModuleType('blah')
  275. try:
  276. del loader.module.__loader__
  277. except AttributeError:
  278. pass
  279. with warnings.catch_warnings():
  280. warnings.simplefilter('ignore', DeprecationWarning)
  281. self.assertEqual(loader, loader.load_module('blah').__loader__)
  282. def test_attribute_is_None(self):
  283. loader = self.DummyLoader()
  284. loader.module = types.ModuleType('blah')
  285. loader.module.__loader__ = None
  286. with warnings.catch_warnings():
  287. warnings.simplefilter('ignore', DeprecationWarning)
  288. self.assertEqual(loader, loader.load_module('blah').__loader__)
  289. def test_not_reset(self):
  290. loader = self.DummyLoader()
  291. loader.module = types.ModuleType('blah')
  292. loader.module.__loader__ = 42
  293. with warnings.catch_warnings():
  294. warnings.simplefilter('ignore', DeprecationWarning)
  295. self.assertEqual(42, loader.load_module('blah').__loader__)
  296. (Frozen_SetLoaderTests,
  297. Source_SetLoaderTests
  298. ) = util.test_both(SetLoaderTests, util=importlib_util)
  299. class ResolveNameTests:
  300. """Tests importlib.util.resolve_name()."""
  301. def test_absolute(self):
  302. # bacon
  303. self.assertEqual('bacon', self.util.resolve_name('bacon', None))
  304. def test_absolute_within_package(self):
  305. # bacon in spam
  306. self.assertEqual('bacon', self.util.resolve_name('bacon', 'spam'))
  307. def test_no_package(self):
  308. # .bacon in ''
  309. with self.assertRaises(ValueError):
  310. self.util.resolve_name('.bacon', '')
  311. def test_in_package(self):
  312. # .bacon in spam
  313. self.assertEqual('spam.eggs.bacon',
  314. self.util.resolve_name('.bacon', 'spam.eggs'))
  315. def test_other_package(self):
  316. # ..bacon in spam.bacon
  317. self.assertEqual('spam.bacon',
  318. self.util.resolve_name('..bacon', 'spam.eggs'))
  319. def test_escape(self):
  320. # ..bacon in spam
  321. with self.assertRaises(ValueError):
  322. self.util.resolve_name('..bacon', 'spam')
  323. (Frozen_ResolveNameTests,
  324. Source_ResolveNameTests
  325. ) = util.test_both(ResolveNameTests, util=importlib_util)
  326. class FindSpecTests:
  327. class FakeMetaFinder:
  328. @staticmethod
  329. def find_spec(name, path=None, target=None): return name, path, target
  330. def test_sys_modules(self):
  331. name = 'some_mod'
  332. with util.uncache(name):
  333. module = types.ModuleType(name)
  334. loader = 'a loader!'
  335. spec = self.machinery.ModuleSpec(name, loader)
  336. module.__loader__ = loader
  337. module.__spec__ = spec
  338. sys.modules[name] = module
  339. found = self.util.find_spec(name)
  340. self.assertEqual(found, spec)
  341. def test_sys_modules_without___loader__(self):
  342. name = 'some_mod'
  343. with util.uncache(name):
  344. module = types.ModuleType(name)
  345. del module.__loader__
  346. loader = 'a loader!'
  347. spec = self.machinery.ModuleSpec(name, loader)
  348. module.__spec__ = spec
  349. sys.modules[name] = module
  350. found = self.util.find_spec(name)
  351. self.assertEqual(found, spec)
  352. def test_sys_modules_spec_is_None(self):
  353. name = 'some_mod'
  354. with util.uncache(name):
  355. module = types.ModuleType(name)
  356. module.__spec__ = None
  357. sys.modules[name] = module
  358. with self.assertRaises(ValueError):
  359. self.util.find_spec(name)
  360. def test_sys_modules_loader_is_None(self):
  361. name = 'some_mod'
  362. with util.uncache(name):
  363. module = types.ModuleType(name)
  364. spec = self.machinery.ModuleSpec(name, None)
  365. module.__spec__ = spec
  366. sys.modules[name] = module
  367. found = self.util.find_spec(name)
  368. self.assertEqual(found, spec)
  369. def test_sys_modules_spec_is_not_set(self):
  370. name = 'some_mod'
  371. with util.uncache(name):
  372. module = types.ModuleType(name)
  373. try:
  374. del module.__spec__
  375. except AttributeError:
  376. pass
  377. sys.modules[name] = module
  378. with self.assertRaises(ValueError):
  379. self.util.find_spec(name)
  380. def test_success(self):
  381. name = 'some_mod'
  382. with util.uncache(name):
  383. with util.import_state(meta_path=[self.FakeMetaFinder]):
  384. self.assertEqual((name, None, None),
  385. self.util.find_spec(name))
  386. def test_nothing(self):
  387. # None is returned upon failure to find a loader.
  388. self.assertIsNone(self.util.find_spec('nevergoingtofindthismodule'))
  389. def test_find_submodule(self):
  390. name = 'spam'
  391. subname = 'ham'
  392. with util.temp_module(name, pkg=True) as pkg_dir:
  393. fullname, _ = util.submodule(name, subname, pkg_dir)
  394. spec = self.util.find_spec(fullname)
  395. self.assertIsNot(spec, None)
  396. self.assertIn(name, sorted(sys.modules))
  397. self.assertNotIn(fullname, sorted(sys.modules))
  398. # Ensure successive calls behave the same.
  399. spec_again = self.util.find_spec(fullname)
  400. self.assertEqual(spec_again, spec)
  401. def test_find_submodule_parent_already_imported(self):
  402. name = 'spam'
  403. subname = 'ham'
  404. with util.temp_module(name, pkg=True) as pkg_dir:
  405. self.init.import_module(name)
  406. fullname, _ = util.submodule(name, subname, pkg_dir)
  407. spec = self.util.find_spec(fullname)
  408. self.assertIsNot(spec, None)
  409. self.assertIn(name, sorted(sys.modules))
  410. self.assertNotIn(fullname, sorted(sys.modules))
  411. # Ensure successive calls behave the same.
  412. spec_again = self.util.find_spec(fullname)
  413. self.assertEqual(spec_again, spec)
  414. def test_find_relative_module(self):
  415. name = 'spam'
  416. subname = 'ham'
  417. with util.temp_module(name, pkg=True) as pkg_dir:
  418. fullname, _ = util.submodule(name, subname, pkg_dir)
  419. relname = '.' + subname
  420. spec = self.util.find_spec(relname, name)
  421. self.assertIsNot(spec, None)
  422. self.assertIn(name, sorted(sys.modules))
  423. self.assertNotIn(fullname, sorted(sys.modules))
  424. # Ensure successive calls behave the same.
  425. spec_again = self.util.find_spec(fullname)
  426. self.assertEqual(spec_again, spec)
  427. def test_find_relative_module_missing_package(self):
  428. name = 'spam'
  429. subname = 'ham'
  430. with util.temp_module(name, pkg=True) as pkg_dir:
  431. fullname, _ = util.submodule(name, subname, pkg_dir)
  432. relname = '.' + subname
  433. with self.assertRaises(ValueError):
  434. self.util.find_spec(relname)
  435. self.assertNotIn(name, sorted(sys.modules))
  436. self.assertNotIn(fullname, sorted(sys.modules))
  437. def test_find_submodule_in_module(self):
  438. # ModuleNotFoundError raised when a module is specified as
  439. # a parent instead of a package.
  440. with self.assertRaises(ModuleNotFoundError):
  441. self.util.find_spec('module.name')
  442. (Frozen_FindSpecTests,
  443. Source_FindSpecTests
  444. ) = util.test_both(FindSpecTests, init=init, util=importlib_util,
  445. machinery=machinery)
  446. class MagicNumberTests:
  447. def test_length(self):
  448. # Should be 4 bytes.
  449. self.assertEqual(len(self.util.MAGIC_NUMBER), 4)
  450. def test_incorporates_rn(self):
  451. # The magic number uses \r\n to come out wrong when splitting on lines.
  452. self.assertTrue(self.util.MAGIC_NUMBER.endswith(b'\r\n'))
  453. (Frozen_MagicNumberTests,
  454. Source_MagicNumberTests
  455. ) = util.test_both(MagicNumberTests, util=importlib_util)
  456. class PEP3147Tests:
  457. """Tests of PEP 3147-related functions: cache_from_source and source_from_cache."""
  458. tag = sys.implementation.cache_tag
  459. @unittest.skipUnless(sys.implementation.cache_tag is not None,
  460. 'requires sys.implementation.cache_tag not be None')
  461. def test_cache_from_source(self):
  462. # Given the path to a .py file, return the path to its PEP 3147
  463. # defined .pyc file (i.e. under __pycache__).
  464. path = os.path.join('foo', 'bar', 'baz', 'qux.py')
  465. expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
  466. 'qux.{}.pyc'.format(self.tag))
  467. self.assertEqual(self.util.cache_from_source(path, optimization=''),
  468. expect)
  469. def test_cache_from_source_no_cache_tag(self):
  470. # No cache tag means NotImplementedError.
  471. with support.swap_attr(sys.implementation, 'cache_tag', None):
  472. with self.assertRaises(NotImplementedError):
  473. self.util.cache_from_source('whatever.py')
  474. def test_cache_from_source_no_dot(self):
  475. # Directory with a dot, filename without dot.
  476. path = os.path.join('foo.bar', 'file')
  477. expect = os.path.join('foo.bar', '__pycache__',
  478. 'file{}.pyc'.format(self.tag))
  479. self.assertEqual(self.util.cache_from_source(path, optimization=''),
  480. expect)
  481. def test_cache_from_source_debug_override(self):
  482. # Given the path to a .py file, return the path to its PEP 3147/PEP 488
  483. # defined .pyc file (i.e. under __pycache__).
  484. path = os.path.join('foo', 'bar', 'baz', 'qux.py')
  485. with warnings.catch_warnings():
  486. warnings.simplefilter('ignore')
  487. self.assertEqual(self.util.cache_from_source(path, False),
  488. self.util.cache_from_source(path, optimization=1))
  489. self.assertEqual(self.util.cache_from_source(path, True),
  490. self.util.cache_from_source(path, optimization=''))
  491. with warnings.catch_warnings():
  492. warnings.simplefilter('error')
  493. with self.assertRaises(DeprecationWarning):
  494. self.util.cache_from_source(path, False)
  495. with self.assertRaises(DeprecationWarning):
  496. self.util.cache_from_source(path, True)
  497. def test_cache_from_source_cwd(self):
  498. path = 'foo.py'
  499. expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
  500. self.assertEqual(self.util.cache_from_source(path, optimization=''),
  501. expect)
  502. def test_cache_from_source_override(self):
  503. # When debug_override is not None, it can be any true-ish or false-ish
  504. # value.
  505. path = os.path.join('foo', 'bar', 'baz.py')
  506. # However if the bool-ishness can't be determined, the exception
  507. # propagates.
  508. class Bearish:
  509. def __bool__(self): raise RuntimeError
  510. with warnings.catch_warnings():
  511. warnings.simplefilter('ignore')
  512. self.assertEqual(self.util.cache_from_source(path, []),
  513. self.util.cache_from_source(path, optimization=1))
  514. self.assertEqual(self.util.cache_from_source(path, [17]),
  515. self.util.cache_from_source(path, optimization=''))
  516. with self.assertRaises(RuntimeError):
  517. self.util.cache_from_source('/foo/bar/baz.py', Bearish())
  518. def test_cache_from_source_optimization_empty_string(self):
  519. # Setting 'optimization' to '' leads to no optimization tag (PEP 488).
  520. path = 'foo.py'
  521. expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
  522. self.assertEqual(self.util.cache_from_source(path, optimization=''),
  523. expect)
  524. def test_cache_from_source_optimization_None(self):
  525. # Setting 'optimization' to None uses the interpreter's optimization.
  526. # (PEP 488)
  527. path = 'foo.py'
  528. optimization_level = sys.flags.optimize
  529. almost_expect = os.path.join('__pycache__', 'foo.{}'.format(self.tag))
  530. if optimization_level == 0:
  531. expect = almost_expect + '.pyc'
  532. elif optimization_level <= 2:
  533. expect = almost_expect + '.opt-{}.pyc'.format(optimization_level)
  534. else:
  535. msg = '{!r} is a non-standard optimization level'.format(optimization_level)
  536. self.skipTest(msg)
  537. self.assertEqual(self.util.cache_from_source(path, optimization=None),
  538. expect)
  539. def test_cache_from_source_optimization_set(self):
  540. # The 'optimization' parameter accepts anything that has a string repr
  541. # that passes str.alnum().
  542. path = 'foo.py'
  543. valid_characters = string.ascii_letters + string.digits
  544. almost_expect = os.path.join('__pycache__', 'foo.{}'.format(self.tag))
  545. got = self.util.cache_from_source(path, optimization=valid_characters)
  546. # Test all valid characters are accepted.
  547. self.assertEqual(got,
  548. almost_expect + '.opt-{}.pyc'.format(valid_characters))
  549. # str() should be called on argument.
  550. self.assertEqual(self.util.cache_from_source(path, optimization=42),
  551. almost_expect + '.opt-42.pyc')
  552. # Invalid characters raise ValueError.
  553. with self.assertRaises(ValueError):
  554. self.util.cache_from_source(path, optimization='path/is/bad')
  555. def test_cache_from_source_debug_override_optimization_both_set(self):
  556. # Can only set one of the optimization-related parameters.
  557. with warnings.catch_warnings():
  558. warnings.simplefilter('ignore')
  559. with self.assertRaises(TypeError):
  560. self.util.cache_from_source('foo.py', False, optimization='')
  561. @unittest.skipUnless(os.sep == '\\' and os.altsep == '/',
  562. 'test meaningful only where os.altsep is defined')
  563. def test_sep_altsep_and_sep_cache_from_source(self):
  564. # Windows path and PEP 3147 where sep is right of altsep.
  565. self.assertEqual(
  566. self.util.cache_from_source('\\foo\\bar\\baz/qux.py', optimization=''),
  567. '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
  568. @unittest.skipUnless(sys.implementation.cache_tag is not None,
  569. 'requires sys.implementation.cache_tag not be None')
  570. def test_source_from_cache_path_like_arg(self):
  571. path = pathlib.PurePath('foo', 'bar', 'baz', 'qux.py')
  572. expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
  573. 'qux.{}.pyc'.format(self.tag))
  574. self.assertEqual(self.util.cache_from_source(path, optimization=''),
  575. expect)
  576. @unittest.skipUnless(sys.implementation.cache_tag is not None,
  577. 'requires sys.implementation.cache_tag to not be '
  578. 'None')
  579. def test_source_from_cache(self):
  580. # Given the path to a PEP 3147 defined .pyc file, return the path to
  581. # its source. This tests the good path.
  582. path = os.path.join('foo', 'bar', 'baz', '__pycache__',
  583. 'qux.{}.pyc'.format(self.tag))
  584. expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
  585. self.assertEqual(self.util.source_from_cache(path), expect)
  586. def test_source_from_cache_no_cache_tag(self):
  587. # If sys.implementation.cache_tag is None, raise NotImplementedError.
  588. path = os.path.join('blah', '__pycache__', 'whatever.pyc')
  589. with support.swap_attr(sys.implementation, 'cache_tag', None):
  590. with self.assertRaises(NotImplementedError):
  591. self.util.source_from_cache(path)
  592. def test_source_from_cache_bad_path(self):
  593. # When the path to a pyc file is not in PEP 3147 format, a ValueError
  594. # is raised.
  595. self.assertRaises(
  596. ValueError, self.util.source_from_cache, '/foo/bar/bazqux.pyc')
  597. def test_source_from_cache_no_slash(self):
  598. # No slashes at all in path -> ValueError
  599. self.assertRaises(
  600. ValueError, self.util.source_from_cache, 'foo.cpython-32.pyc')
  601. def test_source_from_cache_too_few_dots(self):
  602. # Too few dots in final path component -> ValueError
  603. self.assertRaises(
  604. ValueError, self.util.source_from_cache, '__pycache__/foo.pyc')
  605. def test_source_from_cache_too_many_dots(self):
  606. with self.assertRaises(ValueError):
  607. self.util.source_from_cache(
  608. '__pycache__/foo.cpython-32.opt-1.foo.pyc')
  609. def test_source_from_cache_not_opt(self):
  610. # Non-`opt-` path component -> ValueError
  611. self.assertRaises(
  612. ValueError, self.util.source_from_cache,
  613. '__pycache__/foo.cpython-32.foo.pyc')
  614. def test_source_from_cache_no__pycache__(self):
  615. # Another problem with the path -> ValueError
  616. self.assertRaises(
  617. ValueError, self.util.source_from_cache,
  618. '/foo/bar/foo.cpython-32.foo.pyc')
  619. def test_source_from_cache_optimized_bytecode(self):
  620. # Optimized bytecode is not an issue.
  621. path = os.path.join('__pycache__', 'foo.{}.opt-1.pyc'.format(self.tag))
  622. self.assertEqual(self.util.source_from_cache(path), 'foo.py')
  623. def test_source_from_cache_missing_optimization(self):
  624. # An empty optimization level is a no-no.
  625. path = os.path.join('__pycache__', 'foo.{}.opt-.pyc'.format(self.tag))
  626. with self.assertRaises(ValueError):
  627. self.util.source_from_cache(path)
  628. @unittest.skipUnless(sys.implementation.cache_tag is not None,
  629. 'requires sys.implementation.cache_tag to not be '
  630. 'None')
  631. def test_source_from_cache_path_like_arg(self):
  632. path = pathlib.PurePath('foo', 'bar', 'baz', '__pycache__',
  633. 'qux.{}.pyc'.format(self.tag))
  634. expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
  635. self.assertEqual(self.util.source_from_cache(path), expect)
  636. (Frozen_PEP3147Tests,
  637. Source_PEP3147Tests
  638. ) = util.test_both(PEP3147Tests, util=importlib_util)
  639. class MagicNumberTests(unittest.TestCase):
  640. """
  641. Test release compatibility issues relating to importlib
  642. """
  643. @unittest.skipUnless(
  644. sys.version_info.releaselevel in ('candidate', 'final'),
  645. 'only applies to candidate or final python release levels'
  646. )
  647. def test_magic_number(self):
  648. """
  649. Each python minor release should generally have a MAGIC_NUMBER
  650. that does not change once the release reaches candidate status.
  651. Once a release reaches candidate status, the value of the constant
  652. EXPECTED_MAGIC_NUMBER in this test should be changed.
  653. This test will then check that the actual MAGIC_NUMBER matches
  654. the expected value for the release.
  655. In exceptional cases, it may be required to change the MAGIC_NUMBER
  656. for a maintenance release. In this case the change should be
  657. discussed in python-dev. If a change is required, community
  658. stakeholders such as OS package maintainers must be notified
  659. in advance. Such exceptional releases will then require an
  660. adjustment to this test case.
  661. """
  662. EXPECTED_MAGIC_NUMBER = 3394
  663. actual = int.from_bytes(importlib.util.MAGIC_NUMBER[:2], 'little')
  664. msg = (
  665. "To avoid breaking backwards compatibility with cached bytecode "
  666. "files that can't be automatically regenerated by the current "
  667. "user, candidate and final releases require the current "
  668. "importlib.util.MAGIC_NUMBER to match the expected "
  669. "magic number in this test. Set the expected "
  670. "magic number in this test to the current MAGIC_NUMBER to "
  671. "continue with the release.\n\n"
  672. "Changing the MAGIC_NUMBER for a maintenance release "
  673. "requires discussion in python-dev and notification of "
  674. "community stakeholders."
  675. )
  676. self.assertEqual(EXPECTED_MAGIC_NUMBER, actual, msg)
  677. if __name__ == '__main__':
  678. unittest.main()