Issue #19712: Update test.test_importlib.import_ to test/use PEP 451

where appropriate.
This commit is contained in:
Brett Cannon 2013-12-06 12:07:25 -05:00
parent 010ff584bc
commit 86aae6a7b3
8 changed files with 114 additions and 61 deletions

View file

@ -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