Debian Codegraph @

lib-python/3/test/test_imp.py

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