From bcb26c53c095c7bcd0e5415088e25dbd27f12592 Mon Sep 17 00:00:00 2001 From: Brett Cannon Date: Sun, 1 Feb 2009 04:00:05 +0000 Subject: Rename importlib.test.support to importlib.test.util. --- Lib/importlib/NOTES | 4 + Lib/importlib/test/builtin/test_finder.py | 6 +- Lib/importlib/test/builtin/test_loader.py | 6 +- .../test/extension/test_case_sensitivity.py | 12 +- Lib/importlib/test/extension/test_loader.py | 6 +- Lib/importlib/test/frozen/support.py | 24 ---- Lib/importlib/test/frozen/test_loader.py | 10 +- Lib/importlib/test/import_/test___package__.py | 40 +++--- Lib/importlib/test/import_/test_caching.py | 25 ++-- Lib/importlib/test/import_/test_fromlist.py | 57 ++++---- Lib/importlib/test/import_/test_meta_path.py | 34 ++--- Lib/importlib/test/import_/test_packages.py | 14 +- Lib/importlib/test/import_/test_path.py | 36 +++-- .../test/import_/test_relative_imports.py | 47 ++++--- Lib/importlib/test/source/test_case_sensitivity.py | 4 +- Lib/importlib/test/source/test_finder.py | 1 - Lib/importlib/test/source/test_loader.py | 1 - Lib/importlib/test/source/test_path_hook.py | 4 +- Lib/importlib/test/source/test_source_encoding.py | 1 - Lib/importlib/test/source/util.py | 4 +- Lib/importlib/test/support.py | 153 --------------------- Lib/importlib/test/test_api.py | 18 +-- Lib/importlib/test/util.py | 153 +++++++++++++++++++++ 23 files changed, 316 insertions(+), 344 deletions(-) delete mode 100644 Lib/importlib/test/frozen/support.py delete mode 100644 Lib/importlib/test/support.py create mode 100644 Lib/importlib/test/util.py diff --git a/Lib/importlib/NOTES b/Lib/importlib/NOTES index 8351f1e..fd3e0e3 100644 --- a/Lib/importlib/NOTES +++ b/Lib/importlib/NOTES @@ -3,6 +3,10 @@ to do * Reorganize support code. + + Separate out support code for extensions out of test_support_hook. + + Move util.import_ and utill.mock_modules to import_, importlib_only, + mock_path_hook? + + Add a file loader mock that returns monotonically increasing mtime. - Use in source/test_reload. - Use in source/test_load_module_mixed. diff --git a/Lib/importlib/test/builtin/test_finder.py b/Lib/importlib/test/builtin/test_finder.py index 70aed97..eacc36c 100644 --- a/Lib/importlib/test/builtin/test_finder.py +++ b/Lib/importlib/test/builtin/test_finder.py @@ -1,6 +1,6 @@ from importlib import machinery from .. import abc -from .. import support +from .. import util import sys import unittest @@ -14,7 +14,7 @@ class FinderTests(abc.FinderTests): def test_module(self): # Common case. - with support.uncache(self.name): + with util.uncache(self.name): self.assert_(machinery.BuiltinImporter.find_module(self.name)) def test_package(self): @@ -40,7 +40,7 @@ class FinderTests(abc.FinderTests): def test_ignore_path(self): # The value for 'path' should always trigger a failed import. - with support.uncache(self.name): + with util.uncache(self.name): loader = machinery.BuiltinImporter.find_module(self.name, ['pkg']) self.assert_(loader is None) diff --git a/Lib/importlib/test/builtin/test_loader.py b/Lib/importlib/test/builtin/test_loader.py index 3de0526..940529e 100644 --- a/Lib/importlib/test/builtin/test_loader.py +++ b/Lib/importlib/test/builtin/test_loader.py @@ -1,7 +1,7 @@ import importlib from importlib import machinery from .. import abc -from .. import support +from .. import util import sys import types @@ -29,7 +29,7 @@ class LoaderTests(abc.LoaderTests): def test_module(self): # Common case. - with support.uncache(self.name): + with util.uncache(self.name): module = self.load_module(self.name) self.verify(module) @@ -47,7 +47,7 @@ class LoaderTests(abc.LoaderTests): def test_module_reuse(self): # Test that the same module is used in a reload. - with support.uncache(self.name): + with util.uncache(self.name): module1 = self.load_module(self.name) module2 = self.load_module(self.name) self.assert_(module1 is module2) diff --git a/Lib/importlib/test/extension/test_case_sensitivity.py b/Lib/importlib/test/extension/test_case_sensitivity.py index 575bf69..c328af2 100644 --- a/Lib/importlib/test/extension/test_case_sensitivity.py +++ b/Lib/importlib/test/extension/test_case_sensitivity.py @@ -1,12 +1,12 @@ import sys -from test import support as test_support +from test import support import unittest import importlib -from .. import support +from .. import util from . import test_path_hook -@support.case_insensitive_tests +@util.case_insensitive_tests class ExtensionModuleCaseSensitivityTest(unittest.TestCase): def find_module(self): @@ -17,13 +17,13 @@ class ExtensionModuleCaseSensitivityTest(unittest.TestCase): return finder.find_module(bad_name) def test_case_sensitive(self): - with test_support.EnvironmentVarGuard() as env: + with support.EnvironmentVarGuard() as env: env.unset('PYTHONCASEOK') loader = self.find_module() self.assert_(loader is None) def test_case_insensitivity(self): - with test_support.EnvironmentVarGuard() as env: + with support.EnvironmentVarGuard() as env: env.set('PYTHONCASEOK', '1') loader = self.find_module() self.assert_(hasattr(loader, 'load_module')) @@ -32,7 +32,7 @@ class ExtensionModuleCaseSensitivityTest(unittest.TestCase): def test_main(): - test_support.run_unittest(ExtensionModuleCaseSensitivityTest) + support.run_unittest(ExtensionModuleCaseSensitivityTest) if __name__ == '__main__': diff --git a/Lib/importlib/test/extension/test_loader.py b/Lib/importlib/test/extension/test_loader.py index 51d6161..1e43fdd 100644 --- a/Lib/importlib/test/extension/test_loader.py +++ b/Lib/importlib/test/extension/test_loader.py @@ -1,7 +1,7 @@ import importlib from . import test_path_hook from .. import abc -from .. import support +from .. import util import sys import unittest @@ -18,7 +18,7 @@ class LoaderTests(abc.LoaderTests): return loader.load_module(fullname) def test_module(self): - with support.uncache(test_path_hook.NAME): + with util.uncache(test_path_hook.NAME): module = self.load_module(test_path_hook.NAME) for attr, value in [('__name__', test_path_hook.NAME), ('__file__', test_path_hook.FILEPATH)]: @@ -34,7 +34,7 @@ class LoaderTests(abc.LoaderTests): pass def test_module_reuse(self): - with support.uncache(test_path_hook.NAME): + with util.uncache(test_path_hook.NAME): module1 = self.load_module(test_path_hook.NAME) module2 = self.load_module(test_path_hook.NAME) self.assert_(module1 is module2) diff --git a/Lib/importlib/test/frozen/support.py b/Lib/importlib/test/frozen/support.py deleted file mode 100644 index e08b89e..0000000 --- a/Lib/importlib/test/frozen/support.py +++ /dev/null @@ -1,24 +0,0 @@ -import sys - - -class Null: - - """Just absorb what is given.""" - - def __getattr__(self): - return lambda *args, **kwargs: None - - -class SilenceStdout: - - """Silence sys.stdout.""" - - def setUp(self): - """Substitute sys.stdout with something that does not print to the - screen thanks to what bytecode is frozen.""" - sys.stdout = Null() - super().setUp() - - def tearDown(self): - sys.stdout = sys.__stdout__ - super().tearDown() diff --git a/Lib/importlib/test/frozen/test_loader.py b/Lib/importlib/test/frozen/test_loader.py index 63a9742..c6f4463 100644 --- a/Lib/importlib/test/frozen/test_loader.py +++ b/Lib/importlib/test/frozen/test_loader.py @@ -1,12 +1,12 @@ from importlib import machinery from .. import abc -from .. import support +from .. import util class LoaderTests(abc.LoaderTests): def test_module(self): - with support.uncache('__hello__'): + with util.uncache('__hello__'): module = machinery.FrozenImporter.load_module('__hello__') check = {'__name__': '__hello__', '__file__': '', '__package__': None} @@ -14,7 +14,7 @@ class LoaderTests(abc.LoaderTests): self.assertEqual(getattr(module, attr), value) def test_package(self): - with support.uncache('__phello__'): + with util.uncache('__phello__'): module = machinery.FrozenImporter.load_module('__phello__') check = {'__name__': '__phello__', '__file__': '', '__package__': '__phello__', '__path__': ['__phello__']} @@ -25,7 +25,7 @@ class LoaderTests(abc.LoaderTests): (attr, attr_value, value)) def test_lacking_parent(self): - with support.uncache('__phello__', '__phello__.spam'): + with util.uncache('__phello__', '__phello__.spam'): module = machinery.FrozenImporter.load_module('__phello__.spam') check = {'__name__': '__phello__.spam', '__file__': '', '__package__': '__phello__'} @@ -36,7 +36,7 @@ class LoaderTests(abc.LoaderTests): (attr, attr_value, value)) def test_module_reuse(self): - with support.uncache('__hello__'): + with util.uncache('__hello__'): module1 = machinery.FrozenImporter.load_module('__hello__') module2 = machinery.FrozenImporter.load_module('__hello__') self.assert_(module1 is module2) diff --git a/Lib/importlib/test/import_/test___package__.py b/Lib/importlib/test/import_/test___package__.py index 64dab3a..d29ca44 100644 --- a/Lib/importlib/test/import_/test___package__.py +++ b/Lib/importlib/test/import_/test___package__.py @@ -5,7 +5,7 @@ of using the typical __path__/__name__ test). """ import unittest -from .. import support +from .. import util class Using__package__(unittest.TestCase): @@ -34,19 +34,19 @@ class Using__package__(unittest.TestCase): def test_using___package__(self): # [__package__] - with support.mock_modules('pkg.__init__', 'pkg.fake') as importer: - with support.import_state(meta_path=[importer]): - support.import_('pkg.fake') - module = support.import_('', globals={'__package__': 'pkg.fake'}, + with util.mock_modules('pkg.__init__', 'pkg.fake') as importer: + with util.import_state(meta_path=[importer]): + util.import_('pkg.fake') + module = util.import_('', globals={'__package__': 'pkg.fake'}, fromlist=['attr'], level=2) self.assertEquals(module.__name__, 'pkg') def test_using___name__(self): # [__name__] - with support.mock_modules('pkg.__init__', 'pkg.fake') as importer: - with support.import_state(meta_path=[importer]): - support.import_('pkg.fake') - module = support.import_('', + with util.mock_modules('pkg.__init__', 'pkg.fake') as importer: + with util.import_state(meta_path=[importer]): + util.import_('pkg.fake') + module = util.import_('', globals={'__name__': 'pkg.fake', '__path__': []}, fromlist=['attr'], level=2) @@ -54,12 +54,12 @@ class Using__package__(unittest.TestCase): def test_bad__package__(self): globals = {'__package__': ''} - self.assertRaises(SystemError, support.import_,'', globals, {}, + self.assertRaises(SystemError, util.import_,'', globals, {}, ['relimport'], 1) def test_bunk__package__(self): globals = {'__package__': 42} - self.assertRaises(ValueError, support.import_, '', globals, {}, + self.assertRaises(ValueError, util.import_, '', globals, {}, ['relimport'], 1) @@ -77,26 +77,26 @@ class Setting__package__(unittest.TestCase): # [top-level] def test_top_level(self): - with support.mock_modules('top_level') as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules('top_level') as mock: + with util.import_state(meta_path=[mock]): del mock['top_level'].__package__ - module = support.import_('top_level') + module = util.import_('top_level') self.assert_(module.__package__ is None) # [package] def test_package(self): - with support.mock_modules('pkg.__init__') as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules('pkg.__init__') as mock: + with util.import_state(meta_path=[mock]): del mock['pkg'].__package__ - module = support.import_('pkg') + module = util.import_('pkg') self.assertEqual(module.__package__, 'pkg') # [submodule] def test_submodule(self): - with support.mock_modules('pkg.__init__', 'pkg.mod') as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules('pkg.__init__', 'pkg.mod') as mock: + with util.import_state(meta_path=[mock]): del mock['pkg.mod'].__package__ - pkg = support.import_('pkg.mod') + pkg = util.import_('pkg.mod') module = getattr(pkg, 'mod') self.assertEqual(module.__package__, 'pkg') diff --git a/Lib/importlib/test/import_/test_caching.py b/Lib/importlib/test/import_/test_caching.py index 57690d4..a4b7b46 100644 --- a/Lib/importlib/test/import_/test_caching.py +++ b/Lib/importlib/test/import_/test_caching.py @@ -1,6 +1,5 @@ """Test that sys.modules is used properly by import.""" -from ..support import import_, mock_modules, importlib_only, import_state - +from .. import util import sys from types import MethodType import unittest @@ -24,11 +23,11 @@ class UseCache(unittest.TestCase): # [use cache] module_to_use = "some module found!" sys.modules['some_module'] = module_to_use - module = import_('some_module') + module = util.import_('some_module') self.assertEqual(id(module_to_use), id(module)) def create_mock(self, *names, return_=None): - mock = mock_modules(*names) + mock = util.mock_modules(*names) original_load = mock.load_module def load_module(self, fullname): original_load(fullname) @@ -38,31 +37,31 @@ class UseCache(unittest.TestCase): # __import__ inconsistent between loaders and built-in import when it comes # to when to use the module in sys.modules and when not to. - @importlib_only + @util.importlib_only def test_using_cache_after_loader(self): # [from cache on return] with self.create_mock('module') as mock: - with import_state(meta_path=[mock]): - module = import_('module') + with util.import_state(meta_path=[mock]): + module = util.import_('module') self.assertEquals(id(module), id(sys.modules['module'])) # See test_using_cache_after_loader() for reasoning. - @importlib_only + @util.importlib_only def test_using_cache_for_assigning_to_attribute(self): # [from cache to attribute] with self.create_mock('pkg.__init__', 'pkg.module') as importer: - with import_state(meta_path=[importer]): - module = import_('pkg.module') + with util.import_state(meta_path=[importer]): + module = util.import_('pkg.module') self.assert_(hasattr(module, 'module')) self.assert_(id(module.module), id(sys.modules['pkg.module'])) # See test_using_cache_after_loader() for reasoning. - @importlib_only + @util.importlib_only def test_using_cache_for_fromlist(self): # [from cache for fromlist] with self.create_mock('pkg.__init__', 'pkg.module') as importer: - with import_state(meta_path=[importer]): - module = import_('pkg', fromlist=['module']) + with util.import_state(meta_path=[importer]): + module = util.import_('pkg', fromlist=['module']) self.assert_(hasattr(module, 'module')) self.assertEquals(id(module.module), id(sys.modules['pkg.module'])) diff --git a/Lib/importlib/test/import_/test_fromlist.py b/Lib/importlib/test/import_/test_fromlist.py index 884b516..4e0d86a 100644 --- a/Lib/importlib/test/import_/test_fromlist.py +++ b/Lib/importlib/test/import_/test_fromlist.py @@ -1,6 +1,5 @@ """Test that the semantics relating to the 'fromlist' argument are correct.""" -from ..support import import_, mock_modules, import_state - +from .. import util import unittest class ReturnValue(unittest.TestCase): @@ -16,16 +15,16 @@ class ReturnValue(unittest.TestCase): def test_return_from_import(self): # [import return] - with mock_modules('pkg.__init__', 'pkg.module') as importer: - with import_state(meta_path=[importer]): - module = import_('pkg.module') + with util.mock_modules('pkg.__init__', 'pkg.module') as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('pkg.module') self.assertEquals(module.__name__, 'pkg') def test_return_from_from_import(self): # [from return] - with mock_modules('pkg.__init__', 'pkg.module')as importer: - with import_state(meta_path=[importer]): - module = import_('pkg.module', fromlist=['attr']) + with util.mock_modules('pkg.__init__', 'pkg.module')as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('pkg.module', fromlist=['attr']) self.assertEquals(module.__name__, 'pkg.module') @@ -48,59 +47,59 @@ class HandlingFromlist(unittest.TestCase): def test_object(self): # [object case] - with mock_modules('module') as importer: - with import_state(meta_path=[importer]): - module = import_('module', fromlist=['attr']) + with util.mock_modules('module') as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('module', fromlist=['attr']) self.assertEquals(module.__name__, 'module') def test_unexistent_object(self): # [bad object] - with mock_modules('module') as importer: - with import_state(meta_path=[importer]): - module = import_('module', fromlist=['non_existent']) + with util.mock_modules('module') as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('module', fromlist=['non_existent']) self.assertEquals(module.__name__, 'module') self.assert_(not hasattr(module, 'non_existent')) def test_module_from_package(self): # [module] - with mock_modules('pkg.__init__', 'pkg.module') as importer: - with import_state(meta_path=[importer]): - module = import_('pkg', fromlist=['module']) + with util.mock_modules('pkg.__init__', 'pkg.module') as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('pkg', fromlist=['module']) self.assertEquals(module.__name__, 'pkg') self.assert_(hasattr(module, 'module')) self.assertEquals(module.module.__name__, 'pkg.module') def test_no_module_from_package(self): # [no module] - with mock_modules('pkg.__init__') as importer: - with import_state(meta_path=[importer]): - module = import_('pkg', fromlist='non_existent') + with util.mock_modules('pkg.__init__') as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('pkg', fromlist='non_existent') self.assertEquals(module.__name__, 'pkg') self.assert_(not hasattr(module, 'non_existent')) def test_empty_string(self): - with mock_modules('pkg.__init__', 'pkg.mod') as importer: - with import_state(meta_path=[importer]): - module = import_('pkg.mod', fromlist=['']) + with util.mock_modules('pkg.__init__', 'pkg.mod') as importer: + with util.import_state(meta_path=[importer]): + module = util.import_('pkg.mod', fromlist=['']) self.assertEquals(module.__name__, 'pkg.mod') def test_using_star(self): # [using *] - with mock_modules('pkg.__init__', 'pkg.module') as mock: - with import_state(meta_path=[mock]): + with util.mock_modules('pkg.__init__', 'pkg.module') as mock: + with util.import_state(meta_path=[mock]): mock['pkg'].__all__ = ['module'] - module = import_('pkg', fromlist=['*']) + module = util.import_('pkg', fromlist=['*']) self.assertEquals(module.__name__, 'pkg') self.assert_(hasattr(module, 'module')) self.assertEqual(module.module.__name__, 'pkg.module') def test_star_with_others(self): # [using * with others] - context = mock_modules('pkg.__init__', 'pkg.module1', 'pkg.module2') + context = util.mock_modules('pkg.__init__', 'pkg.module1', 'pkg.module2') with context as mock: - with import_state(meta_path=[mock]): + with util.import_state(meta_path=[mock]): mock['pkg'].__all__ = ['module1'] - module = import_('pkg', fromlist=['module2', '*']) + module = util.import_('pkg', fromlist=['module2', '*']) self.assertEquals(module.__name__, 'pkg') self.assert_(hasattr(module, 'module1')) self.assert_(hasattr(module, 'module2')) diff --git a/Lib/importlib/test/import_/test_meta_path.py b/Lib/importlib/test/import_/test_meta_path.py index 37f40d7..a7b2591 100644 --- a/Lib/importlib/test/import_/test_meta_path.py +++ b/Lib/importlib/test/import_/test_meta_path.py @@ -1,5 +1,4 @@ -from ..support import import_state, mock_modules, import_ - +from .. import util from contextlib import nested from types import MethodType import unittest @@ -16,24 +15,25 @@ class CallingOrder(unittest.TestCase): def test_first_called(self): # [first called] mod = 'top_level' - first = mock_modules(mod) - second = mock_modules(mod) - with nested(mock_modules(mod), mock_modules(mod)) as (first, second): + first = util.mock_modules(mod) + second = util.mock_modules(mod) + context = nested(util.mock_modules(mod), util.mock_modules(mod)) + with context as (first, second): first.modules[mod] = 42 second.modules[mod] = -13 - with import_state(meta_path=[first, second]): - self.assertEquals(import_(mod), 42) + with util.import_state(meta_path=[first, second]): + self.assertEquals(util.import_(mod), 42) def test_continuing(self): # [continuing] mod_name = 'for_real' - first = mock_modules('nonexistent') - second = mock_modules(mod_name) + first = util.mock_modules('nonexistent') + second = util.mock_modules(mod_name) with nested(first, second): first.find_module = lambda self, fullname, path=None: None second.modules[mod_name] = 42 - with import_state(meta_path=[first, second]): - self.assertEquals(import_(mod_name), 42) + with util.import_state(meta_path=[first, second]): + self.assertEquals(util.import_(mod_name), 42) class CallSignature(unittest.TestCase): @@ -54,11 +54,11 @@ class CallSignature(unittest.TestCase): # [no path] mod_name = 'top_level' assert '.' not in mod_name - with mock_modules(mod_name) as importer: + with util.mock_modules(mod_name) as importer: log, wrapped_call = self.log(importer.find_module) importer.find_module = MethodType(wrapped_call, importer) - with import_state(meta_path=[importer]): - import_(mod_name) + with util.import_state(meta_path=[importer]): + util.import_(mod_name) assert len(log) == 1 args = log[0][0] kwargs = log[0][1] @@ -74,12 +74,12 @@ class CallSignature(unittest.TestCase): mod_name = pkg_name + '.module' path = [42] assert '.' in mod_name - with mock_modules(pkg_name+'.__init__', mod_name) as importer: + with util.mock_modules(pkg_name+'.__init__', mod_name) as importer: importer.modules[pkg_name].__path__ = path log, wrapped_call = self.log(importer.find_module) importer.find_module = MethodType(wrapped_call, importer) - with import_state(meta_path=[importer]): - import_(mod_name) + with util.import_state(meta_path=[importer]): + util.import_(mod_name) assert len(log) == 2 args = log[1][0] kwargs = log[1][1] diff --git a/Lib/importlib/test/import_/test_packages.py b/Lib/importlib/test/import_/test_packages.py index 013bbdc..7f17c4b 100644 --- a/Lib/importlib/test/import_/test_packages.py +++ b/Lib/importlib/test/import_/test_packages.py @@ -1,7 +1,7 @@ +from .. import util import sys import unittest import importlib -from .. import support class ParentModuleTests(unittest.TestCase): @@ -9,15 +9,15 @@ class ParentModuleTests(unittest.TestCase): """Importing a submodule should import the parent modules.""" def test_import_parent(self): - with support.mock_modules('pkg.__init__', 'pkg.module') as mock: - with support.import_state(meta_path=[mock]): - module = support.import_('pkg.module') + with util.mock_modules('pkg.__init__', 'pkg.module') as mock: + with util.import_state(meta_path=[mock]): + module = util.import_('pkg.module') self.assert_('pkg' in sys.modules) def test_bad_parent(self): - with support.mock_modules('pkg.module') as mock: - with support.import_state(meta_path=[mock]): - self.assertRaises(ImportError, support.import_, 'pkg.module') + with util.mock_modules('pkg.module') as mock: + with util.import_state(meta_path=[mock]): + self.assertRaises(ImportError, util.import_, 'pkg.module') def test_main(): diff --git a/Lib/importlib/test/import_/test_path.py b/Lib/importlib/test/import_/test_path.py index c939907..5935dc4 100644 --- a/Lib/importlib/test/import_/test_path.py +++ b/Lib/importlib/test/import_/test_path.py @@ -1,6 +1,4 @@ -from ..support import (mock_modules, import_state, import_, mock_path_hook, - importlib_only, uncache) - +from .. import util from contextlib import nested from imp import new_module import sys @@ -32,7 +30,7 @@ class BaseTests(unittest.TestCase): def order_test(self, to_import, entry, search_path, path=[]): # [order] log = [] - class LogFindModule(mock_modules): + class LogFindModule(util.mock_modules): def find_module(self, fullname): log.append(self) return super().find_module(fullname) @@ -42,12 +40,12 @@ class BaseTests(unittest.TestCase): hitter = LogFindModule(to_import) with nested(misser, hitter): cache = dict(zip(search_path, (misser, hitter))) - with import_state(path=path, path_importer_cache=cache): - import_(to_import) + with util.import_state(path=path, path_importer_cache=cache): + util.import_(to_import) self.assertEquals(log[0], misser) self.assertEquals(log[1], hitter) - @importlib_only # __import__ uses PyDict_GetItem(), bypassing log. + @util.importlib_only # __import__ uses PyDict_GetItem(), bypassing log. def cache_use_test(self, to_import, entry, path=[]): # [cache check], [cache use] log = [] @@ -56,11 +54,11 @@ class BaseTests(unittest.TestCase): log.append(item) return super(LoggingDict, self).__getitem__(item) - with mock_modules(to_import) as importer: + with util.mock_modules(to_import) as importer: cache = LoggingDict() cache[entry] = importer - with import_state(path=[entry], path_importer_cache=cache): - module = import_(to_import, fromlist=['a']) + with util.import_state(path=[entry], path_importer_cache=cache): + module = util.import_(to_import, fromlist=['a']) self.assert_(module is importer[to_import]) self.assertEquals(len(cache), 1) self.assertEquals([entry], log) @@ -71,11 +69,11 @@ class BaseTests(unittest.TestCase): def logging_hook(entry): log.append(entry) raise ImportError - with mock_modules(to_import) as importer: - hitter = mock_path_hook(entry, importer=importer) + with util.mock_modules(to_import) as importer: + hitter = util.mock_path_hook(entry, importer=importer) path_hooks = [logging_hook, logging_hook, hitter] - with import_state(path_hooks=path_hooks, path=path): - import_(to_import) + with util.import_state(path_hooks=path_hooks, path=path): + util.import_(to_import) self.assertEquals(sys.path_importer_cache[entry], importer) self.assertEquals(len(log), 2) @@ -90,7 +88,7 @@ class BaseTests(unittest.TestCase): raise ImportError try: - import_(to_import) + util.import_(to_import) except ImportError: pass @@ -113,7 +111,7 @@ class PathTests(BaseTests): def test_path_argument(self): name = 'total junk' - with uncache(name): + with util.uncache(name): self.path_argument_test(name) @@ -122,13 +120,13 @@ class __path__Tests(BaseTests): """Tests for __path__.""" def run_test(self, test, entry, path, *args): - with mock_modules('pkg.__init__') as importer: + with util.mock_modules('pkg.__init__') as importer: importer['pkg'].__path__ = path importer.load_module('pkg') test('pkg.hit', entry, *args) - @importlib_only # XXX Unknown reason why this fails. + @util.importlib_only # XXX Unknown reason why this fails. def test_order(self): self.run_test(self.order_test, 'second', ('first', 'second'), ['first', 'second']) @@ -146,7 +144,7 @@ class __path__Tests(BaseTests): module.__path__ = ['random __path__'] name = 'pkg.whatever' sys.modules['pkg'] = module - with uncache('pkg', name): + with util.uncache('pkg', name): self.path_argument_test(name) diff --git a/Lib/importlib/test/import_/test_relative_imports.py b/Lib/importlib/test/import_/test_relative_imports.py index 73ef530..fb543ad 100644 --- a/Lib/importlib/test/import_/test_relative_imports.py +++ b/Lib/importlib/test/import_/test_relative_imports.py @@ -1,7 +1,5 @@ """Test relative imports (PEP 328).""" - -from ..support import uncache, import_, mock_modules, import_state - +from .. import util import sys import unittest @@ -65,10 +63,10 @@ class RelativeImports(unittest.TestCase): uncache_names.append(name) else: uncache_names.append(name[:-len('.__init__')]) - with mock_modules(*create) as importer: - with import_state(meta_path=[importer]): + with util.mock_modules(*create) as importer: + with util.import_state(meta_path=[importer]): for global_ in globals_: - with uncache(*uncache_names): + with util.uncache(*uncache_names): callback(global_) @@ -77,8 +75,8 @@ class RelativeImports(unittest.TestCase): create = 'pkg.__init__', 'pkg.mod2' globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'} def callback(global_): - import_('pkg') # For __import__(). - module = import_('', global_, fromlist=['mod2'], level=1) + util.import_('pkg') # For __import__(). + module = util.import_('', global_, fromlist=['mod2'], level=1) self.assertEqual(module.__name__, 'pkg') self.assert_(hasattr(module, 'mod2')) self.assertEqual(module.mod2.attr, 'pkg.mod2') @@ -89,8 +87,8 @@ class RelativeImports(unittest.TestCase): create = 'pkg.__init__', 'pkg.mod2' globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'} def callback(global_): - import_('pkg') # For __import__(). - module = import_('mod2', global_, fromlist=['attr'], level=1) + util.import_('pkg') # For __import__(). + module = util.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) @@ -101,8 +99,8 @@ class RelativeImports(unittest.TestCase): globals_ = ({'__package__': 'pkg'}, {'__name__': 'pkg', '__path__': ['blah']}) def callback(global_): - import_('pkg') # For __import__(). - module = import_('', global_, fromlist=['module'], + util.import_('pkg') # For __import__(). + module = util.import_('', global_, fromlist=['module'], level=1) self.assertEqual(module.__name__, 'pkg') self.assert_(hasattr(module, 'module')) @@ -114,8 +112,8 @@ class RelativeImports(unittest.TestCase): create = 'pkg.__init__', 'pkg.module' globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'} def callback(global_): - import_('pkg') # For __import__(). - module = import_('', global_, fromlist=['attr'], level=1) + util.import_('pkg') # For __import__(). + module = util.import_('', global_, fromlist=['attr'], level=1) self.assertEqual(module.__name__, 'pkg') self.relative_import_test(create, globals_, callback) @@ -126,7 +124,7 @@ class RelativeImports(unittest.TestCase): globals_ = ({'__package__': 'pkg.subpkg1'}, {'__name__': 'pkg.subpkg1', '__path__': ['blah']}) def callback(global_): - module = import_('', global_, fromlist=['subpkg2'], level=2) + module = util.import_('', global_, fromlist=['subpkg2'], level=2) self.assertEqual(module.__name__, 'pkg') self.assert_(hasattr(module, 'subpkg2')) self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__') @@ -141,8 +139,8 @@ class RelativeImports(unittest.TestCase): {'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5', '__path__': ['blah']}) def callback(global_): - import_(globals_[0]['__package__']) - module = import_('', global_, fromlist=['attr'], level=6) + util.import_(globals_[0]['__package__']) + module = util.import_('', global_, fromlist=['attr'], level=6) self.assertEqual(module.__name__, 'pkg') self.relative_import_test(create, globals_, callback) @@ -152,8 +150,8 @@ class RelativeImports(unittest.TestCase): globals_ = ({'__package__': 'pkg'}, {'__name__': 'pkg', '__path__': ['blah']}) def callback(global_): - import_('pkg') - self.assertRaises(ValueError, import_, '', global_, + util.import_('pkg') + self.assertRaises(ValueError, util.import_, '', global_, fromlist=['top_level'], level=2) self.relative_import_test(create, globals_, callback) @@ -162,14 +160,14 @@ class RelativeImports(unittest.TestCase): create = ['top_level', 'pkg.__init__', 'pkg.module'] globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'} def callback(global_): - import_('pkg') - self.assertRaises(ValueError, import_, '', global_, + util.import_('pkg') + self.assertRaises(ValueError, util.import_, '', global_, fromlist=['top_level'], level=2) self.relative_import_test(create, globals_, callback) def test_empty_name_w_level_0(self): # [empty name] - self.assertRaises(ValueError, import_, '') + self.assertRaises(ValueError, util.import_, '') def test_import_from_different_package(self): # Test importing from a different package than the caller. @@ -183,8 +181,9 @@ class RelativeImports(unittest.TestCase): '__runpy_pkg__.uncle.cousin.nephew'] globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'} def callback(global_): - import_('__runpy_pkg__.__runpy_pkg__') - module = import_('uncle.cousin', globals_, {}, fromlist=['nephew'], + util.import_('__runpy_pkg__.__runpy_pkg__') + module = util.import_('uncle.cousin', globals_, {}, + fromlist=['nephew'], level=2) self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin') self.relative_import_test(create, globals_, callback) diff --git a/Lib/importlib/test/source/test_case_sensitivity.py b/Lib/importlib/test/source/test_case_sensitivity.py index 955d6ec..6bd86cf 100644 --- a/Lib/importlib/test/source/test_case_sensitivity.py +++ b/Lib/importlib/test/source/test_case_sensitivity.py @@ -1,6 +1,6 @@ """Test case-sensitivity (PEP 235).""" import importlib -from .. import support +from .. import util from . import util as source_util import os import sys @@ -8,7 +8,7 @@ from test import support as test_support import unittest -@support.case_insensitive_tests +@util.case_insensitive_tests class CaseSensitivityTest(unittest.TestCase): """PEP 235 dictates that on case-preserving, case-insensitive file systems diff --git a/Lib/importlib/test/source/test_finder.py b/Lib/importlib/test/source/test_finder.py index a84d914..0f1f549 100644 --- a/Lib/importlib/test/source/test_finder.py +++ b/Lib/importlib/test/source/test_finder.py @@ -1,6 +1,5 @@ import importlib from .. import abc -from .. import support from . import util as source_util import os import py_compile diff --git a/Lib/importlib/test/source/test_loader.py b/Lib/importlib/test/source/test_loader.py index 67930fc..e333b85 100644 --- a/Lib/importlib/test/source/test_loader.py +++ b/Lib/importlib/test/source/test_loader.py @@ -1,6 +1,5 @@ import importlib from .. import abc -from .. import support from . import util as source_util import imp diff --git a/Lib/importlib/test/source/test_path_hook.py b/Lib/importlib/test/source/test_path_hook.py index 5fa3fd9..5aac42e 100644 --- a/Lib/importlib/test/source/test_path_hook.py +++ b/Lib/importlib/test/source/test_path_hook.py @@ -1,5 +1,5 @@ import importlib -from . import util +from . import util as source_util import unittest @@ -9,7 +9,7 @@ class PathHookTest(unittest.TestCase): def test_success(self): # XXX Only work on existing directories? - with util.create_modules('dummy') as mapping: + with source_util.create_modules('dummy') as mapping: self.assert_(hasattr(importlib.FileImporter(mapping['.root']), 'find_module')) diff --git a/Lib/importlib/test/source/test_source_encoding.py b/Lib/importlib/test/source/test_source_encoding.py index 7c9a57b..5ffdf8f 100644 --- a/Lib/importlib/test/source/test_source_encoding.py +++ b/Lib/importlib/test/source/test_source_encoding.py @@ -1,5 +1,4 @@ import importlib -from .. import support from . import util as source_util import codecs diff --git a/Lib/importlib/test/source/util.py b/Lib/importlib/test/source/util.py index 5400c82..333647d 100644 --- a/Lib/importlib/test/source/util.py +++ b/Lib/importlib/test/source/util.py @@ -1,11 +1,11 @@ -from .. import support as util +from .. import util import contextlib import imp import os import os.path import sys import tempfile -from test import support as support +from test import support def writes_bytecode(fxn): diff --git a/Lib/importlib/test/support.py b/Lib/importlib/test/support.py deleted file mode 100644 index 1518d74..0000000 --- a/Lib/importlib/test/support.py +++ /dev/null @@ -1,153 +0,0 @@ -from importlib import Import - -from contextlib import contextmanager -from functools import update_wrapper -import imp -import os.path -from test.support import unlink -import sys - - -using___import__ = False - -def import_(*args, **kwargs): - """Delegate to allow for injecting different implementations of import.""" - if using___import__: - return __import__(*args, **kwargs) - return Import()(*args, **kwargs) - -def importlib_only(fxn): - """Decorator to mark which tests are not supported by the current - implementation of __import__().""" - def inner(*args, **kwargs): - if using___import__: - return - else: - return fxn(*args, **kwargs) - update_wrapper(inner, fxn) - return inner - - -def case_insensitive_tests(class_): - """Class decorator that nullifies tests that require a case-insensitive - file system.""" - if sys.platform not in ('win32', 'darwin', 'cygwin'): - return object() - else: - return class_ - - -@contextmanager -def uncache(*names): - """Uncache a module from sys.modules. - - A basic sanity check is performed to prevent uncaching modules that either - cannot/shouldn't be uncached. - - """ - for name in names: - if name in ('sys', 'marshal', 'imp'): - raise ValueError( - "cannot uncache {0} as it will break _importlib".format(name)) - try: - del sys.modules[name] - except KeyError: - pass - try: - yield - finally: - for name in names: - try: - del sys.modules[name] - except KeyError: - pass - -@contextmanager -def import_state(**kwargs): - """Context manager to manage the various importers and stored state in the - sys module. - - The 'modules' attribute is not supported as the interpreter state stores a - pointer to the dict that the interpreter uses internally; - reassigning to sys.modules does not have the desired effect. - - """ - originals = {} - try: - for attr, default in (('meta_path', []), ('path', []), - ('path_hooks', []), - ('path_importer_cache', {})): - originals[attr] = getattr(sys, attr) - if attr in kwargs: - new_value = kwargs[attr] - del kwargs[attr] - else: - new_value = default - setattr(sys, attr, new_value) - if len(kwargs): - raise ValueError( - 'unrecognized arguments: {0}'.format(kwargs.keys())) - yield - finally: - for attr, value in originals.items(): - setattr(sys, attr, value) - - -class mock_modules: - - """A mock importer/loader.""" - - def __init__(self, *names): - self.modules = {} - for name in names: - if not name.endswith('.__init__'): - import_name = name - else: - import_name = name[:-len('.__init__')] - if '.' not in name: - package = None - elif import_name == name: - package = name.rsplit('.', 1)[0] - else: - package = import_name - module = imp.new_module(import_name) - module.__loader__ = self - module.__file__ = '' - module.__package__ = package - module.attr = name - if import_name != name: - module.__path__ = [''] - self.modules[import_name] = module - - def __getitem__(self, name): - return self.modules[name] - - def find_module(self, fullname, path=None): - if fullname not in self.modules: - return None - else: - return self - - def load_module(self, fullname): - if fullname not in self.modules: - raise ImportError - else: - sys.modules[fullname] = self.modules[fullname] - return self.modules[fullname] - - 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) - - -def mock_path_hook(*entries, importer): - """A mock sys.path_hooks entry.""" - def hook(entry): - if entry not in entries: - raise ImportError - return importer - return hook diff --git a/Lib/importlib/test/test_api.py b/Lib/importlib/test/test_api.py index 75053a0..2958adb 100644 --- a/Lib/importlib/test/test_api.py +++ b/Lib/importlib/test/test_api.py @@ -1,6 +1,6 @@ import unittest import importlib -from . import support +from . import util class ImportModuleTests(unittest.TestCase): @@ -9,8 +9,8 @@ class ImportModuleTests(unittest.TestCase): def test_module_import(self): # Test importing a top-level module. - with support.mock_modules('top_level') as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules('top_level') as mock: + with util.import_state(meta_path=[mock]): module = importlib.import_module('top_level') self.assertEqual(module.__name__, 'top_level') @@ -19,8 +19,8 @@ class ImportModuleTests(unittest.TestCase): pkg_name = 'pkg' pkg_long_name = '{0}.__init__'.format(pkg_name) name = '{0}.mod'.format(pkg_name) - with support.mock_modules(pkg_long_name, name) as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules(pkg_long_name, name) as mock: + with util.import_state(meta_path=[mock]): module = importlib.import_module(name) self.assertEqual(module.__name__, name) @@ -31,8 +31,8 @@ class ImportModuleTests(unittest.TestCase): module_name = 'mod' absolute_name = '{0}.{1}'.format(pkg_name, module_name) relative_name = '.{0}'.format(module_name) - with support.mock_modules(pkg_long_name, absolute_name) as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules(pkg_long_name, absolute_name) as mock: + with util.import_state(meta_path=[mock]): module = importlib.import_module(relative_name, pkg_name) self.assertEqual(module.__name__, absolute_name) @@ -42,8 +42,8 @@ class ImportModuleTests(unittest.TestCase): pkg_name = 'pkg' pkg_long_name = '{0}.__init__'.format(pkg_name) name = '{0}.mod'.format(pkg_name) - with support.mock_modules(pkg_long_name, name) as mock: - with support.import_state(meta_path=[mock]): + with util.mock_modules(pkg_long_name, name) as mock: + with util.import_state(meta_path=[mock]): module = importlib.import_module(name, pkg_name) self.assertEqual(module.__name__, name) diff --git a/Lib/importlib/test/util.py b/Lib/importlib/test/util.py new file mode 100644 index 0000000..1518d74 --- /dev/null +++ b/Lib/importlib/test/util.py @@ -0,0 +1,153 @@ +from importlib import Import + +from contextlib import contextmanager +from functools import update_wrapper +import imp +import os.path +from test.support import unlink +import sys + + +using___import__ = False + +def import_(*args, **kwargs): + """Delegate to allow for injecting different implementations of import.""" + if using___import__: + return __import__(*args, **kwargs) + return Import()(*args, **kwargs) + +def importlib_only(fxn): + """Decorator to mark which tests are not supported by the current + implementation of __import__().""" + def inner(*args, **kwargs): + if using___import__: + return + else: + return fxn(*args, **kwargs) + update_wrapper(inner, fxn) + return inner + + +def case_insensitive_tests(class_): + """Class decorator that nullifies tests that require a case-insensitive + file system.""" + if sys.platform not in ('win32', 'darwin', 'cygwin'): + return object() + else: + return class_ + + +@contextmanager +def uncache(*names): + """Uncache a module from sys.modules. + + A basic sanity check is performed to prevent uncaching modules that either + cannot/shouldn't be uncached. + + """ + for name in names: + if name in ('sys', 'marshal', 'imp'): + raise ValueError( + "cannot uncache {0} as it will break _importlib".format(name)) + try: + del sys.modules[name] + except KeyError: + pass + try: + yield + finally: + for name in names: + try: + del sys.modules[name] + except KeyError: + pass + +@contextmanager +def import_state(**kwargs): + """Context manager to manage the various importers and stored state in the + sys module. + + The 'modules' attribute is not supported as the interpreter state stores a + pointer to the dict that the interpreter uses internally; + reassigning to sys.modules does not have the desired effect. + + """ + originals = {} + try: + for attr, default in (('meta_path', []), ('path', []), + ('path_hooks', []), + ('path_importer_cache', {})): + originals[attr] = getattr(sys, attr) + if attr in kwargs: + new_value = kwargs[attr] + del kwargs[attr] + else: + new_value = default + setattr(sys, attr, new_value) + if len(kwargs): + raise ValueError( + 'unrecognized arguments: {0}'.format(kwargs.keys())) + yield + finally: + for attr, value in originals.items(): + setattr(sys, attr, value) + + +class mock_modules: + + """A mock importer/loader.""" + + def __init__(self, *names): + self.modules = {} + for name in names: + if not name.endswith('.__init__'): + import_name = name + else: + import_name = name[:-len('.__init__')] + if '.' not in name: + package = None + elif import_name == name: + package = name.rsplit('.', 1)[0] + else: + package = import_name + module = imp.new_module(import_name) + module.__loader__ = self + module.__file__ = '' + module.__package__ = package + module.attr = name + if import_name != name: + module.__path__ = [''] + self.modules[import_name] = module + + def __getitem__(self, name): + return self.modules[name] + + def find_module(self, fullname, path=None): + if fullname not in self.modules: + return None + else: + return self + + def load_module(self, fullname): + if fullname not in self.modules: + raise ImportError + else: + sys.modules[fullname] = self.modules[fullname] + return self.modules[fullname] + + 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) + + +def mock_path_hook(*entries, importer): + """A mock sys.path_hooks entry.""" + def hook(entry): + if entry not in entries: + raise ImportError + return importer + return hook -- cgit v0.12