Debian Codegraph @

Lib/test/test_importlib/test_util.py

raw
1 from test.test_importlib import util
2
3 abc = util.import_importlib('importlib.abc')
4 init = util.import_importlib('importlib')
5 machinery = util.import_importlib('importlib.machinery')
6 importlib_util = util.import_importlib('importlib.util')
7
8 import importlib.util
9 from importlib import _bootstrap_external
10 import os
11 import pathlib
12 import re
13 import string
14 import sys
15 from test import support
16 from test.support import os_helper
17 import textwrap
18 import types
19 import unittest
20 import unittest.mock
21 import warnings
22
23 try:
24 import _testsinglephase
25 except ImportError:
26 _testsinglephase = None
27 try:
28 import _testmultiphase
29 except ImportError:
30 _testmultiphase = None
31 try:
32 import _interpreters
33 except ModuleNotFoundError:
34 _interpreters = None
35
36
37 class DecodeSourceBytesTests:
38
39 source = "string ='ü'"
40
41 def test_ut8_default(self):
42 source_bytes = self.source.encode('utf-8')
43 self.assertEqual(self.util.decode_source(source_bytes), self.source)
44
45 def test_specified_encoding(self):
46 source = '# coding=latin-1\n' + self.source
47 source_bytes = source.encode('latin-1')
48 assert source_bytes != source.encode('utf-8')
49 self.assertEqual(self.util.decode_source(source_bytes), source)
50
51 def test_universal_newlines(self):
52 source = '\r\n'.join([self.source, self.source])
53 source_bytes = source.encode('utf-8')
54 self.assertEqual(self.util.decode_source(source_bytes),
55 '\n'.join([self.source, self.source]))
56
57
58 (Frozen_DecodeSourceBytesTests,
59 Source_DecodeSourceBytesTests
60 ) = util.test_both(DecodeSourceBytesTests, util=importlib_util)
61
62
63 class ModuleFromSpecTests:
64
65 def test_no_create_module(self):
66 class Loader:
67 def exec_module(self, module):
68 pass
69 spec = self.machinery.ModuleSpec('test', Loader())
70 with self.assertRaises(ImportError):
71 module = self.util.module_from_spec(spec)
72
73 def test_create_module_returns_None(self):
74 class Loader(self.abc.Loader):
75 def create_module(self, spec):
76 return None
77 spec = self.machinery.ModuleSpec('test', Loader())
78 module = self.util.module_from_spec(spec)
79 self.assertIsInstance(module, types.ModuleType)
80 self.assertEqual(module.__name__, spec.name)
81
82 def test_create_module(self):
83 name = 'already set'
84 class CustomModule(types.ModuleType):
85 pass
86 class Loader(self.abc.Loader):
87 def create_module(self, spec):
88 module = CustomModule(spec.name)
89 module.__name__ = name
90 return module
91 spec = self.machinery.ModuleSpec('test', Loader())
92 module = self.util.module_from_spec(spec)
93 self.assertIsInstance(module, CustomModule)
94 self.assertEqual(module.__name__, name)
95
96 def test___name__(self):
97 spec = self.machinery.ModuleSpec('test', object())
98 module = self.util.module_from_spec(spec)
99 self.assertEqual(module.__name__, spec.name)
100
101 def test___spec__(self):
102 spec = self.machinery.ModuleSpec('test', object())
103 module = self.util.module_from_spec(spec)
104 self.assertEqual(module.__spec__, spec)
105
106 def test___loader__(self):
107 loader = object()
108 spec = self.machinery.ModuleSpec('test', loader)
109 module = self.util.module_from_spec(spec)
110 self.assertIs(module.__loader__, loader)
111
112 def test___package__(self):
113 spec = self.machinery.ModuleSpec('test.pkg', object())
114 module = self.util.module_from_spec(spec)
115 self.assertEqual(module.__package__, spec.parent)
116
117 def test___path__(self):
118 spec = self.machinery.ModuleSpec('test', object(), is_package=True)
119 module = self.util.module_from_spec(spec)
120 self.assertEqual(module.__path__, spec.submodule_search_locations)
121
122 def test___file__(self):
123 spec = self.machinery.ModuleSpec('test', object(), origin='some/path')
124 spec.has_location = True
125 module = self.util.module_from_spec(spec)
126 self.assertEqual(module.__file__, spec.origin)
127
128 def test___cached__(self):
129 spec = self.machinery.ModuleSpec('test', object())
130 spec.cached = 'some/path'
131 spec.has_location = True
132 module = self.util.module_from_spec(spec)
133 self.assertEqual(module.__cached__, spec.cached)
134
135 (Frozen_ModuleFromSpecTests,
136 Source_ModuleFromSpecTests
137 ) = util.test_both(ModuleFromSpecTests, abc=abc, machinery=machinery,
138 util=importlib_util)
139
140
141 class ResolveNameTests:
142
143 """Tests importlib.util.resolve_name()."""
144
145 def test_absolute(self):
146 # bacon
147 self.assertEqual('bacon', self.util.resolve_name('bacon', None))
148
149 def test_absolute_within_package(self):
150 # bacon in spam
151 self.assertEqual('bacon', self.util.resolve_name('bacon', 'spam'))
152
153 def test_no_package(self):
154 # .bacon in ''
155 with self.assertRaises(ImportError):
156 self.util.resolve_name('.bacon', '')
157
158 def test_in_package(self):
159 # .bacon in spam
160 self.assertEqual('spam.eggs.bacon',
161 self.util.resolve_name('.bacon', 'spam.eggs'))
162
163 def test_other_package(self):
164 # ..bacon in spam.bacon
165 self.assertEqual('spam.bacon',
166 self.util.resolve_name('..bacon', 'spam.eggs'))
167
168 def test_escape(self):
169 # ..bacon in spam
170 with self.assertRaises(ImportError):
171 self.util.resolve_name('..bacon', 'spam')
172
173
174 (Frozen_ResolveNameTests,
175 Source_ResolveNameTests
176 ) = util.test_both(ResolveNameTests, util=importlib_util)
177
178
179 class FindSpecTests:
180
181 class FakeMetaFinder:
182 @staticmethod
183 def find_spec(name, path=None, target=None): return name, path, target
184
185 def test_sys_modules(self):
186 name = 'some_mod'
187 with util.uncache(name):
188 module = types.ModuleType(name)
189 loader = 'a loader!'
190 spec = self.machinery.ModuleSpec(name, loader)
191 module.__loader__ = loader
192 module.__spec__ = spec
193 sys.modules[name] = module
194 found = self.util.find_spec(name)
195 self.assertEqual(found, spec)
196
197 def test_sys_modules_without___loader__(self):
198 name = 'some_mod'
199 with util.uncache(name):
200 module = types.ModuleType(name)
201 del module.__loader__
202 loader = 'a loader!'
203 spec = self.machinery.ModuleSpec(name, loader)
204 module.__spec__ = spec
205 sys.modules[name] = module
206 found = self.util.find_spec(name)
207 self.assertEqual(found, spec)
208
209 def test_sys_modules_spec_is_None(self):
210 name = 'some_mod'
211 with util.uncache(name):
212 module = types.ModuleType(name)
213 module.__spec__ = None
214 sys.modules[name] = module
215 with self.assertRaises(ValueError):
216 self.util.find_spec(name)
217
218 def test_sys_modules_loader_is_None(self):
219 name = 'some_mod'
220 with util.uncache(name):
221 module = types.ModuleType(name)
222 spec = self.machinery.ModuleSpec(name, None)
223 module.__spec__ = spec
224 sys.modules[name] = module
225 found = self.util.find_spec(name)
226 self.assertEqual(found, spec)
227
228 def test_sys_modules_spec_is_not_set(self):
229 name = 'some_mod'
230 with util.uncache(name):
231 module = types.ModuleType(name)
232 try:
233 del module.__spec__
234 except AttributeError:
235 pass
236 sys.modules[name] = module
237 with self.assertRaises(ValueError):
238 self.util.find_spec(name)
239
240 def test_success(self):
241 name = 'some_mod'
242 with util.uncache(name):
243 with util.import_state(meta_path=[self.FakeMetaFinder]):
244 self.assertEqual((name, None, None),
245 self.util.find_spec(name))
246
247 def test_nothing(self):
248 # None is returned upon failure to find a loader.
249 self.assertIsNone(self.util.find_spec('nevergoingtofindthismodule'))
250
251 def test_find_submodule(self):
252 name = 'spam'
253 subname = 'ham'
254 with util.temp_module(name, pkg=True) as pkg_dir:
255 fullname, _ = util.submodule(name, subname, pkg_dir)
256 spec = self.util.find_spec(fullname)
257 self.assertIsNot(spec, None)
258 self.assertIn(name, sorted(sys.modules))
259 self.assertNotIn(fullname, sorted(sys.modules))
260 # Ensure successive calls behave the same.
261 spec_again = self.util.find_spec(fullname)
262 self.assertEqual(spec_again, spec)
263
264 def test_find_submodule_parent_already_imported(self):
265 name = 'spam'
266 subname = 'ham'
267 with util.temp_module(name, pkg=True) as pkg_dir:
268 self.init.import_module(name)
269 fullname, _ = util.submodule(name, subname, pkg_dir)
270 spec = self.util.find_spec(fullname)
271 self.assertIsNot(spec, None)
272 self.assertIn(name, sorted(sys.modules))
273 self.assertNotIn(fullname, sorted(sys.modules))
274 # Ensure successive calls behave the same.
275 spec_again = self.util.find_spec(fullname)
276 self.assertEqual(spec_again, spec)
277
278 def test_find_relative_module(self):
279 name = 'spam'
280 subname = 'ham'
281 with util.temp_module(name, pkg=True) as pkg_dir:
282 fullname, _ = util.submodule(name, subname, pkg_dir)
283 relname = '.' + subname
284 spec = self.util.find_spec(relname, name)
285 self.assertIsNot(spec, None)
286 self.assertIn(name, sorted(sys.modules))
287 self.assertNotIn(fullname, sorted(sys.modules))
288 # Ensure successive calls behave the same.
289 spec_again = self.util.find_spec(fullname)
290 self.assertEqual(spec_again, spec)
291
292 def test_find_relative_module_missing_package(self):
293 name = 'spam'
294 subname = 'ham'
295 with util.temp_module(name, pkg=True) as pkg_dir:
296 fullname, _ = util.submodule(name, subname, pkg_dir)
297 relname = '.' + subname
298 with self.assertRaises(ImportError):
299 self.util.find_spec(relname)
300 self.assertNotIn(name, sorted(sys.modules))
301 self.assertNotIn(fullname, sorted(sys.modules))
302
303 def test_find_submodule_in_module(self):
304 # ModuleNotFoundError raised when a module is specified as
305 # a parent instead of a package.
306 with self.assertRaises(ModuleNotFoundError):
307 self.util.find_spec('module.name')
308
309
310 (Frozen_FindSpecTests,
311 Source_FindSpecTests
312 ) = util.test_both(FindSpecTests, init=init, util=importlib_util,
313 machinery=machinery)
314
315
316 class MagicNumberTests:
317
318 def test_length(self):
319 # Should be 4 bytes.
320 self.assertEqual(len(self.util.MAGIC_NUMBER), 4)
321
322 def test_incorporates_rn(self):
323 # The magic number uses \r\n to come out wrong when splitting on lines.
324 self.assertEndsWith(self.util.MAGIC_NUMBER, b'\r\n')
325
326
327 (Frozen_MagicNumberTests,
328 Source_MagicNumberTests
329 ) = util.test_both(MagicNumberTests, util=importlib_util)
330
331
332 class PEP3147Tests:
333
334 """Tests of PEP 3147-related functions: cache_from_source and source_from_cache."""
335
336 tag = sys.implementation.cache_tag
337
338 def setUp(self):
339 # Most of these tests assume the default (unset) pycache prefix, so
340 # clear it for the duration of the test (e.g. when the test suite is
341 # run with PYTHONPYCACHEPREFIX set). Tests that need a specific prefix
342 # set their own via util.temporary_pycache_prefix().
343 self._orig_pycache_prefix = sys.pycache_prefix
344 sys.pycache_prefix = None
345
346 def tearDown(self):
347 sys.pycache_prefix = self._orig_pycache_prefix
348
349 @unittest.skipIf(sys.implementation.cache_tag is None,
350 'requires sys.implementation.cache_tag not be None')
351 def test_cache_from_source(self):
352 # Given the path to a .py file, return the path to its PEP 3147
353 # defined .pyc file (i.e. under __pycache__).
354 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
355 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
356 'qux.{}.pyc'.format(self.tag))
357 self.assertEqual(self.util.cache_from_source(path, optimization=''),
358 expect)
359
360 def test_cache_from_source_no_cache_tag(self):
361 # No cache tag means NotImplementedError.
362 with support.swap_attr(sys.implementation, 'cache_tag', None):
363 with self.assertRaises(NotImplementedError):
364 self.util.cache_from_source('whatever.py')
365
366 def test_cache_from_source_no_dot(self):
367 # Directory with a dot, filename without dot.
368 path = os.path.join('foo.bar', 'file')
369 expect = os.path.join('foo.bar', '__pycache__',
370 'file{}.pyc'.format(self.tag))
371 self.assertEqual(self.util.cache_from_source(path, optimization=''),
372 expect)
373
374 def test_cache_from_source_debug_override(self):
375 # Given the path to a .py file, return the path to its PEP 3147/PEP 488
376 # defined .pyc file (i.e. under __pycache__).
377 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
378 with warnings.catch_warnings():
379 warnings.simplefilter('ignore')
380 self.assertEqual(self.util.cache_from_source(path, False),
381 self.util.cache_from_source(path, optimization=1))
382 self.assertEqual(self.util.cache_from_source(path, True),
383 self.util.cache_from_source(path, optimization=''))
384 with warnings.catch_warnings():
385 warnings.simplefilter('error')
386 with self.assertRaises(DeprecationWarning):
387 self.util.cache_from_source(path, False)
388 with self.assertRaises(DeprecationWarning):
389 self.util.cache_from_source(path, True)
390
391 def test_cache_from_source_cwd(self):
392 path = 'foo.py'
393 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
394 self.assertEqual(self.util.cache_from_source(path, optimization=''),
395 expect)
396
397 def test_cache_from_source_override(self):
398 # When debug_override is not None, it can be any true-ish or false-ish
399 # value.
400 path = os.path.join('foo', 'bar', 'baz.py')
401 # However if the bool-ishness can't be determined, the exception
402 # propagates.
403 class Bearish:
404 def __bool__(self): raise RuntimeError
405 with warnings.catch_warnings():
406 warnings.simplefilter('ignore')
407 self.assertEqual(self.util.cache_from_source(path, []),
408 self.util.cache_from_source(path, optimization=1))
409 self.assertEqual(self.util.cache_from_source(path, [17]),
410 self.util.cache_from_source(path, optimization=''))
411 with self.assertRaises(RuntimeError):
412 self.util.cache_from_source('/foo/bar/baz.py', Bearish())
413
414
415 def test_cache_from_source_optimization_empty_string(self):
416 # Setting 'optimization' to '' leads to no optimization tag (PEP 488).
417 path = 'foo.py'
418 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
419 self.assertEqual(self.util.cache_from_source(path, optimization=''),
420 expect)
421
422 def test_cache_from_source_optimization_None(self):
423 # Setting 'optimization' to None uses the interpreter's optimization.
424 # (PEP 488)
425 path = 'foo.py'
426 optimization_level = sys.flags.optimize
427 almost_expect = os.path.join('__pycache__', 'foo.{}'.format(self.tag))
428 if optimization_level == 0:
429 expect = almost_expect + '.pyc'
430 elif optimization_level <= 2:
431 expect = almost_expect + '.opt-{}.pyc'.format(optimization_level)
432 else:
433 msg = '{!r} is a non-standard optimization level'.format(optimization_level)
434 self.skipTest(msg)
435 self.assertEqual(self.util.cache_from_source(path, optimization=None),
436 expect)
437
438 def test_cache_from_source_optimization_set(self):
439 # The 'optimization' parameter accepts anything that has a string repr
440 # that passes str.alnum().
441 path = 'foo.py'
442 valid_characters = string.ascii_letters + string.digits
443 almost_expect = os.path.join('__pycache__', 'foo.{}'.format(self.tag))
444 got = self.util.cache_from_source(path, optimization=valid_characters)
445 # Test all valid characters are accepted.
446 self.assertEqual(got,
447 almost_expect + '.opt-{}.pyc'.format(valid_characters))
448 # str() should be called on argument.
449 self.assertEqual(self.util.cache_from_source(path, optimization=42),
450 almost_expect + '.opt-42.pyc')
451 # Invalid characters raise ValueError.
452 with self.assertRaises(ValueError):
453 self.util.cache_from_source(path, optimization='path/is/bad')
454
455 def test_cache_from_source_debug_override_optimization_both_set(self):
456 # Can only set one of the optimization-related parameters.
457 with warnings.catch_warnings():
458 warnings.simplefilter('ignore')
459 with self.assertRaises(TypeError):
460 self.util.cache_from_source('foo.py', False, optimization='')
461
462 @unittest.skipUnless(os.sep == '\\' and os.altsep == '/',
463 'test meaningful only where os.altsep is defined')
464 def test_sep_altsep_and_sep_cache_from_source(self):
465 # Windows path and PEP 3147 where sep is right of altsep.
466 self.assertEqual(
467 self.util.cache_from_source('\\foo\\bar\\baz/qux.py', optimization=''),
468 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
469
470 @unittest.skipIf(sys.implementation.cache_tag is None,
471 'requires sys.implementation.cache_tag not be None')
472 def test_cache_from_source_path_like_arg(self):
473 path = pathlib.PurePath('foo', 'bar', 'baz', 'qux.py')
474 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
475 'qux.{}.pyc'.format(self.tag))
476 self.assertEqual(self.util.cache_from_source(path, optimization=''),
477 expect)
478
479 @unittest.skipIf(sys.implementation.cache_tag is None,
480 'requires sys.implementation.cache_tag to not be None')
481 def test_source_from_cache(self):
482 # Given the path to a PEP 3147 defined .pyc file, return the path to
483 # its source. This tests the good path.
484 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
485 'qux.{}.pyc'.format(self.tag))
486 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
487 self.assertEqual(self.util.source_from_cache(path), expect)
488
489 def test_source_from_cache_no_cache_tag(self):
490 # If sys.implementation.cache_tag is None, raise NotImplementedError.
491 path = os.path.join('blah', '__pycache__', 'whatever.pyc')
492 with support.swap_attr(sys.implementation, 'cache_tag', None):
493 with self.assertRaises(NotImplementedError):
494 self.util.source_from_cache(path)
495
496 def test_source_from_cache_bad_path(self):
497 # When the path to a pyc file is not in PEP 3147 format, a ValueError
498 # is raised.
499 self.assertRaises(
500 ValueError, self.util.source_from_cache, '/foo/bar/bazqux.pyc')
501
502 def test_source_from_cache_no_slash(self):
503 # No slashes at all in path -> ValueError
504 self.assertRaises(
505 ValueError, self.util.source_from_cache, 'foo.cpython-32.pyc')
506
507 def test_source_from_cache_too_few_dots(self):
508 # Too few dots in final path component -> ValueError
509 self.assertRaises(
510 ValueError, self.util.source_from_cache, '__pycache__/foo.pyc')
511
512 def test_source_from_cache_too_many_dots(self):
513 with self.assertRaises(ValueError):
514 self.util.source_from_cache(
515 '__pycache__/foo.cpython-32.opt-1.foo.pyc')
516
517 def test_source_from_cache_not_opt(self):
518 # Non-`opt-` path component -> ValueError
519 self.assertRaises(
520 ValueError, self.util.source_from_cache,
521 '__pycache__/foo.cpython-32.foo.pyc')
522
523 def test_source_from_cache_no__pycache__(self):
524 # Another problem with the path -> ValueError
525 self.assertRaises(
526 ValueError, self.util.source_from_cache,
527 '/foo/bar/foo.cpython-32.foo.pyc')
528
529 def test_source_from_cache_optimized_bytecode(self):
530 # Optimized bytecode is not an issue.
531 path = os.path.join('__pycache__', 'foo.{}.opt-1.pyc'.format(self.tag))
532 self.assertEqual(self.util.source_from_cache(path), 'foo.py')
533
534 def test_source_from_cache_missing_optimization(self):
535 # An empty optimization level is a no-no.
536 path = os.path.join('__pycache__', 'foo.{}.opt-.pyc'.format(self.tag))
537 with self.assertRaises(ValueError):
538 self.util.source_from_cache(path)
539
540 @unittest.skipIf(sys.implementation.cache_tag is None,
541 'requires sys.implementation.cache_tag to not be None')
542 def test_source_from_cache_path_like_arg(self):
543 path = pathlib.PurePath('foo', 'bar', 'baz', '__pycache__',
544 'qux.{}.pyc'.format(self.tag))
545 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
546 self.assertEqual(self.util.source_from_cache(path), expect)
547
548 @unittest.skipIf(sys.implementation.cache_tag is None,
549 'requires sys.implementation.cache_tag to not be None')
550 def test_cache_from_source_respects_pycache_prefix(self):
551 # If pycache_prefix is set, cache_from_source will return a bytecode
552 # path inside that directory (in a subdirectory mirroring the .py file's
553 # path) rather than in a __pycache__ dir next to the py file.
554 pycache_prefixes = [
555 os.path.join(os.path.sep, 'tmp', 'bytecode'),
556 os.path.join(os.path.sep, 'tmp', '\u2603'), # non-ASCII in path!
557 os.path.join(os.path.sep, 'tmp', 'trailing-slash') + os.path.sep,
558 ]
559 drive = ''
560 if os.name == 'nt':
561 drive = 'C:'
562 pycache_prefixes = [
563 f'{drive}{prefix}' for prefix in pycache_prefixes]
564 pycache_prefixes += [r'\\?\C:\foo', r'\\localhost\c$\bar']
565 for pycache_prefix in pycache_prefixes:
566 with self.subTest(path=pycache_prefix):
567 path = drive + os.path.join(
568 os.path.sep, 'foo', 'bar', 'baz', 'qux.py')
569 expect = os.path.join(
570 pycache_prefix, 'foo', 'bar', 'baz',
571 'qux.{}.pyc'.format(self.tag))
572 with util.temporary_pycache_prefix(pycache_prefix):
573 self.assertEqual(
574 self.util.cache_from_source(path, optimization=''),
575 expect)
576
577 @unittest.skipIf(sys.implementation.cache_tag is None,
578 'requires sys.implementation.cache_tag to not be None')
579 def test_cache_from_source_respects_pycache_prefix_relative(self):
580 # If the .py path we are given is relative, we will resolve to an
581 # absolute path before prefixing with pycache_prefix, to avoid any
582 # possible ambiguity.
583 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
584 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
585 root = os.path.splitdrive(os.getcwd())[0] + os.path.sep
586 expect = os.path.join(
587 pycache_prefix,
588 os.path.relpath(os.getcwd(), root),
589 'foo', 'bar', 'baz', f'qux.{self.tag}.pyc')
590 with util.temporary_pycache_prefix(pycache_prefix):
591 self.assertEqual(
592 self.util.cache_from_source(path, optimization=''),
593 os.path.normpath(expect))
594
595 @unittest.skipIf(sys.implementation.cache_tag is None,
596 'requires sys.implementation.cache_tag to not be None')
597 def test_cache_from_source_in_root_with_pycache_prefix(self):
598 # Regression test for gh-82916
599 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
600 path = 'qux.py'
601 expect = os.path.join(os.path.sep, 'tmp', 'bytecode',
602 f'qux.{self.tag}.pyc')
603 with util.temporary_pycache_prefix(pycache_prefix):
604 with os_helper.change_cwd('/'):
605 self.assertEqual(self.util.cache_from_source(path), expect)
606
607 @unittest.skipIf(sys.implementation.cache_tag is None,
608 'requires sys.implementation.cache_tag to not be None')
609 def test_source_from_cache_inside_pycache_prefix(self):
610 # If pycache_prefix is set and the cache path we get is inside it,
611 # we return an absolute path to the py file based on the remainder of
612 # the path within pycache_prefix.
613 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
614 path = os.path.join(pycache_prefix, 'foo', 'bar', 'baz',
615 f'qux.{self.tag}.pyc')
616 expect = os.path.join(os.path.sep, 'foo', 'bar', 'baz', 'qux.py')
617 with util.temporary_pycache_prefix(pycache_prefix):
618 self.assertEqual(self.util.source_from_cache(path), expect)
619
620 @unittest.skipIf(sys.implementation.cache_tag is None,
621 'requires sys.implementation.cache_tag to not be None')
622 def test_source_from_cache_outside_pycache_prefix(self):
623 # If pycache_prefix is set but the cache path we get is not inside
624 # it, just ignore it and handle the cache path according to the default
625 # behavior.
626 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
627 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
628 f'qux.{self.tag}.pyc')
629 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
630 with util.temporary_pycache_prefix(pycache_prefix):
631 self.assertEqual(self.util.source_from_cache(path), expect)
632
633
634 (Frozen_PEP3147Tests,
635 Source_PEP3147Tests
636 ) = util.test_both(PEP3147Tests, util=importlib_util)
637
638
639 class MagicNumberTests(unittest.TestCase):
640 """
641 Test release compatibility issues relating to importlib
642 """
643 @unittest.skipUnless(
644 sys.version_info.releaselevel in ('candidate', 'final'),
645 'only applies to candidate or final python release levels'
646 )
647 def test_magic_number(self):
648 # Each python minor release should generally have a MAGIC_NUMBER
649 # that does not change once the release reaches candidate status.
650
651 # Once a release reaches candidate status, the value of the constant
652 # EXPECTED_MAGIC_NUMBER in this test should be changed.
653 # This test will then check that the actual MAGIC_NUMBER matches
654 # the expected value for the release.
655
656 # In exceptional cases, it may be required to change the MAGIC_NUMBER
657 # for a maintenance release. In this case the change should be
658 # discussed in python-dev. If a change is required, community
659 # stakeholders such as OS package maintainers must be notified
660 # in advance. Such exceptional releases will then require an
661 # adjustment to this test case.
662 EXPECTED_MAGIC_NUMBER = 3571
663 actual = int.from_bytes(importlib.util.MAGIC_NUMBER[:2], 'little')
664
665 msg = (
666 "To avoid breaking backwards compatibility with cached bytecode "
667 "files that can't be automatically regenerated by the current "
668 "user, candidate and final releases require the current "
669 "importlib.util.MAGIC_NUMBER to match the expected "
670 "magic number in this test. Set the expected "
671 "magic number in this test to the current MAGIC_NUMBER to "
672 "continue with the release.\n\n"
673 "Changing the MAGIC_NUMBER for a maintenance release "
674 "requires discussion in python-dev and notification of "
675 "community stakeholders."
676 )
677 self.assertEqual(EXPECTED_MAGIC_NUMBER, actual, msg)
678
679
680 @unittest.skipIf(_interpreters is None, 'subinterpreters required')
681 class IncompatibleExtensionModuleRestrictionsTests(unittest.TestCase):
682
683 def run_with_own_gil(self, script):
684 interpid = _interpreters.create('isolated')
685 def ensure_destroyed():
686 try:
687 _interpreters.destroy(interpid)
688 except _interpreters.InterpreterNotFoundError:
689 pass
690 self.addCleanup(ensure_destroyed)
691 excsnap = _interpreters.exec(interpid, script)
692 if excsnap is not None:
693 if excsnap.type.__name__ == 'ImportError':
694 raise ImportError(excsnap.msg)
695
696 def run_with_shared_gil(self, script):
697 interpid = _interpreters.create('legacy')
698 def ensure_destroyed():
699 try:
700 _interpreters.destroy(interpid)
701 except _interpreters.InterpreterNotFoundError:
702 pass
703 self.addCleanup(ensure_destroyed)
704 excsnap = _interpreters.exec(interpid, script)
705 if excsnap is not None:
706 if excsnap.type.__name__ == 'ImportError':
707 raise ImportError(excsnap.msg)
708
709 @unittest.skipIf(_testsinglephase is None, "test requires _testsinglephase module")
710 # gh-117649: single-phase init modules are not currently supported in
711 # subinterpreters in the free-threaded build
712 @support.expected_failure_if_gil_disabled()
713 def test_single_phase_init_module(self):
714 script = textwrap.dedent('''
715 from importlib.util import _incompatible_extension_module_restrictions
716 with _incompatible_extension_module_restrictions(disable_check=True):
717 import _testsinglephase
718 ''')
719 with self.subTest('check disabled, shared GIL'):
720 self.run_with_shared_gil(script)
721 with self.subTest('check disabled, per-interpreter GIL'):
722 self.run_with_own_gil(script)
723
724 script = textwrap.dedent(f'''
725 from importlib.util import _incompatible_extension_module_restrictions
726 with _incompatible_extension_module_restrictions(disable_check=False):
727 import _testsinglephase
728 ''')
729 with self.subTest('check enabled, shared GIL'):
730 with self.assertRaises(ImportError):
731 self.run_with_shared_gil(script)
732 with self.subTest('check enabled, per-interpreter GIL'):
733 with self.assertRaises(ImportError):
734 self.run_with_own_gil(script)
735
736 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
737 @support.requires_gil_enabled("gh-117649: not supported in free-threaded build")
738 def test_incomplete_multi_phase_init_module(self):
739 # Apple extensions must be distributed as frameworks. This requires
740 # a specialist loader.
741 if support.is_apple_mobile:
742 loader = "AppleFrameworkLoader"
743 else:
744 loader = "ExtensionFileLoader"
745
746 prescript = textwrap.dedent(f'''
747 from importlib.util import spec_from_loader, module_from_spec
748 from importlib.machinery import {loader}
749
750 name = '_test_shared_gil_only'
751 filename = {_testmultiphase.__file__!r}
752 loader = {loader}(name, filename)
753 spec = spec_from_loader(name, loader)
754
755 ''')
756
757 script = prescript + textwrap.dedent('''
758 from importlib.util import _incompatible_extension_module_restrictions
759 with _incompatible_extension_module_restrictions(disable_check=True):
760 module = module_from_spec(spec)
761 loader.exec_module(module)
762 ''')
763 with self.subTest('check disabled, shared GIL'):
764 self.run_with_shared_gil(script)
765 with self.subTest('check disabled, per-interpreter GIL'):
766 self.run_with_own_gil(script)
767
768 script = prescript + textwrap.dedent('''
769 from importlib.util import _incompatible_extension_module_restrictions
770 with _incompatible_extension_module_restrictions(disable_check=False):
771 module = module_from_spec(spec)
772 loader.exec_module(module)
773 ''')
774 with self.subTest('check enabled, shared GIL'):
775 self.run_with_shared_gil(script)
776 with self.subTest('check enabled, per-interpreter GIL'):
777 with self.assertRaises(ImportError):
778 self.run_with_own_gil(script)
779
780 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
781 def test_complete_multi_phase_init_module(self):
782 script = textwrap.dedent('''
783 from importlib.util import _incompatible_extension_module_restrictions
784 with _incompatible_extension_module_restrictions(disable_check=True):
785 import _testmultiphase
786 ''')
787 with self.subTest('check disabled, shared GIL'):
788 self.run_with_shared_gil(script)
789 with self.subTest('check disabled, per-interpreter GIL'):
790 self.run_with_own_gil(script)
791
792 script = textwrap.dedent(f'''
793 from importlib.util import _incompatible_extension_module_restrictions
794 with _incompatible_extension_module_restrictions(disable_check=False):
795 import _testmultiphase
796 ''')
797 with self.subTest('check enabled, shared GIL'):
798 self.run_with_shared_gil(script)
799 with self.subTest('check enabled, per-interpreter GIL'):
800 self.run_with_own_gil(script)
801
802
803 class PatchAtomicWrites:
804 def __init__(self, truncate_at_length, never_complete=False):
805 self.truncate_at_length = truncate_at_length
806 self.never_complete = never_complete
807 self.seen_write = False
808 self._children = []
809
810 def __enter__(self):
811 import _pyio
812
813 oldwrite = os.write
814
815 # Emulate an os.write that only writes partial data.
816 def write(fd, data):
817 if self.seen_write and self.never_complete:
818 return None
819 self.seen_write = True
820 return oldwrite(fd, data[:self.truncate_at_length])
821
822 # Need to patch _io to be _pyio, so that io.FileIO is affected by the
823 # os.write patch.
824 self.children = [
825 support.swap_attr(_bootstrap_external, '_io', _pyio),
826 support.swap_attr(os, 'write', write)
827 ]
828 for child in self.children:
829 child.__enter__()
830 return self
831
832 def __exit__(self, exc_type, exc_val, exc_tb):
833 for child in self.children:
834 child.__exit__(exc_type, exc_val, exc_tb)
835
836
837 class MiscTests(unittest.TestCase):
838
839 def test_atomic_write_retries_incomplete_writes(self):
840 truncate_at_length = 100
841 length = truncate_at_length * 2
842
843 with PatchAtomicWrites(truncate_at_length=truncate_at_length) as cm:
844 # Make sure we write something longer than the point where we
845 # truncate.
846 content = b'x' * length
847 _bootstrap_external._write_atomic(os_helper.TESTFN, content)
848 self.assertTrue(cm.seen_write)
849
850 self.assertEqual(os.stat(support.os_helper.TESTFN).st_size, length)
851 os.unlink(support.os_helper.TESTFN)
852
853 def test_atomic_write_errors_if_unable_to_complete(self):
854 truncate_at_length = 100
855
856 with (
857 PatchAtomicWrites(
858 truncate_at_length=truncate_at_length, never_complete=True,
859 ) as cm,
860 self.assertRaises(OSError)
861 ):
862 # Make sure we write something longer than the point where we
863 # truncate.
864 content = b'x' * (truncate_at_length * 2)
865 _bootstrap_external._write_atomic(os_helper.TESTFN, content)
866 self.assertTrue(cm.seen_write)
867
868 with self.assertRaises(OSError):
869 os.stat(support.os_helper.TESTFN) # Check that the file did not get written.
870
871
872 if __name__ == '__main__':
873 unittest.main()