Debian Codegraph @

Lib/test/test_import/__init__.py

raw
1 import builtins
2 import errno
3 import glob
4 import json
5 import importlib.util
6 from importlib._bootstrap_external import _get_sourcefile
7 from importlib.machinery import (
8 AppleFrameworkLoader,
9 BuiltinImporter,
10 ExtensionFileLoader,
11 FrozenImporter,
12 SourceFileLoader,
13 )
14 import marshal
15 import os
16 import py_compile
17 import random
18 import shutil
19 import stat
20 import subprocess
21 import sys
22 import textwrap
23 import threading
24 import time
25 import types
26 import unittest
27 from unittest import mock
28 import _imp
29
30 from test.support import os_helper
31 from test.support import (
32 STDLIB_DIR,
33 swap_attr,
34 swap_item,
35 cpython_only,
36 is_apple_mobile,
37 is_emscripten,
38 is_wasi,
39 run_in_subinterp,
40 run_in_subinterp_with_config,
41 Py_TRACE_REFS,
42 requires_gil_enabled,
43 Py_GIL_DISABLED,
44 force_not_colorized_test_class,
45 catch_unraisable_exception
46 )
47 from test.support.import_helper import (
48 forget, make_legacy_pyc, unlink, unload, ready_to_import,
49 DirsOnSysPath, CleanImport, import_module)
50 from test.support.os_helper import (
51 TESTFN, rmtree, temp_umask, TESTFN_UNENCODABLE)
52 from test.support import script_helper
53 from test.support import threading_helper
54 from test.support.testcase import ExtraAssertions
55 from test.test_importlib.util import uncache
56 from types import ModuleType
57 try:
58 import _testsinglephase
59 except ImportError:
60 _testsinglephase = None
61 try:
62 import _testmultiphase
63 except ImportError:
64 _testmultiphase = None
65 try:
66 import _interpreters
67 except ModuleNotFoundError:
68 _interpreters = None
69 try:
70 import _testinternalcapi
71 except ImportError:
72 _testinternalcapi = None
73
74
75 skip_if_dont_write_bytecode = unittest.skipIf(
76 sys.dont_write_bytecode,
77 "test meaningful only when writing bytecode")
78
79
80 def _require_loader(module, loader, skip):
81 if isinstance(module, str):
82 module = __import__(module)
83
84 MODULE_KINDS = {
85 BuiltinImporter: 'built-in',
86 ExtensionFileLoader: 'extension',
87 AppleFrameworkLoader: 'framework extension',
88 FrozenImporter: 'frozen',
89 SourceFileLoader: 'pure Python',
90 }
91
92 expected = loader
93 assert isinstance(expected, type), expected
94 expected = MODULE_KINDS[expected]
95
96 actual = module.__spec__.loader
97 if not isinstance(actual, type):
98 actual = type(actual)
99 actual = MODULE_KINDS[actual]
100
101 if actual != expected:
102 err = f'expected module to be {expected}, got {module.__spec__}'
103 if skip:
104 raise unittest.SkipTest(err)
105 raise Exception(err)
106 return module
107
108 def require_builtin(module, *, skip=False):
109 module = _require_loader(module, BuiltinImporter, skip)
110 assert module.__spec__.origin == 'built-in', module.__spec__
111
112 def require_extension(module, *, skip=False):
113 # Apple extensions must be distributed as frameworks. This requires
114 # a specialist loader.
115 if is_apple_mobile:
116 _require_loader(module, AppleFrameworkLoader, skip)
117 else:
118 _require_loader(module, ExtensionFileLoader, skip)
119
120 def require_frozen(module, *, skip=True):
121 module = _require_loader(module, FrozenImporter, skip)
122 assert module.__spec__.origin == 'frozen', module.__spec__
123
124 def require_pure_python(module, *, skip=False):
125 _require_loader(module, SourceFileLoader, skip)
126
127 def create_extension_loader(modname, filename):
128 # Apple extensions must be distributed as frameworks. This requires
129 # a specialist loader.
130 if is_apple_mobile:
131 return AppleFrameworkLoader(modname, filename)
132 else:
133 return ExtensionFileLoader(modname, filename)
134
135 def import_extension_from_file(modname, filename, *, put_in_sys_modules=True):
136 loader = create_extension_loader(modname, filename)
137 spec = importlib.util.spec_from_loader(modname, loader)
138 module = importlib.util.module_from_spec(spec)
139 loader.exec_module(module)
140 if put_in_sys_modules:
141 sys.modules[modname] = module
142 return module
143
144
145 def remove_files(name):
146 for f in (name + ".py",
147 name + ".pyc",
148 name + ".pyw",
149 name + "$py.class"):
150 unlink(f)
151 rmtree('__pycache__')
152
153
154 def no_rerun(reason):
155 """Skip rerunning for a particular test.
156
157 WARNING: Use this decorator with care; skipping rerunning makes it
158 impossible to find reference leaks. Provide a clear reason for skipping the
159 test using the 'reason' parameter.
160 """
161 def deco(func):
162 _has_run = False
163 def wrapper(self):
164 nonlocal _has_run
165 if _has_run:
166 self.skipTest(reason)
167 func(self)
168 _has_run = True
169 return wrapper
170 return deco
171
172
173 if _testsinglephase is not None:
174 def restore__testsinglephase(*, _orig=_testsinglephase):
175 # We started with the module imported and want to restore
176 # it to its nominal state.
177 sys.modules.pop('_testsinglephase', None)
178 _orig._clear_globals()
179 origin = _orig.__spec__.origin
180 _testinternalcapi.clear_extension('_testsinglephase', origin)
181 import _testsinglephase
182
183
184 def requires_singlephase_init(meth):
185 """Decorator to skip if single-phase init modules are not supported."""
186 if not isinstance(meth, type):
187 def meth(self, _meth=meth):
188 try:
189 return _meth(self)
190 finally:
191 restore__testsinglephase()
192 meth = cpython_only(meth)
193 msg = "gh-117694: free-threaded build does not currently support single-phase init modules in sub-interpreters"
194 meth = requires_gil_enabled(msg)(meth)
195 return unittest.skipIf(_testsinglephase is None,
196 'test requires _testsinglephase module')(meth)
197
198
199 def requires_subinterpreters(meth):
200 """Decorator to skip a test if subinterpreters are not supported."""
201 return unittest.skipIf(_interpreters is None,
202 'subinterpreters required')(meth)
203
204
205 class ModuleSnapshot(types.SimpleNamespace):
206 """A representation of a module for testing.
207
208 Fields:
209
210 * id - the module's object ID
211 * module - the actual module or an adequate substitute
212 * __file__
213 * __spec__
214 * name
215 * origin
216 * ns - a copy (dict) of the module's __dict__ (or None)
217 * ns_id - the object ID of the module's __dict__
218 * cached - the sys.modules[mod.__spec__.name] entry (or None)
219 * cached_id - the object ID of the sys.modules entry (or None)
220
221 In cases where the value is not available (e.g. due to serialization),
222 the value will be None.
223 """
224 _fields = tuple('id module ns ns_id cached cached_id'.split())
225
226 @classmethod
227 def from_module(cls, mod):
228 name = mod.__spec__.name
229 cached = sys.modules.get(name)
230 return cls(
231 id=id(mod),
232 module=mod,
233 ns=types.SimpleNamespace(**mod.__dict__),
234 ns_id=id(mod.__dict__),
235 cached=cached,
236 cached_id=id(cached),
237 )
238
239 SCRIPT = textwrap.dedent('''
240 {imports}
241
242 name = {name!r}
243
244 {prescript}
245
246 mod = {name}
247
248 {body}
249
250 {postscript}
251 ''')
252 IMPORTS = textwrap.dedent('''
253 import sys
254 ''').strip()
255 SCRIPT_BODY = textwrap.dedent('''
256 # Capture the snapshot data.
257 cached = sys.modules.get(name)
258 snapshot = dict(
259 id=id(mod),
260 module=dict(
261 __file__=mod.__file__,
262 __spec__=dict(
263 name=mod.__spec__.name,
264 origin=mod.__spec__.origin,
265 ),
266 ),
267 ns=None,
268 ns_id=id(mod.__dict__),
269 cached=None,
270 cached_id=id(cached) if cached else None,
271 )
272 ''').strip()
273 CLEANUP_SCRIPT = textwrap.dedent('''
274 # Clean up the module.
275 sys.modules.pop(name, None)
276 ''').strip()
277
278 @classmethod
279 def build_script(cls, name, *,
280 prescript=None,
281 import_first=False,
282 postscript=None,
283 postcleanup=False,
284 ):
285 if postcleanup is True:
286 postcleanup = cls.CLEANUP_SCRIPT
287 elif isinstance(postcleanup, str):
288 postcleanup = textwrap.dedent(postcleanup).strip()
289 postcleanup = cls.CLEANUP_SCRIPT + os.linesep + postcleanup
290 else:
291 postcleanup = ''
292 prescript = textwrap.dedent(prescript).strip() if prescript else ''
293 postscript = textwrap.dedent(postscript).strip() if postscript else ''
294
295 if postcleanup:
296 if postscript:
297 postscript = postscript + os.linesep * 2 + postcleanup
298 else:
299 postscript = postcleanup
300
301 if import_first:
302 prescript += textwrap.dedent(f'''
303
304 # Now import the module.
305 assert name not in sys.modules
306 import {name}''')
307
308 return cls.SCRIPT.format(
309 imports=cls.IMPORTS.strip(),
310 name=name,
311 prescript=prescript.strip(),
312 body=cls.SCRIPT_BODY.strip(),
313 postscript=postscript,
314 )
315
316 @classmethod
317 def parse(cls, text):
318 raw = json.loads(text)
319 mod = raw['module']
320 mod['__spec__'] = types.SimpleNamespace(**mod['__spec__'])
321 raw['module'] = types.SimpleNamespace(**mod)
322 return cls(**raw)
323
324 @classmethod
325 def from_subinterp(cls, name, interpid=None, *, pipe=None, **script_kwds):
326 if pipe is not None:
327 return cls._from_subinterp(name, interpid, pipe, script_kwds)
328 pipe = os.pipe()
329 try:
330 return cls._from_subinterp(name, interpid, pipe, script_kwds)
331 finally:
332 r, w = pipe
333 os.close(r)
334 os.close(w)
335
336 @classmethod
337 def _from_subinterp(cls, name, interpid, pipe, script_kwargs):
338 r, w = pipe
339
340 # Build the script.
341 postscript = textwrap.dedent(f'''
342 # Send the result over the pipe.
343 import json
344 import os
345 os.write({w}, json.dumps(snapshot).encode())
346
347 ''')
348 _postscript = script_kwargs.get('postscript')
349 if _postscript:
350 _postscript = textwrap.dedent(_postscript).lstrip()
351 postscript += _postscript
352 script_kwargs['postscript'] = postscript.strip()
353 script = cls.build_script(name, **script_kwargs)
354
355 # Run the script.
356 if interpid is None:
357 ret = run_in_subinterp(script)
358 if ret != 0:
359 raise AssertionError(f'{ret} != 0')
360 else:
361 _interpreters.run_string(interpid, script)
362
363 # Parse the results.
364 text = os.read(r, 1000)
365 return cls.parse(text.decode())
366
367
368 @force_not_colorized_test_class
369 class ImportTests(unittest.TestCase, ExtraAssertions):
370
371 def setUp(self):
372 remove_files(TESTFN)
373 importlib.invalidate_caches()
374
375 def tearDown(self):
376 unload(TESTFN)
377
378 def test_import_raises_ModuleNotFoundError(self):
379 with self.assertRaises(ModuleNotFoundError):
380 import something_that_should_not_exist_anywhere
381
382 def test_import_null_byte_in_name_raises_ModuleNotFoundError(self):
383 # gh-150633: module names containing null bytes should not
384 # lead to duplicates in sys.modules
385 before = set(sys.modules.keys())
386 with self.assertRaises(ModuleNotFoundError):
387 __import__('zipimport\x00junk')
388
389 self.assertEqual(set(sys.modules.keys()), before)
390
391 def test_from_import_missing_module_raises_ModuleNotFoundError(self):
392 with self.assertRaises(ModuleNotFoundError):
393 from something_that_should_not_exist_anywhere import blah
394
395 def test_from_import_missing_attr_raises_ImportError(self):
396 with self.assertRaises(ImportError):
397 from importlib import something_that_should_not_exist_anywhere
398
399 def test_from_import_missing_attr_has_name_and_path(self):
400 with CleanImport('os'):
401 import os
402 with self.assertRaises(ImportError) as cm:
403 from os import i_dont_exist
404 self.assertEqual(cm.exception.name, 'os')
405 self.assertEqual(cm.exception.path, os.__file__)
406 self.assertRegex(str(cm.exception), r"cannot import name 'i_dont_exist' from 'os' \(.*os.py\)")
407
408 @cpython_only
409 def test_from_import_missing_attr_has_name_and_so_path(self):
410 _testcapi = import_module("_testcapi")
411 with self.assertRaises(ImportError) as cm:
412 from _testcapi import i_dont_exist
413 self.assertEqual(cm.exception.name, '_testcapi')
414 if hasattr(_testcapi, "__file__"):
415 # The path on the exception is strictly the spec origin, not the
416 # module's __file__. For most cases, these are the same; but on
417 # iOS, the Framework relocation process results in the exception
418 # being raised from the spec location.
419 self.assertEqual(cm.exception.path, _testcapi.__spec__.origin)
420 self.assertRegex(
421 str(cm.exception),
422 r"cannot import name 'i_dont_exist' from '_testcapi' \(.*(\.(so|pyd))?\)"
423 )
424 else:
425 self.assertEqual(
426 str(cm.exception),
427 "cannot import name 'i_dont_exist' from '_testcapi' (unknown location)"
428 )
429
430 def test_from_import_missing_attr_has_name(self):
431 with self.assertRaises(ImportError) as cm:
432 # _warning has no path as it's a built-in module.
433 from _warning import i_dont_exist
434 self.assertEqual(cm.exception.name, '_warning')
435 self.assertIsNone(cm.exception.path)
436
437 def test_from_import_missing_attr_path_is_canonical(self):
438 with self.assertRaises(ImportError) as cm:
439 from os.path import i_dont_exist
440 self.assertIn(cm.exception.name, {'posixpath', 'ntpath'})
441 self.assertIsNotNone(cm.exception)
442
443 def test_from_import_star_invalid_type(self):
444 import re
445 with ready_to_import() as (name, path):
446 with open(path, 'w', encoding='utf-8') as f:
447 f.write("__all__ = [b'invalid_type']")
448 globals = {}
449 with self.assertRaisesRegex(
450 TypeError, f"{re.escape(name)}\\.__all__ must be str"
451 ):
452 exec(f"from {name} import *", globals)
453 self.assertNotIn(b"invalid_type", globals)
454 with ready_to_import() as (name, path):
455 with open(path, 'w', encoding='utf-8') as f:
456 f.write("globals()[b'invalid_type'] = object()")
457 globals = {}
458 with self.assertRaisesRegex(
459 TypeError, f"{re.escape(name)}\\.__dict__ must be str"
460 ):
461 exec(f"from {name} import *", globals)
462 self.assertNotIn(b"invalid_type", globals)
463
464 def test_case_sensitivity(self):
465 # Brief digression to test that import is case-sensitive: if we got
466 # this far, we know for sure that "random" exists.
467 with self.assertRaises(ImportError):
468 import RAnDoM
469
470 def test_double_const(self):
471 # Importing double_const checks that float constants
472 # serialiazed by marshal as PYC files don't lose precision
473 # (SF bug 422177).
474 from test.test_import.data import double_const
475 unload('test.test_import.data.double_const')
476 from test.test_import.data import double_const # noqa: F811
477
478 def test_import(self):
479 def test_with_extension(ext):
480 # The extension is normally ".py", perhaps ".pyw".
481 source = TESTFN + ext
482 pyc = TESTFN + ".pyc"
483
484 with open(source, "w", encoding='utf-8') as f:
485 print("# This tests Python's ability to import a",
486 ext, "file.", file=f)
487 a = random.randrange(1000)
488 b = random.randrange(1000)
489 print("a =", a, file=f)
490 print("b =", b, file=f)
491
492 if TESTFN in sys.modules:
493 del sys.modules[TESTFN]
494 importlib.invalidate_caches()
495 try:
496 try:
497 mod = __import__(TESTFN)
498 except ImportError as err:
499 self.fail("import from %s failed: %s" % (ext, err))
500
501 self.assertEqual(mod.a, a,
502 "module loaded (%s) but contents invalid" % mod)
503 self.assertEqual(mod.b, b,
504 "module loaded (%s) but contents invalid" % mod)
505 finally:
506 forget(TESTFN)
507 unlink(source)
508 unlink(pyc)
509
510 sys.path.insert(0, os.curdir)
511 try:
512 test_with_extension(".py")
513 if sys.platform.startswith("win"):
514 for ext in [".PY", ".Py", ".pY", ".pyw", ".PYW", ".pYw"]:
515 test_with_extension(ext)
516 finally:
517 del sys.path[0]
518
519 def test_module_with_large_stack(self, module='longlist'):
520 # Regression test for http://bugs.python.org/issue561858.
521 filename = module + '.py'
522
523 # Create a file with a list of 65000 elements.
524 with open(filename, 'w', encoding='utf-8') as f:
525 f.write('d = [\n')
526 for i in range(65000):
527 f.write('"",\n')
528 f.write(']')
529
530 try:
531 # Compile & remove .py file; we only need .pyc.
532 # Bytecode must be relocated from the PEP 3147 bytecode-only location.
533 py_compile.compile(filename)
534 finally:
535 unlink(filename)
536
537 # Need to be able to load from current dir.
538 sys.path.append('')
539 importlib.invalidate_caches()
540
541 namespace = {}
542 try:
543 make_legacy_pyc(filename)
544 # This used to crash.
545 exec('import ' + module, None, namespace)
546 finally:
547 # Cleanup.
548 del sys.path[-1]
549 unlink(filename + 'c')
550 unlink(filename + 'o')
551
552 # Remove references to the module (unload the module)
553 namespace.clear()
554 try:
555 del sys.modules[module]
556 except KeyError:
557 pass
558
559 def test_failing_import_sticks(self):
560 source = TESTFN + ".py"
561 with open(source, "w", encoding='utf-8') as f:
562 print("a = 1/0", file=f)
563
564 # New in 2.4, we shouldn't be able to import that no matter how often
565 # we try.
566 sys.path.insert(0, os.curdir)
567 importlib.invalidate_caches()
568 if TESTFN in sys.modules:
569 del sys.modules[TESTFN]
570 try:
571 for i in [1, 2, 3]:
572 self.assertRaises(ZeroDivisionError, __import__, TESTFN)
573 self.assertNotIn(TESTFN, sys.modules,
574 "damaged module in sys.modules on %i try" % i)
575 finally:
576 del sys.path[0]
577 remove_files(TESTFN)
578
579 def test_import_name_binding(self):
580 # import x.y.z binds x in the current namespace
581 import test as x
582 import test.support
583 self.assertIs(x, test, x.__name__)
584 self.assertHasAttr(test.support, "__file__")
585
586 # import x.y.z as w binds z as w
587 import test.support as y
588 self.assertIs(y, test.support, y.__name__)
589
590 def test_issue31286(self):
591 # import in a 'finally' block resulted in SystemError
592 try:
593 x = ...
594 finally:
595 import test.support.script_helper as x
596
597 # import in a 'while' loop resulted in stack overflow
598 i = 0
599 while i < 10:
600 import test.support.script_helper as x
601 i += 1
602
603 # import in a 'for' loop resulted in segmentation fault
604 for i in range(2):
605 import test.support.script_helper as x # noqa: F811
606
607 def test_failing_reload(self):
608 # A failing reload should leave the module object in sys.modules.
609 source = TESTFN + os.extsep + "py"
610 with open(source, "w", encoding='utf-8') as f:
611 f.write("a = 1\nb=2\n")
612
613 sys.path.insert(0, os.curdir)
614 try:
615 mod = __import__(TESTFN)
616 self.assertIn(TESTFN, sys.modules)
617 self.assertEqual(mod.a, 1, "module has wrong attribute values")
618 self.assertEqual(mod.b, 2, "module has wrong attribute values")
619
620 # On WinXP, just replacing the .py file wasn't enough to
621 # convince reload() to reparse it. Maybe the timestamp didn't
622 # move enough. We force it to get reparsed by removing the
623 # compiled file too.
624 remove_files(TESTFN)
625
626 # Now damage the module.
627 with open(source, "w", encoding='utf-8') as f:
628 f.write("a = 10\nb=20//0\n")
629
630 self.assertRaises(ZeroDivisionError, importlib.reload, mod)
631 # But we still expect the module to be in sys.modules.
632 mod = sys.modules.get(TESTFN)
633 self.assertIsNotNone(mod, "expected module to be in sys.modules")
634
635 # We should have replaced a w/ 10, but the old b value should
636 # stick.
637 self.assertEqual(mod.a, 10, "module has wrong attribute values")
638 self.assertEqual(mod.b, 2, "module has wrong attribute values")
639
640 finally:
641 del sys.path[0]
642 remove_files(TESTFN)
643 unload(TESTFN)
644
645 @skip_if_dont_write_bytecode
646 def test_file_to_source(self):
647 # check if __file__ points to the source file where available
648 source = TESTFN + ".py"
649 with open(source, "w", encoding='utf-8') as f:
650 f.write("test = None\n")
651
652 sys.path.insert(0, os.curdir)
653 try:
654 mod = __import__(TESTFN)
655 self.assertEndsWith(mod.__file__, '.py')
656 os.remove(source)
657 del sys.modules[TESTFN]
658 make_legacy_pyc(source)
659 importlib.invalidate_caches()
660 mod = __import__(TESTFN)
661 base, ext = os.path.splitext(mod.__file__)
662 self.assertEqual(ext, '.pyc')
663 finally:
664 del sys.path[0]
665 remove_files(TESTFN)
666 if TESTFN in sys.modules:
667 del sys.modules[TESTFN]
668
669 def test_import_by_filename(self):
670 path = os.path.abspath(TESTFN)
671 encoding = sys.getfilesystemencoding()
672 try:
673 path.encode(encoding)
674 except UnicodeEncodeError:
675 self.skipTest('path is not encodable to {}'.format(encoding))
676 with self.assertRaises(ImportError) as c:
677 __import__(path)
678
679 def test_import_in_del_does_not_crash(self):
680 # Issue 4236
681 testfn = script_helper.make_script('', TESTFN, textwrap.dedent("""\
682 import sys
683 class C:
684 def __del__(self):
685 import importlib
686 sys.argv.insert(0, C())
687 """))
688 script_helper.assert_python_ok(testfn)
689
690 @skip_if_dont_write_bytecode
691 def test_timestamp_overflow(self):
692 # A modification timestamp larger than 2**32 should not be a problem
693 # when importing a module (issue #11235).
694 sys.path.insert(0, os.curdir)
695 try:
696 source = TESTFN + ".py"
697 compiled = importlib.util.cache_from_source(source)
698 with open(source, 'w', encoding='utf-8') as f:
699 pass
700 try:
701 os.utime(source, (2 ** 33 - 5, 2 ** 33 - 5))
702 except OverflowError:
703 self.skipTest("cannot set modification time to large integer")
704 except OSError as e:
705 if e.errno not in (getattr(errno, 'EOVERFLOW', None),
706 getattr(errno, 'EINVAL', None)):
707 raise
708 self.skipTest("cannot set modification time to large integer ({})".format(e))
709 __import__(TESTFN)
710 # The pyc file was created.
711 os.stat(compiled)
712 finally:
713 del sys.path[0]
714 remove_files(TESTFN)
715
716 def test_bogus_fromlist(self):
717 try:
718 __import__('http', fromlist=['blah'])
719 except ImportError:
720 self.fail("fromlist must allow bogus names")
721
722 @cpython_only
723 def test_delete_builtins_import(self):
724 args = ["-c", "del __builtins__.__import__; import os"]
725 popen = script_helper.spawn_python(*args)
726 stdout, stderr = popen.communicate()
727 self.assertIn(b"ImportError", stdout)
728
729 def test_from_import_message_for_nonexistent_module(self):
730 with self.assertRaisesRegex(ImportError, "^No module named 'bogus'"):
731 from bogus import foo
732
733 def test_from_import_message_for_existing_module(self):
734 with self.assertRaisesRegex(ImportError, "^cannot import name 'bogus'"):
735 from re import bogus
736
737 def test_from_import_AttributeError(self):
738 # Issue #24492: trying to import an attribute that raises an
739 # AttributeError should lead to an ImportError.
740 class AlwaysAttributeError:
741 def __getattr__(self, _):
742 raise AttributeError
743
744 module_name = 'test_from_import_AttributeError'
745 self.addCleanup(unload, module_name)
746 sys.modules[module_name] = AlwaysAttributeError()
747 with self.assertRaises(ImportError) as cm:
748 from test_from_import_AttributeError import does_not_exist
749
750 self.assertEqual(str(cm.exception),
751 "cannot import name 'does_not_exist' from '<unknown module name>' (unknown location)")
752
753 @cpython_only
754 def test_issue31492(self):
755 # There shouldn't be an assertion failure in case of failing to import
756 # from a module with a bad __name__ attribute, or in case of failing
757 # to access an attribute of such a module.
758 with swap_attr(os, '__name__', None):
759 with self.assertRaises(ImportError):
760 from os import does_not_exist
761
762 with self.assertRaises(AttributeError):
763 os.does_not_exist
764
765 @threading_helper.requires_working_threading()
766 def test_concurrency(self):
767 # bpo 38091: this is a hack to slow down the code that calls
768 # has_deadlock(); the logic was itself sometimes deadlocking.
769 def delay_has_deadlock(frame, event, arg):
770 if event == 'call' and frame.f_code.co_name == 'has_deadlock':
771 time.sleep(0.1)
772
773 sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'data'))
774 try:
775 exc = None
776 def run():
777 sys.settrace(delay_has_deadlock)
778 event.wait()
779 try:
780 import package
781 except BaseException as e:
782 nonlocal exc
783 exc = e
784 sys.settrace(None)
785
786 for i in range(10):
787 event = threading.Event()
788 threads = [threading.Thread(target=run) for x in range(2)]
789 try:
790 with threading_helper.start_threads(threads, event.set):
791 time.sleep(0)
792 finally:
793 sys.modules.pop('package', None)
794 sys.modules.pop('package.submodule', None)
795 if exc is not None:
796 raise exc
797 finally:
798 del sys.path[0]
799
800 @unittest.skipUnless(sys.platform == "win32", "Windows-specific")
801 def test_dll_dependency_import(self):
802 from _winapi import GetModuleFileName
803 dllname = GetModuleFileName(sys.dllhandle)
804 pydname = importlib.util.find_spec("_sqlite3").origin
805 depname = os.path.join(
806 os.path.dirname(pydname),
807 "sqlite3{}.dll".format("_d" if "_d" in pydname else ""))
808
809 with os_helper.temp_dir() as tmp:
810 tmp2 = os.path.join(tmp, "DLLs")
811 os.mkdir(tmp2)
812
813 pyexe = os.path.join(tmp, os.path.basename(sys.executable))
814 shutil.copy(sys.executable, pyexe)
815 shutil.copy(dllname, tmp)
816 for f in glob.glob(os.path.join(glob.escape(sys.prefix), "vcruntime*.dll")):
817 shutil.copy(f, tmp)
818
819 shutil.copy(pydname, tmp2)
820
821 env = None
822 env = {k.upper(): os.environ[k] for k in os.environ}
823 env["PYTHONPATH"] = tmp2 + ";" + STDLIB_DIR
824
825 # Test 1: import with added DLL directory
826 subprocess.check_call([
827 pyexe, "-Sc", ";".join([
828 "import os",
829 "p = os.add_dll_directory({!r})".format(
830 os.path.dirname(depname)),
831 "import _sqlite3",
832 "p.close"
833 ])],
834 stderr=subprocess.STDOUT,
835 env=env,
836 cwd=os.path.dirname(pyexe))
837
838 # Test 2: import with DLL adjacent to PYD
839 shutil.copy(depname, tmp2)
840 subprocess.check_call([pyexe, "-Sc", "import _sqlite3"],
841 stderr=subprocess.STDOUT,
842 env=env,
843 cwd=os.path.dirname(pyexe))
844
845 def test_issue105979(self):
846 # this used to crash
847 with self.assertRaises(ImportError) as cm:
848 _imp.get_frozen_object("x", b"6\'\xd5Cu\x12")
849 self.assertIn("Frozen object named 'x' is invalid",
850 str(cm.exception))
851
852 def test_frozen_module_from_import_error(self):
853 with self.assertRaises(ImportError) as cm:
854 from os import this_will_never_exist
855 self.assertIn(
856 f"cannot import name 'this_will_never_exist' from 'os' ({os.__file__})",
857 str(cm.exception),
858 )
859 with self.assertRaises(ImportError) as cm:
860 from sys import this_will_never_exist
861 self.assertIn(
862 "cannot import name 'this_will_never_exist' from 'sys' (unknown location)",
863 str(cm.exception),
864 )
865
866 scripts = [
867 """
868 import os
869 os.__spec__.has_location = False
870 os.__file__ = []
871 from os import this_will_never_exist
872 """,
873 """
874 import os
875 os.__spec__.has_location = False
876 del os.__file__
877 from os import this_will_never_exist
878 """,
879 """
880 import os
881 os.__spec__.origin = []
882 os.__file__ = []
883 from os import this_will_never_exist
884 """
885 ]
886 for script in scripts:
887 with self.subTest(script=script):
888 expected_error = (
889 b"cannot import name 'this_will_never_exist' "
890 b"from 'os' (unknown location)"
891 )
892 popen = script_helper.spawn_python("-c", script)
893 stdout, stderr = popen.communicate()
894 self.assertIn(expected_error, stdout)
895
896 def test_non_module_from_import_error(self):
897 prefix = """
898 import sys
899 class NotAModule: ...
900 nm = NotAModule()
901 nm.symbol = 123
902 sys.modules["not_a_module"] = nm
903 from not_a_module import symbol
904 """
905 scripts = [
906 prefix + "from not_a_module import missing_symbol",
907 prefix + "nm.__spec__ = []\nfrom not_a_module import missing_symbol",
908 ]
909 for script in scripts:
910 with self.subTest(script=script):
911 expected_error = (
912 b"ImportError: cannot import name 'missing_symbol' from "
913 b"'<unknown module name>' (unknown location)"
914 )
915 popen = script_helper.spawn_python("-c", script)
916 stdout, stderr = popen.communicate()
917 self.assertIn(expected_error, stdout)
918
919 def test_script_shadowing_stdlib(self):
920 script_errors = [
921 (
922 "import fractions\nfractions.Fraction",
923 rb"AttributeError: module 'fractions' has no attribute 'Fraction'"
924 ),
925 (
926 "from fractions import Fraction",
927 rb"ImportError: cannot import name 'Fraction' from 'fractions'"
928 )
929 ]
930 for script, error in script_errors:
931 with self.subTest(script=script), os_helper.temp_dir() as tmp:
932 with open(os.path.join(tmp, "fractions.py"), "w", encoding='utf-8') as f:
933 f.write(script)
934
935 expected_error = error + (
936 rb" \(consider renaming '.*fractions.py' since it has the "
937 rb"same name as the standard library module named 'fractions' "
938 rb"and prevents importing that standard library module\)"
939 )
940
941 popen = script_helper.spawn_python(os.path.join(tmp, "fractions.py"), cwd=tmp)
942 stdout, stderr = popen.communicate()
943 self.assertRegex(stdout, expected_error)
944
945 popen = script_helper.spawn_python('-m', 'fractions', cwd=tmp)
946 stdout, stderr = popen.communicate()
947 self.assertRegex(stdout, expected_error)
948
949 popen = script_helper.spawn_python('-c', 'import fractions', cwd=tmp)
950 stdout, stderr = popen.communicate()
951 self.assertRegex(stdout, expected_error)
952
953 # and there's no error at all when using -P
954 popen = script_helper.spawn_python('-P', 'fractions.py', cwd=tmp)
955 stdout, stderr = popen.communicate()
956 self.assertEqual(stdout, b'')
957
958 tmp_child = os.path.join(tmp, "child")
959 os.mkdir(tmp_child)
960
961 # test the logic with different cwd
962 popen = script_helper.spawn_python(os.path.join(tmp, "fractions.py"), cwd=tmp_child)
963 stdout, stderr = popen.communicate()
964 self.assertRegex(stdout, expected_error)
965
966 popen = script_helper.spawn_python('-m', 'fractions', cwd=tmp_child)
967 stdout, stderr = popen.communicate()
968 self.assertEqual(stdout, b'') # no error
969
970 popen = script_helper.spawn_python('-c', 'import fractions', cwd=tmp_child)
971 stdout, stderr = popen.communicate()
972 self.assertEqual(stdout, b'') # no error
973
974 def test_package_shadowing_stdlib_module(self):
975 script_errors = [
976 (
977 "fractions.Fraction",
978 rb"AttributeError: module 'fractions' has no attribute 'Fraction'"
979 ),
980 (
981 "from fractions import Fraction",
982 rb"ImportError: cannot import name 'Fraction' from 'fractions'"
983 )
984 ]
985 for script, error in script_errors:
986 with self.subTest(script=script), os_helper.temp_dir() as tmp:
987 os.mkdir(os.path.join(tmp, "fractions"))
988 with open(
989 os.path.join(tmp, "fractions", "__init__.py"), "w", encoding='utf-8'
990 ) as f:
991 f.write("shadowing_module = True")
992 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
993 f.write("import fractions; fractions.shadowing_module\n")
994 f.write(script)
995
996 expected_error = error + (
997 rb" \(consider renaming '.*[\\/]fractions[\\/]+__init__.py' since it has the "
998 rb"same name as the standard library module named 'fractions' "
999 rb"and prevents importing that standard library module\)"
1000 )
1001
1002 popen = script_helper.spawn_python(os.path.join(tmp, "main.py"), cwd=tmp)
1003 stdout, stderr = popen.communicate()
1004 self.assertRegex(stdout, expected_error)
1005
1006 popen = script_helper.spawn_python('-m', 'main', cwd=tmp)
1007 stdout, stderr = popen.communicate()
1008 self.assertRegex(stdout, expected_error)
1009
1010 # and there's no shadowing at all when using -P
1011 popen = script_helper.spawn_python('-P', 'main.py', cwd=tmp)
1012 stdout, stderr = popen.communicate()
1013 self.assertRegex(stdout, b"module 'fractions' has no attribute 'shadowing_module'")
1014
1015 def test_script_shadowing_third_party(self):
1016 script_errors = [
1017 (
1018 "import numpy\nnumpy.array",
1019 rb"AttributeError: module 'numpy' has no attribute 'array'"
1020 ),
1021 (
1022 "from numpy import array",
1023 rb"ImportError: cannot import name 'array' from 'numpy'"
1024 )
1025 ]
1026 for script, error in script_errors:
1027 with self.subTest(script=script), os_helper.temp_dir() as tmp:
1028 with open(os.path.join(tmp, "numpy.py"), "w", encoding='utf-8') as f:
1029 f.write(script)
1030
1031 expected_error = error + (
1032 rb" \(consider renaming '.*numpy.py' if it has the "
1033 rb"same name as a library you intended to import\)\s+\Z"
1034 )
1035
1036 popen = script_helper.spawn_python(os.path.join(tmp, "numpy.py"))
1037 stdout, stderr = popen.communicate()
1038 self.assertRegex(stdout, expected_error)
1039
1040 popen = script_helper.spawn_python('-m', 'numpy', cwd=tmp)
1041 stdout, stderr = popen.communicate()
1042 self.assertRegex(stdout, expected_error)
1043
1044 popen = script_helper.spawn_python('-c', 'import numpy', cwd=tmp)
1045 stdout, stderr = popen.communicate()
1046 self.assertRegex(stdout, expected_error)
1047
1048 def test_script_maybe_not_shadowing_third_party(self):
1049 with os_helper.temp_dir() as tmp:
1050 with open(os.path.join(tmp, "numpy.py"), "w", encoding='utf-8') as f:
1051 f.write("this_script_does_not_attempt_to_import_numpy = True")
1052
1053 expected_error = (
1054 rb"AttributeError: module 'numpy' has no attribute 'attr'\s+\Z"
1055 )
1056 popen = script_helper.spawn_python('-c', 'import numpy; numpy.attr', cwd=tmp)
1057 stdout, stderr = popen.communicate()
1058 self.assertRegex(stdout, expected_error)
1059
1060 expected_error = (
1061 rb"ImportError: cannot import name 'attr' from 'numpy' \(.*\)\s+\Z"
1062 )
1063 popen = script_helper.spawn_python('-c', 'from numpy import attr', cwd=tmp)
1064 stdout, stderr = popen.communicate()
1065 self.assertRegex(stdout, expected_error)
1066
1067 def test_script_shadowing_stdlib_edge_cases(self):
1068 with os_helper.temp_dir() as tmp:
1069 with open(os.path.join(tmp, "fractions.py"), "w", encoding='utf-8') as f:
1070 f.write("shadowing_module = True")
1071
1072 # Unhashable str subclass
1073 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1074 f.write("""
1075 import fractions
1076 fractions.shadowing_module
1077 class substr(str):
1078 __hash__ = None
1079 fractions.__name__ = substr('fractions')
1080 try:
1081 fractions.Fraction
1082 except TypeError as e:
1083 print(str(e))
1084 """)
1085 popen = script_helper.spawn_python("main.py", cwd=tmp)
1086 stdout, stderr = popen.communicate()
1087 self.assertEqual(stdout.rstrip(), b"unhashable type: 'substr'")
1088
1089 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1090 f.write("""
1091 import fractions
1092 fractions.shadowing_module
1093 class substr(str):
1094 __hash__ = None
1095 fractions.__name__ = substr('fractions')
1096 try:
1097 from fractions import Fraction
1098 except TypeError as e:
1099 print(str(e))
1100 """)
1101
1102 popen = script_helper.spawn_python("main.py", cwd=tmp)
1103 stdout, stderr = popen.communicate()
1104 self.assertEqual(stdout.rstrip(), b"unhashable type: 'substr'")
1105
1106 # Various issues with sys module
1107 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1108 f.write("""
1109 import fractions
1110 fractions.shadowing_module
1111
1112 import sys
1113 sys.stdlib_module_names = None
1114 try:
1115 fractions.Fraction
1116 except AttributeError as e:
1117 print(str(e))
1118
1119 del sys.stdlib_module_names
1120 try:
1121 fractions.Fraction
1122 except AttributeError as e:
1123 print(str(e))
1124
1125 sys.path = [0]
1126 try:
1127 fractions.Fraction
1128 except AttributeError as e:
1129 print(str(e))
1130 """)
1131 popen = script_helper.spawn_python("main.py", cwd=tmp)
1132 stdout, stderr = popen.communicate()
1133 lines = stdout.splitlines()
1134 self.assertEqual(len(lines), 3)
1135 for line in lines:
1136 self.assertEqual(line, b"module 'fractions' has no attribute 'Fraction'")
1137
1138 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1139 f.write("""
1140 import fractions
1141 fractions.shadowing_module
1142
1143 import sys
1144 sys.stdlib_module_names = None
1145 try:
1146 from fractions import Fraction
1147 except ImportError as e:
1148 print(str(e))
1149
1150 del sys.stdlib_module_names
1151 try:
1152 from fractions import Fraction
1153 except ImportError as e:
1154 print(str(e))
1155
1156 sys.path = [0]
1157 try:
1158 from fractions import Fraction
1159 except ImportError as e:
1160 print(str(e))
1161 """)
1162 popen = script_helper.spawn_python("main.py", cwd=tmp)
1163 stdout, stderr = popen.communicate()
1164 lines = stdout.splitlines()
1165 self.assertEqual(len(lines), 3)
1166 for line in lines:
1167 self.assertRegex(line, rb"cannot import name 'Fraction' from 'fractions' \(.*\)")
1168
1169 # Various issues with origin
1170 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1171 f.write("""
1172 import fractions
1173 fractions.shadowing_module
1174 del fractions.__spec__.origin
1175 try:
1176 fractions.Fraction
1177 except AttributeError as e:
1178 print(str(e))
1179
1180 fractions.__spec__.origin = []
1181 try:
1182 fractions.Fraction
1183 except AttributeError as e:
1184 print(str(e))
1185 """)
1186
1187 popen = script_helper.spawn_python("main.py", cwd=tmp)
1188 stdout, stderr = popen.communicate()
1189 lines = stdout.splitlines()
1190 self.assertEqual(len(lines), 2)
1191 for line in lines:
1192 self.assertEqual(line, b"module 'fractions' has no attribute 'Fraction'")
1193
1194 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1195 f.write("""
1196 import fractions
1197 fractions.shadowing_module
1198 del fractions.__spec__.origin
1199 try:
1200 from fractions import Fraction
1201 except ImportError as e:
1202 print(str(e))
1203
1204 fractions.__spec__.origin = []
1205 try:
1206 from fractions import Fraction
1207 except ImportError as e:
1208 print(str(e))
1209 """)
1210 popen = script_helper.spawn_python("main.py", cwd=tmp)
1211 stdout, stderr = popen.communicate()
1212 lines = stdout.splitlines()
1213 self.assertEqual(len(lines), 2)
1214 for line in lines:
1215 self.assertRegex(line, rb"cannot import name 'Fraction' from 'fractions' \(.*\)")
1216
1217 @unittest.skipIf(sys.platform == 'win32', 'Cannot delete cwd on Windows')
1218 @unittest.skipIf(sys.platform == 'sunos5', 'Cannot delete cwd on Solaris/Illumos')
1219 @unittest.skipIf(sys.platform.startswith('aix'), 'Cannot delete cwd on AIX')
1220 def test_script_shadowing_stdlib_cwd_failure(self):
1221 with os_helper.temp_dir() as tmp:
1222 subtmp = os.path.join(tmp, "subtmp")
1223 os.mkdir(subtmp)
1224 with open(os.path.join(subtmp, "main.py"), "w", encoding='utf-8') as f:
1225 f.write(f"""
1226 import sys
1227 assert sys.path[0] == ''
1228
1229 import os
1230 import shutil
1231 shutil.rmtree(os.getcwd())
1232
1233 os.does_not_exist
1234 """)
1235 # Use -c to ensure sys.path[0] is ""
1236 popen = script_helper.spawn_python("-c", "import main", cwd=subtmp)
1237 stdout, stderr = popen.communicate()
1238 expected_error = rb"AttributeError: module 'os' has no attribute 'does_not_exist'"
1239 self.assertRegex(stdout, expected_error)
1240
1241 def test_script_shadowing_stdlib_sys_path_modification(self):
1242 script_errors = [
1243 (
1244 "import fractions\nfractions.Fraction",
1245 rb"AttributeError: module 'fractions' has no attribute 'Fraction'"
1246 ),
1247 (
1248 "from fractions import Fraction",
1249 rb"ImportError: cannot import name 'Fraction' from 'fractions'"
1250 )
1251 ]
1252 for script, error in script_errors:
1253 with self.subTest(script=script), os_helper.temp_dir() as tmp:
1254 with open(os.path.join(tmp, "fractions.py"), "w", encoding='utf-8') as f:
1255 f.write("shadowing_module = True")
1256 with open(os.path.join(tmp, "main.py"), "w", encoding='utf-8') as f:
1257 f.write('import sys; sys.path.insert(0, "this_folder_does_not_exist")\n')
1258 f.write(script)
1259 expected_error = error + (
1260 rb" \(consider renaming '.*fractions.py' since it has the "
1261 rb"same name as the standard library module named 'fractions' "
1262 rb"and prevents importing that standard library module\)"
1263 )
1264
1265 popen = script_helper.spawn_python("main.py", cwd=tmp)
1266 stdout, stderr = popen.communicate()
1267 self.assertRegex(stdout, expected_error)
1268
1269 def test_create_dynamic_null(self):
1270 with self.assertRaisesRegex(ValueError, 'embedded null character'):
1271 class Spec:
1272 name = "a\x00b"
1273 origin = "abc"
1274 _imp.create_dynamic(Spec())
1275
1276 with self.assertRaisesRegex(ValueError, 'embedded null character'):
1277 class Spec2:
1278 name = "abc"
1279 origin = "a\x00b"
1280 _imp.create_dynamic(Spec2())
1281
1282
1283 @skip_if_dont_write_bytecode
1284 class FilePermissionTests(unittest.TestCase):
1285 # tests for file mode on cached .pyc files
1286
1287 @unittest.skipUnless(os.name == 'posix',
1288 "test meaningful only on posix systems")
1289 @unittest.skipIf(
1290 is_emscripten or is_wasi,
1291 "Emscripten's/WASI's umask is a stub."
1292 )
1293 def test_creation_mode(self):
1294 mask = 0o022
1295 with temp_umask(mask), ready_to_import() as (name, path):
1296 cached_path = importlib.util.cache_from_source(path)
1297 module = __import__(name)
1298 if not os.path.exists(cached_path):
1299 self.fail("__import__ did not result in creation of "
1300 "a .pyc file")
1301 stat_info = os.stat(cached_path)
1302
1303 # Check that the umask is respected, and the executable bits
1304 # aren't set.
1305 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)),
1306 oct(0o666 & ~mask))
1307
1308 @unittest.skipUnless(os.name == 'posix',
1309 "test meaningful only on posix systems")
1310 @os_helper.skip_unless_working_chmod
1311 def test_cached_mode_issue_2051(self):
1312 # permissions of .pyc should match those of .py, regardless of mask
1313 mode = 0o600
1314 with temp_umask(0o022), ready_to_import() as (name, path):
1315 cached_path = importlib.util.cache_from_source(path)
1316 os.chmod(path, mode)
1317 __import__(name)
1318 if not os.path.exists(cached_path):
1319 self.fail("__import__ did not result in creation of "
1320 "a .pyc file")
1321 stat_info = os.stat(cached_path)
1322
1323 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(mode))
1324
1325 @unittest.skipUnless(os.name == 'posix',
1326 "test meaningful only on posix systems")
1327 @os_helper.skip_unless_working_chmod
1328 def test_cached_readonly(self):
1329 mode = 0o400
1330 with temp_umask(0o022), ready_to_import() as (name, path):
1331 cached_path = importlib.util.cache_from_source(path)
1332 os.chmod(path, mode)
1333 __import__(name)
1334 if not os.path.exists(cached_path):
1335 self.fail("__import__ did not result in creation of "
1336 "a .pyc file")
1337 stat_info = os.stat(cached_path)
1338
1339 expected = mode | 0o200 # Account for fix for issue #6074
1340 self.assertEqual(oct(stat.S_IMODE(stat_info.st_mode)), oct(expected))
1341
1342 def test_pyc_always_writable(self):
1343 # Initially read-only .pyc files on Windows used to cause problems
1344 # with later updates, see issue #6074 for details
1345 with ready_to_import() as (name, path):
1346 # Write a Python file, make it read-only and import it
1347 with open(path, 'w', encoding='utf-8') as f:
1348 f.write("x = 'original'\n")
1349 # Tweak the mtime of the source to ensure pyc gets updated later
1350 s = os.stat(path)
1351 os.utime(path, (s.st_atime, s.st_mtime-100000000))
1352 os.chmod(path, 0o400)
1353 m = __import__(name)
1354 self.assertEqual(m.x, 'original')
1355 # Change the file and then reimport it
1356 os.chmod(path, 0o600)
1357 with open(path, 'w', encoding='utf-8') as f:
1358 f.write("x = 'rewritten'\n")
1359 unload(name)
1360 importlib.invalidate_caches()
1361 m = __import__(name)
1362 self.assertEqual(m.x, 'rewritten')
1363 # Now delete the source file and check the pyc was rewritten
1364 unlink(path)
1365 unload(name)
1366 importlib.invalidate_caches()
1367 bytecode_only = path + "c"
1368 os.rename(importlib.util.cache_from_source(path), bytecode_only)
1369 m = __import__(name)
1370 self.assertEqual(m.x, 'rewritten')
1371
1372
1373 class PycRewritingTests(unittest.TestCase):
1374 # Test that the `co_filename` attribute on code objects always points
1375 # to the right file, even when various things happen (e.g. both the .py
1376 # and the .pyc file are renamed).
1377
1378 module_name = "unlikely_module_name"
1379 module_source = """
1380 import sys
1381 code_filename = sys._getframe().f_code.co_filename
1382 module_filename = __file__
1383 constant = 1
1384 def func():
1385 pass
1386 func_filename = func.__code__.co_filename
1387 """
1388 dir_name = os.path.abspath(TESTFN)
1389 file_name = os.path.join(dir_name, module_name) + os.extsep + "py"
1390 compiled_name = importlib.util.cache_from_source(file_name)
1391
1392 def setUp(self):
1393 self.sys_path = sys.path[:]
1394 self.orig_module = sys.modules.pop(self.module_name, None)
1395 os.mkdir(self.dir_name)
1396 with open(self.file_name, "w", encoding='utf-8') as f:
1397 f.write(self.module_source)
1398 sys.path.insert(0, self.dir_name)
1399 importlib.invalidate_caches()
1400
1401 def tearDown(self):
1402 sys.path[:] = self.sys_path
1403 if self.orig_module is not None:
1404 sys.modules[self.module_name] = self.orig_module
1405 else:
1406 unload(self.module_name)
1407 unlink(self.file_name)
1408 unlink(self.compiled_name)
1409 rmtree(self.dir_name)
1410
1411 def import_module(self):
1412 ns = globals()
1413 __import__(self.module_name, ns, ns)
1414 return sys.modules[self.module_name]
1415
1416 def test_basics(self):
1417 mod = self.import_module()
1418 self.assertEqual(mod.module_filename, self.file_name)
1419 self.assertEqual(mod.code_filename, self.file_name)
1420 self.assertEqual(mod.func_filename, self.file_name)
1421 del sys.modules[self.module_name]
1422 mod = self.import_module()
1423 self.assertEqual(mod.module_filename, self.file_name)
1424 self.assertEqual(mod.code_filename, self.file_name)
1425 self.assertEqual(mod.func_filename, self.file_name)
1426
1427 def test_incorrect_code_name(self):
1428 py_compile.compile(self.file_name, dfile="another_module.py")
1429 mod = self.import_module()
1430 self.assertEqual(mod.module_filename, self.file_name)
1431 self.assertEqual(mod.code_filename, self.file_name)
1432 self.assertEqual(mod.func_filename, self.file_name)
1433
1434 def test_module_without_source(self):
1435 target = "another_module.py"
1436 py_compile.compile(self.file_name, dfile=target)
1437 os.remove(self.file_name)
1438 pyc_file = make_legacy_pyc(self.file_name)
1439 importlib.invalidate_caches()
1440 mod = self.import_module()
1441 self.assertEqual(mod.module_filename, pyc_file)
1442 self.assertEqual(mod.code_filename, target)
1443 self.assertEqual(mod.func_filename, target)
1444
1445 def test_foreign_code(self):
1446 py_compile.compile(self.file_name)
1447 with open(self.compiled_name, "rb") as f:
1448 header = f.read(16)
1449 code = marshal.load(f)
1450 constants = list(code.co_consts)
1451 foreign_code = importlib.import_module.__code__
1452 pos = constants.index(1)
1453 constants[pos] = foreign_code
1454 code = code.replace(co_consts=tuple(constants))
1455 with open(self.compiled_name, "wb") as f:
1456 f.write(header)
1457 marshal.dump(code, f)
1458 mod = self.import_module()
1459 self.assertEqual(mod.constant.co_filename, foreign_code.co_filename)
1460
1461
1462 class PathsTests(unittest.TestCase, ExtraAssertions):
1463 SAMPLES = ('test', 'test\u00e4\u00f6\u00fc\u00df', 'test\u00e9\u00e8',
1464 'test\u00b0\u00b3\u00b2')
1465 path = TESTFN
1466
1467 def setUp(self):
1468 os.mkdir(self.path)
1469 self.syspath = sys.path[:]
1470
1471 def tearDown(self):
1472 rmtree(self.path)
1473 sys.path[:] = self.syspath
1474
1475 # Regression test for http://bugs.python.org/issue1293.
1476 def test_trailing_slash(self):
1477 with open(os.path.join(self.path, 'test_trailing_slash.py'),
1478 'w', encoding='utf-8') as f:
1479 f.write("testdata = 'test_trailing_slash'")
1480 sys.path.append(self.path+'/')
1481 mod = __import__("test_trailing_slash")
1482 self.assertEqual(mod.testdata, 'test_trailing_slash')
1483 unload("test_trailing_slash")
1484
1485 # Regression test for http://bugs.python.org/issue3677.
1486 @unittest.skipUnless(sys.platform == 'win32', 'Windows-specific')
1487 def test_UNC_path(self):
1488 with open(os.path.join(self.path, 'test_unc_path.py'), 'w') as f:
1489 f.write("testdata = 'test_unc_path'")
1490 importlib.invalidate_caches()
1491 # Create the UNC path, like \\myhost\c$\foo\bar.
1492 path = os.path.abspath(self.path)
1493 import socket
1494 hn = socket.gethostname()
1495 drive = path[0]
1496 unc = "\\\\%s\\%s$"%(hn, drive)
1497 unc += path[2:]
1498 try:
1499 os.listdir(unc)
1500 except OSError as e:
1501 if e.errno in (errno.EPERM, errno.EACCES, errno.ENOENT):
1502 # See issue #15338
1503 self.skipTest("cannot access administrative share %r" % (unc,))
1504 raise
1505 sys.path.insert(0, unc)
1506 try:
1507 mod = __import__("test_unc_path")
1508 except ImportError as e:
1509 self.fail("could not import 'test_unc_path' from %r: %r"
1510 % (unc, e))
1511 self.assertEqual(mod.testdata, 'test_unc_path')
1512 self.assertStartsWith(mod.__file__, unc)
1513 unload("test_unc_path")
1514
1515
1516 class RelativeImportTests(unittest.TestCase, ExtraAssertions):
1517
1518 def tearDown(self):
1519 unload("test.relimport")
1520 setUp = tearDown
1521
1522 def test_relimport_star(self):
1523 # This will import * from .test_import.
1524 from .. import relimport
1525 self.assertHasAttr(relimport, "RelativeImportTests")
1526
1527 def test_issue3221(self):
1528 # Note for mergers: the 'absolute' tests from the 2.x branch
1529 # are missing in Py3k because implicit relative imports are
1530 # a thing of the past
1531 #
1532 # Regression test for http://bugs.python.org/issue3221.
1533 def check_relative():
1534 exec("from . import relimport", ns)
1535
1536 # Check relative import OK with __package__ and __name__ correct
1537 ns = dict(__package__='test', __name__='test.notarealmodule')
1538 check_relative()
1539
1540 # Check relative import OK with only __name__ wrong
1541 ns = dict(__package__='test', __name__='notarealpkg.notarealmodule')
1542 check_relative()
1543
1544 # Check relative import fails with only __package__ wrong
1545 ns = dict(__package__='foo', __name__='test.notarealmodule')
1546 self.assertRaises(ModuleNotFoundError, check_relative)
1547
1548 # Check relative import fails with __package__ and __name__ wrong
1549 ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
1550 self.assertRaises(ModuleNotFoundError, check_relative)
1551
1552 # Check relative import fails with package set to a non-string
1553 ns = dict(__package__=object())
1554 self.assertRaises(TypeError, check_relative)
1555
1556 def test_parentless_import_shadowed_by_global(self):
1557 # Test as if this were done from the REPL where this error most commonly occurs (bpo-37409).
1558 script_helper.assert_python_failure('-W', 'ignore', '-c',
1559 "foo = 1; from . import foo")
1560
1561 def test_absolute_import_without_future(self):
1562 # If explicit relative import syntax is used, then do not try
1563 # to perform an absolute import in the face of failure.
1564 # Issue #7902.
1565 with self.assertRaises(ImportError):
1566 from .os import sep
1567 self.fail("explicit relative import triggered an "
1568 "implicit absolute import")
1569
1570 def test_import_from_non_package(self):
1571 path = os.path.join(os.path.dirname(__file__), 'data', 'package2')
1572 with uncache('submodule1', 'submodule2'), DirsOnSysPath(path):
1573 with self.assertRaises(ImportError):
1574 import submodule1
1575 self.assertNotIn('submodule1', sys.modules)
1576 self.assertNotIn('submodule2', sys.modules)
1577
1578 def test_import_from_unloaded_package(self):
1579 with uncache('package2', 'package2.submodule1', 'package2.submodule2'), \
1580 DirsOnSysPath(os.path.join(os.path.dirname(__file__), 'data')):
1581 import package2.submodule1
1582 package2.submodule1.submodule2
1583
1584 def test_rebinding(self):
1585 # The same data is also used for testing pkgutil.resolve_name()
1586 # in test_pkgutil and mock.patch in test_unittest.
1587 path = os.path.join(os.path.dirname(__file__), 'data')
1588 with uncache('package3', 'package3.submodule'), DirsOnSysPath(path):
1589 from package3 import submodule
1590 self.assertEqual(submodule.attr, 'rebound')
1591 import package3.submodule as submodule
1592 self.assertEqual(submodule.attr, 'rebound')
1593 with uncache('package3', 'package3.submodule'), DirsOnSysPath(path):
1594 import package3.submodule as submodule
1595 self.assertEqual(submodule.attr, 'rebound')
1596 from package3 import submodule
1597 self.assertEqual(submodule.attr, 'rebound')
1598
1599 def test_rebinding2(self):
1600 path = os.path.join(os.path.dirname(__file__), 'data')
1601 with uncache('package4', 'package4.submodule'), DirsOnSysPath(path):
1602 import package4.submodule as submodule
1603 self.assertEqual(submodule.attr, 'submodule')
1604 from package4 import submodule
1605 self.assertEqual(submodule.attr, 'submodule')
1606 with uncache('package4', 'package4.submodule'), DirsOnSysPath(path):
1607 from package4 import submodule
1608 self.assertEqual(submodule.attr, 'origin')
1609 import package4.submodule as submodule
1610 self.assertEqual(submodule.attr, 'submodule')
1611
1612
1613 class OverridingImportBuiltinTests(unittest.TestCase):
1614 def test_override_builtin(self):
1615 # Test that overriding builtins.__import__ can bypass sys.modules.
1616 import os
1617
1618 def foo():
1619 import os
1620 return os
1621 self.assertEqual(foo(), os) # Quick sanity check.
1622
1623 with swap_attr(builtins, "__import__", lambda *x: 5):
1624 self.assertEqual(foo(), 5)
1625
1626 # Test what happens when we shadow __import__ in globals(); this
1627 # currently does not impact the import process, but if this changes,
1628 # other code will need to change, so keep this test as a tripwire.
1629 with swap_item(globals(), "__import__", lambda *x: 5):
1630 self.assertEqual(foo(), os)
1631
1632
1633 class PycacheTests(unittest.TestCase):
1634 # Test the various PEP 3147/488-related behaviors.
1635
1636 def _clean(self):
1637 forget(TESTFN)
1638 rmtree('__pycache__')
1639 unlink(self.source)
1640
1641 def setUp(self):
1642 # These tests assume bytecode is written next to the source in a
1643 # local __pycache__ directory, so neutralize any pycache prefix (e.g.
1644 # when the test suite is run with PYTHONPYCACHEPREFIX set).
1645 self._orig_pycache_prefix = sys.pycache_prefix
1646 sys.pycache_prefix = None
1647 self.source = TESTFN + '.py'
1648 self._clean()
1649 with open(self.source, 'w', encoding='utf-8') as fp:
1650 print('# This is a test file written by test_import.py', file=fp)
1651 sys.path.insert(0, os.curdir)
1652 importlib.invalidate_caches()
1653
1654 def tearDown(self):
1655 assert sys.path[0] == os.curdir, 'Unexpected sys.path[0]'
1656 del sys.path[0]
1657 self._clean()
1658 sys.pycache_prefix = self._orig_pycache_prefix
1659
1660 @skip_if_dont_write_bytecode
1661 def test_import_pyc_path(self):
1662 self.assertFalse(os.path.exists('__pycache__'))
1663 __import__(TESTFN)
1664 self.assertTrue(os.path.exists('__pycache__'))
1665 pyc_path = importlib.util.cache_from_source(self.source)
1666 self.assertTrue(os.path.exists(pyc_path),
1667 'bytecode file {!r} for {!r} does not '
1668 'exist'.format(pyc_path, TESTFN))
1669
1670 @unittest.skipUnless(os.name == 'posix',
1671 "test meaningful only on posix systems")
1672 @skip_if_dont_write_bytecode
1673 @os_helper.skip_unless_working_chmod
1674 @os_helper.skip_if_dac_override
1675 @unittest.skipIf(is_emscripten, "umask is a stub")
1676 def test_unwritable_directory(self):
1677 # When the umask causes the new __pycache__ directory to be
1678 # unwritable, the import still succeeds but no .pyc file is written.
1679 with temp_umask(0o222):
1680 __import__(TESTFN)
1681 self.assertTrue(os.path.exists('__pycache__'))
1682 pyc_path = importlib.util.cache_from_source(self.source)
1683 self.assertFalse(os.path.exists(pyc_path),
1684 'bytecode file {!r} for {!r} '
1685 'exists'.format(pyc_path, TESTFN))
1686
1687 @skip_if_dont_write_bytecode
1688 def test_missing_source(self):
1689 # With PEP 3147 cache layout, removing the source but leaving the pyc
1690 # file does not satisfy the import.
1691 __import__(TESTFN)
1692 pyc_file = importlib.util.cache_from_source(self.source)
1693 self.assertTrue(os.path.exists(pyc_file))
1694 os.remove(self.source)
1695 forget(TESTFN)
1696 importlib.invalidate_caches()
1697 self.assertRaises(ImportError, __import__, TESTFN)
1698
1699 @skip_if_dont_write_bytecode
1700 def test_missing_source_legacy(self):
1701 # Like test_missing_source() except that for backward compatibility,
1702 # when the pyc file lives where the py file would have been (and named
1703 # without the tag), it is importable. The __file__ of the imported
1704 # module is the pyc location.
1705 __import__(TESTFN)
1706 # pyc_file gets removed in _clean() via tearDown().
1707 pyc_file = make_legacy_pyc(self.source)
1708 os.remove(self.source)
1709 unload(TESTFN)
1710 importlib.invalidate_caches()
1711 m = __import__(TESTFN)
1712 try:
1713 self.assertEqual(m.__file__,
1714 os.path.join(os.getcwd(), os.path.relpath(pyc_file)))
1715 finally:
1716 os.remove(pyc_file)
1717
1718 def test___cached__(self):
1719 # Modules now also have an __cached__ that points to the pyc file.
1720 m = __import__(TESTFN)
1721 pyc_file = importlib.util.cache_from_source(TESTFN + '.py')
1722 self.assertEqual(m.__cached__, os.path.join(os.getcwd(), pyc_file))
1723
1724 @skip_if_dont_write_bytecode
1725 def test___cached___legacy_pyc(self):
1726 # Like test___cached__() except that for backward compatibility,
1727 # when the pyc file lives where the py file would have been (and named
1728 # without the tag), it is importable. The __cached__ of the imported
1729 # module is the pyc location.
1730 __import__(TESTFN)
1731 # pyc_file gets removed in _clean() via tearDown().
1732 pyc_file = make_legacy_pyc(self.source)
1733 os.remove(self.source)
1734 unload(TESTFN)
1735 importlib.invalidate_caches()
1736 m = __import__(TESTFN)
1737 self.assertEqual(m.__cached__,
1738 os.path.join(os.getcwd(), os.path.relpath(pyc_file)))
1739
1740 @skip_if_dont_write_bytecode
1741 def test_package___cached__(self):
1742 # Like test___cached__ but for packages.
1743 def cleanup():
1744 rmtree('pep3147')
1745 unload('pep3147.foo')
1746 unload('pep3147')
1747 os.mkdir('pep3147')
1748 self.addCleanup(cleanup)
1749 # Touch the __init__.py
1750 with open(os.path.join('pep3147', '__init__.py'), 'wb'):
1751 pass
1752 with open(os.path.join('pep3147', 'foo.py'), 'wb'):
1753 pass
1754 importlib.invalidate_caches()
1755 m = __import__('pep3147.foo')
1756 init_pyc = importlib.util.cache_from_source(
1757 os.path.join('pep3147', '__init__.py'))
1758 self.assertEqual(m.__cached__, os.path.join(os.getcwd(), init_pyc))
1759 foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py'))
1760 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
1761 os.path.join(os.getcwd(), foo_pyc))
1762
1763 def test_package___cached___from_pyc(self):
1764 # Like test___cached__ but ensuring __cached__ when imported from a
1765 # PEP 3147 pyc file.
1766 def cleanup():
1767 rmtree('pep3147')
1768 unload('pep3147.foo')
1769 unload('pep3147')
1770 os.mkdir('pep3147')
1771 self.addCleanup(cleanup)
1772 # Touch the __init__.py
1773 with open(os.path.join('pep3147', '__init__.py'), 'wb'):
1774 pass
1775 with open(os.path.join('pep3147', 'foo.py'), 'wb'):
1776 pass
1777 importlib.invalidate_caches()
1778 m = __import__('pep3147.foo')
1779 unload('pep3147.foo')
1780 unload('pep3147')
1781 importlib.invalidate_caches()
1782 m = __import__('pep3147.foo')
1783 init_pyc = importlib.util.cache_from_source(
1784 os.path.join('pep3147', '__init__.py'))
1785 self.assertEqual(m.__cached__, os.path.join(os.getcwd(), init_pyc))
1786 foo_pyc = importlib.util.cache_from_source(os.path.join('pep3147', 'foo.py'))
1787 self.assertEqual(sys.modules['pep3147.foo'].__cached__,
1788 os.path.join(os.getcwd(), foo_pyc))
1789
1790 def test_recompute_pyc_same_second(self):
1791 # Even when the source file doesn't change timestamp, a change in
1792 # source size is enough to trigger recomputation of the pyc file.
1793 __import__(TESTFN)
1794 unload(TESTFN)
1795 with open(self.source, 'a', encoding='utf-8') as fp:
1796 print("x = 5", file=fp)
1797 m = __import__(TESTFN)
1798 self.assertEqual(m.x, 5)
1799
1800
1801 class TestSymbolicallyLinkedPackage(unittest.TestCase):
1802 package_name = 'sample'
1803 tagged = package_name + '-tagged'
1804
1805 def setUp(self):
1806 os_helper.rmtree(self.tagged)
1807 os_helper.rmtree(self.package_name)
1808 self.orig_sys_path = sys.path[:]
1809
1810 # create a sample package; imagine you have a package with a tag and
1811 # you want to symbolically link it from its untagged name.
1812 os.mkdir(self.tagged)
1813 self.addCleanup(os_helper.rmtree, self.tagged)
1814 init_file = os.path.join(self.tagged, '__init__.py')
1815 os_helper.create_empty_file(init_file)
1816 assert os.path.exists(init_file)
1817
1818 # now create a symlink to the tagged package
1819 # sample -> sample-tagged
1820 os.symlink(self.tagged, self.package_name, target_is_directory=True)
1821 self.addCleanup(os_helper.unlink, self.package_name)
1822 importlib.invalidate_caches()
1823
1824 self.assertEqual(os.path.isdir(self.package_name), True)
1825
1826 assert os.path.isfile(os.path.join(self.package_name, '__init__.py'))
1827
1828 def tearDown(self):
1829 sys.path[:] = self.orig_sys_path
1830
1831 # regression test for issue6727
1832 @unittest.skipUnless(
1833 not hasattr(sys, 'getwindowsversion')
1834 or sys.getwindowsversion() >= (6, 0),
1835 "Windows Vista or later required")
1836 @os_helper.skip_unless_symlink
1837 def test_symlinked_dir_importable(self):
1838 # make sure sample can only be imported from the current directory.
1839 sys.path[:] = ['.']
1840 assert os.path.exists(self.package_name)
1841 assert os.path.exists(os.path.join(self.package_name, '__init__.py'))
1842
1843 # Try to import the package
1844 importlib.import_module(self.package_name)
1845
1846
1847 @cpython_only
1848 class ImportlibBootstrapTests(unittest.TestCase, ExtraAssertions):
1849 # These tests check that importlib is bootstrapped.
1850
1851 def test_frozen_importlib(self):
1852 mod = sys.modules['_frozen_importlib']
1853 self.assertTrue(mod)
1854
1855 def test_frozen_importlib_is_bootstrap(self):
1856 from importlib import _bootstrap
1857 mod = sys.modules['_frozen_importlib']
1858 self.assertIs(mod, _bootstrap)
1859 self.assertEqual(mod.__name__, 'importlib._bootstrap')
1860 self.assertEqual(mod.__package__, 'importlib')
1861 self.assertEndsWith(mod.__file__, '_bootstrap.py')
1862
1863 def test_frozen_importlib_external_is_bootstrap_external(self):
1864 from importlib import _bootstrap_external
1865 mod = sys.modules['_frozen_importlib_external']
1866 self.assertIs(mod, _bootstrap_external)
1867 self.assertEqual(mod.__name__, 'importlib._bootstrap_external')
1868 self.assertEqual(mod.__package__, 'importlib')
1869 self.assertEndsWith(mod.__file__, '_bootstrap_external.py')
1870
1871 def test_there_can_be_only_one(self):
1872 # Issue #15386 revealed a tricky loophole in the bootstrapping
1873 # This test is technically redundant, since the bug caused importing
1874 # this test module to crash completely, but it helps prove the point
1875 from importlib import machinery
1876 mod = sys.modules['_frozen_importlib']
1877 self.assertIs(machinery.ModuleSpec, mod.ModuleSpec)
1878
1879
1880 @cpython_only
1881 class GetSourcefileTests(unittest.TestCase):
1882
1883 """Test importlib._bootstrap_external._get_sourcefile() as used by the C API.
1884
1885 Because of the peculiarities of the need of this function, the tests are
1886 knowingly whitebox tests.
1887
1888 """
1889
1890 def test_get_sourcefile(self):
1891 # Given a valid bytecode path, return the path to the corresponding
1892 # source file if it exists.
1893 with mock.patch('importlib._bootstrap_external._path_isfile') as _path_isfile:
1894 _path_isfile.return_value = True
1895 path = TESTFN + '.pyc'
1896 expect = TESTFN + '.py'
1897 self.assertEqual(_get_sourcefile(path), expect)
1898
1899 def test_get_sourcefile_no_source(self):
1900 # Given a valid bytecode path without a corresponding source path,
1901 # return the original bytecode path.
1902 with mock.patch('importlib._bootstrap_external._path_isfile') as _path_isfile:
1903 _path_isfile.return_value = False
1904 path = TESTFN + '.pyc'
1905 self.assertEqual(_get_sourcefile(path), path)
1906
1907 def test_get_sourcefile_bad_ext(self):
1908 # Given a path with an invalid bytecode extension, return the
1909 # bytecode path passed as the argument.
1910 path = TESTFN + '.bad_ext'
1911 self.assertEqual(_get_sourcefile(path), path)
1912
1913
1914 class ImportTracebackTests(unittest.TestCase):
1915
1916 def setUp(self):
1917 os.mkdir(TESTFN)
1918 self.old_path = sys.path[:]
1919 sys.path.insert(0, TESTFN)
1920
1921 def tearDown(self):
1922 sys.path[:] = self.old_path
1923 rmtree(TESTFN)
1924
1925 def create_module(self, mod, contents, ext=".py"):
1926 fname = os.path.join(TESTFN, mod + ext)
1927 with open(fname, "w", encoding='utf-8') as f:
1928 f.write(contents)
1929 self.addCleanup(unload, mod)
1930 importlib.invalidate_caches()
1931 return fname
1932
1933 def assert_traceback(self, tb, files):
1934 deduped_files = []
1935 while tb:
1936 code = tb.tb_frame.f_code
1937 fn = code.co_filename
1938 if not deduped_files or fn != deduped_files[-1]:
1939 deduped_files.append(fn)
1940 tb = tb.tb_next
1941 self.assertEqual(len(deduped_files), len(files), deduped_files)
1942 for fn, pat in zip(deduped_files, files):
1943 self.assertIn(pat, fn)
1944
1945 def test_nonexistent_module(self):
1946 try:
1947 # assertRaises() clears __traceback__
1948 import nonexistent_xyzzy
1949 except ImportError as e:
1950 tb = e.__traceback__
1951 else:
1952 self.fail("ImportError should have been raised")
1953 self.assert_traceback(tb, [__file__])
1954
1955 def test_nonexistent_module_nested(self):
1956 self.create_module("foo", "import nonexistent_xyzzy")
1957 try:
1958 import foo
1959 except ImportError as e:
1960 tb = e.__traceback__
1961 else:
1962 self.fail("ImportError should have been raised")
1963 self.assert_traceback(tb, [__file__, 'foo.py'])
1964
1965 def test_exec_failure(self):
1966 self.create_module("foo", "1/0")
1967 try:
1968 import foo
1969 except ZeroDivisionError as e:
1970 tb = e.__traceback__
1971 else:
1972 self.fail("ZeroDivisionError should have been raised")
1973 self.assert_traceback(tb, [__file__, 'foo.py'])
1974
1975 def test_exec_failure_nested(self):
1976 self.create_module("foo", "import bar")
1977 self.create_module("bar", "1/0")
1978 try:
1979 import foo
1980 except ZeroDivisionError as e:
1981 tb = e.__traceback__
1982 else:
1983 self.fail("ZeroDivisionError should have been raised")
1984 self.assert_traceback(tb, [__file__, 'foo.py', 'bar.py'])
1985
1986 # A few more examples from issue #15425
1987 def test_syntax_error(self):
1988 self.create_module("foo", "invalid syntax is invalid")
1989 try:
1990 import foo
1991 except SyntaxError as e:
1992 tb = e.__traceback__
1993 else:
1994 self.fail("SyntaxError should have been raised")
1995 self.assert_traceback(tb, [__file__])
1996
1997 def _setup_broken_package(self, parent, child):
1998 pkg_name = "_parent_foo"
1999 self.addCleanup(unload, pkg_name)
2000 pkg_path = os.path.join(TESTFN, pkg_name)
2001 os.mkdir(pkg_path)
2002 # Touch the __init__.py
2003 init_path = os.path.join(pkg_path, '__init__.py')
2004 with open(init_path, 'w', encoding='utf-8') as f:
2005 f.write(parent)
2006 bar_path = os.path.join(pkg_path, 'bar.py')
2007 with open(bar_path, 'w', encoding='utf-8') as f:
2008 f.write(child)
2009 importlib.invalidate_caches()
2010 return init_path, bar_path
2011
2012 def test_broken_submodule(self):
2013 init_path, bar_path = self._setup_broken_package("", "1/0")
2014 try:
2015 import _parent_foo.bar
2016 except ZeroDivisionError as e:
2017 tb = e.__traceback__
2018 else:
2019 self.fail("ZeroDivisionError should have been raised")
2020 self.assert_traceback(tb, [__file__, bar_path])
2021
2022 def test_broken_from(self):
2023 init_path, bar_path = self._setup_broken_package("", "1/0")
2024 try:
2025 from _parent_foo import bar
2026 except ZeroDivisionError as e:
2027 tb = e.__traceback__
2028 else:
2029 self.fail("ImportError should have been raised")
2030 self.assert_traceback(tb, [__file__, bar_path])
2031
2032 def test_broken_parent(self):
2033 init_path, bar_path = self._setup_broken_package("1/0", "")
2034 try:
2035 import _parent_foo.bar
2036 except ZeroDivisionError as e:
2037 tb = e.__traceback__
2038 else:
2039 self.fail("ZeroDivisionError should have been raised")
2040 self.assert_traceback(tb, [__file__, init_path])
2041
2042 def test_broken_parent_from(self):
2043 init_path, bar_path = self._setup_broken_package("1/0", "")
2044 try:
2045 from _parent_foo import bar
2046 except ZeroDivisionError as e:
2047 tb = e.__traceback__
2048 else:
2049 self.fail("ZeroDivisionError should have been raised")
2050 self.assert_traceback(tb, [__file__, init_path])
2051
2052 @cpython_only
2053 def test_import_bug(self):
2054 # We simulate a bug in importlib and check that it's not stripped
2055 # away from the traceback.
2056 self.create_module("foo", "")
2057 importlib = sys.modules['_frozen_importlib_external']
2058 if 'load_module' in vars(importlib.SourceLoader):
2059 old_exec_module = importlib.SourceLoader.exec_module
2060 else:
2061 old_exec_module = None
2062 try:
2063 def exec_module(*args):
2064 1/0
2065 importlib.SourceLoader.exec_module = exec_module
2066 try:
2067 import foo
2068 except ZeroDivisionError as e:
2069 tb = e.__traceback__
2070 else:
2071 self.fail("ZeroDivisionError should have been raised")
2072 self.assert_traceback(tb, [__file__, '<frozen importlib', __file__])
2073 finally:
2074 if old_exec_module is None:
2075 del importlib.SourceLoader.exec_module
2076 else:
2077 importlib.SourceLoader.exec_module = old_exec_module
2078
2079 @unittest.skipUnless(TESTFN_UNENCODABLE, 'need TESTFN_UNENCODABLE')
2080 def test_unencodable_filename(self):
2081 # Issue #11619: The Python parser and the import machinery must not
2082 # encode filenames, especially on Windows
2083 pyname = script_helper.make_script('', TESTFN_UNENCODABLE, 'pass')
2084 self.addCleanup(unlink, pyname)
2085 name = pyname[:-3]
2086 script_helper.assert_python_ok("-c", "mod = __import__(%a)" % name,
2087 __isolated=False)
2088
2089
2090 class CircularImportTests(unittest.TestCase):
2091
2092 """See the docstrings of the modules being imported for the purpose of the
2093 test."""
2094
2095 def tearDown(self):
2096 """Make sure no modules pre-exist in sys.modules which are being used to
2097 test."""
2098 for key in list(sys.modules.keys()):
2099 if key.startswith('test.test_import.data.circular_imports'):
2100 del sys.modules[key]
2101
2102 def test_direct(self):
2103 try:
2104 import test.test_import.data.circular_imports.basic
2105 except ImportError:
2106 self.fail('circular import through relative imports failed')
2107
2108 def test_indirect(self):
2109 try:
2110 import test.test_import.data.circular_imports.indirect
2111 except ImportError:
2112 self.fail('relative import in module contributing to circular '
2113 'import failed')
2114
2115 def test_subpackage(self):
2116 try:
2117 import test.test_import.data.circular_imports.subpackage
2118 except ImportError:
2119 self.fail('circular import involving a subpackage failed')
2120
2121 def test_rebinding(self):
2122 try:
2123 import test.test_import.data.circular_imports.rebinding as rebinding
2124 except ImportError:
2125 self.fail('circular import with rebinding of module attribute failed')
2126 from test.test_import.data.circular_imports.subpkg import util
2127 self.assertIs(util.util, rebinding.util)
2128
2129 def test_binding(self):
2130 try:
2131 import test.test_import.data.circular_imports.binding
2132 except ImportError:
2133 self.fail('circular import with binding a submodule to a name failed')
2134
2135 def test_crossreference1(self):
2136 import test.test_import.data.circular_imports.use
2137 import test.test_import.data.circular_imports.source
2138
2139 def test_crossreference2(self):
2140 with self.assertRaises(AttributeError) as cm:
2141 import test.test_import.data.circular_imports.source
2142 errmsg = str(cm.exception)
2143 self.assertIn('test.test_import.data.circular_imports.source', errmsg)
2144 self.assertIn('spam', errmsg)
2145 self.assertIn('partially initialized module', errmsg)
2146 self.assertIn('circular import', errmsg)
2147
2148 def test_circular_from_import(self):
2149 with self.assertRaises(ImportError) as cm:
2150 import test.test_import.data.circular_imports.from_cycle1
2151 self.assertIn(
2152 "cannot import name 'b' from partially initialized module "
2153 "'test.test_import.data.circular_imports.from_cycle1' "
2154 "(most likely due to a circular import)",
2155 str(cm.exception),
2156 )
2157
2158 def test_circular_import(self):
2159 with self.assertRaisesRegex(
2160 AttributeError,
2161 r"partially initialized module 'test.test_import.data.circular_imports.import_cycle' "
2162 r"from '.*' has no attribute 'some_attribute' \(most likely due to a circular import\)"
2163 ):
2164 import test.test_import.data.circular_imports.import_cycle
2165
2166 def test_absolute_circular_submodule(self):
2167 with self.assertRaises(AttributeError) as cm:
2168 import test.test_import.data.circular_imports.subpkg2.parent
2169 self.assertIn(
2170 "cannot access submodule 'parent' of module "
2171 "'test.test_import.data.circular_imports.subpkg2' "
2172 "(most likely due to a circular import)",
2173 str(cm.exception),
2174 )
2175
2176 @requires_singlephase_init
2177 @unittest.skipIf(_testsinglephase is None, "test requires _testsinglephase module")
2178 def test_singlephase_circular(self):
2179 """Regression test for gh-123950
2180
2181 Import a single-phase-init module that imports itself
2182 from the PyInit_* function (before it's added to sys.modules).
2183 Manages its own cache (which is `static`, and so incompatible
2184 with multiple interpreters or interpreter reset).
2185 """
2186 name = '_testsinglephase_circular'
2187 helper_name = 'test.test_import.data.circular_imports.singlephase'
2188 with uncache(name, helper_name):
2189 filename = _testsinglephase.__file__
2190 # We don't put the module in sys.modules: that the *inner*
2191 # import should do that.
2192 mod = import_extension_from_file(name, filename,
2193 put_in_sys_modules=False)
2194
2195 self.assertEqual(mod.helper_mod_name, helper_name)
2196 self.assertIn(name, sys.modules)
2197 self.assertIn(helper_name, sys.modules)
2198
2199 self.assertIn(name, sys.modules)
2200 self.assertIn(helper_name, sys.modules)
2201 self.assertNotIn(name, sys.modules)
2202 self.assertNotIn(helper_name, sys.modules)
2203 self.assertIs(mod.clear_static_var(), mod)
2204 _testinternalcapi.clear_extension('_testsinglephase_circular',
2205 mod.__spec__.origin)
2206
2207 def test_unwritable_module(self):
2208 self.addCleanup(unload, "test.test_import.data.unwritable")
2209 self.addCleanup(unload, "test.test_import.data.unwritable.x")
2210
2211 import test.test_import.data.unwritable as unwritable
2212 with self.assertWarns(ImportWarning):
2213 from test.test_import.data.unwritable import x
2214
2215 self.assertNotEqual(type(unwritable), ModuleType)
2216 self.assertEqual(type(x), ModuleType)
2217 with self.assertRaises(AttributeError):
2218 unwritable.x = 42
2219
2220
2221 class SubinterpImportTests(unittest.TestCase):
2222
2223 RUN_KWARGS = dict(
2224 allow_fork=False,
2225 allow_exec=False,
2226 allow_threads=True,
2227 allow_daemon_threads=False,
2228 # Isolation-related config values aren't included here.
2229 )
2230 ISOLATED = dict(
2231 use_main_obmalloc=False,
2232 gil=2,
2233 )
2234 NOT_ISOLATED = {k: not v for k, v in ISOLATED.items()}
2235 NOT_ISOLATED['gil'] = 1
2236
2237 @unittest.skipUnless(hasattr(os, "pipe"), "requires os.pipe()")
2238 def pipe(self):
2239 r, w = os.pipe()
2240 self.addCleanup(os.close, r)
2241 self.addCleanup(os.close, w)
2242 if hasattr(os, 'set_blocking'):
2243 os.set_blocking(r, False)
2244 return (r, w)
2245
2246 def import_script(self, name, fd, filename=None, check_override=None):
2247 override_text = ''
2248 if check_override is not None:
2249 override_text = f'''
2250 import _imp
2251 _imp._override_multi_interp_extensions_check({check_override})
2252 '''
2253 if filename:
2254 # Apple extensions must be distributed as frameworks. This requires
2255 # a specialist loader.
2256 if is_apple_mobile:
2257 loader = "AppleFrameworkLoader"
2258 else:
2259 loader = "ExtensionFileLoader"
2260
2261 return textwrap.dedent(f'''
2262 from importlib.util import spec_from_loader, module_from_spec
2263 from importlib.machinery import {loader}
2264 import os, sys
2265 {override_text}
2266 loader = {loader}({name!r}, {filename!r})
2267 spec = spec_from_loader({name!r}, loader)
2268 try:
2269 module = module_from_spec(spec)
2270 loader.exec_module(module)
2271 except ImportError as exc:
2272 text = 'ImportError: ' + str(exc)
2273 else:
2274 text = 'okay'
2275 os.write({fd}, text.encode('utf-8'))
2276 ''')
2277 else:
2278 return textwrap.dedent(f'''
2279 import os, sys
2280 {override_text}
2281 try:
2282 import {name}
2283 except ImportError as exc:
2284 text = 'ImportError: ' + str(exc)
2285 else:
2286 text = 'okay'
2287 os.write({fd}, text.encode('utf-8'))
2288 ''')
2289
2290 def run_here(self, name, filename=None, *,
2291 check_singlephase_setting=False,
2292 check_singlephase_override=None,
2293 isolated=False,
2294 ):
2295 """
2296 Try importing the named module in a subinterpreter.
2297
2298 The subinterpreter will be in the current process.
2299 The module will have already been imported in the main interpreter.
2300 Thus, for extension/builtin modules, the module definition will
2301 have been loaded already and cached globally.
2302
2303 "check_singlephase_setting" determines whether or not
2304 the interpreter will be configured to check for modules
2305 that are not compatible with use in multiple interpreters.
2306
2307 This should always return "okay" for all modules if the
2308 setting is False (with no override).
2309 """
2310 __import__(name)
2311
2312 kwargs = dict(
2313 **self.RUN_KWARGS,
2314 **(self.ISOLATED if isolated else self.NOT_ISOLATED),
2315 check_multi_interp_extensions=check_singlephase_setting,
2316 )
2317
2318 r, w = self.pipe()
2319 script = self.import_script(name, w, filename,
2320 check_singlephase_override)
2321
2322 ret = run_in_subinterp_with_config(script, **kwargs)
2323 self.assertEqual(ret, 0)
2324 return os.read(r, 100)
2325
2326 def check_compatible_here(self, name, filename=None, *,
2327 strict=False,
2328 isolated=False,
2329 ):
2330 # Verify that the named module may be imported in a subinterpreter.
2331 # (See run_here() for more info.)
2332 out = self.run_here(name, filename,
2333 check_singlephase_setting=strict,
2334 isolated=isolated,
2335 )
2336 self.assertEqual(out, b'okay')
2337
2338 def check_incompatible_here(self, name, filename=None, *, isolated=False):
2339 # Differences from check_compatible_here():
2340 # * verify that import fails
2341 # * "strict" is always True
2342 out = self.run_here(name, filename,
2343 check_singlephase_setting=True,
2344 isolated=isolated,
2345 )
2346 self.assertEqual(
2347 out.decode('utf-8'),
2348 f'ImportError: module {name} does not support loading in subinterpreters',
2349 )
2350
2351 def check_compatible_fresh(self, name, *, strict=False, isolated=False):
2352 # Differences from check_compatible_here():
2353 # * subinterpreter in a new process
2354 # * module has never been imported before in that process
2355 # * this tests importing the module for the first time
2356 kwargs = dict(
2357 **self.RUN_KWARGS,
2358 **(self.ISOLATED if isolated else self.NOT_ISOLATED),
2359 check_multi_interp_extensions=strict,
2360 )
2361 gil = kwargs['gil']
2362 kwargs['gil'] = 'default' if gil == 0 else (
2363 'shared' if gil == 1 else 'own' if gil == 2 else gil)
2364 _, out, err = script_helper.assert_python_ok('-c', textwrap.dedent(f'''
2365 import _testinternalcapi, sys
2366 assert (
2367 {name!r} in sys.builtin_module_names or
2368 {name!r} not in sys.modules
2369 ), repr({name!r})
2370 config = type(sys.implementation)(**{kwargs})
2371 ret = _testinternalcapi.run_in_subinterp_with_config(
2372 {self.import_script(name, "sys.stdout.fileno()")!r},
2373 config,
2374 )
2375 assert ret == 0, ret
2376 '''))
2377 self.assertEqual(err, b'')
2378 self.assertEqual(out, b'okay')
2379
2380 def check_incompatible_fresh(self, name, *, isolated=False):
2381 # Differences from check_compatible_fresh():
2382 # * verify that import fails
2383 # * "strict" is always True
2384 kwargs = dict(
2385 **self.RUN_KWARGS,
2386 **(self.ISOLATED if isolated else self.NOT_ISOLATED),
2387 check_multi_interp_extensions=True,
2388 )
2389 gil = kwargs['gil']
2390 kwargs['gil'] = 'default' if gil == 0 else (
2391 'shared' if gil == 1 else 'own' if gil == 2 else gil)
2392 _, out, err = script_helper.assert_python_ok('-c', textwrap.dedent(f'''
2393 import _testinternalcapi, sys
2394 assert {name!r} not in sys.modules, {name!r}
2395 config = type(sys.implementation)(**{kwargs})
2396 ret = _testinternalcapi.run_in_subinterp_with_config(
2397 {self.import_script(name, "sys.stdout.fileno()")!r},
2398 config,
2399 )
2400 assert ret == 0, ret
2401 '''))
2402 self.assertEqual(err, b'')
2403 self.assertEqual(
2404 out.decode('utf-8'),
2405 f'ImportError: module {name} does not support loading in subinterpreters',
2406 )
2407
2408 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
2409 def test_builtin_compat(self):
2410 # For now we avoid using sys or builtins
2411 # since they still don't implement multi-phase init.
2412 module = '_imp'
2413 require_builtin(module)
2414 if not Py_GIL_DISABLED:
2415 with self.subTest(f'{module}: not strict'):
2416 self.check_compatible_here(module, strict=False)
2417 with self.subTest(f'{module}: strict, not fresh'):
2418 self.check_compatible_here(module, strict=True)
2419
2420 @cpython_only
2421 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
2422 def test_frozen_compat(self):
2423 module = '_frozen_importlib'
2424 require_frozen(module, skip=True)
2425 if __import__(module).__spec__.origin != 'frozen':
2426 raise unittest.SkipTest(f'{module} is unexpectedly not frozen')
2427 if not Py_GIL_DISABLED:
2428 with self.subTest(f'{module}: not strict'):
2429 self.check_compatible_here(module, strict=False)
2430 with self.subTest(f'{module}: strict, not fresh'):
2431 self.check_compatible_here(module, strict=True)
2432
2433 @requires_singlephase_init
2434 def test_single_init_extension_compat(self):
2435 module = '_testsinglephase'
2436 require_extension(module)
2437 with self.subTest(f'{module}: not strict'):
2438 self.check_compatible_here(module, strict=False)
2439 with self.subTest(f'{module}: strict, not fresh'):
2440 self.check_incompatible_here(module)
2441 with self.subTest(f'{module}: strict, fresh'):
2442 self.check_incompatible_fresh(module)
2443 with self.subTest(f'{module}: isolated, fresh'):
2444 self.check_incompatible_fresh(module, isolated=True)
2445
2446 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
2447 def test_multi_init_extension_compat(self):
2448 # Module with Py_MOD_PER_INTERPRETER_GIL_SUPPORTED
2449 module = '_testmultiphase'
2450 require_extension(module)
2451
2452 if not Py_GIL_DISABLED:
2453 with self.subTest(f'{module}: not strict'):
2454 self.check_compatible_here(module, strict=False)
2455 with self.subTest(f'{module}: strict, not fresh'):
2456 self.check_compatible_here(module, strict=True)
2457 with self.subTest(f'{module}: strict, fresh'):
2458 self.check_compatible_fresh(module, strict=True)
2459
2460 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
2461 def test_multi_init_extension_non_isolated_compat(self):
2462 # Module with Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED
2463 # and Py_MOD_GIL_NOT_USED
2464 modname = '_test_non_isolated'
2465 filename = _testmultiphase.__file__
2466 module = import_extension_from_file(modname, filename)
2467
2468 require_extension(module)
2469 with self.subTest(f'{modname}: isolated'):
2470 self.check_incompatible_here(modname, filename, isolated=True)
2471 with self.subTest(f'{modname}: not isolated'):
2472 self.check_incompatible_here(modname, filename, isolated=False)
2473 if not Py_GIL_DISABLED:
2474 with self.subTest(f'{modname}: not strict'):
2475 self.check_compatible_here(modname, filename, strict=False)
2476
2477 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
2478 def test_multi_init_extension_per_interpreter_gil_compat(self):
2479
2480 # _test_shared_gil_only:
2481 # Explicit Py_MOD_MULTIPLE_INTERPRETERS_SUPPORTED (default)
2482 # and Py_MOD_GIL_NOT_USED
2483 # _test_no_multiple_interpreter_slot:
2484 # No Py_mod_multiple_interpreters slot
2485 # and Py_MOD_GIL_NOT_USED
2486 for modname in ('_test_shared_gil_only',
2487 '_test_no_multiple_interpreter_slot'):
2488 with self.subTest(modname=modname):
2489
2490 filename = _testmultiphase.__file__
2491 module = import_extension_from_file(modname, filename)
2492
2493 require_extension(module)
2494 with self.subTest(f'{modname}: isolated, strict'):
2495 self.check_incompatible_here(modname, filename,
2496 isolated=True)
2497 with self.subTest(f'{modname}: not isolated, strict'):
2498 self.check_compatible_here(modname, filename,
2499 strict=True, isolated=False)
2500 if not Py_GIL_DISABLED:
2501 with self.subTest(f'{modname}: not isolated, not strict'):
2502 self.check_compatible_here(
2503 modname, filename, strict=False, isolated=False)
2504
2505 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
2506 def test_python_compat(self):
2507 module = 'threading'
2508 require_pure_python(module)
2509 if not Py_GIL_DISABLED:
2510 with self.subTest(f'{module}: not strict'):
2511 self.check_compatible_here(module, strict=False)
2512 with self.subTest(f'{module}: strict, not fresh'):
2513 self.check_compatible_here(module, strict=True)
2514 with self.subTest(f'{module}: strict, fresh'):
2515 self.check_compatible_fresh(module, strict=True)
2516
2517 @requires_singlephase_init
2518 def test_singlephase_check_with_setting_and_override(self):
2519 module = '_testsinglephase'
2520 require_extension(module)
2521
2522 def check_compatible(setting, override):
2523 out = self.run_here(
2524 module,
2525 check_singlephase_setting=setting,
2526 check_singlephase_override=override,
2527 )
2528 self.assertEqual(out, b'okay')
2529
2530 def check_incompatible(setting, override):
2531 out = self.run_here(
2532 module,
2533 check_singlephase_setting=setting,
2534 check_singlephase_override=override,
2535 )
2536 self.assertNotEqual(out, b'okay')
2537
2538 with self.subTest('config: check enabled; override: enabled'):
2539 check_incompatible(True, 1)
2540 with self.subTest('config: check enabled; override: use config'):
2541 check_incompatible(True, 0)
2542 with self.subTest('config: check enabled; override: disabled'):
2543 check_compatible(True, -1)
2544
2545 with self.subTest('config: check disabled; override: enabled'):
2546 check_incompatible(False, 1)
2547 with self.subTest('config: check disabled; override: use config'):
2548 check_compatible(False, 0)
2549 with self.subTest('config: check disabled; override: disabled'):
2550 check_compatible(False, -1)
2551
2552 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
2553 def test_isolated_config(self):
2554 module = 'threading'
2555 require_pure_python(module)
2556 with self.subTest(f'{module}: strict, not fresh'):
2557 self.check_compatible_here(module, strict=True, isolated=True)
2558 with self.subTest(f'{module}: strict, fresh'):
2559 self.check_compatible_fresh(module, strict=True, isolated=True)
2560
2561 @requires_subinterpreters
2562 @requires_singlephase_init
2563 def test_disallowed_reimport(self):
2564 # See https://github.com/python/cpython/issues/104621.
2565 script = textwrap.dedent('''
2566 import _testsinglephase
2567 print(_testsinglephase)
2568 ''')
2569 interpid = _interpreters.create()
2570 self.addCleanup(lambda: _interpreters.destroy(interpid))
2571
2572 excsnap = _interpreters.run_string(interpid, script)
2573 self.assertIsNot(excsnap, None)
2574
2575 excsnap = _interpreters.run_string(interpid, script)
2576 self.assertIsNot(excsnap, None)
2577
2578 @requires_subinterpreters
2579 def test_pyinit_function_raises_exception(self):
2580 # gh-144601: PyInit functions that raised exceptions would cause a
2581 # crash when imported from a subinterpreter.
2582 import _testsinglephase
2583 filename = _testsinglephase.__file__
2584 script = f"""if True:
2585 from test.test_import import import_extension_from_file
2586
2587 import_extension_from_file('_testsinglephase_raise_exception', {filename!r})"""
2588
2589 interp = _interpreters.create()
2590 try:
2591 with catch_unraisable_exception() as cm:
2592 exception = _interpreters.run_string(interp, script)
2593 unraisable = cm.unraisable
2594 finally:
2595 _interpreters.destroy(interp)
2596
2597 self.assertIsNotNone(exception)
2598 self.assertIsNotNone(exception.type.__name__, "ImportError")
2599 self.assertIsNotNone(exception.msg, "failed to import from subinterpreter due to exception")
2600 self.assertIsNotNone(unraisable)
2601 self.assertIs(unraisable.exc_type, RuntimeError)
2602 self.assertEqual(str(unraisable.exc_value), "evil")
2603
2604
2605 class TestSinglePhaseSnapshot(ModuleSnapshot):
2606 """A representation of a single-phase init module for testing.
2607
2608 Fields from ModuleSnapshot:
2609
2610 * id - id(mod)
2611 * module - mod or a SimpleNamespace with __file__ & __spec__
2612 * ns - a shallow copy of mod.__dict__
2613 * ns_id - id(mod.__dict__)
2614 * cached - sys.modules[name] (or None if not there or not snapshotable)
2615 * cached_id - id(sys.modules[name]) (or None if not there)
2616
2617 Extra fields:
2618
2619 * summed - the result of calling "mod.sum(1, 2)"
2620 * lookedup - the result of calling "mod.look_up_self()"
2621 * lookedup_id - the object ID of self.lookedup
2622 * state_initialized - the result of calling "mod.state_initialized()"
2623 * init_count - (optional) the result of calling "mod.initialized_count()"
2624
2625 Overridden methods from ModuleSnapshot:
2626
2627 * from_module()
2628 * parse()
2629
2630 Other methods from ModuleSnapshot:
2631
2632 * build_script()
2633 * from_subinterp()
2634
2635 ----
2636
2637 There are 5 modules in Modules/_testsinglephase.c:
2638
2639 * _testsinglephase
2640 * has global state
2641 * extra loads skip the init function, copy def.m_base.m_copy
2642 * counts calls to init function
2643 * _testsinglephase_basic_wrapper
2644 * _testsinglephase by another name (and separate init function symbol)
2645 * _testsinglephase_basic_copy
2646 * same as _testsinglephase but with own def (and init func)
2647 * _testsinglephase_with_reinit
2648 * has no global or module state
2649 * mod.state_initialized returns None
2650 * an extra load in the main interpreter calls the cached init func
2651 * an extra load in legacy subinterpreters does a full load
2652 * _testsinglephase_with_state
2653 * has module state
2654 * an extra load in the main interpreter calls the cached init func
2655 * an extra load in legacy subinterpreters does a full load
2656
2657 (See Modules/_testsinglephase.c for more info.)
2658
2659 For all those modules, the snapshot after the initial load (not in
2660 the global extensions cache) would look like the following:
2661
2662 * initial load
2663 * id: ID of nww module object
2664 * ns: exactly what the module init put there
2665 * ns_id: ID of new module's __dict__
2666 * cached_id: same as self.id
2667 * summed: 3 (never changes)
2668 * lookedup_id: same as self.id
2669 * state_initialized: a timestamp between the time of the load
2670 and the time of the snapshot
2671 * init_count: 1 (None for _testsinglephase_with_reinit)
2672
2673 For the other scenarios it varies.
2674
2675 For the _testsinglephase, _testsinglephase_basic_wrapper, and
2676 _testsinglephase_basic_copy modules, the snapshot should look
2677 like the following:
2678
2679 * reloaded
2680 * id: no change
2681 * ns: matches what the module init function put there,
2682 including the IDs of all contained objects,
2683 plus any extra attributes added before the reload
2684 * ns_id: no change
2685 * cached_id: no change
2686 * lookedup_id: no change
2687 * state_initialized: no change
2688 * init_count: no change
2689 * already loaded
2690 * (same as initial load except for ns and state_initialized)
2691 * ns: matches the initial load, incl. IDs of contained objects
2692 * state_initialized: no change from initial load
2693
2694 For _testsinglephase_with_reinit:
2695
2696 * reloaded: same as initial load (old module & ns is discarded)
2697 * already loaded: same as initial load (old module & ns is discarded)
2698
2699 For _testsinglephase_with_state:
2700
2701 * reloaded
2702 * (same as initial load (old module & ns is discarded),
2703 except init_count)
2704 * init_count: increase by 1
2705 * already loaded: same as reloaded
2706 """
2707
2708 @classmethod
2709 def from_module(cls, mod):
2710 self = super().from_module(mod)
2711 self.summed = mod.sum(1, 2)
2712 self.lookedup = mod.look_up_self()
2713 self.lookedup_id = id(self.lookedup)
2714 self.state_initialized = mod.state_initialized()
2715 if hasattr(mod, 'initialized_count'):
2716 self.init_count = mod.initialized_count()
2717 return self
2718
2719 SCRIPT_BODY = ModuleSnapshot.SCRIPT_BODY + textwrap.dedent('''
2720 snapshot['module'].update(dict(
2721 int_const=mod.int_const,
2722 str_const=mod.str_const,
2723 _module_initialized=mod._module_initialized,
2724 ))
2725 snapshot.update(dict(
2726 summed=mod.sum(1, 2),
2727 lookedup_id=id(mod.look_up_self()),
2728 state_initialized=mod.state_initialized(),
2729 init_count=mod.initialized_count(),
2730 has_spam=hasattr(mod, 'spam'),
2731 spam=getattr(mod, 'spam', None),
2732 ))
2733 ''').rstrip()
2734
2735 @classmethod
2736 def parse(cls, text):
2737 self = super().parse(text)
2738 if not self.has_spam:
2739 del self.spam
2740 del self.has_spam
2741 return self
2742
2743
2744 @requires_singlephase_init
2745 class SinglephaseInitTests(unittest.TestCase, ExtraAssertions):
2746
2747 NAME = '_testsinglephase'
2748
2749 @classmethod
2750 def setUpClass(cls):
2751 spec = importlib.util.find_spec(cls.NAME)
2752 cls.LOADER = type(spec.loader)
2753
2754 # Apple extensions must be distributed as frameworks. This requires
2755 # a specialist loader, and we need to differentiate between the
2756 # spec.origin and the original file location.
2757 if is_apple_mobile:
2758 assert cls.LOADER is AppleFrameworkLoader
2759
2760 cls.ORIGIN = spec.origin
2761 with open(spec.origin + ".origin", "r") as f:
2762 cls.FILE = os.path.join(
2763 os.path.dirname(sys.executable),
2764 f.read().strip()
2765 )
2766 else:
2767 assert cls.LOADER is ExtensionFileLoader
2768
2769 cls.ORIGIN = spec.origin
2770 cls.FILE = spec.origin
2771
2772 # Start fresh.
2773 cls.clean_up()
2774
2775 def tearDown(self):
2776 # Clean up the module.
2777 self.clean_up()
2778
2779 @classmethod
2780 def clean_up(cls):
2781 name = cls.NAME
2782 if name in sys.modules:
2783 if hasattr(sys.modules[name], '_clear_globals'):
2784 assert sys.modules[name].__file__ == cls.FILE, \
2785 f"{sys.modules[name].__file__} != {cls.FILE}"
2786
2787 sys.modules[name]._clear_globals()
2788 del sys.modules[name]
2789 # Clear all internally cached data for the extension.
2790 _testinternalcapi.clear_extension(name, cls.ORIGIN)
2791
2792 #########################
2793 # helpers
2794
2795 def add_module_cleanup(self, name):
2796 def clean_up():
2797 # Clear all internally cached data for the extension.
2798 _testinternalcapi.clear_extension(name, self.ORIGIN)
2799 self.addCleanup(clean_up)
2800
2801 def _load_dynamic(self, name, path):
2802 """
2803 Load an extension module.
2804 """
2805 # This is essentially copied from the old imp module.
2806 from importlib._bootstrap import _load
2807 loader = self.LOADER(name, path)
2808
2809 # Issue bpo-24748: Skip the sys.modules check in _load_module_shim;
2810 # always load new extension.
2811 spec = importlib.util.spec_from_file_location(name, path,
2812 loader=loader)
2813 return _load(spec)
2814
2815 def load(self, name):
2816 try:
2817 already_loaded = self.already_loaded
2818 except AttributeError:
2819 already_loaded = self.already_loaded = {}
2820 assert name not in already_loaded
2821 mod = self._load_dynamic(name, self.ORIGIN)
2822 self.assertNotIn(mod, already_loaded.values())
2823 already_loaded[name] = mod
2824 return types.SimpleNamespace(
2825 name=name,
2826 module=mod,
2827 snapshot=TestSinglePhaseSnapshot.from_module(mod),
2828 )
2829
2830 def re_load(self, name, mod):
2831 assert sys.modules[name] is mod
2832 assert mod.__dict__ == mod.__dict__
2833 reloaded = self._load_dynamic(name, self.ORIGIN)
2834 return types.SimpleNamespace(
2835 name=name,
2836 module=reloaded,
2837 snapshot=TestSinglePhaseSnapshot.from_module(reloaded),
2838 )
2839
2840 # subinterpreters
2841
2842 def add_subinterpreter(self):
2843 interpid = _interpreters.create('legacy')
2844 def ensure_destroyed():
2845 try:
2846 _interpreters.destroy(interpid)
2847 except _interpreters.InterpreterNotFoundError:
2848 pass
2849 self.addCleanup(ensure_destroyed)
2850 _interpreters.exec(interpid, textwrap.dedent('''
2851 import sys
2852 import _testinternalcapi
2853 '''))
2854 def clean_up():
2855 _interpreters.exec(interpid, textwrap.dedent(f'''
2856 name = {self.NAME!r}
2857 if name in sys.modules:
2858 sys.modules.pop(name)._clear_globals()
2859 _testinternalcapi.clear_extension(name, {self.ORIGIN!r})
2860 '''))
2861 _interpreters.destroy(interpid)
2862 self.addCleanup(clean_up)
2863 return interpid
2864
2865 def import_in_subinterp(self, interpid=None, *,
2866 postscript=None,
2867 postcleanup=False,
2868 ):
2869 name = self.NAME
2870
2871 if postcleanup:
2872 import_ = 'import _testinternalcapi' if interpid is None else ''
2873 postcleanup = f'''
2874 {import_}
2875 mod._clear_globals()
2876 _testinternalcapi.clear_extension(name, {self.ORIGIN!r})
2877 '''
2878
2879 try:
2880 pipe = self._pipe
2881 except AttributeError:
2882 r, w = pipe = self._pipe = os.pipe()
2883 self.addCleanup(os.close, r)
2884 self.addCleanup(os.close, w)
2885
2886 snapshot = TestSinglePhaseSnapshot.from_subinterp(
2887 name,
2888 interpid,
2889 pipe=pipe,
2890 import_first=True,
2891 postscript=postscript,
2892 postcleanup=postcleanup,
2893 )
2894
2895 return types.SimpleNamespace(
2896 name=name,
2897 module=None,
2898 snapshot=snapshot,
2899 )
2900
2901 # checks
2902
2903 def check_common(self, loaded):
2904 isolated = False
2905
2906 mod = loaded.module
2907 if not mod:
2908 # It came from a subinterpreter.
2909 isolated = True
2910 mod = loaded.snapshot.module
2911 # mod.__name__ might not match, but the spec will.
2912 self.assertEqual(mod.__spec__.name, loaded.name)
2913 self.assertEqual(mod.__file__, self.FILE)
2914 self.assertEqual(mod.__spec__.origin, self.ORIGIN)
2915 if not isolated:
2916 self.assertIsSubclass(mod.error, Exception)
2917 self.assertEqual(mod.int_const, 1969)
2918 self.assertEqual(mod.str_const, 'something different')
2919 self.assertIsInstance(mod._module_initialized, float)
2920 self.assertGreater(mod._module_initialized, 0)
2921
2922 snap = loaded.snapshot
2923 self.assertEqual(snap.summed, 3)
2924 if snap.state_initialized is not None:
2925 self.assertIsInstance(snap.state_initialized, float)
2926 self.assertGreater(snap.state_initialized, 0)
2927 if isolated:
2928 # The "looked up" module is interpreter-specific
2929 # (interp->imports.modules_by_index was set for the module).
2930 self.assertEqual(snap.lookedup_id, snap.id)
2931 self.assertEqual(snap.cached_id, snap.id)
2932 with self.assertRaises(AttributeError):
2933 snap.spam
2934 else:
2935 self.assertIs(snap.lookedup, mod)
2936 self.assertIs(snap.cached, mod)
2937
2938 def check_direct(self, loaded):
2939 # The module has its own PyModuleDef, with a matching name.
2940 self.assertEqual(loaded.module.__name__, loaded.name)
2941 self.assertIs(loaded.snapshot.lookedup, loaded.module)
2942
2943 def check_indirect(self, loaded, orig):
2944 # The module re-uses another's PyModuleDef, with a different name.
2945 assert orig is not loaded.module
2946 assert orig.__name__ != loaded.name
2947 self.assertNotEqual(loaded.module.__name__, loaded.name)
2948 self.assertIs(loaded.snapshot.lookedup, loaded.module)
2949
2950 def check_basic(self, loaded, expected_init_count):
2951 # m_size == -1
2952 # The module loads fresh the first time and copies m_copy after.
2953 snap = loaded.snapshot
2954 self.assertIsNot(snap.state_initialized, None)
2955 self.assertIsInstance(snap.init_count, int)
2956 self.assertGreater(snap.init_count, 0)
2957 self.assertEqual(snap.init_count, expected_init_count)
2958
2959 def check_with_reinit(self, loaded):
2960 # m_size >= 0
2961 # The module loads fresh every time.
2962 pass
2963
2964 def check_fresh(self, loaded):
2965 """
2966 The module had not been loaded before (at least since fully reset).
2967 """
2968 snap = loaded.snapshot
2969 # The module's init func was run.
2970 # A copy of the module's __dict__ was stored in def->m_base.m_copy.
2971 # The previous m_copy was deleted first.
2972 # _PyRuntime.imports.extensions was set.
2973 self.assertEqual(snap.init_count, 1)
2974 # The global state was initialized.
2975 # The module attrs were initialized from that state.
2976 self.assertEqual(snap.module._module_initialized,
2977 snap.state_initialized)
2978
2979 def check_semi_fresh(self, loaded, base, prev):
2980 """
2981 The module had been loaded before and then reset
2982 (but the module global state wasn't).
2983 """
2984 snap = loaded.snapshot
2985 # The module's init func was run again.
2986 # A copy of the module's __dict__ was stored in def->m_base.m_copy.
2987 # The previous m_copy was deleted first.
2988 # The module globals did not get reset.
2989 self.assertNotEqual(snap.id, base.snapshot.id)
2990 self.assertNotEqual(snap.id, prev.snapshot.id)
2991 self.assertEqual(snap.init_count, prev.snapshot.init_count + 1)
2992 # The global state was updated.
2993 # The module attrs were initialized from that state.
2994 self.assertEqual(snap.module._module_initialized,
2995 snap.state_initialized)
2996 self.assertNotEqual(snap.state_initialized,
2997 base.snapshot.state_initialized)
2998 self.assertNotEqual(snap.state_initialized,
2999 prev.snapshot.state_initialized)
3000
3001 def check_copied(self, loaded, base):
3002 """
3003 The module had been loaded before and never reset.
3004 """
3005 snap = loaded.snapshot
3006 # The module's init func was not run again.
3007 # The interpreter copied m_copy, as set by the other interpreter,
3008 # with objects owned by the other interpreter.
3009 # The module globals did not get reset.
3010 self.assertNotEqual(snap.id, base.snapshot.id)
3011 self.assertEqual(snap.init_count, base.snapshot.init_count)
3012 # The global state was not updated since the init func did not run.
3013 # The module attrs were not directly initialized from that state.
3014 # The state and module attrs still match the previous loading.
3015 self.assertEqual(snap.module._module_initialized,
3016 snap.state_initialized)
3017 self.assertEqual(snap.state_initialized,
3018 base.snapshot.state_initialized)
3019
3020 #########################
3021 # the tests
3022
3023 def test_cleared_globals(self):
3024 loaded = self.load(self.NAME)
3025 _testsinglephase = loaded.module
3026 init_before = _testsinglephase.state_initialized()
3027
3028 _testsinglephase._clear_globals()
3029 init_after = _testsinglephase.state_initialized()
3030 init_count = _testsinglephase.initialized_count()
3031
3032 self.assertGreater(init_before, 0)
3033 self.assertEqual(init_after, 0)
3034 self.assertEqual(init_count, -1)
3035
3036 def test_variants(self):
3037 # Exercise the most meaningful variants described in Python/import.c.
3038 self.maxDiff = None
3039
3040 # Check the "basic" module.
3041
3042 name = self.NAME
3043 expected_init_count = 1
3044 with self.subTest(name):
3045 loaded = self.load(name)
3046
3047 self.check_common(loaded)
3048 self.check_direct(loaded)
3049 self.check_basic(loaded, expected_init_count)
3050 basic = loaded.module
3051
3052 # Check its indirect variants.
3053
3054 name = f'{self.NAME}_basic_wrapper'
3055 self.add_module_cleanup(name)
3056 expected_init_count += 1
3057 with self.subTest(name):
3058 loaded = self.load(name)
3059
3060 self.check_common(loaded)
3061 self.check_indirect(loaded, basic)
3062 self.check_basic(loaded, expected_init_count)
3063
3064 # Currently PyState_AddModule() always replaces the cached module.
3065 self.assertIs(basic.look_up_self(), loaded.module)
3066 self.assertEqual(basic.initialized_count(), expected_init_count)
3067
3068 # The cached module shouldn't change after this point.
3069 basic_lookedup = loaded.module
3070
3071 # Check its direct variant.
3072
3073 name = f'{self.NAME}_basic_copy'
3074 self.add_module_cleanup(name)
3075 expected_init_count += 1
3076 with self.subTest(name):
3077 loaded = self.load(name)
3078
3079 self.check_common(loaded)
3080 self.check_direct(loaded)
3081 self.check_basic(loaded, expected_init_count)
3082
3083 # This should change the cached module for _testsinglephase.
3084 self.assertIs(basic.look_up_self(), basic_lookedup)
3085 self.assertEqual(basic.initialized_count(), expected_init_count)
3086
3087 # Check the non-basic variant that has no state.
3088
3089 name = f'{self.NAME}_with_reinit'
3090 self.add_module_cleanup(name)
3091 with self.subTest(name):
3092 loaded = self.load(name)
3093
3094 self.check_common(loaded)
3095 self.assertIs(loaded.snapshot.state_initialized, None)
3096 self.check_direct(loaded)
3097 self.check_with_reinit(loaded)
3098
3099 # This should change the cached module for _testsinglephase.
3100 self.assertIs(basic.look_up_self(), basic_lookedup)
3101 self.assertEqual(basic.initialized_count(), expected_init_count)
3102
3103 # Check the basic variant that has state.
3104
3105 name = f'{self.NAME}_with_state'
3106 self.add_module_cleanup(name)
3107 with self.subTest(name):
3108 loaded = self.load(name)
3109 self.addCleanup(loaded.module._clear_module_state)
3110
3111 self.check_common(loaded)
3112 self.assertIsNot(loaded.snapshot.state_initialized, None)
3113 self.check_direct(loaded)
3114 self.check_with_reinit(loaded)
3115
3116 # This should change the cached module for _testsinglephase.
3117 self.assertIs(basic.look_up_self(), basic_lookedup)
3118 self.assertEqual(basic.initialized_count(), expected_init_count)
3119
3120 def test_basic_reloaded(self):
3121 # m_copy is copied into the existing module object.
3122 # Global state is not changed.
3123 self.maxDiff = None
3124
3125 for name in [
3126 self.NAME, # the "basic" module
3127 f'{self.NAME}_basic_wrapper', # the indirect variant
3128 f'{self.NAME}_basic_copy', # the direct variant
3129 ]:
3130 self.add_module_cleanup(name)
3131 with self.subTest(name):
3132 loaded = self.load(name)
3133 reloaded = self.re_load(name, loaded.module)
3134
3135 self.check_common(loaded)
3136 self.check_common(reloaded)
3137
3138 # Make sure the original __dict__ did not get replaced.
3139 self.assertEqual(id(loaded.module.__dict__),
3140 loaded.snapshot.ns_id)
3141 self.assertEqual(loaded.snapshot.ns.__dict__,
3142 loaded.module.__dict__)
3143
3144 self.assertEqual(reloaded.module.__spec__.name, reloaded.name)
3145 self.assertEqual(reloaded.module.__name__,
3146 reloaded.snapshot.ns.__name__)
3147
3148 self.assertIs(reloaded.module, loaded.module)
3149 self.assertIs(reloaded.module.__dict__, loaded.module.__dict__)
3150 # It only happens to be the same but that's good enough here.
3151 # We really just want to verify that the re-loaded attrs
3152 # didn't change.
3153 self.assertIs(reloaded.snapshot.lookedup,
3154 loaded.snapshot.lookedup)
3155 self.assertEqual(reloaded.snapshot.state_initialized,
3156 loaded.snapshot.state_initialized)
3157 self.assertEqual(reloaded.snapshot.init_count,
3158 loaded.snapshot.init_count)
3159
3160 self.assertIs(reloaded.snapshot.cached, reloaded.module)
3161
3162 def test_with_reinit_reloaded(self):
3163 # The module's m_init func is run again.
3164 self.maxDiff = None
3165
3166 # Keep a reference around.
3167 basic = self.load(self.NAME)
3168
3169 for name, has_state in [
3170 (f'{self.NAME}_with_reinit', False), # m_size == 0
3171 (f'{self.NAME}_with_state', True), # m_size > 0
3172 ]:
3173 self.add_module_cleanup(name)
3174 with self.subTest(name=name, has_state=has_state):
3175 loaded = self.load(name)
3176 if has_state:
3177 self.addCleanup(loaded.module._clear_module_state)
3178
3179 reloaded = self.re_load(name, loaded.module)
3180 if has_state:
3181 self.addCleanup(reloaded.module._clear_module_state)
3182
3183 self.check_common(loaded)
3184 self.check_common(reloaded)
3185
3186 # Make sure the original __dict__ did not get replaced.
3187 self.assertEqual(id(loaded.module.__dict__),
3188 loaded.snapshot.ns_id)
3189 self.assertEqual(loaded.snapshot.ns.__dict__,
3190 loaded.module.__dict__)
3191
3192 self.assertEqual(reloaded.module.__spec__.name, reloaded.name)
3193 self.assertEqual(reloaded.module.__name__,
3194 reloaded.snapshot.ns.__name__)
3195
3196 self.assertIsNot(reloaded.module, loaded.module)
3197 self.assertNotEqual(reloaded.module.__dict__,
3198 loaded.module.__dict__)
3199 self.assertIs(reloaded.snapshot.lookedup, reloaded.module)
3200 if loaded.snapshot.state_initialized is None:
3201 self.assertIs(reloaded.snapshot.state_initialized, None)
3202 else:
3203 self.assertGreater(reloaded.snapshot.state_initialized,
3204 loaded.snapshot.state_initialized)
3205
3206 self.assertIs(reloaded.snapshot.cached, reloaded.module)
3207
3208 @unittest.skipIf(_testinternalcapi is None, "requires _testinternalcapi")
3209 def test_check_state_first(self):
3210 for variant in ['', '_with_reinit', '_with_state']:
3211 name = f'{self.NAME}{variant}_check_cache_first'
3212 with self.subTest(name):
3213 mod = self._load_dynamic(name, self.ORIGIN)
3214 self.assertEqual(mod.__name__, name)
3215 sys.modules.pop(name, None)
3216 _testinternalcapi.clear_extension(name, self.ORIGIN)
3217
3218 # Currently, for every single-phrase init module loaded
3219 # in multiple interpreters, those interpreters share a
3220 # PyModuleDef for that object, which can be a problem.
3221 # Also, we test with a single-phase module that has global state,
3222 # which is shared by all interpreters.
3223
3224 @no_rerun(reason="module state is not cleared (see gh-140657)")
3225 @requires_subinterpreters
3226 def test_basic_multiple_interpreters_main_no_reset(self):
3227 # without resetting; already loaded in main interpreter
3228
3229 # At this point:
3230 # * alive in 0 interpreters
3231 # * module def may or may not be loaded already
3232 # * module def not in _PyRuntime.imports.extensions
3233 # * mod init func has not run yet (since reset, at least)
3234 # * m_copy not set (hasn't been loaded yet or already cleared)
3235 # * module's global state has not been initialized yet
3236 # (or already cleared)
3237
3238 main_loaded = self.load(self.NAME)
3239 _testsinglephase = main_loaded.module
3240 # Attrs set after loading are not in m_copy.
3241 _testsinglephase.spam = 'spam, spam, spam, spam, eggs, and spam'
3242
3243 self.check_common(main_loaded)
3244 self.check_fresh(main_loaded)
3245
3246 interpid1 = self.add_subinterpreter()
3247 interpid2 = self.add_subinterpreter()
3248
3249 # At this point:
3250 # * alive in 1 interpreter (main)
3251 # * module def in _PyRuntime.imports.extensions
3252 # * mod init func ran for the first time (since reset, at least)
3253 # * m_copy was copied from the main interpreter (was NULL)
3254 # * module's global state was initialized
3255
3256 # Use an interpreter that gets destroyed right away.
3257 loaded = self.import_in_subinterp()
3258 self.check_common(loaded)
3259 self.check_copied(loaded, main_loaded)
3260
3261 # At this point:
3262 # * alive in 1 interpreter (main)
3263 # * module def still in _PyRuntime.imports.extensions
3264 # * mod init func ran again
3265 # * m_copy is NULL (claered when the interpreter was destroyed)
3266 # (was from main interpreter)
3267 # * module's global state was updated, not reset
3268
3269 # Use a subinterpreter that sticks around.
3270 loaded = self.import_in_subinterp(interpid1)
3271 self.check_common(loaded)
3272 self.check_copied(loaded, main_loaded)
3273
3274 # At this point:
3275 # * alive in 2 interpreters (main, interp1)
3276 # * module def still in _PyRuntime.imports.extensions
3277 # * mod init func ran again
3278 # * m_copy was copied from interp1
3279 # * module's global state was updated, not reset
3280
3281 # Use a subinterpreter while the previous one is still alive.
3282 loaded = self.import_in_subinterp(interpid2)
3283 self.check_common(loaded)
3284 self.check_copied(loaded, main_loaded)
3285
3286 # At this point:
3287 # * alive in 3 interpreters (main, interp1, interp2)
3288 # * module def still in _PyRuntime.imports.extensions
3289 # * mod init func ran again
3290 # * m_copy was copied from interp2 (was from interp1)
3291 # * module's global state was updated, not reset
3292
3293 @no_rerun(reason="rerun not possible; module state is never cleared (see gh-102251)")
3294 @requires_subinterpreters
3295 def test_basic_multiple_interpreters_deleted_no_reset(self):
3296 # without resetting; already loaded in a deleted interpreter
3297
3298 if Py_TRACE_REFS:
3299 # It's a Py_TRACE_REFS build.
3300 # This test breaks interpreter isolation a little,
3301 # which causes problems on Py_TRACE_REF builds.
3302 raise unittest.SkipTest('crashes on Py_TRACE_REFS builds')
3303
3304 # At this point:
3305 # * alive in 0 interpreters
3306 # * module def may or may not be loaded already
3307 # * module def not in _PyRuntime.imports.extensions
3308 # * mod init func has not run yet (since reset, at least)
3309 # * m_copy not set (hasn't been loaded yet or already cleared)
3310 # * module's global state has not been initialized yet
3311 # (or already cleared)
3312
3313 interpid1 = self.add_subinterpreter()
3314 interpid2 = self.add_subinterpreter()
3315
3316 # First, load in the main interpreter but then completely clear it.
3317 loaded_main = self.load(self.NAME)
3318 loaded_main.module._clear_globals()
3319 _testinternalcapi.clear_extension(self.NAME, self.ORIGIN)
3320
3321 # At this point:
3322 # * alive in 0 interpreters
3323 # * module def loaded already
3324 # * module def was in _PyRuntime.imports.extensions, but cleared
3325 # * mod init func ran for the first time (since reset, at least)
3326 # * m_copy was set, but cleared (was NULL)
3327 # * module's global state was initialized but cleared
3328
3329 # Start with an interpreter that gets destroyed right away.
3330 base = self.import_in_subinterp(
3331 postscript='''
3332 # Attrs set after loading are not in m_copy.
3333 mod.spam = 'spam, spam, mash, spam, eggs, and spam'
3334 ''')
3335 self.check_common(base)
3336 self.check_fresh(base)
3337
3338 # At this point:
3339 # * alive in 0 interpreters
3340 # * module def in _PyRuntime.imports.extensions
3341 # * mod init func ran for the first time (since reset)
3342 # * m_copy is still set (owned by main interpreter)
3343 # * module's global state was initialized, not reset
3344
3345 # Use a subinterpreter that sticks around.
3346 loaded_interp1 = self.import_in_subinterp(interpid1)
3347 self.check_common(loaded_interp1)
3348 self.check_copied(loaded_interp1, base)
3349
3350 # At this point:
3351 # * alive in 1 interpreter (interp1)
3352 # * module def still in _PyRuntime.imports.extensions
3353 # * mod init func did not run again
3354 # * m_copy was not changed
3355 # * module's global state was not touched
3356
3357 # Use a subinterpreter while the previous one is still alive.
3358 loaded_interp2 = self.import_in_subinterp(interpid2)
3359 self.check_common(loaded_interp2)
3360 self.check_copied(loaded_interp2, loaded_interp1)
3361
3362 # At this point:
3363 # * alive in 2 interpreters (interp1, interp2)
3364 # * module def still in _PyRuntime.imports.extensions
3365 # * mod init func did not run again
3366 # * m_copy was not changed
3367 # * module's global state was not touched
3368
3369 @requires_subinterpreters
3370 def test_basic_multiple_interpreters_reset_each(self):
3371 # resetting between each interpreter
3372
3373 # At this point:
3374 # * alive in 0 interpreters
3375 # * module def may or may not be loaded already
3376 # * module def not in _PyRuntime.imports.extensions
3377 # * mod init func has not run yet (since reset, at least)
3378 # * m_copy not set (hasn't been loaded yet or already cleared)
3379 # * module's global state has not been initialized yet
3380 # (or already cleared)
3381
3382 interpid1 = self.add_subinterpreter()
3383 interpid2 = self.add_subinterpreter()
3384
3385 # Use an interpreter that gets destroyed right away.
3386 loaded = self.import_in_subinterp(
3387 postscript='''
3388 # Attrs set after loading are not in m_copy.
3389 mod.spam = 'spam, spam, mash, spam, eggs, and spam'
3390 ''',
3391 postcleanup=True,
3392 )
3393 self.check_common(loaded)
3394 self.check_fresh(loaded)
3395
3396 # At this point:
3397 # * alive in 0 interpreters
3398 # * module def in _PyRuntime.imports.extensions
3399 # * mod init func ran for the first time (since reset, at least)
3400 # * m_copy is NULL (claered when the interpreter was destroyed)
3401 # * module's global state was initialized, not reset
3402
3403 # Use a subinterpreter that sticks around.
3404 loaded = self.import_in_subinterp(interpid1, postcleanup=True)
3405 self.check_common(loaded)
3406 self.check_fresh(loaded)
3407
3408 # At this point:
3409 # * alive in 1 interpreter (interp1)
3410 # * module def still in _PyRuntime.imports.extensions
3411 # * mod init func ran again
3412 # * m_copy was copied from interp1 (was NULL)
3413 # * module's global state was initialized, not reset
3414
3415 # Use a subinterpreter while the previous one is still alive.
3416 loaded = self.import_in_subinterp(interpid2, postcleanup=True)
3417 self.check_common(loaded)
3418 self.check_fresh(loaded)
3419
3420 # At this point:
3421 # * alive in 2 interpreters (interp2, interp2)
3422 # * module def still in _PyRuntime.imports.extensions
3423 # * mod init func ran again
3424 # * m_copy was copied from interp2 (was from interp1)
3425 # * module's global state was initialized, not reset
3426
3427
3428 if __name__ == '__main__':
3429 # Test needs to be a package, so we can do relative imports.
3430 unittest.main()