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 @unittest.skipIf(sys.implementation.cache_tag is None,
339 'requires sys.implementation.cache_tag not be None')
340 def test_cache_from_source(self):
341 # Given the path to a .py file, return the path to its PEP 3147
342 # defined .pyc file (i.e. under __pycache__).
343 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
344 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
345 'qux.{}.pyc'.format(self.tag))
346 self.assertEqual(self.util.cache_from_source(path, optimization=''),
347 expect)
348
349 def test_cache_from_source_no_cache_tag(self):
350 # No cache tag means NotImplementedError.
351 with support.swap_attr(sys.implementation, 'cache_tag', None):
352 with self.assertRaises(NotImplementedError):
353 self.util.cache_from_source('whatever.py')
354
355 def test_cache_from_source_no_dot(self):
356 # Directory with a dot, filename without dot.
357 path = os.path.join('foo.bar', 'file')
358 expect = os.path.join('foo.bar', '__pycache__',
359 'file{}.pyc'.format(self.tag))
360 self.assertEqual(self.util.cache_from_source(path, optimization=''),
361 expect)
362
363 def test_cache_from_source_debug_override(self):
364 # Given the path to a .py file, return the path to its PEP 3147/PEP 488
365 # defined .pyc file (i.e. under __pycache__).
366 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
367 with warnings.catch_warnings():
368 warnings.simplefilter('ignore')
369 self.assertEqual(self.util.cache_from_source(path, False),
370 self.util.cache_from_source(path, optimization=1))
371 self.assertEqual(self.util.cache_from_source(path, True),
372 self.util.cache_from_source(path, optimization=''))
373 with warnings.catch_warnings():
374 warnings.simplefilter('error')
375 with self.assertRaises(DeprecationWarning):
376 self.util.cache_from_source(path, False)
377 with self.assertRaises(DeprecationWarning):
378 self.util.cache_from_source(path, True)
379
380 def test_cache_from_source_cwd(self):
381 path = 'foo.py'
382 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
383 self.assertEqual(self.util.cache_from_source(path, optimization=''),
384 expect)
385
386 def test_cache_from_source_override(self):
387 # When debug_override is not None, it can be any true-ish or false-ish
388 # value.
389 path = os.path.join('foo', 'bar', 'baz.py')
390 # However if the bool-ishness can't be determined, the exception
391 # propagates.
392 class Bearish:
393 def __bool__(self): raise RuntimeError
394 with warnings.catch_warnings():
395 warnings.simplefilter('ignore')
396 self.assertEqual(self.util.cache_from_source(path, []),
397 self.util.cache_from_source(path, optimization=1))
398 self.assertEqual(self.util.cache_from_source(path, [17]),
399 self.util.cache_from_source(path, optimization=''))
400 with self.assertRaises(RuntimeError):
401 self.util.cache_from_source('/foo/bar/baz.py', Bearish())
402
403
404 def test_cache_from_source_optimization_empty_string(self):
405 # Setting 'optimization' to '' leads to no optimization tag (PEP 488).
406 path = 'foo.py'
407 expect = os.path.join('__pycache__', 'foo.{}.pyc'.format(self.tag))
408 self.assertEqual(self.util.cache_from_source(path, optimization=''),
409 expect)
410
411 def test_cache_from_source_optimization_None(self):
412 # Setting 'optimization' to None uses the interpreter's optimization.
413 # (PEP 488)
414 path = 'foo.py'
415 optimization_level = sys.flags.optimize
416 almost_expect = os.path.join('__pycache__', 'foo.{}'.format(self.tag))
417 if optimization_level == 0:
418 expect = almost_expect + '.pyc'
419 elif optimization_level <= 2:
420 expect = almost_expect + '.opt-{}.pyc'.format(optimization_level)
421 else:
422 msg = '{!r} is a non-standard optimization level'.format(optimization_level)
423 self.skipTest(msg)
424 self.assertEqual(self.util.cache_from_source(path, optimization=None),
425 expect)
426
427 def test_cache_from_source_optimization_set(self):
428 # The 'optimization' parameter accepts anything that has a string repr
429 # that passes str.alnum().
430 path = 'foo.py'
431 valid_characters = string.ascii_letters + string.digits
432 almost_expect = os.path.join('__pycache__', 'foo.{}'.format(self.tag))
433 got = self.util.cache_from_source(path, optimization=valid_characters)
434 # Test all valid characters are accepted.
435 self.assertEqual(got,
436 almost_expect + '.opt-{}.pyc'.format(valid_characters))
437 # str() should be called on argument.
438 self.assertEqual(self.util.cache_from_source(path, optimization=42),
439 almost_expect + '.opt-42.pyc')
440 # Invalid characters raise ValueError.
441 with self.assertRaises(ValueError):
442 self.util.cache_from_source(path, optimization='path/is/bad')
443
444 def test_cache_from_source_debug_override_optimization_both_set(self):
445 # Can only set one of the optimization-related parameters.
446 with warnings.catch_warnings():
447 warnings.simplefilter('ignore')
448 with self.assertRaises(TypeError):
449 self.util.cache_from_source('foo.py', False, optimization='')
450
451 @unittest.skipUnless(os.sep == '\\' and os.altsep == '/',
452 'test meaningful only where os.altsep is defined')
453 def test_sep_altsep_and_sep_cache_from_source(self):
454 # Windows path and PEP 3147 where sep is right of altsep.
455 self.assertEqual(
456 self.util.cache_from_source('\\foo\\bar\\baz/qux.py', optimization=''),
457 '\\foo\\bar\\baz\\__pycache__\\qux.{}.pyc'.format(self.tag))
458
459 @unittest.skipIf(sys.implementation.cache_tag is None,
460 'requires sys.implementation.cache_tag not be None')
461 def test_cache_from_source_path_like_arg(self):
462 path = pathlib.PurePath('foo', 'bar', 'baz', 'qux.py')
463 expect = os.path.join('foo', 'bar', 'baz', '__pycache__',
464 'qux.{}.pyc'.format(self.tag))
465 self.assertEqual(self.util.cache_from_source(path, optimization=''),
466 expect)
467
468 @unittest.skipIf(sys.implementation.cache_tag is None,
469 'requires sys.implementation.cache_tag to not be None')
470 def test_source_from_cache(self):
471 # Given the path to a PEP 3147 defined .pyc file, return the path to
472 # its source. This tests the good path.
473 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
474 'qux.{}.pyc'.format(self.tag))
475 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
476 self.assertEqual(self.util.source_from_cache(path), expect)
477
478 def test_source_from_cache_no_cache_tag(self):
479 # If sys.implementation.cache_tag is None, raise NotImplementedError.
480 path = os.path.join('blah', '__pycache__', 'whatever.pyc')
481 with support.swap_attr(sys.implementation, 'cache_tag', None):
482 with self.assertRaises(NotImplementedError):
483 self.util.source_from_cache(path)
484
485 def test_source_from_cache_bad_path(self):
486 # When the path to a pyc file is not in PEP 3147 format, a ValueError
487 # is raised.
488 self.assertRaises(
489 ValueError, self.util.source_from_cache, '/foo/bar/bazqux.pyc')
490
491 def test_source_from_cache_no_slash(self):
492 # No slashes at all in path -> ValueError
493 self.assertRaises(
494 ValueError, self.util.source_from_cache, 'foo.cpython-32.pyc')
495
496 def test_source_from_cache_too_few_dots(self):
497 # Too few dots in final path component -> ValueError
498 self.assertRaises(
499 ValueError, self.util.source_from_cache, '__pycache__/foo.pyc')
500
501 def test_source_from_cache_too_many_dots(self):
502 with self.assertRaises(ValueError):
503 self.util.source_from_cache(
504 '__pycache__/foo.cpython-32.opt-1.foo.pyc')
505
506 def test_source_from_cache_not_opt(self):
507 # Non-`opt-` path component -> ValueError
508 self.assertRaises(
509 ValueError, self.util.source_from_cache,
510 '__pycache__/foo.cpython-32.foo.pyc')
511
512 def test_source_from_cache_no__pycache__(self):
513 # Another problem with the path -> ValueError
514 self.assertRaises(
515 ValueError, self.util.source_from_cache,
516 '/foo/bar/foo.cpython-32.foo.pyc')
517
518 def test_source_from_cache_optimized_bytecode(self):
519 # Optimized bytecode is not an issue.
520 path = os.path.join('__pycache__', 'foo.{}.opt-1.pyc'.format(self.tag))
521 self.assertEqual(self.util.source_from_cache(path), 'foo.py')
522
523 def test_source_from_cache_missing_optimization(self):
524 # An empty optimization level is a no-no.
525 path = os.path.join('__pycache__', 'foo.{}.opt-.pyc'.format(self.tag))
526 with self.assertRaises(ValueError):
527 self.util.source_from_cache(path)
528
529 @unittest.skipIf(sys.implementation.cache_tag is None,
530 'requires sys.implementation.cache_tag to not be None')
531 def test_source_from_cache_path_like_arg(self):
532 path = pathlib.PurePath('foo', 'bar', 'baz', '__pycache__',
533 'qux.{}.pyc'.format(self.tag))
534 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
535 self.assertEqual(self.util.source_from_cache(path), expect)
536
537 @unittest.skipIf(sys.implementation.cache_tag is None,
538 'requires sys.implementation.cache_tag to not be None')
539 def test_cache_from_source_respects_pycache_prefix(self):
540 # If pycache_prefix is set, cache_from_source will return a bytecode
541 # path inside that directory (in a subdirectory mirroring the .py file's
542 # path) rather than in a __pycache__ dir next to the py file.
543 pycache_prefixes = [
544 os.path.join(os.path.sep, 'tmp', 'bytecode'),
545 os.path.join(os.path.sep, 'tmp', '\u2603'), # non-ASCII in path!
546 os.path.join(os.path.sep, 'tmp', 'trailing-slash') + os.path.sep,
547 ]
548 drive = ''
549 if os.name == 'nt':
550 drive = 'C:'
551 pycache_prefixes = [
552 f'{drive}{prefix}' for prefix in pycache_prefixes]
553 pycache_prefixes += [r'\\?\C:\foo', r'\\localhost\c$\bar']
554 for pycache_prefix in pycache_prefixes:
555 with self.subTest(path=pycache_prefix):
556 path = drive + os.path.join(
557 os.path.sep, 'foo', 'bar', 'baz', 'qux.py')
558 expect = os.path.join(
559 pycache_prefix, 'foo', 'bar', 'baz',
560 'qux.{}.pyc'.format(self.tag))
561 with util.temporary_pycache_prefix(pycache_prefix):
562 self.assertEqual(
563 self.util.cache_from_source(path, optimization=''),
564 expect)
565
566 @unittest.skipIf(sys.implementation.cache_tag is None,
567 'requires sys.implementation.cache_tag to not be None')
568 def test_cache_from_source_respects_pycache_prefix_relative(self):
569 # If the .py path we are given is relative, we will resolve to an
570 # absolute path before prefixing with pycache_prefix, to avoid any
571 # possible ambiguity.
572 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
573 path = os.path.join('foo', 'bar', 'baz', 'qux.py')
574 root = os.path.splitdrive(os.getcwd())[0] + os.path.sep
575 expect = os.path.join(
576 pycache_prefix,
577 os.path.relpath(os.getcwd(), root),
578 'foo', 'bar', 'baz', f'qux.{self.tag}.pyc')
579 with util.temporary_pycache_prefix(pycache_prefix):
580 self.assertEqual(
581 self.util.cache_from_source(path, optimization=''),
582 os.path.normpath(expect))
583
584 @unittest.skipIf(sys.implementation.cache_tag is None,
585 'requires sys.implementation.cache_tag to not be None')
586 def test_cache_from_source_in_root_with_pycache_prefix(self):
587 # Regression test for gh-82916
588 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
589 path = 'qux.py'
590 expect = os.path.join(os.path.sep, 'tmp', 'bytecode',
591 f'qux.{self.tag}.pyc')
592 with util.temporary_pycache_prefix(pycache_prefix):
593 with os_helper.change_cwd('/'):
594 self.assertEqual(self.util.cache_from_source(path), expect)
595
596 @unittest.skipIf(sys.implementation.cache_tag is None,
597 'requires sys.implementation.cache_tag to not be None')
598 def test_source_from_cache_inside_pycache_prefix(self):
599 # If pycache_prefix is set and the cache path we get is inside it,
600 # we return an absolute path to the py file based on the remainder of
601 # the path within pycache_prefix.
602 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
603 path = os.path.join(pycache_prefix, 'foo', 'bar', 'baz',
604 f'qux.{self.tag}.pyc')
605 expect = os.path.join(os.path.sep, 'foo', 'bar', 'baz', 'qux.py')
606 with util.temporary_pycache_prefix(pycache_prefix):
607 self.assertEqual(self.util.source_from_cache(path), expect)
608
609 @unittest.skipIf(sys.implementation.cache_tag is None,
610 'requires sys.implementation.cache_tag to not be None')
611 def test_source_from_cache_outside_pycache_prefix(self):
612 # If pycache_prefix is set but the cache path we get is not inside
613 # it, just ignore it and handle the cache path according to the default
614 # behavior.
615 pycache_prefix = os.path.join(os.path.sep, 'tmp', 'bytecode')
616 path = os.path.join('foo', 'bar', 'baz', '__pycache__',
617 f'qux.{self.tag}.pyc')
618 expect = os.path.join('foo', 'bar', 'baz', 'qux.py')
619 with util.temporary_pycache_prefix(pycache_prefix):
620 self.assertEqual(self.util.source_from_cache(path), expect)
621
622
623 (Frozen_PEP3147Tests,
624 Source_PEP3147Tests
625 ) = util.test_both(PEP3147Tests, util=importlib_util)
626
627
628 class MagicNumberTests(unittest.TestCase):
629 """
630 Test release compatibility issues relating to importlib
631 """
632 @unittest.skipUnless(
633 sys.version_info.releaselevel in ('candidate', 'final'),
634 'only applies to candidate or final python release levels'
635 )
636 def test_magic_number(self):
637 # Each python minor release should generally have a MAGIC_NUMBER
638 # that does not change once the release reaches candidate status.
639
640 # Once a release reaches candidate status, the value of the constant
641 # EXPECTED_MAGIC_NUMBER in this test should be changed.
642 # This test will then check that the actual MAGIC_NUMBER matches
643 # the expected value for the release.
644
645 # In exceptional cases, it may be required to change the MAGIC_NUMBER
646 # for a maintenance release. In this case the change should be
647 # discussed in python-dev. If a change is required, community
648 # stakeholders such as OS package maintainers must be notified
649 # in advance. Such exceptional releases will then require an
650 # adjustment to this test case.
651 EXPECTED_MAGIC_NUMBER = 3571
652 actual = int.from_bytes(importlib.util.MAGIC_NUMBER[:2], 'little')
653
654 msg = (
655 "To avoid breaking backwards compatibility with cached bytecode "
656 "files that can't be automatically regenerated by the current "
657 "user, candidate and final releases require the current "
658 "importlib.util.MAGIC_NUMBER to match the expected "
659 "magic number in this test. Set the expected "
660 "magic number in this test to the current MAGIC_NUMBER to "
661 "continue with the release.\n\n"
662 "Changing the MAGIC_NUMBER for a maintenance release "
663 "requires discussion in python-dev and notification of "
664 "community stakeholders."
665 )
666 self.assertEqual(EXPECTED_MAGIC_NUMBER, actual, msg)
667
668
669 @unittest.skipIf(_interpreters is None, 'subinterpreters required')
670 class IncompatibleExtensionModuleRestrictionsTests(unittest.TestCase):
671
672 def run_with_own_gil(self, script):
673 interpid = _interpreters.create('isolated')
674 def ensure_destroyed():
675 try:
676 _interpreters.destroy(interpid)
677 except _interpreters.InterpreterNotFoundError:
678 pass
679 self.addCleanup(ensure_destroyed)
680 excsnap = _interpreters.exec(interpid, script)
681 if excsnap is not None:
682 if excsnap.type.__name__ == 'ImportError':
683 raise ImportError(excsnap.msg)
684
685 def run_with_shared_gil(self, script):
686 interpid = _interpreters.create('legacy')
687 def ensure_destroyed():
688 try:
689 _interpreters.destroy(interpid)
690 except _interpreters.InterpreterNotFoundError:
691 pass
692 self.addCleanup(ensure_destroyed)
693 excsnap = _interpreters.exec(interpid, script)
694 if excsnap is not None:
695 if excsnap.type.__name__ == 'ImportError':
696 raise ImportError(excsnap.msg)
697
698 @unittest.skipIf(_testsinglephase is None, "test requires _testsinglephase module")
699 # gh-117649: single-phase init modules are not currently supported in
700 # subinterpreters in the free-threaded build
701 @support.expected_failure_if_gil_disabled()
702 def test_single_phase_init_module(self):
703 script = textwrap.dedent('''
704 from importlib.util import _incompatible_extension_module_restrictions
705 with _incompatible_extension_module_restrictions(disable_check=True):
706 import _testsinglephase
707 ''')
708 with self.subTest('check disabled, shared GIL'):
709 self.run_with_shared_gil(script)
710 with self.subTest('check disabled, per-interpreter GIL'):
711 self.run_with_own_gil(script)
712
713 script = textwrap.dedent(f'''
714 from importlib.util import _incompatible_extension_module_restrictions
715 with _incompatible_extension_module_restrictions(disable_check=False):
716 import _testsinglephase
717 ''')
718 with self.subTest('check enabled, shared GIL'):
719 with self.assertRaises(ImportError):
720 self.run_with_shared_gil(script)
721 with self.subTest('check enabled, per-interpreter GIL'):
722 with self.assertRaises(ImportError):
723 self.run_with_own_gil(script)
724
725 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
726 @support.requires_gil_enabled("gh-117649: not supported in free-threaded build")
727 def test_incomplete_multi_phase_init_module(self):
728 # Apple extensions must be distributed as frameworks. This requires
729 # a specialist loader.
730 if support.is_apple_mobile:
731 loader = "AppleFrameworkLoader"
732 else:
733 loader = "ExtensionFileLoader"
734
735 prescript = textwrap.dedent(f'''
736 from importlib.util import spec_from_loader, module_from_spec
737 from importlib.machinery import {loader}
738
739 name = '_test_shared_gil_only'
740 filename = {_testmultiphase.__file__!r}
741 loader = {loader}(name, filename)
742 spec = spec_from_loader(name, loader)
743
744 ''')
745
746 script = prescript + textwrap.dedent('''
747 from importlib.util import _incompatible_extension_module_restrictions
748 with _incompatible_extension_module_restrictions(disable_check=True):
749 module = module_from_spec(spec)
750 loader.exec_module(module)
751 ''')
752 with self.subTest('check disabled, shared GIL'):
753 self.run_with_shared_gil(script)
754 with self.subTest('check disabled, per-interpreter GIL'):
755 self.run_with_own_gil(script)
756
757 script = prescript + textwrap.dedent('''
758 from importlib.util import _incompatible_extension_module_restrictions
759 with _incompatible_extension_module_restrictions(disable_check=False):
760 module = module_from_spec(spec)
761 loader.exec_module(module)
762 ''')
763 with self.subTest('check enabled, shared GIL'):
764 self.run_with_shared_gil(script)
765 with self.subTest('check enabled, per-interpreter GIL'):
766 with self.assertRaises(ImportError):
767 self.run_with_own_gil(script)
768
769 @unittest.skipIf(_testmultiphase is None, "test requires _testmultiphase module")
770 def test_complete_multi_phase_init_module(self):
771 script = textwrap.dedent('''
772 from importlib.util import _incompatible_extension_module_restrictions
773 with _incompatible_extension_module_restrictions(disable_check=True):
774 import _testmultiphase
775 ''')
776 with self.subTest('check disabled, shared GIL'):
777 self.run_with_shared_gil(script)
778 with self.subTest('check disabled, per-interpreter GIL'):
779 self.run_with_own_gil(script)
780
781 script = textwrap.dedent(f'''
782 from importlib.util import _incompatible_extension_module_restrictions
783 with _incompatible_extension_module_restrictions(disable_check=False):
784 import _testmultiphase
785 ''')
786 with self.subTest('check enabled, shared GIL'):
787 self.run_with_shared_gil(script)
788 with self.subTest('check enabled, per-interpreter GIL'):
789 self.run_with_own_gil(script)
790
791
792 class PatchAtomicWrites:
793 def __init__(self, truncate_at_length, never_complete=False):
794 self.truncate_at_length = truncate_at_length
795 self.never_complete = never_complete
796 self.seen_write = False
797 self._children = []
798
799 def __enter__(self):
800 import _pyio
801
802 oldwrite = os.write
803
804 # Emulate an os.write that only writes partial data.
805 def write(fd, data):
806 if self.seen_write and self.never_complete:
807 return None
808 self.seen_write = True
809 return oldwrite(fd, data[:self.truncate_at_length])
810
811 # Need to patch _io to be _pyio, so that io.FileIO is affected by the
812 # os.write patch.
813 self.children = [
814 support.swap_attr(_bootstrap_external, '_io', _pyio),
815 support.swap_attr(os, 'write', write)
816 ]
817 for child in self.children:
818 child.__enter__()
819 return self
820
821 def __exit__(self, exc_type, exc_val, exc_tb):
822 for child in self.children:
823 child.__exit__(exc_type, exc_val, exc_tb)
824
825
826 class MiscTests(unittest.TestCase):
827
828 def test_atomic_write_retries_incomplete_writes(self):
829 truncate_at_length = 100
830 length = truncate_at_length * 2
831
832 with PatchAtomicWrites(truncate_at_length=truncate_at_length) as cm:
833 # Make sure we write something longer than the point where we
834 # truncate.
835 content = b'x' * length
836 _bootstrap_external._write_atomic(os_helper.TESTFN, content)
837 self.assertTrue(cm.seen_write)
838
839 self.assertEqual(os.stat(support.os_helper.TESTFN).st_size, length)
840 os.unlink(support.os_helper.TESTFN)
841
842 def test_atomic_write_errors_if_unable_to_complete(self):
843 truncate_at_length = 100
844
845 with (
846 PatchAtomicWrites(
847 truncate_at_length=truncate_at_length, never_complete=True,
848 ) as cm,
849 self.assertRaises(OSError)
850 ):
851 # Make sure we write something longer than the point where we
852 # truncate.
853 content = b'x' * (truncate_at_length * 2)
854 _bootstrap_external._write_atomic(os_helper.TESTFN, content)
855 self.assertTrue(cm.seen_write)
856
857 with self.assertRaises(OSError):
858 os.stat(support.os_helper.TESTFN) # Check that the file did not get written.
859
860
861 if __name__ == '__main__':
862 unittest.main()