diff options
Diffstat (limited to 'Lib/test/test_importlib/import_')
-rw-r--r-- | Lib/test/test_importlib/import_/__init__.py | 5 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/__main__.py | 4 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test___loader__.py | 75 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test___package__.py | 163 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_api.py | 119 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_caching.py | 93 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_fromlist.py | 175 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_meta_path.py | 125 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_packages.py | 110 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_path.py | 278 | ||||
-rw-r--r-- | Lib/test/test_importlib/import_/test_relative_imports.py | 233 |
11 files changed, 0 insertions, 1380 deletions
diff --git a/Lib/test/test_importlib/import_/__init__.py b/Lib/test/test_importlib/import_/__init__.py deleted file mode 100644 index 4b16ecc..0000000 --- a/Lib/test/test_importlib/import_/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -import os -from test.support import load_package_tests - -def load_tests(*args): - return load_package_tests(os.path.dirname(__file__), *args) diff --git a/Lib/test/test_importlib/import_/__main__.py b/Lib/test/test_importlib/import_/__main__.py deleted file mode 100644 index 40a23a2..0000000 --- a/Lib/test/test_importlib/import_/__main__.py +++ /dev/null @@ -1,4 +0,0 @@ -from . import load_tests -import unittest - -unittest.main() diff --git a/Lib/test/test_importlib/import_/test___loader__.py b/Lib/test/test_importlib/import_/test___loader__.py deleted file mode 100644 index 4b18093..0000000 --- a/Lib/test/test_importlib/import_/test___loader__.py +++ /dev/null @@ -1,75 +0,0 @@ -from importlib import machinery -import sys -import types -import unittest - -from .. import util - - -class SpecLoaderMock: - - def find_spec(self, fullname, path=None, target=None): - return machinery.ModuleSpec(fullname, self) - - def create_module(self, spec): - return None - - def exec_module(self, module): - pass - - -class SpecLoaderAttributeTests: - - def test___loader__(self): - loader = SpecLoaderMock() - with util.uncache('blah'), util.import_state(meta_path=[loader]): - module = self.__import__('blah') - self.assertEqual(loader, module.__loader__) - - -(Frozen_SpecTests, - Source_SpecTests - ) = util.test_both(SpecLoaderAttributeTests, __import__=util.__import__) - - -class LoaderMock: - - def find_module(self, fullname, path=None): - return self - - def load_module(self, fullname): - sys.modules[fullname] = self.module - return self.module - - -class LoaderAttributeTests: - - def test___loader___missing(self): - module = types.ModuleType('blah') - try: - del module.__loader__ - except AttributeError: - pass - loader = LoaderMock() - loader.module = module - with util.uncache('blah'), util.import_state(meta_path=[loader]): - module = self.__import__('blah') - self.assertEqual(loader, module.__loader__) - - def test___loader___is_None(self): - module = types.ModuleType('blah') - module.__loader__ = None - loader = LoaderMock() - loader.module = module - with util.uncache('blah'), util.import_state(meta_path=[loader]): - returned_module = self.__import__('blah') - self.assertEqual(loader, module.__loader__) - - -(Frozen_Tests, - Source_Tests - ) = util.test_both(LoaderAttributeTests, __import__=util.__import__) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test___package__.py b/Lib/test/test_importlib/import_/test___package__.py deleted file mode 100644 index 761b256..0000000 --- a/Lib/test/test_importlib/import_/test___package__.py +++ /dev/null @@ -1,163 +0,0 @@ -"""PEP 366 ("Main module explicit relative imports") specifies the -semantics for the __package__ attribute on modules. This attribute is -used, when available, to detect which package a module belongs to (instead -of using the typical __path__/__name__ test). - -""" -import unittest -import warnings -from .. import util - - -class Using__package__: - - """Use of __package__ supersedes the use of __name__/__path__ to calculate - what package a module belongs to. The basic algorithm is [__package__]:: - - def resolve_name(name, package, level): - level -= 1 - base = package.rsplit('.', level)[0] - return '{0}.{1}'.format(base, name) - - But since there is no guarantee that __package__ has been set (or not been - set to None [None]), there has to be a way to calculate the attribute's value - [__name__]:: - - def calc_package(caller_name, has___path__): - if has__path__: - return caller_name - else: - return caller_name.rsplit('.', 1)[0] - - Then the normal algorithm for relative name imports can proceed as if - __package__ had been set. - - """ - - def import_module(self, globals_): - with self.mock_modules('pkg.__init__', 'pkg.fake') as importer: - with util.import_state(meta_path=[importer]): - self.__import__('pkg.fake') - module = self.__import__('', - globals=globals_, - fromlist=['attr'], level=2) - return module - - def test_using___package__(self): - # [__package__] - module = self.import_module({'__package__': 'pkg.fake'}) - self.assertEqual(module.__name__, 'pkg') - - def test_using___name__(self): - # [__name__] - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - module = self.import_module({'__name__': 'pkg.fake', - '__path__': []}) - self.assertEqual(module.__name__, 'pkg') - - def test_warn_when_using___name__(self): - with self.assertWarns(ImportWarning): - self.import_module({'__name__': 'pkg.fake', '__path__': []}) - - def test_None_as___package__(self): - # [None] - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - module = self.import_module({ - '__name__': 'pkg.fake', '__path__': [], '__package__': None }) - self.assertEqual(module.__name__, 'pkg') - - def test_spec_fallback(self): - # If __package__ isn't defined, fall back on __spec__.parent. - module = self.import_module({'__spec__': FakeSpec('pkg.fake')}) - self.assertEqual(module.__name__, 'pkg') - - def test_warn_when_package_and_spec_disagree(self): - # Raise an ImportWarning if __package__ != __spec__.parent. - with self.assertWarns(ImportWarning): - self.import_module({'__package__': 'pkg.fake', - '__spec__': FakeSpec('pkg.fakefake')}) - - def test_bad__package__(self): - globals = {'__package__': '<not real>'} - with self.assertRaises(ModuleNotFoundError): - self.__import__('', globals, {}, ['relimport'], 1) - - def test_bunk__package__(self): - globals = {'__package__': 42} - with self.assertRaises(TypeError): - self.__import__('', globals, {}, ['relimport'], 1) - - -class FakeSpec: - def __init__(self, parent): - self.parent = parent - - -class Using__package__PEP302(Using__package__): - mock_modules = util.mock_modules - - -(Frozen_UsingPackagePEP302, - Source_UsingPackagePEP302 - ) = util.test_both(Using__package__PEP302, __import__=util.__import__) - - -class Using__package__PEP451(Using__package__): - mock_modules = util.mock_spec - - -(Frozen_UsingPackagePEP451, - Source_UsingPackagePEP451 - ) = util.test_both(Using__package__PEP451, __import__=util.__import__) - - -class Setting__package__: - - """Because __package__ is a new feature, it is not always set by a loader. - Import will set it as needed to help with the transition to relying on - __package__. - - For a top-level module, __package__ is set to None [top-level]. For a - package __name__ is used for __package__ [package]. For submodules the - value is __name__.rsplit('.', 1)[0] [submodule]. - - """ - - __import__ = util.__import__['Source'] - - # [top-level] - def test_top_level(self): - with self.mock_modules('top_level') as mock: - with util.import_state(meta_path=[mock]): - del mock['top_level'].__package__ - module = self.__import__('top_level') - self.assertEqual(module.__package__, '') - - # [package] - def test_package(self): - with self.mock_modules('pkg.__init__') as mock: - with util.import_state(meta_path=[mock]): - del mock['pkg'].__package__ - module = self.__import__('pkg') - self.assertEqual(module.__package__, 'pkg') - - # [submodule] - def test_submodule(self): - with self.mock_modules('pkg.__init__', 'pkg.mod') as mock: - with util.import_state(meta_path=[mock]): - del mock['pkg.mod'].__package__ - pkg = self.__import__('pkg.mod') - module = getattr(pkg, 'mod') - self.assertEqual(module.__package__, 'pkg') - -class Setting__package__PEP302(Setting__package__, unittest.TestCase): - mock_modules = util.mock_modules - -class Setting__package__PEP451(Setting__package__, unittest.TestCase): - mock_modules = util.mock_spec - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_api.py b/Lib/test/test_importlib/import_/test_api.py deleted file mode 100644 index 0cd9de4..0000000 --- a/Lib/test/test_importlib/import_/test_api.py +++ /dev/null @@ -1,119 +0,0 @@ -from .. import util - -from importlib import machinery -import sys -import types -import unittest - -PKG_NAME = 'fine' -SUBMOD_NAME = 'fine.bogus' - - -class BadSpecFinderLoader: - @classmethod - def find_spec(cls, fullname, path=None, target=None): - if fullname == SUBMOD_NAME: - spec = machinery.ModuleSpec(fullname, cls) - return spec - - @staticmethod - def create_module(spec): - return None - - @staticmethod - def exec_module(module): - if module.__name__ == SUBMOD_NAME: - raise ImportError('I cannot be loaded!') - - -class BadLoaderFinder: - @classmethod - def find_module(cls, fullname, path): - if fullname == SUBMOD_NAME: - return cls - - @classmethod - def load_module(cls, fullname): - if fullname == SUBMOD_NAME: - raise ImportError('I cannot be loaded!') - - -class APITest: - - """Test API-specific details for __import__ (e.g. raising the right - exception when passing in an int for the module name).""" - - def test_raises_ModuleNotFoundError(self): - with self.assertRaises(ModuleNotFoundError): - util.import_importlib('some module that does not exist') - - def test_name_requires_rparition(self): - # Raise TypeError if a non-string is passed in for the module name. - with self.assertRaises(TypeError): - self.__import__(42) - - def test_negative_level(self): - # Raise ValueError when a negative level is specified. - # PEP 328 did away with sys.module None entries and the ambiguity of - # absolute/relative imports. - with self.assertRaises(ValueError): - self.__import__('os', globals(), level=-1) - - def test_nonexistent_fromlist_entry(self): - # If something in fromlist doesn't exist, that's okay. - # issue15715 - mod = types.ModuleType(PKG_NAME) - mod.__path__ = ['XXX'] - with util.import_state(meta_path=[self.bad_finder_loader]): - with util.uncache(PKG_NAME): - sys.modules[PKG_NAME] = mod - self.__import__(PKG_NAME, fromlist=['not here']) - - def test_fromlist_load_error_propagates(self): - # If something in fromlist triggers an exception not related to not - # existing, let that exception propagate. - # issue15316 - mod = types.ModuleType(PKG_NAME) - mod.__path__ = ['XXX'] - with util.import_state(meta_path=[self.bad_finder_loader]): - with util.uncache(PKG_NAME): - sys.modules[PKG_NAME] = mod - with self.assertRaises(ImportError): - self.__import__(PKG_NAME, - fromlist=[SUBMOD_NAME.rpartition('.')[-1]]) - - def test_blocked_fromlist(self): - # If fromlist entry is None, let a ModuleNotFoundError propagate. - # issue31642 - mod = types.ModuleType(PKG_NAME) - mod.__path__ = [] - with util.import_state(meta_path=[self.bad_finder_loader]): - with util.uncache(PKG_NAME, SUBMOD_NAME): - sys.modules[PKG_NAME] = mod - sys.modules[SUBMOD_NAME] = None - with self.assertRaises(ModuleNotFoundError) as cm: - self.__import__(PKG_NAME, - fromlist=[SUBMOD_NAME.rpartition('.')[-1]]) - self.assertEqual(cm.exception.name, SUBMOD_NAME) - - -class OldAPITests(APITest): - bad_finder_loader = BadLoaderFinder - - -(Frozen_OldAPITests, - Source_OldAPITests - ) = util.test_both(OldAPITests, __import__=util.__import__) - - -class SpecAPITests(APITest): - bad_finder_loader = BadSpecFinderLoader - - -(Frozen_SpecAPITests, - Source_SpecAPITests - ) = util.test_both(SpecAPITests, __import__=util.__import__) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_caching.py b/Lib/test/test_importlib/import_/test_caching.py deleted file mode 100644 index 8079add..0000000 --- a/Lib/test/test_importlib/import_/test_caching.py +++ /dev/null @@ -1,93 +0,0 @@ -"""Test that sys.modules is used properly by import.""" -from .. import util -import sys -from types import MethodType -import unittest - - -class UseCache: - - """When it comes to sys.modules, import prefers it over anything else. - - Once a name has been resolved, sys.modules is checked to see if it contains - the module desired. If so, then it is returned [use cache]. If it is not - found, then the proper steps are taken to perform the import, but - sys.modules is still used to return the imported module (e.g., not what a - loader returns) [from cache on return]. This also applies to imports of - things contained within a package and thus get assigned as an attribute - [from cache to attribute] or pulled in thanks to a fromlist import - [from cache for fromlist]. But if sys.modules contains None then - ImportError is raised [None in cache]. - - """ - - def test_using_cache(self): - # [use cache] - module_to_use = "some module found!" - with util.uncache('some_module'): - sys.modules['some_module'] = module_to_use - module = self.__import__('some_module') - self.assertEqual(id(module_to_use), id(module)) - - def test_None_in_cache(self): - #[None in cache] - name = 'using_None' - with util.uncache(name): - sys.modules[name] = None - with self.assertRaises(ImportError) as cm: - self.__import__(name) - self.assertEqual(cm.exception.name, name) - - -(Frozen_UseCache, - Source_UseCache - ) = util.test_both(UseCache, __import__=util.__import__) - - -class ImportlibUseCache(UseCache, unittest.TestCase): - - # Pertinent only to PEP 302; exec_module() doesn't return a module. - - __import__ = util.__import__['Source'] - - def create_mock(self, *names, return_=None): - mock = util.mock_modules(*names) - original_load = mock.load_module - def load_module(self, fullname): - original_load(fullname) - return return_ - mock.load_module = MethodType(load_module, mock) - return mock - - # __import__ inconsistent between loaders and built-in import when it comes - # to when to use the module in sys.modules and when not to. - def test_using_cache_after_loader(self): - # [from cache on return] - with self.create_mock('module') as mock: - with util.import_state(meta_path=[mock]): - module = self.__import__('module') - self.assertEqual(id(module), id(sys.modules['module'])) - - # See test_using_cache_after_loader() for reasoning. - def test_using_cache_for_assigning_to_attribute(self): - # [from cache to attribute] - with self.create_mock('pkg.__init__', 'pkg.module') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg.module') - self.assertTrue(hasattr(module, 'module')) - self.assertEqual(id(module.module), - id(sys.modules['pkg.module'])) - - # See test_using_cache_after_loader() for reasoning. - def test_using_cache_for_fromlist(self): - # [from cache for fromlist] - with self.create_mock('pkg.__init__', 'pkg.module') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg', fromlist=['module']) - self.assertTrue(hasattr(module, 'module')) - self.assertEqual(id(module.module), - id(sys.modules['pkg.module'])) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_fromlist.py b/Lib/test/test_importlib/import_/test_fromlist.py deleted file mode 100644 index 018c172..0000000 --- a/Lib/test/test_importlib/import_/test_fromlist.py +++ /dev/null @@ -1,175 +0,0 @@ -"""Test that the semantics relating to the 'fromlist' argument are correct.""" -from .. import util -import warnings -import unittest - - -class ReturnValue: - - """The use of fromlist influences what import returns. - - If direct ``import ...`` statement is used, the root module or package is - returned [import return]. But if fromlist is set, then the specified module - is actually returned (whether it is a relative import or not) - [from return]. - - """ - - def test_return_from_import(self): - # [import return] - with util.mock_spec('pkg.__init__', 'pkg.module') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg.module') - self.assertEqual(module.__name__, 'pkg') - - def test_return_from_from_import(self): - # [from return] - with util.mock_modules('pkg.__init__', 'pkg.module')as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg.module', fromlist=['attr']) - self.assertEqual(module.__name__, 'pkg.module') - - -(Frozen_ReturnValue, - Source_ReturnValue - ) = util.test_both(ReturnValue, __import__=util.__import__) - - -class HandlingFromlist: - - """Using fromlist triggers different actions based on what is being asked - of it. - - If fromlist specifies an object on a module, nothing special happens - [object case]. This is even true if the object does not exist [bad object]. - - If a package is being imported, then what is listed in fromlist may be - treated as a module to be imported [module]. And this extends to what is - contained in __all__ when '*' is imported [using *]. And '*' does not need - to be the only name in the fromlist [using * with others]. - - """ - - def test_object(self): - # [object case] - with util.mock_modules('module') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('module', fromlist=['attr']) - self.assertEqual(module.__name__, 'module') - - def test_nonexistent_object(self): - # [bad object] - with util.mock_modules('module') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('module', fromlist=['non_existent']) - self.assertEqual(module.__name__, 'module') - self.assertFalse(hasattr(module, 'non_existent')) - - def test_module_from_package(self): - # [module] - with util.mock_modules('pkg.__init__', 'pkg.module') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg', fromlist=['module']) - self.assertEqual(module.__name__, 'pkg') - self.assertTrue(hasattr(module, 'module')) - self.assertEqual(module.module.__name__, 'pkg.module') - - def test_nonexistent_from_package(self): - with util.mock_modules('pkg.__init__') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg', fromlist=['non_existent']) - self.assertEqual(module.__name__, 'pkg') - self.assertFalse(hasattr(module, 'non_existent')) - - def test_module_from_package_triggers_ModuleNotFoundError(self): - # If a submodule causes an ModuleNotFoundError because it tries - # to import a module which doesn't exist, that should let the - # ModuleNotFoundError propagate. - def module_code(): - import i_do_not_exist - with util.mock_modules('pkg.__init__', 'pkg.mod', - module_code={'pkg.mod': module_code}) as importer: - with util.import_state(meta_path=[importer]): - with self.assertRaises(ModuleNotFoundError) as exc: - self.__import__('pkg', fromlist=['mod']) - self.assertEqual('i_do_not_exist', exc.exception.name) - - def test_empty_string(self): - with util.mock_modules('pkg.__init__', 'pkg.mod') as importer: - with util.import_state(meta_path=[importer]): - module = self.__import__('pkg.mod', fromlist=['']) - self.assertEqual(module.__name__, 'pkg.mod') - - def basic_star_test(self, fromlist=['*']): - # [using *] - with util.mock_modules('pkg.__init__', 'pkg.module') as mock: - with util.import_state(meta_path=[mock]): - mock['pkg'].__all__ = ['module'] - module = self.__import__('pkg', fromlist=fromlist) - self.assertEqual(module.__name__, 'pkg') - self.assertTrue(hasattr(module, 'module')) - self.assertEqual(module.module.__name__, 'pkg.module') - - def test_using_star(self): - # [using *] - self.basic_star_test() - - def test_fromlist_as_tuple(self): - self.basic_star_test(('*',)) - - def test_star_with_others(self): - # [using * with others] - context = util.mock_modules('pkg.__init__', 'pkg.module1', 'pkg.module2') - with context as mock: - with util.import_state(meta_path=[mock]): - mock['pkg'].__all__ = ['module1'] - module = self.__import__('pkg', fromlist=['module2', '*']) - self.assertEqual(module.__name__, 'pkg') - self.assertTrue(hasattr(module, 'module1')) - self.assertTrue(hasattr(module, 'module2')) - self.assertEqual(module.module1.__name__, 'pkg.module1') - self.assertEqual(module.module2.__name__, 'pkg.module2') - - def test_nonexistent_in_all(self): - with util.mock_modules('pkg.__init__') as importer: - with util.import_state(meta_path=[importer]): - importer['pkg'].__all__ = ['non_existent'] - module = self.__import__('pkg', fromlist=['*']) - self.assertEqual(module.__name__, 'pkg') - self.assertFalse(hasattr(module, 'non_existent')) - - def test_star_in_all(self): - with util.mock_modules('pkg.__init__') as importer: - with util.import_state(meta_path=[importer]): - importer['pkg'].__all__ = ['*'] - module = self.__import__('pkg', fromlist=['*']) - self.assertEqual(module.__name__, 'pkg') - self.assertFalse(hasattr(module, '*')) - - def test_invalid_type(self): - with util.mock_modules('pkg.__init__') as importer: - with util.import_state(meta_path=[importer]), \ - warnings.catch_warnings(): - warnings.simplefilter('error', BytesWarning) - with self.assertRaisesRegex(TypeError, r'\bfrom\b'): - self.__import__('pkg', fromlist=[b'attr']) - with self.assertRaisesRegex(TypeError, r'\bfrom\b'): - self.__import__('pkg', fromlist=iter([b'attr'])) - - def test_invalid_type_in_all(self): - with util.mock_modules('pkg.__init__') as importer: - with util.import_state(meta_path=[importer]), \ - warnings.catch_warnings(): - warnings.simplefilter('error', BytesWarning) - importer['pkg'].__all__ = [b'attr'] - with self.assertRaisesRegex(TypeError, r'\bpkg\.__all__\b'): - self.__import__('pkg', fromlist=['*']) - - -(Frozen_FromList, - Source_FromList - ) = util.test_both(HandlingFromlist, __import__=util.__import__) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_meta_path.py b/Lib/test/test_importlib/import_/test_meta_path.py deleted file mode 100644 index 5a41e89..0000000 --- a/Lib/test/test_importlib/import_/test_meta_path.py +++ /dev/null @@ -1,125 +0,0 @@ -from .. import util -import importlib._bootstrap -import sys -from types import MethodType -import unittest -import warnings - - -class CallingOrder: - - """Calls to the importers on sys.meta_path happen in order that they are - specified in the sequence, starting with the first importer - [first called], and then continuing on down until one is found that doesn't - return None [continuing].""" - - - def test_first_called(self): - # [first called] - mod = 'top_level' - with util.mock_spec(mod) as first, util.mock_spec(mod) as second: - with util.import_state(meta_path=[first, second]): - self.assertIs(self.__import__(mod), first.modules[mod]) - - def test_continuing(self): - # [continuing] - mod_name = 'for_real' - with util.mock_spec('nonexistent') as first, \ - util.mock_spec(mod_name) as second: - first.find_spec = lambda self, fullname, path=None, parent=None: None - with util.import_state(meta_path=[first, second]): - self.assertIs(self.__import__(mod_name), second.modules[mod_name]) - - def test_empty(self): - # Raise an ImportWarning if sys.meta_path is empty. - module_name = 'nothing' - try: - del sys.modules[module_name] - except KeyError: - pass - with util.import_state(meta_path=[]): - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - self.assertIsNone(importlib._bootstrap._find_spec('nothing', - None)) - self.assertEqual(len(w), 1) - self.assertTrue(issubclass(w[-1].category, ImportWarning)) - - -(Frozen_CallingOrder, - Source_CallingOrder - ) = util.test_both(CallingOrder, __import__=util.__import__) - - -class CallSignature: - - """If there is no __path__ entry on the parent module, then 'path' is None - [no path]. Otherwise, the value for __path__ is passed in for the 'path' - argument [path set].""" - - def log_finder(self, importer): - fxn = getattr(importer, self.finder_name) - log = [] - def wrapper(self, *args, **kwargs): - log.append([args, kwargs]) - return fxn(*args, **kwargs) - return log, wrapper - - def test_no_path(self): - # [no path] - mod_name = 'top_level' - assert '.' not in mod_name - with self.mock_modules(mod_name) as importer: - log, wrapped_call = self.log_finder(importer) - setattr(importer, self.finder_name, MethodType(wrapped_call, importer)) - with util.import_state(meta_path=[importer]): - self.__import__(mod_name) - assert len(log) == 1 - args = log[0][0] - # Assuming all arguments are positional. - self.assertEqual(args[0], mod_name) - self.assertIsNone(args[1]) - - def test_with_path(self): - # [path set] - pkg_name = 'pkg' - mod_name = pkg_name + '.module' - path = [42] - assert '.' in mod_name - with self.mock_modules(pkg_name+'.__init__', mod_name) as importer: - importer.modules[pkg_name].__path__ = path - log, wrapped_call = self.log_finder(importer) - setattr(importer, self.finder_name, MethodType(wrapped_call, importer)) - with util.import_state(meta_path=[importer]): - self.__import__(mod_name) - assert len(log) == 2 - args = log[1][0] - kwargs = log[1][1] - # Assuming all arguments are positional. - self.assertFalse(kwargs) - self.assertEqual(args[0], mod_name) - self.assertIs(args[1], path) - - -class CallSignaturePEP302(CallSignature): - mock_modules = util.mock_modules - finder_name = 'find_module' - - -(Frozen_CallSignaturePEP302, - Source_CallSignaturePEP302 - ) = util.test_both(CallSignaturePEP302, __import__=util.__import__) - - -class CallSignaturePEP451(CallSignature): - mock_modules = util.mock_spec - finder_name = 'find_spec' - - -(Frozen_CallSignaturePEP451, - Source_CallSignaturePEP451 - ) = util.test_both(CallSignaturePEP451, __import__=util.__import__) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_packages.py b/Lib/test/test_importlib/import_/test_packages.py deleted file mode 100644 index 2439604..0000000 --- a/Lib/test/test_importlib/import_/test_packages.py +++ /dev/null @@ -1,110 +0,0 @@ -from .. import util -import sys -import unittest -from test import support - - -class ParentModuleTests: - - """Importing a submodule should import the parent modules.""" - - def test_import_parent(self): - with util.mock_spec('pkg.__init__', 'pkg.module') as mock: - with util.import_state(meta_path=[mock]): - module = self.__import__('pkg.module') - self.assertIn('pkg', sys.modules) - - def test_bad_parent(self): - with util.mock_spec('pkg.module') as mock: - with util.import_state(meta_path=[mock]): - with self.assertRaises(ImportError) as cm: - self.__import__('pkg.module') - self.assertEqual(cm.exception.name, 'pkg') - - def test_raising_parent_after_importing_child(self): - def __init__(): - import pkg.module - 1/0 - mock = util.mock_spec('pkg.__init__', 'pkg.module', - module_code={'pkg': __init__}) - with mock: - with util.import_state(meta_path=[mock]): - with self.assertRaises(ZeroDivisionError): - self.__import__('pkg') - self.assertNotIn('pkg', sys.modules) - self.assertIn('pkg.module', sys.modules) - with self.assertRaises(ZeroDivisionError): - self.__import__('pkg.module') - self.assertNotIn('pkg', sys.modules) - self.assertIn('pkg.module', sys.modules) - - def test_raising_parent_after_relative_importing_child(self): - def __init__(): - from . import module - 1/0 - mock = util.mock_spec('pkg.__init__', 'pkg.module', - module_code={'pkg': __init__}) - with mock: - with util.import_state(meta_path=[mock]): - with self.assertRaises((ZeroDivisionError, ImportError)): - # This raises ImportError on the "from . import module" - # line, not sure why. - self.__import__('pkg') - self.assertNotIn('pkg', sys.modules) - with self.assertRaises((ZeroDivisionError, ImportError)): - self.__import__('pkg.module') - self.assertNotIn('pkg', sys.modules) - # XXX False - #self.assertIn('pkg.module', sys.modules) - - def test_raising_parent_after_double_relative_importing_child(self): - def __init__(): - from ..subpkg import module - 1/0 - mock = util.mock_spec('pkg.__init__', 'pkg.subpkg.__init__', - 'pkg.subpkg.module', - module_code={'pkg.subpkg': __init__}) - with mock: - with util.import_state(meta_path=[mock]): - with self.assertRaises((ZeroDivisionError, ImportError)): - # This raises ImportError on the "from ..subpkg import module" - # line, not sure why. - self.__import__('pkg.subpkg') - self.assertNotIn('pkg.subpkg', sys.modules) - with self.assertRaises((ZeroDivisionError, ImportError)): - self.__import__('pkg.subpkg.module') - self.assertNotIn('pkg.subpkg', sys.modules) - # XXX False - #self.assertIn('pkg.subpkg.module', sys.modules) - - def test_module_not_package(self): - # Try to import a submodule from a non-package should raise ImportError. - assert not hasattr(sys, '__path__') - with self.assertRaises(ImportError) as cm: - self.__import__('sys.no_submodules_here') - self.assertEqual(cm.exception.name, 'sys.no_submodules_here') - - def test_module_not_package_but_side_effects(self): - # If a module injects something into sys.modules as a side-effect, then - # pick up on that fact. - name = 'mod' - subname = name + '.b' - def module_injection(): - sys.modules[subname] = 'total bunk' - mock_spec = util.mock_spec('mod', - module_code={'mod': module_injection}) - with mock_spec as mock: - with util.import_state(meta_path=[mock]): - try: - submodule = self.__import__(subname) - finally: - support.unload(subname) - - -(Frozen_ParentTests, - Source_ParentTests - ) = util.test_both(ParentModuleTests, __import__=util.__import__) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_path.py b/Lib/test/test_importlib/import_/test_path.py deleted file mode 100644 index 18c81dd..0000000 --- a/Lib/test/test_importlib/import_/test_path.py +++ /dev/null @@ -1,278 +0,0 @@ -from .. import util - -importlib = util.import_importlib('importlib') -machinery = util.import_importlib('importlib.machinery') - -import os -import sys -import tempfile -from types import ModuleType -import unittest -import warnings -import zipimport - - -class FinderTests: - - """Tests for PathFinder.""" - - find = None - check_found = None - - def test_failure(self): - # Test None returned upon not finding a suitable loader. - module = '<test module>' - with util.import_state(): - self.assertIsNone(self.find(module)) - - def test_sys_path(self): - # Test that sys.path is used when 'path' is None. - # Implicitly tests that sys.path_importer_cache is used. - module = '<test module>' - path = '<test path>' - importer = util.mock_spec(module) - with util.import_state(path_importer_cache={path: importer}, - path=[path]): - found = self.find(module) - self.check_found(found, importer) - - def test_path(self): - # Test that 'path' is used when set. - # Implicitly tests that sys.path_importer_cache is used. - module = '<test module>' - path = '<test path>' - importer = util.mock_spec(module) - with util.import_state(path_importer_cache={path: importer}): - found = self.find(module, [path]) - self.check_found(found, importer) - - def test_empty_list(self): - # An empty list should not count as asking for sys.path. - module = 'module' - path = '<test path>' - importer = util.mock_spec(module) - with util.import_state(path_importer_cache={path: importer}, - path=[path]): - self.assertIsNone(self.find('module', [])) - - def test_path_hooks(self): - # Test that sys.path_hooks is used. - # Test that sys.path_importer_cache is set. - module = '<test module>' - path = '<test path>' - importer = util.mock_spec(module) - hook = util.mock_path_hook(path, importer=importer) - with util.import_state(path_hooks=[hook]): - found = self.find(module, [path]) - self.check_found(found, importer) - self.assertIn(path, sys.path_importer_cache) - self.assertIs(sys.path_importer_cache[path], importer) - - def test_empty_path_hooks(self): - # Test that if sys.path_hooks is empty a warning is raised, - # sys.path_importer_cache gets None set, and PathFinder returns None. - path_entry = 'bogus_path' - with util.import_state(path_importer_cache={}, path_hooks=[], - path=[path_entry]): - with warnings.catch_warnings(record=True) as w: - warnings.simplefilter('always') - self.assertIsNone(self.find('os')) - self.assertIsNone(sys.path_importer_cache[path_entry]) - self.assertEqual(len(w), 1) - self.assertTrue(issubclass(w[-1].category, ImportWarning)) - - def test_path_importer_cache_empty_string(self): - # The empty string should create a finder using the cwd. - path = '' - module = '<test module>' - importer = util.mock_spec(module) - hook = util.mock_path_hook(os.getcwd(), importer=importer) - with util.import_state(path=[path], path_hooks=[hook]): - found = self.find(module) - self.check_found(found, importer) - self.assertIn(os.getcwd(), sys.path_importer_cache) - - def test_None_on_sys_path(self): - # Putting None in sys.path[0] caused an import regression from Python - # 3.2: http://bugs.python.org/issue16514 - new_path = sys.path[:] - new_path.insert(0, None) - new_path_importer_cache = sys.path_importer_cache.copy() - new_path_importer_cache.pop(None, None) - new_path_hooks = [zipimport.zipimporter, - self.machinery.FileFinder.path_hook( - *self.importlib._bootstrap_external._get_supported_file_loaders())] - missing = object() - email = sys.modules.pop('email', missing) - try: - with util.import_state(meta_path=sys.meta_path[:], - path=new_path, - path_importer_cache=new_path_importer_cache, - path_hooks=new_path_hooks): - module = self.importlib.import_module('email') - self.assertIsInstance(module, ModuleType) - finally: - if email is not missing: - sys.modules['email'] = email - - def test_finder_with_find_module(self): - class TestFinder: - def find_module(self, fullname): - return self.to_return - failing_finder = TestFinder() - failing_finder.to_return = None - path = 'testing path' - with util.import_state(path_importer_cache={path: failing_finder}): - self.assertIsNone( - self.machinery.PathFinder.find_spec('whatever', [path])) - success_finder = TestFinder() - success_finder.to_return = __loader__ - with util.import_state(path_importer_cache={path: success_finder}): - spec = self.machinery.PathFinder.find_spec('whatever', [path]) - self.assertEqual(spec.loader, __loader__) - - def test_finder_with_find_loader(self): - class TestFinder: - loader = None - portions = [] - def find_loader(self, fullname): - return self.loader, self.portions - path = 'testing path' - with util.import_state(path_importer_cache={path: TestFinder()}): - self.assertIsNone( - self.machinery.PathFinder.find_spec('whatever', [path])) - success_finder = TestFinder() - success_finder.loader = __loader__ - with util.import_state(path_importer_cache={path: success_finder}): - spec = self.machinery.PathFinder.find_spec('whatever', [path]) - self.assertEqual(spec.loader, __loader__) - - def test_finder_with_find_spec(self): - class TestFinder: - spec = None - def find_spec(self, fullname, target=None): - return self.spec - path = 'testing path' - with util.import_state(path_importer_cache={path: TestFinder()}): - self.assertIsNone( - self.machinery.PathFinder.find_spec('whatever', [path])) - success_finder = TestFinder() - success_finder.spec = self.machinery.ModuleSpec('whatever', __loader__) - with util.import_state(path_importer_cache={path: success_finder}): - got = self.machinery.PathFinder.find_spec('whatever', [path]) - self.assertEqual(got, success_finder.spec) - - def test_deleted_cwd(self): - # Issue #22834 - old_dir = os.getcwd() - self.addCleanup(os.chdir, old_dir) - new_dir = tempfile.mkdtemp() - try: - os.chdir(new_dir) - try: - os.rmdir(new_dir) - except OSError: - # EINVAL on Solaris, EBUSY on AIX, ENOTEMPTY on Windows - self.skipTest("platform does not allow " - "the deletion of the cwd") - except: - os.chdir(old_dir) - os.rmdir(new_dir) - raise - - with util.import_state(path=['']): - # Do not want FileNotFoundError raised. - self.assertIsNone(self.machinery.PathFinder.find_spec('whatever')) - - def test_invalidate_caches_finders(self): - # Finders with an invalidate_caches() method have it called. - class FakeFinder: - def __init__(self): - self.called = False - - def invalidate_caches(self): - self.called = True - - cache = {'leave_alone': object(), 'finder_to_invalidate': FakeFinder()} - with util.import_state(path_importer_cache=cache): - self.machinery.PathFinder.invalidate_caches() - self.assertTrue(cache['finder_to_invalidate'].called) - - def test_invalidate_caches_clear_out_None(self): - # Clear out None in sys.path_importer_cache() when invalidating caches. - cache = {'clear_out': None} - with util.import_state(path_importer_cache=cache): - self.machinery.PathFinder.invalidate_caches() - self.assertEqual(len(cache), 0) - - -class FindModuleTests(FinderTests): - def find(self, *args, **kwargs): - return self.machinery.PathFinder.find_module(*args, **kwargs) - def check_found(self, found, importer): - self.assertIs(found, importer) - - -(Frozen_FindModuleTests, - Source_FindModuleTests -) = util.test_both(FindModuleTests, importlib=importlib, machinery=machinery) - - -class FindSpecTests(FinderTests): - def find(self, *args, **kwargs): - return self.machinery.PathFinder.find_spec(*args, **kwargs) - def check_found(self, found, importer): - self.assertIs(found.loader, importer) - - -(Frozen_FindSpecTests, - Source_FindSpecTests - ) = util.test_both(FindSpecTests, importlib=importlib, machinery=machinery) - - -class PathEntryFinderTests: - - def test_finder_with_failing_find_spec(self): - # PathEntryFinder with find_module() defined should work. - # Issue #20763. - class Finder: - path_location = 'test_finder_with_find_module' - def __init__(self, path): - if path != self.path_location: - raise ImportError - - @staticmethod - def find_module(fullname): - return None - - - with util.import_state(path=[Finder.path_location]+sys.path[:], - path_hooks=[Finder]): - self.machinery.PathFinder.find_spec('importlib') - - def test_finder_with_failing_find_module(self): - # PathEntryFinder with find_module() defined should work. - # Issue #20763. - class Finder: - path_location = 'test_finder_with_find_module' - def __init__(self, path): - if path != self.path_location: - raise ImportError - - @staticmethod - def find_module(fullname): - return None - - - with util.import_state(path=[Finder.path_location]+sys.path[:], - path_hooks=[Finder]): - self.machinery.PathFinder.find_module('importlib') - - -(Frozen_PEFTests, - Source_PEFTests - ) = util.test_both(PathEntryFinderTests, machinery=machinery) - - -if __name__ == '__main__': - unittest.main() diff --git a/Lib/test/test_importlib/import_/test_relative_imports.py b/Lib/test/test_importlib/import_/test_relative_imports.py deleted file mode 100644 index 41aa182..0000000 --- a/Lib/test/test_importlib/import_/test_relative_imports.py +++ /dev/null @@ -1,233 +0,0 @@ -"""Test relative imports (PEP 328).""" -from .. import util -import unittest -import warnings - - -class RelativeImports: - - """PEP 328 introduced relative imports. This allows for imports to occur - from within a package without having to specify the actual package name. - - A simple example is to import another module within the same package - [module from module]:: - - # From pkg.mod1 with pkg.mod2 being a module. - from . import mod2 - - This also works for getting an attribute from a module that is specified - in a relative fashion [attr from module]:: - - # From pkg.mod1. - from .mod2 import attr - - But this is in no way restricted to working between modules; it works - from [package to module],:: - - # From pkg, importing pkg.module which is a module. - from . import module - - [module to package],:: - - # Pull attr from pkg, called from pkg.module which is a module. - from . import attr - - and [package to package]:: - - # From pkg.subpkg1 (both pkg.subpkg[1,2] are packages). - from .. import subpkg2 - - The number of dots used is in no way restricted [deep import]:: - - # Import pkg.attr from pkg.pkg1.pkg2.pkg3.pkg4.pkg5. - from ...... import attr - - To prevent someone from accessing code that is outside of a package, one - cannot reach the location containing the root package itself:: - - # From pkg.__init__ [too high from package] - from .. import top_level - - # From pkg.module [too high from module] - from .. import top_level - - Relative imports are the only type of import that allow for an empty - module name for an import [empty name]. - - """ - - def relative_import_test(self, create, globals_, callback): - """Abstract out boilerplace for setting up for an import test.""" - uncache_names = [] - for name in create: - if not name.endswith('.__init__'): - uncache_names.append(name) - else: - uncache_names.append(name[:-len('.__init__')]) - with util.mock_spec(*create) as importer: - with util.import_state(meta_path=[importer]): - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - for global_ in globals_: - with util.uncache(*uncache_names): - callback(global_) - - - def test_module_from_module(self): - # [module from module] - create = 'pkg.__init__', 'pkg.mod2' - globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'} - def callback(global_): - self.__import__('pkg') # For __import__(). - module = self.__import__('', global_, fromlist=['mod2'], level=1) - self.assertEqual(module.__name__, 'pkg') - self.assertTrue(hasattr(module, 'mod2')) - self.assertEqual(module.mod2.attr, 'pkg.mod2') - self.relative_import_test(create, globals_, callback) - - def test_attr_from_module(self): - # [attr from module] - create = 'pkg.__init__', 'pkg.mod2' - globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'} - def callback(global_): - self.__import__('pkg') # For __import__(). - module = self.__import__('mod2', global_, fromlist=['attr'], - level=1) - self.assertEqual(module.__name__, 'pkg.mod2') - self.assertEqual(module.attr, 'pkg.mod2') - self.relative_import_test(create, globals_, callback) - - def test_package_to_module(self): - # [package to module] - create = 'pkg.__init__', 'pkg.module' - globals_ = ({'__package__': 'pkg'}, - {'__name__': 'pkg', '__path__': ['blah']}) - def callback(global_): - self.__import__('pkg') # For __import__(). - module = self.__import__('', global_, fromlist=['module'], - level=1) - self.assertEqual(module.__name__, 'pkg') - self.assertTrue(hasattr(module, 'module')) - self.assertEqual(module.module.attr, 'pkg.module') - self.relative_import_test(create, globals_, callback) - - def test_module_to_package(self): - # [module to package] - create = 'pkg.__init__', 'pkg.module' - globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'} - def callback(global_): - self.__import__('pkg') # For __import__(). - module = self.__import__('', global_, fromlist=['attr'], level=1) - self.assertEqual(module.__name__, 'pkg') - self.relative_import_test(create, globals_, callback) - - def test_package_to_package(self): - # [package to package] - create = ('pkg.__init__', 'pkg.subpkg1.__init__', - 'pkg.subpkg2.__init__') - globals_ = ({'__package__': 'pkg.subpkg1'}, - {'__name__': 'pkg.subpkg1', '__path__': ['blah']}) - def callback(global_): - module = self.__import__('', global_, fromlist=['subpkg2'], - level=2) - self.assertEqual(module.__name__, 'pkg') - self.assertTrue(hasattr(module, 'subpkg2')) - self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__') - self.relative_import_test(create, globals_, callback) - - def test_deep_import(self): - # [deep import] - create = ['pkg.__init__'] - for count in range(1,6): - create.append('{0}.pkg{1}.__init__'.format( - create[-1][:-len('.__init__')], count)) - globals_ = ({'__package__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5'}, - {'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5', - '__path__': ['blah']}) - def callback(global_): - self.__import__(globals_[0]['__package__']) - module = self.__import__('', global_, fromlist=['attr'], level=6) - self.assertEqual(module.__name__, 'pkg') - self.relative_import_test(create, globals_, callback) - - def test_too_high_from_package(self): - # [too high from package] - create = ['top_level', 'pkg.__init__'] - globals_ = ({'__package__': 'pkg'}, - {'__name__': 'pkg', '__path__': ['blah']}) - def callback(global_): - self.__import__('pkg') - with self.assertRaises(ImportError): - self.__import__('', global_, fromlist=['top_level'], - level=2) - self.relative_import_test(create, globals_, callback) - - def test_too_high_from_module(self): - # [too high from module] - create = ['top_level', 'pkg.__init__', 'pkg.module'] - globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'} - def callback(global_): - self.__import__('pkg') - with self.assertRaises(ImportError): - self.__import__('', global_, fromlist=['top_level'], - level=2) - self.relative_import_test(create, globals_, callback) - - def test_empty_name_w_level_0(self): - # [empty name] - with self.assertRaises(ValueError): - self.__import__('') - - def test_import_from_different_package(self): - # Test importing from a different package than the caller. - # in pkg.subpkg1.mod - # from ..subpkg2 import mod - create = ['__runpy_pkg__.__init__', - '__runpy_pkg__.__runpy_pkg__.__init__', - '__runpy_pkg__.uncle.__init__', - '__runpy_pkg__.uncle.cousin.__init__', - '__runpy_pkg__.uncle.cousin.nephew'] - globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'} - def callback(global_): - self.__import__('__runpy_pkg__.__runpy_pkg__') - module = self.__import__('uncle.cousin', globals_, {}, - fromlist=['nephew'], - level=2) - self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin') - self.relative_import_test(create, globals_, callback) - - def test_import_relative_import_no_fromlist(self): - # Import a relative module w/ no fromlist. - create = ['crash.__init__', 'crash.mod'] - globals_ = [{'__package__': 'crash', '__name__': 'crash'}] - def callback(global_): - self.__import__('crash') - mod = self.__import__('mod', global_, {}, [], 1) - self.assertEqual(mod.__name__, 'crash.mod') - self.relative_import_test(create, globals_, callback) - - def test_relative_import_no_globals(self): - # No globals for a relative import is an error. - with warnings.catch_warnings(): - warnings.simplefilter("ignore") - with self.assertRaises(KeyError): - self.__import__('sys', level=1) - - def test_relative_import_no_package(self): - with self.assertRaises(ImportError): - self.__import__('a', {'__package__': '', '__spec__': None}, - level=1) - - def test_relative_import_no_package_exists_absolute(self): - with self.assertRaises(ImportError): - self.__import__('sys', {'__package__': '', '__spec__': None}, - level=1) - - -(Frozen_RelativeImports, - Source_RelativeImports - ) = util.test_both(RelativeImports, __import__=util.__import__) - - -if __name__ == '__main__': - unittest.main() |