test_imp.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. import gc
  2. import importlib
  3. import importlib.util
  4. import os
  5. import os.path
  6. import py_compile
  7. import sys
  8. from test import support
  9. from test.support import import_helper
  10. from test.support import os_helper
  11. from test.support import script_helper
  12. from test.support import warnings_helper
  13. import unittest
  14. import warnings
  15. imp = warnings_helper.import_deprecated('imp')
  16. import _imp
  17. OS_PATH_NAME = os.path.__name__
  18. def requires_load_dynamic(meth):
  19. """Decorator to skip a test if not running under CPython or lacking
  20. imp.load_dynamic()."""
  21. meth = support.cpython_only(meth)
  22. return unittest.skipIf(getattr(imp, 'load_dynamic', None) is None,
  23. 'imp.load_dynamic() required')(meth)
  24. class LockTests(unittest.TestCase):
  25. """Very basic test of import lock functions."""
  26. def verify_lock_state(self, expected):
  27. self.assertEqual(imp.lock_held(), expected,
  28. "expected imp.lock_held() to be %r" % expected)
  29. def testLock(self):
  30. LOOPS = 50
  31. # The import lock may already be held, e.g. if the test suite is run
  32. # via "import test.autotest".
  33. lock_held_at_start = imp.lock_held()
  34. self.verify_lock_state(lock_held_at_start)
  35. for i in range(LOOPS):
  36. imp.acquire_lock()
  37. self.verify_lock_state(True)
  38. for i in range(LOOPS):
  39. imp.release_lock()
  40. # The original state should be restored now.
  41. self.verify_lock_state(lock_held_at_start)
  42. if not lock_held_at_start:
  43. try:
  44. imp.release_lock()
  45. except RuntimeError:
  46. pass
  47. else:
  48. self.fail("release_lock() without lock should raise "
  49. "RuntimeError")
  50. class ImportTests(unittest.TestCase):
  51. def setUp(self):
  52. mod = importlib.import_module('test.encoded_modules')
  53. self.test_strings = mod.test_strings
  54. self.test_path = mod.__path__
  55. def test_import_encoded_module(self):
  56. for modname, encoding, teststr in self.test_strings:
  57. mod = importlib.import_module('test.encoded_modules.'
  58. 'module_' + modname)
  59. self.assertEqual(teststr, mod.test)
  60. def test_find_module_encoding(self):
  61. for mod, encoding, _ in self.test_strings:
  62. with imp.find_module('module_' + mod, self.test_path)[0] as fd:
  63. self.assertEqual(fd.encoding, encoding)
  64. path = [os.path.dirname(__file__)]
  65. with self.assertRaises(SyntaxError):
  66. imp.find_module('badsyntax_pep3120', path)
  67. def test_issue1267(self):
  68. for mod, encoding, _ in self.test_strings:
  69. fp, filename, info = imp.find_module('module_' + mod,
  70. self.test_path)
  71. with fp:
  72. self.assertNotEqual(fp, None)
  73. self.assertEqual(fp.encoding, encoding)
  74. self.assertEqual(fp.tell(), 0)
  75. self.assertEqual(fp.readline(), '# test %s encoding\n'
  76. % encoding)
  77. fp, filename, info = imp.find_module("tokenize")
  78. with fp:
  79. self.assertNotEqual(fp, None)
  80. self.assertEqual(fp.encoding, "utf-8")
  81. self.assertEqual(fp.tell(), 0)
  82. self.assertEqual(fp.readline(),
  83. '"""Tokenization help for Python programs.\n')
  84. def test_issue3594(self):
  85. temp_mod_name = 'test_imp_helper'
  86. sys.path.insert(0, '.')
  87. try:
  88. with open(temp_mod_name + '.py', 'w', encoding="latin-1") as file:
  89. file.write("# coding: cp1252\nu = 'test.test_imp'\n")
  90. file, filename, info = imp.find_module(temp_mod_name)
  91. file.close()
  92. self.assertEqual(file.encoding, 'cp1252')
  93. finally:
  94. del sys.path[0]
  95. os_helper.unlink(temp_mod_name + '.py')
  96. os_helper.unlink(temp_mod_name + '.pyc')
  97. def test_issue5604(self):
  98. # Test cannot cover imp.load_compiled function.
  99. # Martin von Loewis note what shared library cannot have non-ascii
  100. # character because init_xxx function cannot be compiled
  101. # and issue never happens for dynamic modules.
  102. # But sources modified to follow generic way for processing paths.
  103. # the return encoding could be uppercase or None
  104. fs_encoding = sys.getfilesystemencoding()
  105. # covers utf-8 and Windows ANSI code pages
  106. # one non-space symbol from every page
  107. # (http://en.wikipedia.org/wiki/Code_page)
  108. known_locales = {
  109. 'utf-8' : b'\xc3\xa4',
  110. 'cp1250' : b'\x8C',
  111. 'cp1251' : b'\xc0',
  112. 'cp1252' : b'\xc0',
  113. 'cp1253' : b'\xc1',
  114. 'cp1254' : b'\xc0',
  115. 'cp1255' : b'\xe0',
  116. 'cp1256' : b'\xe0',
  117. 'cp1257' : b'\xc0',
  118. 'cp1258' : b'\xc0',
  119. }
  120. if sys.platform == 'darwin':
  121. self.assertEqual(fs_encoding, 'utf-8')
  122. # Mac OS X uses the Normal Form D decomposition
  123. # http://developer.apple.com/mac/library/qa/qa2001/qa1173.html
  124. special_char = b'a\xcc\x88'
  125. else:
  126. special_char = known_locales.get(fs_encoding)
  127. if not special_char:
  128. self.skipTest("can't run this test with %s as filesystem encoding"
  129. % fs_encoding)
  130. decoded_char = special_char.decode(fs_encoding)
  131. temp_mod_name = 'test_imp_helper_' + decoded_char
  132. test_package_name = 'test_imp_helper_package_' + decoded_char
  133. init_file_name = os.path.join(test_package_name, '__init__.py')
  134. try:
  135. # if the curdir is not in sys.path the test fails when run with
  136. # ./python ./Lib/test/regrtest.py test_imp
  137. sys.path.insert(0, os.curdir)
  138. with open(temp_mod_name + '.py', 'w', encoding="utf-8") as file:
  139. file.write('a = 1\n')
  140. file, filename, info = imp.find_module(temp_mod_name)
  141. with file:
  142. self.assertIsNotNone(file)
  143. self.assertTrue(filename[:-3].endswith(temp_mod_name))
  144. self.assertEqual(info[0], '.py')
  145. self.assertEqual(info[1], 'r')
  146. self.assertEqual(info[2], imp.PY_SOURCE)
  147. mod = imp.load_module(temp_mod_name, file, filename, info)
  148. self.assertEqual(mod.a, 1)
  149. with warnings.catch_warnings():
  150. warnings.simplefilter('ignore')
  151. mod = imp.load_source(temp_mod_name, temp_mod_name + '.py')
  152. self.assertEqual(mod.a, 1)
  153. with warnings.catch_warnings():
  154. warnings.simplefilter('ignore')
  155. if not sys.dont_write_bytecode:
  156. mod = imp.load_compiled(
  157. temp_mod_name,
  158. imp.cache_from_source(temp_mod_name + '.py'))
  159. self.assertEqual(mod.a, 1)
  160. if not os.path.exists(test_package_name):
  161. os.mkdir(test_package_name)
  162. with open(init_file_name, 'w', encoding="utf-8") as file:
  163. file.write('b = 2\n')
  164. with warnings.catch_warnings():
  165. warnings.simplefilter('ignore')
  166. package = imp.load_package(test_package_name, test_package_name)
  167. self.assertEqual(package.b, 2)
  168. finally:
  169. del sys.path[0]
  170. for ext in ('.py', '.pyc'):
  171. os_helper.unlink(temp_mod_name + ext)
  172. os_helper.unlink(init_file_name + ext)
  173. os_helper.rmtree(test_package_name)
  174. os_helper.rmtree('__pycache__')
  175. def test_issue9319(self):
  176. path = os.path.dirname(__file__)
  177. self.assertRaises(SyntaxError,
  178. imp.find_module, "badsyntax_pep3120", [path])
  179. def test_load_from_source(self):
  180. # Verify that the imp module can correctly load and find .py files
  181. # XXX (ncoghlan): It would be nice to use import_helper.CleanImport
  182. # here, but that breaks because the os module registers some
  183. # handlers in copy_reg on import. Since CleanImport doesn't
  184. # revert that registration, the module is left in a broken
  185. # state after reversion. Reinitialising the module contents
  186. # and just reverting os.environ to its previous state is an OK
  187. # workaround
  188. with import_helper.CleanImport('os', 'os.path', OS_PATH_NAME):
  189. import os
  190. orig_path = os.path
  191. orig_getenv = os.getenv
  192. with os_helper.EnvironmentVarGuard():
  193. x = imp.find_module("os")
  194. self.addCleanup(x[0].close)
  195. new_os = imp.load_module("os", *x)
  196. self.assertIs(os, new_os)
  197. self.assertIs(orig_path, new_os.path)
  198. self.assertIsNot(orig_getenv, new_os.getenv)
  199. @requires_load_dynamic
  200. def test_issue15828_load_extensions(self):
  201. # Issue 15828 picked up that the adapter between the old imp API
  202. # and importlib couldn't handle C extensions
  203. example = "_heapq"
  204. x = imp.find_module(example)
  205. file_ = x[0]
  206. if file_ is not None:
  207. self.addCleanup(file_.close)
  208. mod = imp.load_module(example, *x)
  209. self.assertEqual(mod.__name__, example)
  210. @requires_load_dynamic
  211. def test_issue16421_multiple_modules_in_one_dll(self):
  212. # Issue 16421: loading several modules from the same compiled file fails
  213. m = '_testimportmultiple'
  214. fileobj, pathname, description = imp.find_module(m)
  215. fileobj.close()
  216. mod0 = imp.load_dynamic(m, pathname)
  217. mod1 = imp.load_dynamic('_testimportmultiple_foo', pathname)
  218. mod2 = imp.load_dynamic('_testimportmultiple_bar', pathname)
  219. self.assertEqual(mod0.__name__, m)
  220. self.assertEqual(mod1.__name__, '_testimportmultiple_foo')
  221. self.assertEqual(mod2.__name__, '_testimportmultiple_bar')
  222. with self.assertRaises(ImportError):
  223. imp.load_dynamic('nonexistent', pathname)
  224. @requires_load_dynamic
  225. def test_load_dynamic_ImportError_path(self):
  226. # Issue #1559549 added `name` and `path` attributes to ImportError
  227. # in order to provide better detail. Issue #10854 implemented those
  228. # attributes on import failures of extensions on Windows.
  229. path = 'bogus file path'
  230. name = 'extension'
  231. with self.assertRaises(ImportError) as err:
  232. imp.load_dynamic(name, path)
  233. self.assertIn(path, err.exception.path)
  234. self.assertEqual(name, err.exception.name)
  235. @requires_load_dynamic
  236. def test_load_module_extension_file_is_None(self):
  237. # When loading an extension module and the file is None, open one
  238. # on the behalf of imp.load_dynamic().
  239. # Issue #15902
  240. name = '_testimportmultiple'
  241. found = imp.find_module(name)
  242. if found[0] is not None:
  243. found[0].close()
  244. if found[2][2] != imp.C_EXTENSION:
  245. self.skipTest("found module doesn't appear to be a C extension")
  246. imp.load_module(name, None, *found[1:])
  247. @requires_load_dynamic
  248. def test_issue24748_load_module_skips_sys_modules_check(self):
  249. name = 'test.imp_dummy'
  250. try:
  251. del sys.modules[name]
  252. except KeyError:
  253. pass
  254. try:
  255. module = importlib.import_module(name)
  256. spec = importlib.util.find_spec('_testmultiphase')
  257. module = imp.load_dynamic(name, spec.origin)
  258. self.assertEqual(module.__name__, name)
  259. self.assertEqual(module.__spec__.name, name)
  260. self.assertEqual(module.__spec__.origin, spec.origin)
  261. self.assertRaises(AttributeError, getattr, module, 'dummy_name')
  262. self.assertEqual(module.int_const, 1969)
  263. self.assertIs(sys.modules[name], module)
  264. finally:
  265. try:
  266. del sys.modules[name]
  267. except KeyError:
  268. pass
  269. @unittest.skipIf(sys.dont_write_bytecode,
  270. "test meaningful only when writing bytecode")
  271. def test_bug7732(self):
  272. with os_helper.temp_cwd():
  273. source = os_helper.TESTFN + '.py'
  274. os.mkdir(source)
  275. self.assertRaisesRegex(ImportError, '^No module',
  276. imp.find_module, os_helper.TESTFN, ["."])
  277. def test_multiple_calls_to_get_data(self):
  278. # Issue #18755: make sure multiple calls to get_data() can succeed.
  279. loader = imp._LoadSourceCompatibility('imp', imp.__file__,
  280. open(imp.__file__, encoding="utf-8"))
  281. loader.get_data(imp.__file__) # File should be closed
  282. loader.get_data(imp.__file__) # Will need to create a newly opened file
  283. def test_load_source(self):
  284. # Create a temporary module since load_source(name) modifies
  285. # sys.modules[name] attributes like __loader___
  286. modname = f"tmp{__name__}"
  287. mod = type(sys.modules[__name__])(modname)
  288. with support.swap_item(sys.modules, modname, mod):
  289. with self.assertRaisesRegex(ValueError, 'embedded null'):
  290. imp.load_source(modname, __file__ + "\0")
  291. @support.cpython_only
  292. def test_issue31315(self):
  293. # There shouldn't be an assertion failure in imp.create_dynamic(),
  294. # when spec.name is not a string.
  295. create_dynamic = support.get_attribute(imp, 'create_dynamic')
  296. class BadSpec:
  297. name = None
  298. origin = 'foo'
  299. with self.assertRaises(TypeError):
  300. create_dynamic(BadSpec())
  301. def test_issue_35321(self):
  302. # Both _frozen_importlib and _frozen_importlib_external
  303. # should have a spec origin of "frozen" and
  304. # no need to clean up imports in this case.
  305. import _frozen_importlib_external
  306. self.assertEqual(_frozen_importlib_external.__spec__.origin, "frozen")
  307. import _frozen_importlib
  308. self.assertEqual(_frozen_importlib.__spec__.origin, "frozen")
  309. def test_source_hash(self):
  310. self.assertEqual(_imp.source_hash(42, b'hi'), b'\xfb\xd9G\x05\xaf$\x9b~')
  311. self.assertEqual(_imp.source_hash(43, b'hi'), b'\xd0/\x87C\xccC\xff\xe2')
  312. def test_pyc_invalidation_mode_from_cmdline(self):
  313. cases = [
  314. ([], "default"),
  315. (["--check-hash-based-pycs", "default"], "default"),
  316. (["--check-hash-based-pycs", "always"], "always"),
  317. (["--check-hash-based-pycs", "never"], "never"),
  318. ]
  319. for interp_args, expected in cases:
  320. args = interp_args + [
  321. "-c",
  322. "import _imp; print(_imp.check_hash_based_pycs)",
  323. ]
  324. res = script_helper.assert_python_ok(*args)
  325. self.assertEqual(res.out.strip().decode('utf-8'), expected)
  326. def test_find_and_load_checked_pyc(self):
  327. # issue 34056
  328. with os_helper.temp_cwd():
  329. with open('mymod.py', 'wb') as fp:
  330. fp.write(b'x = 42\n')
  331. py_compile.compile(
  332. 'mymod.py',
  333. doraise=True,
  334. invalidation_mode=py_compile.PycInvalidationMode.CHECKED_HASH,
  335. )
  336. file, path, description = imp.find_module('mymod', path=['.'])
  337. mod = imp.load_module('mymod', file, path, description)
  338. self.assertEqual(mod.x, 42)
  339. @support.cpython_only
  340. def test_create_builtin_subinterp(self):
  341. # gh-99578: create_builtin() behavior changes after the creation of the
  342. # first sub-interpreter. Test both code paths, before and after the
  343. # creation of a sub-interpreter. Previously, create_builtin() had
  344. # a reference leak after the creation of the first sub-interpreter.
  345. import builtins
  346. create_builtin = support.get_attribute(_imp, "create_builtin")
  347. class Spec:
  348. name = "builtins"
  349. spec = Spec()
  350. def check_get_builtins():
  351. refcnt = sys.getrefcount(builtins)
  352. mod = _imp.create_builtin(spec)
  353. self.assertIs(mod, builtins)
  354. self.assertEqual(sys.getrefcount(builtins), refcnt + 1)
  355. # Check that a GC collection doesn't crash
  356. gc.collect()
  357. check_get_builtins()
  358. ret = support.run_in_subinterp("import builtins")
  359. self.assertEqual(ret, 0)
  360. check_get_builtins()
  361. class ReloadTests(unittest.TestCase):
  362. """Very basic tests to make sure that imp.reload() operates just like
  363. reload()."""
  364. def test_source(self):
  365. # XXX (ncoghlan): It would be nice to use test.import_helper.CleanImport
  366. # here, but that breaks because the os module registers some
  367. # handlers in copy_reg on import. Since CleanImport doesn't
  368. # revert that registration, the module is left in a broken
  369. # state after reversion. Reinitialising the module contents
  370. # and just reverting os.environ to its previous state is an OK
  371. # workaround
  372. with os_helper.EnvironmentVarGuard():
  373. import os
  374. imp.reload(os)
  375. def test_extension(self):
  376. with import_helper.CleanImport('time'):
  377. import time
  378. imp.reload(time)
  379. def test_builtin(self):
  380. with import_helper.CleanImport('marshal'):
  381. import marshal
  382. imp.reload(marshal)
  383. def test_with_deleted_parent(self):
  384. # see #18681
  385. from html import parser
  386. html = sys.modules.pop('html')
  387. def cleanup():
  388. sys.modules['html'] = html
  389. self.addCleanup(cleanup)
  390. with self.assertRaisesRegex(ImportError, 'html'):
  391. imp.reload(parser)
  392. class PEP3147Tests(unittest.TestCase):
  393. """Tests of PEP 3147."""
  394. tag = imp.get_tag()
  395. @unittest.skipUnless(sys.implementation.cache_tag is not None,
  396. 'requires sys.implementation.cache_tag not be None')
  397. def test_cache_from_source(self):
  398. # Given the path to a .py file, return the path to its PEP 3147
  399. # defined .pyc file (i.e. under __pycache__).
  400. path = os.path.join('foo', 'bar', 'baz', 'qux.py')
  401. expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
  402. 'qux.{}.pyc'.format(self.tag))
  403. self.assertEqual(imp.cache_from_source(path, True), expect)
  404. @unittest.skipUnless(sys.implementation.cache_tag is not None,
  405. 'requires sys.implementation.cache_tag to not be '
  406. 'None')
  407. def test_source_from_cache(self):
  408. # Given the path to a PEP 3147 defined .pyc file, return the path to
  409. # its source. This tests the good path.
  410. path = os.path.join('foo', 'bar', 'baz', '__pycache__',
  411. 'qux.{}.pyc'.format(self.tag))
  412. expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
  413. self.assertEqual(imp.source_from_cache(path), expect)
  414. class NullImporterTests(unittest.TestCase):
  415. @unittest.skipIf(os_helper.TESTFN_UNENCODABLE is None,
  416. "Need an undecodeable filename")
  417. def test_unencodeable(self):
  418. name = os_helper.TESTFN_UNENCODABLE
  419. os.mkdir(name)
  420. try:
  421. self.assertRaises(ImportError, imp.NullImporter, name)
  422. finally:
  423. os.rmdir(name)
  424. if __name__ == "__main__":
  425. unittest.main()