diff options
author | Brett Cannon <brett@python.org> | 2013-12-06 17:07:25 (GMT) |
---|---|---|
committer | Brett Cannon <brett@python.org> | 2013-12-06 17:07:25 (GMT) |
commit | 86aae6a7b3b863529b6cce64859c0f56c7963bc0 (patch) | |
tree | 08235d86bcf078592b2e14a3231ec1c5db60b3a1 /Lib/test/test_importlib/util.py | |
parent | 010ff584bc2f6311ead82221a4e2072c7f31bad3 (diff) | |
download | cpython-86aae6a7b3b863529b6cce64859c0f56c7963bc0.zip cpython-86aae6a7b3b863529b6cce64859c0f56c7963bc0.tar.gz cpython-86aae6a7b3b863529b6cce64859c0f56c7963bc0.tar.bz2 |
Issue #19712: Update test.test_importlib.import_ to test/use PEP 451
where appropriate.
Diffstat (limited to 'Lib/test/test_importlib/util.py')
-rw-r--r-- | Lib/test/test_importlib/util.py | 48 |
1 files changed, 40 insertions, 8 deletions
diff --git a/Lib/test/test_importlib/util.py b/Lib/test/test_importlib/util.py index 80d43b5..a0dee6e 100644 --- a/Lib/test/test_importlib/util.py +++ b/Lib/test/test_importlib/util.py @@ -1,4 +1,5 @@ from contextlib import contextmanager +from importlib import util import os.path from test import support import unittest @@ -101,9 +102,9 @@ def import_state(**kwargs): setattr(sys, attr, value) -class mock_modules: +class _ImporterMock: - """A mock importer/loader.""" + """Base class to help with creating importer mocks.""" def __init__(self, *names, module_code={}): self.modules = {} @@ -133,6 +134,19 @@ class mock_modules: def __getitem__(self, name): return self.modules[name] + def __enter__(self): + self._uncache = uncache(*self.modules.keys()) + self._uncache.__enter__() + return self + + def __exit__(self, *exc_info): + self._uncache.__exit__(None, None, None) + + +class mock_modules(_ImporterMock): + + """Importer mock using PEP 302 APIs.""" + def find_module(self, fullname, path=None): if fullname not in self.modules: return None @@ -152,10 +166,28 @@ class mock_modules: raise return self.modules[fullname] - def __enter__(self): - self._uncache = uncache(*self.modules.keys()) - self._uncache.__enter__() - return self +class mock_spec(_ImporterMock): - def __exit__(self, *exc_info): - self._uncache.__exit__(None, None, None) + """Importer mock using PEP 451 APIs.""" + + def find_spec(self, fullname, path=None, parent=None): + try: + module = self.modules[fullname] + except KeyError: + return None + is_package = hasattr(module, '__path__') + spec = util.spec_from_file_location( + fullname, module.__file__, loader=self, + submodule_search_locations=getattr(module, '__path__', None)) + return spec + + def create_module(self, spec): + if spec.name not in self.modules: + raise ImportError + return self.modules[spec.name] + + def exec_module(self, module): + try: + self.module_code[module.__spec__.name]() + except KeyError: + pass |