Debian Codegraph @

lib-python/3/test/test_importlib/test_util.py

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