Debian Codegraph @

Lib/test/test_importlib/util.py

raw
1 import builtins
2 import contextlib
3 import errno
4 import functools
5 from importlib import machinery, util, invalidate_caches
6 import marshal
7 import os
8 import os.path
9 from test import support
10 from test.support import import_helper
11 from test.support import is_apple_mobile
12 from test.support import os_helper
13 from test.support.testcase import ExtraAssertions
14 import unittest
15 import sys
16 import tempfile
17 import types
18
19 import_helper.import_module("_testmultiphase")
20
21
22 BUILTINS = types.SimpleNamespace()
23 BUILTINS.good_name = None
24 BUILTINS.bad_name = None
25 if 'errno' in sys.builtin_module_names:
26 BUILTINS.good_name = 'errno'
27 if 'importlib' not in sys.builtin_module_names:
28 BUILTINS.bad_name = 'importlib'
29
30 if support.is_wasi:
31 # dlopen() is a shim for WASI as of WASI SDK which fails by default.
32 # We don't provide an implementation, so tests will fail.
33 # But we also don't want to turn off dynamic loading for those that provide
34 # a working implementation.
35 def _extension_details():
36 global EXTENSIONS
37 EXTENSIONS = None
38 else:
39 EXTENSIONS = types.SimpleNamespace()
40 EXTENSIONS.path = None
41 EXTENSIONS.ext = None
42 EXTENSIONS.filename = None
43 EXTENSIONS.file_path = None
44 EXTENSIONS.name = '_testsinglephase'
45
46 def _extension_details():
47 global EXTENSIONS
48 for path in sys.path:
49 for ext in machinery.EXTENSION_SUFFIXES:
50 # Apple mobile platforms mechanically load .so files,
51 # but the findable files are labelled .fwork
52 if is_apple_mobile:
53 ext = ext.replace(".so", ".fwork")
54
55 filename = EXTENSIONS.name + ext
56 file_path = os.path.join(path, filename)
57 if os.path.exists(file_path):
58 EXTENSIONS.path = path
59 EXTENSIONS.ext = ext
60 EXTENSIONS.filename = filename
61 EXTENSIONS.file_path = file_path
62 return
63
64 _extension_details()
65
66
67 def import_importlib(module_name):
68 """Import a module from importlib both w/ and w/o _frozen_importlib."""
69 fresh = ('importlib',) if '.' in module_name else ()
70 frozen = import_helper.import_fresh_module(module_name)
71 source = import_helper.import_fresh_module(module_name, fresh=fresh,
72 blocked=('_frozen_importlib', '_frozen_importlib_external'))
73 return {'Frozen': frozen, 'Source': source}
74
75
76 def specialize_class(cls, kind, base=None, **kwargs):
77 # XXX Support passing in submodule names--load (and cache) them?
78 # That would clean up the test modules a bit more.
79 if base is None:
80 base = unittest.TestCase
81 elif not isinstance(base, type):
82 base = base[kind]
83 name = '{}_{}'.format(kind, cls.__name__)
84 bases = (cls, base, ExtraAssertions)
85 specialized = types.new_class(name, bases)
86 specialized.__module__ = cls.__module__
87 specialized._NAME = cls.__name__
88 specialized._KIND = kind
89 for attr, values in kwargs.items():
90 value = values[kind]
91 setattr(specialized, attr, value)
92 return specialized
93
94
95 def split_frozen(cls, base=None, **kwargs):
96 frozen = specialize_class(cls, 'Frozen', base, **kwargs)
97 source = specialize_class(cls, 'Source', base, **kwargs)
98 return frozen, source
99
100
101 def test_both(test_class, base=None, **kwargs):
102 return split_frozen(test_class, base, **kwargs)
103
104
105 CASE_INSENSITIVE_FS = True
106 # Windows is the only OS that is *always* case-insensitive
107 # (OS X *can* be case-sensitive).
108 if sys.platform not in ('win32', 'cygwin'):
109 changed_name = __file__.upper()
110 if changed_name == __file__:
111 changed_name = __file__.lower()
112 if not os.path.exists(changed_name):
113 CASE_INSENSITIVE_FS = False
114
115 source_importlib = import_importlib('importlib')['Source']
116 __import__ = {'Frozen': staticmethod(builtins.__import__),
117 'Source': staticmethod(source_importlib.__import__)}
118
119
120 def case_insensitive_tests(test):
121 """Class decorator that nullifies tests requiring a case-insensitive
122 file system."""
123 return unittest.skipIf(not CASE_INSENSITIVE_FS,
124 "requires a case-insensitive filesystem")(test)
125
126
127 def submodule(parent, name, pkg_dir, content=''):
128 path = os.path.join(pkg_dir, name + '.py')
129 with open(path, 'w', encoding='utf-8') as subfile:
130 subfile.write(content)
131 return '{}.{}'.format(parent, name), path
132
133
134 def get_code_from_pyc(pyc_path):
135 """Reads a pyc file and returns the unmarshalled code object within.
136
137 No header validation is performed.
138 """
139 with open(pyc_path, 'rb') as pyc_f:
140 pyc_f.seek(16)
141 return marshal.load(pyc_f)
142
143
144 @contextlib.contextmanager
145 def uncache(*names):
146 """Uncache a module from sys.modules.
147
148 A basic sanity check is performed to prevent uncaching modules that either
149 cannot/shouldn't be uncached.
150
151 """
152 for name in names:
153 if name in ('sys', 'marshal'):
154 raise ValueError("cannot uncache {}".format(name))
155 try:
156 del sys.modules[name]
157 except KeyError:
158 pass
159 try:
160 yield
161 finally:
162 for name in names:
163 try:
164 del sys.modules[name]
165 except KeyError:
166 pass
167
168
169 @contextlib.contextmanager
170 def temp_module(name, content='', *, pkg=False):
171 conflicts = [n for n in sys.modules if n.partition('.')[0] == name]
172 with os_helper.temp_cwd(None) as cwd:
173 with uncache(name, *conflicts):
174 with import_helper.DirsOnSysPath(cwd):
175 invalidate_caches()
176
177 location = os.path.join(cwd, name)
178 if pkg:
179 modpath = os.path.join(location, '__init__.py')
180 os.mkdir(name)
181 else:
182 modpath = location + '.py'
183 if content is None:
184 # Make sure the module file gets created.
185 content = ''
186 if content is not None:
187 # not a namespace package
188 with open(modpath, 'w', encoding='utf-8') as modfile:
189 modfile.write(content)
190 yield location
191
192
193 @contextlib.contextmanager
194 def import_state(**kwargs):
195 """Context manager to manage the various importers and stored state in the
196 sys module.
197
198 The 'modules' attribute is not supported as the interpreter state stores a
199 pointer to the dict that the interpreter uses internally;
200 reassigning to sys.modules does not have the desired effect.
201
202 """
203 originals = {}
204 try:
205 for attr, default in (('meta_path', []), ('path', []),
206 ('path_hooks', []),
207 ('path_importer_cache', {})):
208 originals[attr] = getattr(sys, attr)
209 if attr in kwargs:
210 new_value = kwargs[attr]
211 del kwargs[attr]
212 else:
213 new_value = default
214 setattr(sys, attr, new_value)
215 if len(kwargs):
216 raise ValueError('unrecognized arguments: {}'.format(kwargs))
217 yield
218 finally:
219 for attr, value in originals.items():
220 setattr(sys, attr, value)
221
222
223 class _ImporterMock:
224
225 """Base class to help with creating importer mocks."""
226
227 def __init__(self, *names, module_code={}):
228 self.modules = {}
229 self.module_code = {}
230 for name in names:
231 if not name.endswith('.__init__'):
232 import_name = name
233 else:
234 import_name = name[:-len('.__init__')]
235 if '.' not in name:
236 package = None
237 elif import_name == name:
238 package = name.rsplit('.', 1)[0]
239 else:
240 package = import_name
241 module = types.ModuleType(import_name)
242 module.__loader__ = self
243 module.__file__ = '<mock __file__>'
244 module.__package__ = package
245 module.attr = name
246 if import_name != name:
247 module.__path__ = ['<mock __path__>']
248 self.modules[import_name] = module
249 if import_name in module_code:
250 self.module_code[import_name] = module_code[import_name]
251
252 def __getitem__(self, name):
253 return self.modules[name]
254
255 def __enter__(self):
256 self._uncache = uncache(*self.modules.keys())
257 self._uncache.__enter__()
258 return self
259
260 def __exit__(self, *exc_info):
261 self._uncache.__exit__(None, None, None)
262
263
264 class mock_spec(_ImporterMock):
265
266 """Importer mock using PEP 451 APIs."""
267
268 def find_spec(self, fullname, path=None, parent=None):
269 try:
270 module = self.modules[fullname]
271 except KeyError:
272 return None
273 spec = util.spec_from_file_location(
274 fullname, module.__file__, loader=self,
275 submodule_search_locations=getattr(module, '__path__', None))
276 return spec
277
278 def create_module(self, spec):
279 if spec.name not in self.modules:
280 raise ImportError
281 return self.modules[spec.name]
282
283 def exec_module(self, module):
284 try:
285 self.module_code[module.__spec__.name]()
286 except KeyError:
287 pass
288
289
290 def writes_bytecode_files(fxn):
291 """Decorator to protect sys.dont_write_bytecode from mutation and to skip
292 tests that require it to be set to False."""
293 if sys.dont_write_bytecode:
294 return unittest.skip("relies on writing bytecode")(fxn)
295 @functools.wraps(fxn)
296 def wrapper(*args, **kwargs):
297 original = sys.dont_write_bytecode
298 sys.dont_write_bytecode = False
299 try:
300 to_return = fxn(*args, **kwargs)
301 finally:
302 sys.dont_write_bytecode = original
303 return to_return
304 return wrapper
305
306
307 def ensure_bytecode_path(bytecode_path):
308 """Ensure that the __pycache__ directory for PEP 3147 pyc file exists.
309
310 :param bytecode_path: File system path to PEP 3147 pyc file.
311 """
312 try:
313 os.mkdir(os.path.dirname(bytecode_path))
314 except OSError as error:
315 if error.errno != errno.EEXIST:
316 raise
317
318
319 @contextlib.contextmanager
320 def temporary_pycache_prefix(prefix):
321 """Adjust and restore sys.pycache_prefix."""
322 _orig_prefix = sys.pycache_prefix
323 sys.pycache_prefix = prefix
324 try:
325 yield
326 finally:
327 sys.pycache_prefix = _orig_prefix
328
329
330 @contextlib.contextmanager
331 def create_modules(*names):
332 """Temporarily create each named module with an attribute (named 'attr')
333 that contains the name passed into the context manager that caused the
334 creation of the module.
335
336 All files are created in a temporary directory returned by
337 tempfile.mkdtemp(). This directory is inserted at the beginning of
338 sys.path. When the context manager exits all created files (source and
339 bytecode) are explicitly deleted.
340
341 No magic is performed when creating packages! This means that if you create
342 a module within a package you must also create the package's __init__ as
343 well.
344
345 """
346 source = 'attr = {0!r}'
347 created_paths = []
348 mapping = {}
349 state_manager = None
350 uncache_manager = None
351 try:
352 temp_dir = tempfile.mkdtemp()
353 mapping['.root'] = temp_dir
354 import_names = set()
355 for name in names:
356 if not name.endswith('__init__'):
357 import_name = name
358 else:
359 import_name = name[:-len('.__init__')]
360 import_names.add(import_name)
361 if import_name in sys.modules:
362 del sys.modules[import_name]
363 name_parts = name.split('.')
364 file_path = temp_dir
365 for directory in name_parts[:-1]:
366 file_path = os.path.join(file_path, directory)
367 if not os.path.exists(file_path):
368 os.mkdir(file_path)
369 created_paths.append(file_path)
370 file_path = os.path.join(file_path, name_parts[-1] + '.py')
371 with open(file_path, 'w', encoding='utf-8') as file:
372 file.write(source.format(name))
373 created_paths.append(file_path)
374 mapping[name] = file_path
375 uncache_manager = uncache(*import_names)
376 uncache_manager.__enter__()
377 state_manager = import_state(path=[temp_dir])
378 state_manager.__enter__()
379 yield mapping
380 finally:
381 if state_manager is not None:
382 state_manager.__exit__(None, None, None)
383 if uncache_manager is not None:
384 uncache_manager.__exit__(None, None, None)
385 os_helper.rmtree(temp_dir)
386
387
388 def mock_path_hook(*entries, importer):
389 """A mock sys.path_hooks entry."""
390 def hook(entry):
391 if entry not in entries:
392 raise ImportError
393 return importer
394 return hook
395
396
397 class CASEOKTestBase:
398
399 def caseok_env_changed(self, *, should_exist):
400 possibilities = b'PYTHONCASEOK', 'PYTHONCASEOK'
401 if any(x in self.importlib._bootstrap_external._os.environ
402 for x in possibilities) != should_exist:
403 self.skipTest('os.environ changes not reflected in _os.environ')