Debian Codegraph @

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

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