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