Kaydet (Commit) bcb26c53 authored tarafından Brett Cannon's avatar Brett Cannon

Rename importlib.test.support to importlib.test.util.

üst ae9ad186
...@@ -3,6 +3,10 @@ to do ...@@ -3,6 +3,10 @@ to do
* Reorganize support code. * 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. + Add a file loader mock that returns monotonically increasing mtime.
- Use in source/test_reload. - Use in source/test_reload.
- Use in source/test_load_module_mixed. - Use in source/test_load_module_mixed.
......
from importlib import machinery from importlib import machinery
from .. import abc from .. import abc
from .. import support from .. import util
import sys import sys
import unittest import unittest
...@@ -14,7 +14,7 @@ class FinderTests(abc.FinderTests): ...@@ -14,7 +14,7 @@ class FinderTests(abc.FinderTests):
def test_module(self): def test_module(self):
# Common case. # Common case.
with support.uncache(self.name): with util.uncache(self.name):
self.assert_(machinery.BuiltinImporter.find_module(self.name)) self.assert_(machinery.BuiltinImporter.find_module(self.name))
def test_package(self): def test_package(self):
...@@ -40,7 +40,7 @@ class FinderTests(abc.FinderTests): ...@@ -40,7 +40,7 @@ class FinderTests(abc.FinderTests):
def test_ignore_path(self): def test_ignore_path(self):
# The value for 'path' should always trigger a failed import. # 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']) loader = machinery.BuiltinImporter.find_module(self.name, ['pkg'])
self.assert_(loader is None) self.assert_(loader is None)
......
import importlib import importlib
from importlib import machinery from importlib import machinery
from .. import abc from .. import abc
from .. import support from .. import util
import sys import sys
import types import types
...@@ -29,7 +29,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -29,7 +29,7 @@ class LoaderTests(abc.LoaderTests):
def test_module(self): def test_module(self):
# Common case. # Common case.
with support.uncache(self.name): with util.uncache(self.name):
module = self.load_module(self.name) module = self.load_module(self.name)
self.verify(module) self.verify(module)
...@@ -47,7 +47,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -47,7 +47,7 @@ class LoaderTests(abc.LoaderTests):
def test_module_reuse(self): def test_module_reuse(self):
# Test that the same module is used in a reload. # 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) module1 = self.load_module(self.name)
module2 = self.load_module(self.name) module2 = self.load_module(self.name)
self.assert_(module1 is module2) self.assert_(module1 is module2)
......
import sys import sys
from test import support as test_support from test import support
import unittest import unittest
import importlib import importlib
from .. import support from .. import util
from . import test_path_hook from . import test_path_hook
@support.case_insensitive_tests @util.case_insensitive_tests
class ExtensionModuleCaseSensitivityTest(unittest.TestCase): class ExtensionModuleCaseSensitivityTest(unittest.TestCase):
def find_module(self): def find_module(self):
...@@ -17,13 +17,13 @@ class ExtensionModuleCaseSensitivityTest(unittest.TestCase): ...@@ -17,13 +17,13 @@ class ExtensionModuleCaseSensitivityTest(unittest.TestCase):
return finder.find_module(bad_name) return finder.find_module(bad_name)
def test_case_sensitive(self): def test_case_sensitive(self):
with test_support.EnvironmentVarGuard() as env: with support.EnvironmentVarGuard() as env:
env.unset('PYTHONCASEOK') env.unset('PYTHONCASEOK')
loader = self.find_module() loader = self.find_module()
self.assert_(loader is None) self.assert_(loader is None)
def test_case_insensitivity(self): def test_case_insensitivity(self):
with test_support.EnvironmentVarGuard() as env: with support.EnvironmentVarGuard() as env:
env.set('PYTHONCASEOK', '1') env.set('PYTHONCASEOK', '1')
loader = self.find_module() loader = self.find_module()
self.assert_(hasattr(loader, 'load_module')) self.assert_(hasattr(loader, 'load_module'))
...@@ -32,7 +32,7 @@ class ExtensionModuleCaseSensitivityTest(unittest.TestCase): ...@@ -32,7 +32,7 @@ class ExtensionModuleCaseSensitivityTest(unittest.TestCase):
def test_main(): def test_main():
test_support.run_unittest(ExtensionModuleCaseSensitivityTest) support.run_unittest(ExtensionModuleCaseSensitivityTest)
if __name__ == '__main__': if __name__ == '__main__':
......
import importlib import importlib
from . import test_path_hook from . import test_path_hook
from .. import abc from .. import abc
from .. import support from .. import util
import sys import sys
import unittest import unittest
...@@ -18,7 +18,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -18,7 +18,7 @@ class LoaderTests(abc.LoaderTests):
return loader.load_module(fullname) return loader.load_module(fullname)
def test_module(self): 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) module = self.load_module(test_path_hook.NAME)
for attr, value in [('__name__', test_path_hook.NAME), for attr, value in [('__name__', test_path_hook.NAME),
('__file__', test_path_hook.FILEPATH)]: ('__file__', test_path_hook.FILEPATH)]:
...@@ -34,7 +34,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -34,7 +34,7 @@ class LoaderTests(abc.LoaderTests):
pass pass
def test_module_reuse(self): 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) module1 = self.load_module(test_path_hook.NAME)
module2 = self.load_module(test_path_hook.NAME) module2 = self.load_module(test_path_hook.NAME)
self.assert_(module1 is module2) self.assert_(module1 is module2)
......
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()
from importlib import machinery from importlib import machinery
from .. import abc from .. import abc
from .. import support from .. import util
class LoaderTests(abc.LoaderTests): class LoaderTests(abc.LoaderTests):
def test_module(self): def test_module(self):
with support.uncache('__hello__'): with util.uncache('__hello__'):
module = machinery.FrozenImporter.load_module('__hello__') module = machinery.FrozenImporter.load_module('__hello__')
check = {'__name__': '__hello__', '__file__': '<frozen>', check = {'__name__': '__hello__', '__file__': '<frozen>',
'__package__': None} '__package__': None}
...@@ -14,7 +14,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -14,7 +14,7 @@ class LoaderTests(abc.LoaderTests):
self.assertEqual(getattr(module, attr), value) self.assertEqual(getattr(module, attr), value)
def test_package(self): def test_package(self):
with support.uncache('__phello__'): with util.uncache('__phello__'):
module = machinery.FrozenImporter.load_module('__phello__') module = machinery.FrozenImporter.load_module('__phello__')
check = {'__name__': '__phello__', '__file__': '<frozen>', check = {'__name__': '__phello__', '__file__': '<frozen>',
'__package__': '__phello__', '__path__': ['__phello__']} '__package__': '__phello__', '__path__': ['__phello__']}
...@@ -25,7 +25,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -25,7 +25,7 @@ class LoaderTests(abc.LoaderTests):
(attr, attr_value, value)) (attr, attr_value, value))
def test_lacking_parent(self): def test_lacking_parent(self):
with support.uncache('__phello__', '__phello__.spam'): with util.uncache('__phello__', '__phello__.spam'):
module = machinery.FrozenImporter.load_module('__phello__.spam') module = machinery.FrozenImporter.load_module('__phello__.spam')
check = {'__name__': '__phello__.spam', '__file__': '<frozen>', check = {'__name__': '__phello__.spam', '__file__': '<frozen>',
'__package__': '__phello__'} '__package__': '__phello__'}
...@@ -36,7 +36,7 @@ class LoaderTests(abc.LoaderTests): ...@@ -36,7 +36,7 @@ class LoaderTests(abc.LoaderTests):
(attr, attr_value, value)) (attr, attr_value, value))
def test_module_reuse(self): def test_module_reuse(self):
with support.uncache('__hello__'): with util.uncache('__hello__'):
module1 = machinery.FrozenImporter.load_module('__hello__') module1 = machinery.FrozenImporter.load_module('__hello__')
module2 = machinery.FrozenImporter.load_module('__hello__') module2 = machinery.FrozenImporter.load_module('__hello__')
self.assert_(module1 is module2) self.assert_(module1 is module2)
......
...@@ -5,7 +5,7 @@ of using the typical __path__/__name__ test). ...@@ -5,7 +5,7 @@ of using the typical __path__/__name__ test).
""" """
import unittest import unittest
from .. import support from .. import util
class Using__package__(unittest.TestCase): class Using__package__(unittest.TestCase):
...@@ -34,19 +34,19 @@ class Using__package__(unittest.TestCase): ...@@ -34,19 +34,19 @@ class Using__package__(unittest.TestCase):
def test_using___package__(self): def test_using___package__(self):
# [__package__] # [__package__]
with support.mock_modules('pkg.__init__', 'pkg.fake') as importer: with util.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with support.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
support.import_('pkg.fake') util.import_('pkg.fake')
module = support.import_('', globals={'__package__': 'pkg.fake'}, module = util.import_('', globals={'__package__': 'pkg.fake'},
fromlist=['attr'], level=2) fromlist=['attr'], level=2)
self.assertEquals(module.__name__, 'pkg') self.assertEquals(module.__name__, 'pkg')
def test_using___name__(self): def test_using___name__(self):
# [__name__] # [__name__]
with support.mock_modules('pkg.__init__', 'pkg.fake') as importer: with util.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with support.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
support.import_('pkg.fake') util.import_('pkg.fake')
module = support.import_('', module = util.import_('',
globals={'__name__': 'pkg.fake', globals={'__name__': 'pkg.fake',
'__path__': []}, '__path__': []},
fromlist=['attr'], level=2) fromlist=['attr'], level=2)
...@@ -54,12 +54,12 @@ class Using__package__(unittest.TestCase): ...@@ -54,12 +54,12 @@ class Using__package__(unittest.TestCase):
def test_bad__package__(self): def test_bad__package__(self):
globals = {'__package__': '<not real>'} globals = {'__package__': '<not real>'}
self.assertRaises(SystemError, support.import_,'', globals, {}, self.assertRaises(SystemError, util.import_,'', globals, {},
['relimport'], 1) ['relimport'], 1)
def test_bunk__package__(self): def test_bunk__package__(self):
globals = {'__package__': 42} globals = {'__package__': 42}
self.assertRaises(ValueError, support.import_, '', globals, {}, self.assertRaises(ValueError, util.import_, '', globals, {},
['relimport'], 1) ['relimport'], 1)
...@@ -77,26 +77,26 @@ class Setting__package__(unittest.TestCase): ...@@ -77,26 +77,26 @@ class Setting__package__(unittest.TestCase):
# [top-level] # [top-level]
def test_top_level(self): def test_top_level(self):
with support.mock_modules('top_level') as mock: with util.mock_modules('top_level') as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
del mock['top_level'].__package__ del mock['top_level'].__package__
module = support.import_('top_level') module = util.import_('top_level')
self.assert_(module.__package__ is None) self.assert_(module.__package__ is None)
# [package] # [package]
def test_package(self): def test_package(self):
with support.mock_modules('pkg.__init__') as mock: with util.mock_modules('pkg.__init__') as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
del mock['pkg'].__package__ del mock['pkg'].__package__
module = support.import_('pkg') module = util.import_('pkg')
self.assertEqual(module.__package__, 'pkg') self.assertEqual(module.__package__, 'pkg')
# [submodule] # [submodule]
def test_submodule(self): def test_submodule(self):
with support.mock_modules('pkg.__init__', 'pkg.mod') as mock: with util.mock_modules('pkg.__init__', 'pkg.mod') as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
del mock['pkg.mod'].__package__ del mock['pkg.mod'].__package__
pkg = support.import_('pkg.mod') pkg = util.import_('pkg.mod')
module = getattr(pkg, 'mod') module = getattr(pkg, 'mod')
self.assertEqual(module.__package__, 'pkg') self.assertEqual(module.__package__, 'pkg')
......
"""Test that sys.modules is used properly by import.""" """Test that sys.modules is used properly by import."""
from ..support import import_, mock_modules, importlib_only, import_state from .. import util
import sys import sys
from types import MethodType from types import MethodType
import unittest import unittest
...@@ -24,11 +23,11 @@ class UseCache(unittest.TestCase): ...@@ -24,11 +23,11 @@ class UseCache(unittest.TestCase):
# [use cache] # [use cache]
module_to_use = "some module found!" module_to_use = "some module found!"
sys.modules['some_module'] = module_to_use sys.modules['some_module'] = module_to_use
module = import_('some_module') module = util.import_('some_module')
self.assertEqual(id(module_to_use), id(module)) self.assertEqual(id(module_to_use), id(module))
def create_mock(self, *names, return_=None): def create_mock(self, *names, return_=None):
mock = mock_modules(*names) mock = util.mock_modules(*names)
original_load = mock.load_module original_load = mock.load_module
def load_module(self, fullname): def load_module(self, fullname):
original_load(fullname) original_load(fullname)
...@@ -38,31 +37,31 @@ class UseCache(unittest.TestCase): ...@@ -38,31 +37,31 @@ class UseCache(unittest.TestCase):
# __import__ inconsistent between loaders and built-in import when it comes # __import__ inconsistent between loaders and built-in import when it comes
# to when to use the module in sys.modules and when not to. # 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): def test_using_cache_after_loader(self):
# [from cache on return] # [from cache on return]
with self.create_mock('module') as mock: with self.create_mock('module') as mock:
with import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = import_('module') module = util.import_('module')
self.assertEquals(id(module), id(sys.modules['module'])) self.assertEquals(id(module), id(sys.modules['module']))
# See test_using_cache_after_loader() for reasoning. # See test_using_cache_after_loader() for reasoning.
@importlib_only @util.importlib_only
def test_using_cache_for_assigning_to_attribute(self): def test_using_cache_for_assigning_to_attribute(self):
# [from cache to attribute] # [from cache to attribute]
with self.create_mock('pkg.__init__', 'pkg.module') as importer: with self.create_mock('pkg.__init__', 'pkg.module') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg.module') module = util.import_('pkg.module')
self.assert_(hasattr(module, 'module')) self.assert_(hasattr(module, 'module'))
self.assert_(id(module.module), id(sys.modules['pkg.module'])) self.assert_(id(module.module), id(sys.modules['pkg.module']))
# See test_using_cache_after_loader() for reasoning. # See test_using_cache_after_loader() for reasoning.
@importlib_only @util.importlib_only
def test_using_cache_for_fromlist(self): def test_using_cache_for_fromlist(self):
# [from cache for fromlist] # [from cache for fromlist]
with self.create_mock('pkg.__init__', 'pkg.module') as importer: with self.create_mock('pkg.__init__', 'pkg.module') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg', fromlist=['module']) module = util.import_('pkg', fromlist=['module'])
self.assert_(hasattr(module, 'module')) self.assert_(hasattr(module, 'module'))
self.assertEquals(id(module.module), id(sys.modules['pkg.module'])) self.assertEquals(id(module.module), id(sys.modules['pkg.module']))
......
"""Test that the semantics relating to the 'fromlist' argument are correct.""" """Test that the semantics relating to the 'fromlist' argument are correct."""
from ..support import import_, mock_modules, import_state from .. import util
import unittest import unittest
class ReturnValue(unittest.TestCase): class ReturnValue(unittest.TestCase):
...@@ -16,16 +15,16 @@ class ReturnValue(unittest.TestCase): ...@@ -16,16 +15,16 @@ class ReturnValue(unittest.TestCase):
def test_return_from_import(self): def test_return_from_import(self):
# [import return] # [import return]
with mock_modules('pkg.__init__', 'pkg.module') as importer: with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg.module') module = util.import_('pkg.module')
self.assertEquals(module.__name__, 'pkg') self.assertEquals(module.__name__, 'pkg')
def test_return_from_from_import(self): def test_return_from_from_import(self):
# [from return] # [from return]
with mock_modules('pkg.__init__', 'pkg.module')as importer: with util.mock_modules('pkg.__init__', 'pkg.module')as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg.module', fromlist=['attr']) module = util.import_('pkg.module', fromlist=['attr'])
self.assertEquals(module.__name__, 'pkg.module') self.assertEquals(module.__name__, 'pkg.module')
...@@ -48,59 +47,59 @@ class HandlingFromlist(unittest.TestCase): ...@@ -48,59 +47,59 @@ class HandlingFromlist(unittest.TestCase):
def test_object(self): def test_object(self):
# [object case] # [object case]
with mock_modules('module') as importer: with util.mock_modules('module') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('module', fromlist=['attr']) module = util.import_('module', fromlist=['attr'])
self.assertEquals(module.__name__, 'module') self.assertEquals(module.__name__, 'module')
def test_unexistent_object(self): def test_unexistent_object(self):
# [bad object] # [bad object]
with mock_modules('module') as importer: with util.mock_modules('module') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('module', fromlist=['non_existent']) module = util.import_('module', fromlist=['non_existent'])
self.assertEquals(module.__name__, 'module') self.assertEquals(module.__name__, 'module')
self.assert_(not hasattr(module, 'non_existent')) self.assert_(not hasattr(module, 'non_existent'))
def test_module_from_package(self): def test_module_from_package(self):
# [module] # [module]
with mock_modules('pkg.__init__', 'pkg.module') as importer: with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg', fromlist=['module']) module = util.import_('pkg', fromlist=['module'])
self.assertEquals(module.__name__, 'pkg') self.assertEquals(module.__name__, 'pkg')
self.assert_(hasattr(module, 'module')) self.assert_(hasattr(module, 'module'))
self.assertEquals(module.module.__name__, 'pkg.module') self.assertEquals(module.module.__name__, 'pkg.module')
def test_no_module_from_package(self): def test_no_module_from_package(self):
# [no module] # [no module]
with mock_modules('pkg.__init__') as importer: with util.mock_modules('pkg.__init__') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg', fromlist='non_existent') module = util.import_('pkg', fromlist='non_existent')
self.assertEquals(module.__name__, 'pkg') self.assertEquals(module.__name__, 'pkg')
self.assert_(not hasattr(module, 'non_existent')) self.assert_(not hasattr(module, 'non_existent'))
def test_empty_string(self): def test_empty_string(self):
with mock_modules('pkg.__init__', 'pkg.mod') as importer: with util.mock_modules('pkg.__init__', 'pkg.mod') as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_('pkg.mod', fromlist=['']) module = util.import_('pkg.mod', fromlist=[''])
self.assertEquals(module.__name__, 'pkg.mod') self.assertEquals(module.__name__, 'pkg.mod')
def test_using_star(self): def test_using_star(self):
# [using *] # [using *]
with mock_modules('pkg.__init__', 'pkg.module') as mock: with util.mock_modules('pkg.__init__', 'pkg.module') as mock:
with import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
mock['pkg'].__all__ = ['module'] mock['pkg'].__all__ = ['module']
module = import_('pkg', fromlist=['*']) module = util.import_('pkg', fromlist=['*'])
self.assertEquals(module.__name__, 'pkg') self.assertEquals(module.__name__, 'pkg')
self.assert_(hasattr(module, 'module')) self.assert_(hasattr(module, 'module'))
self.assertEqual(module.module.__name__, 'pkg.module') self.assertEqual(module.module.__name__, 'pkg.module')
def test_star_with_others(self): def test_star_with_others(self):
# [using * with others] # [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 context as mock:
with import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
mock['pkg'].__all__ = ['module1'] mock['pkg'].__all__ = ['module1']
module = import_('pkg', fromlist=['module2', '*']) module = util.import_('pkg', fromlist=['module2', '*'])
self.assertEquals(module.__name__, 'pkg') self.assertEquals(module.__name__, 'pkg')
self.assert_(hasattr(module, 'module1')) self.assert_(hasattr(module, 'module1'))
self.assert_(hasattr(module, 'module2')) self.assert_(hasattr(module, 'module2'))
......
from ..support import import_state, mock_modules, import_ from .. import util
from contextlib import nested from contextlib import nested
from types import MethodType from types import MethodType
import unittest import unittest
...@@ -16,24 +15,25 @@ class CallingOrder(unittest.TestCase): ...@@ -16,24 +15,25 @@ class CallingOrder(unittest.TestCase):
def test_first_called(self): def test_first_called(self):
# [first called] # [first called]
mod = 'top_level' mod = 'top_level'
first = mock_modules(mod) first = util.mock_modules(mod)
second = mock_modules(mod) second = util.mock_modules(mod)
with nested(mock_modules(mod), mock_modules(mod)) as (first, second): context = nested(util.mock_modules(mod), util.mock_modules(mod))
with context as (first, second):
first.modules[mod] = 42 first.modules[mod] = 42
second.modules[mod] = -13 second.modules[mod] = -13
with import_state(meta_path=[first, second]): with util.import_state(meta_path=[first, second]):
self.assertEquals(import_(mod), 42) self.assertEquals(util.import_(mod), 42)
def test_continuing(self): def test_continuing(self):
# [continuing] # [continuing]
mod_name = 'for_real' mod_name = 'for_real'
first = mock_modules('nonexistent') first = util.mock_modules('nonexistent')
second = mock_modules(mod_name) second = util.mock_modules(mod_name)
with nested(first, second): with nested(first, second):
first.find_module = lambda self, fullname, path=None: None first.find_module = lambda self, fullname, path=None: None
second.modules[mod_name] = 42 second.modules[mod_name] = 42
with import_state(meta_path=[first, second]): with util.import_state(meta_path=[first, second]):
self.assertEquals(import_(mod_name), 42) self.assertEquals(util.import_(mod_name), 42)
class CallSignature(unittest.TestCase): class CallSignature(unittest.TestCase):
...@@ -54,11 +54,11 @@ class CallSignature(unittest.TestCase): ...@@ -54,11 +54,11 @@ class CallSignature(unittest.TestCase):
# [no path] # [no path]
mod_name = 'top_level' mod_name = 'top_level'
assert '.' not in mod_name 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) log, wrapped_call = self.log(importer.find_module)
importer.find_module = MethodType(wrapped_call, importer) importer.find_module = MethodType(wrapped_call, importer)
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
import_(mod_name) util.import_(mod_name)
assert len(log) == 1 assert len(log) == 1
args = log[0][0] args = log[0][0]
kwargs = log[0][1] kwargs = log[0][1]
...@@ -74,12 +74,12 @@ class CallSignature(unittest.TestCase): ...@@ -74,12 +74,12 @@ class CallSignature(unittest.TestCase):
mod_name = pkg_name + '.module' mod_name = pkg_name + '.module'
path = [42] path = [42]
assert '.' in mod_name 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 importer.modules[pkg_name].__path__ = path
log, wrapped_call = self.log(importer.find_module) log, wrapped_call = self.log(importer.find_module)
importer.find_module = MethodType(wrapped_call, importer) importer.find_module = MethodType(wrapped_call, importer)
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
import_(mod_name) util.import_(mod_name)
assert len(log) == 2 assert len(log) == 2
args = log[1][0] args = log[1][0]
kwargs = log[1][1] kwargs = log[1][1]
......
from .. import util
import sys import sys
import unittest import unittest
import importlib import importlib
from .. import support
class ParentModuleTests(unittest.TestCase): class ParentModuleTests(unittest.TestCase):
...@@ -9,15 +9,15 @@ class ParentModuleTests(unittest.TestCase): ...@@ -9,15 +9,15 @@ class ParentModuleTests(unittest.TestCase):
"""Importing a submodule should import the parent modules.""" """Importing a submodule should import the parent modules."""
def test_import_parent(self): def test_import_parent(self):
with support.mock_modules('pkg.__init__', 'pkg.module') as mock: with util.mock_modules('pkg.__init__', 'pkg.module') as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = support.import_('pkg.module') module = util.import_('pkg.module')
self.assert_('pkg' in sys.modules) self.assert_('pkg' in sys.modules)
def test_bad_parent(self): def test_bad_parent(self):
with support.mock_modules('pkg.module') as mock: with util.mock_modules('pkg.module') as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
self.assertRaises(ImportError, support.import_, 'pkg.module') self.assertRaises(ImportError, util.import_, 'pkg.module')
def test_main(): def test_main():
......
from ..support import (mock_modules, import_state, import_, mock_path_hook, from .. import util
importlib_only, uncache)
from contextlib import nested from contextlib import nested
from imp import new_module from imp import new_module
import sys import sys
...@@ -32,7 +30,7 @@ class BaseTests(unittest.TestCase): ...@@ -32,7 +30,7 @@ class BaseTests(unittest.TestCase):
def order_test(self, to_import, entry, search_path, path=[]): def order_test(self, to_import, entry, search_path, path=[]):
# [order] # [order]
log = [] log = []
class LogFindModule(mock_modules): class LogFindModule(util.mock_modules):
def find_module(self, fullname): def find_module(self, fullname):
log.append(self) log.append(self)
return super().find_module(fullname) return super().find_module(fullname)
...@@ -42,12 +40,12 @@ class BaseTests(unittest.TestCase): ...@@ -42,12 +40,12 @@ class BaseTests(unittest.TestCase):
hitter = LogFindModule(to_import) hitter = LogFindModule(to_import)
with nested(misser, hitter): with nested(misser, hitter):
cache = dict(zip(search_path, (misser, hitter))) cache = dict(zip(search_path, (misser, hitter)))
with import_state(path=path, path_importer_cache=cache): with util.import_state(path=path, path_importer_cache=cache):
import_(to_import) util.import_(to_import)
self.assertEquals(log[0], misser) self.assertEquals(log[0], misser)
self.assertEquals(log[1], hitter) 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=[]): def cache_use_test(self, to_import, entry, path=[]):
# [cache check], [cache use] # [cache check], [cache use]
log = [] log = []
...@@ -56,11 +54,11 @@ class BaseTests(unittest.TestCase): ...@@ -56,11 +54,11 @@ class BaseTests(unittest.TestCase):
log.append(item) log.append(item)
return super(LoggingDict, self).__getitem__(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 = LoggingDict()
cache[entry] = importer cache[entry] = importer
with import_state(path=[entry], path_importer_cache=cache): with util.import_state(path=[entry], path_importer_cache=cache):
module = import_(to_import, fromlist=['a']) module = util.import_(to_import, fromlist=['a'])
self.assert_(module is importer[to_import]) self.assert_(module is importer[to_import])
self.assertEquals(len(cache), 1) self.assertEquals(len(cache), 1)
self.assertEquals([entry], log) self.assertEquals([entry], log)
...@@ -71,11 +69,11 @@ class BaseTests(unittest.TestCase): ...@@ -71,11 +69,11 @@ class BaseTests(unittest.TestCase):
def logging_hook(entry): def logging_hook(entry):
log.append(entry) log.append(entry)
raise ImportError raise ImportError
with mock_modules(to_import) as importer: with util.mock_modules(to_import) as importer:
hitter = mock_path_hook(entry, importer=importer) hitter = util.mock_path_hook(entry, importer=importer)
path_hooks = [logging_hook, logging_hook, hitter] path_hooks = [logging_hook, logging_hook, hitter]
with import_state(path_hooks=path_hooks, path=path): with util.import_state(path_hooks=path_hooks, path=path):
import_(to_import) util.import_(to_import)
self.assertEquals(sys.path_importer_cache[entry], importer) self.assertEquals(sys.path_importer_cache[entry], importer)
self.assertEquals(len(log), 2) self.assertEquals(len(log), 2)
...@@ -90,7 +88,7 @@ class BaseTests(unittest.TestCase): ...@@ -90,7 +88,7 @@ class BaseTests(unittest.TestCase):
raise ImportError raise ImportError
try: try:
import_(to_import) util.import_(to_import)
except ImportError: except ImportError:
pass pass
...@@ -113,7 +111,7 @@ class PathTests(BaseTests): ...@@ -113,7 +111,7 @@ class PathTests(BaseTests):
def test_path_argument(self): def test_path_argument(self):
name = 'total junk' name = 'total junk'
with uncache(name): with util.uncache(name):
self.path_argument_test(name) self.path_argument_test(name)
...@@ -122,13 +120,13 @@ class __path__Tests(BaseTests): ...@@ -122,13 +120,13 @@ class __path__Tests(BaseTests):
"""Tests for __path__.""" """Tests for __path__."""
def run_test(self, test, entry, path, *args): 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['pkg'].__path__ = path
importer.load_module('pkg') importer.load_module('pkg')
test('pkg.hit', entry, *args) 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): def test_order(self):
self.run_test(self.order_test, 'second', ('first', 'second'), ['first', self.run_test(self.order_test, 'second', ('first', 'second'), ['first',
'second']) 'second'])
...@@ -146,7 +144,7 @@ class __path__Tests(BaseTests): ...@@ -146,7 +144,7 @@ class __path__Tests(BaseTests):
module.__path__ = ['random __path__'] module.__path__ = ['random __path__']
name = 'pkg.whatever' name = 'pkg.whatever'
sys.modules['pkg'] = module sys.modules['pkg'] = module
with uncache('pkg', name): with util.uncache('pkg', name):
self.path_argument_test(name) self.path_argument_test(name)
......
"""Test relative imports (PEP 328).""" """Test relative imports (PEP 328)."""
from .. import util
from ..support import uncache, import_, mock_modules, import_state
import sys import sys
import unittest import unittest
...@@ -65,10 +63,10 @@ class RelativeImports(unittest.TestCase): ...@@ -65,10 +63,10 @@ class RelativeImports(unittest.TestCase):
uncache_names.append(name) uncache_names.append(name)
else: else:
uncache_names.append(name[:-len('.__init__')]) uncache_names.append(name[:-len('.__init__')])
with mock_modules(*create) as importer: with util.mock_modules(*create) as importer:
with import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
for global_ in globals_: for global_ in globals_:
with uncache(*uncache_names): with util.uncache(*uncache_names):
callback(global_) callback(global_)
...@@ -77,8 +75,8 @@ class RelativeImports(unittest.TestCase): ...@@ -77,8 +75,8 @@ class RelativeImports(unittest.TestCase):
create = 'pkg.__init__', 'pkg.mod2' create = 'pkg.__init__', 'pkg.mod2'
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'} globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
def callback(global_): def callback(global_):
import_('pkg') # For __import__(). util.import_('pkg') # For __import__().
module = import_('', global_, fromlist=['mod2'], level=1) module = util.import_('', global_, fromlist=['mod2'], level=1)
self.assertEqual(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assert_(hasattr(module, 'mod2')) self.assert_(hasattr(module, 'mod2'))
self.assertEqual(module.mod2.attr, 'pkg.mod2') self.assertEqual(module.mod2.attr, 'pkg.mod2')
...@@ -89,8 +87,8 @@ class RelativeImports(unittest.TestCase): ...@@ -89,8 +87,8 @@ class RelativeImports(unittest.TestCase):
create = 'pkg.__init__', 'pkg.mod2' create = 'pkg.__init__', 'pkg.mod2'
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'} globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
def callback(global_): def callback(global_):
import_('pkg') # For __import__(). util.import_('pkg') # For __import__().
module = import_('mod2', global_, fromlist=['attr'], level=1) module = util.import_('mod2', global_, fromlist=['attr'], level=1)
self.assertEqual(module.__name__, 'pkg.mod2') self.assertEqual(module.__name__, 'pkg.mod2')
self.assertEqual(module.attr, 'pkg.mod2') self.assertEqual(module.attr, 'pkg.mod2')
self.relative_import_test(create, globals_, callback) self.relative_import_test(create, globals_, callback)
...@@ -101,8 +99,8 @@ class RelativeImports(unittest.TestCase): ...@@ -101,8 +99,8 @@ class RelativeImports(unittest.TestCase):
globals_ = ({'__package__': 'pkg'}, globals_ = ({'__package__': 'pkg'},
{'__name__': 'pkg', '__path__': ['blah']}) {'__name__': 'pkg', '__path__': ['blah']})
def callback(global_): def callback(global_):
import_('pkg') # For __import__(). util.import_('pkg') # For __import__().
module = import_('', global_, fromlist=['module'], module = util.import_('', global_, fromlist=['module'],
level=1) level=1)
self.assertEqual(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assert_(hasattr(module, 'module')) self.assert_(hasattr(module, 'module'))
...@@ -114,8 +112,8 @@ class RelativeImports(unittest.TestCase): ...@@ -114,8 +112,8 @@ class RelativeImports(unittest.TestCase):
create = 'pkg.__init__', 'pkg.module' create = 'pkg.__init__', 'pkg.module'
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'} globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
def callback(global_): def callback(global_):
import_('pkg') # For __import__(). util.import_('pkg') # For __import__().
module = import_('', global_, fromlist=['attr'], level=1) module = util.import_('', global_, fromlist=['attr'], level=1)
self.assertEqual(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.relative_import_test(create, globals_, callback) self.relative_import_test(create, globals_, callback)
...@@ -126,7 +124,7 @@ class RelativeImports(unittest.TestCase): ...@@ -126,7 +124,7 @@ class RelativeImports(unittest.TestCase):
globals_ = ({'__package__': 'pkg.subpkg1'}, globals_ = ({'__package__': 'pkg.subpkg1'},
{'__name__': 'pkg.subpkg1', '__path__': ['blah']}) {'__name__': 'pkg.subpkg1', '__path__': ['blah']})
def callback(global_): def callback(global_):
module = import_('', global_, fromlist=['subpkg2'], level=2) module = util.import_('', global_, fromlist=['subpkg2'], level=2)
self.assertEqual(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assert_(hasattr(module, 'subpkg2')) self.assert_(hasattr(module, 'subpkg2'))
self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__') self.assertEqual(module.subpkg2.attr, 'pkg.subpkg2.__init__')
...@@ -141,8 +139,8 @@ class RelativeImports(unittest.TestCase): ...@@ -141,8 +139,8 @@ class RelativeImports(unittest.TestCase):
{'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5', {'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5',
'__path__': ['blah']}) '__path__': ['blah']})
def callback(global_): def callback(global_):
import_(globals_[0]['__package__']) util.import_(globals_[0]['__package__'])
module = import_('', global_, fromlist=['attr'], level=6) module = util.import_('', global_, fromlist=['attr'], level=6)
self.assertEqual(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.relative_import_test(create, globals_, callback) self.relative_import_test(create, globals_, callback)
...@@ -152,8 +150,8 @@ class RelativeImports(unittest.TestCase): ...@@ -152,8 +150,8 @@ class RelativeImports(unittest.TestCase):
globals_ = ({'__package__': 'pkg'}, globals_ = ({'__package__': 'pkg'},
{'__name__': 'pkg', '__path__': ['blah']}) {'__name__': 'pkg', '__path__': ['blah']})
def callback(global_): def callback(global_):
import_('pkg') util.import_('pkg')
self.assertRaises(ValueError, import_, '', global_, self.assertRaises(ValueError, util.import_, '', global_,
fromlist=['top_level'], level=2) fromlist=['top_level'], level=2)
self.relative_import_test(create, globals_, callback) self.relative_import_test(create, globals_, callback)
...@@ -162,14 +160,14 @@ class RelativeImports(unittest.TestCase): ...@@ -162,14 +160,14 @@ class RelativeImports(unittest.TestCase):
create = ['top_level', 'pkg.__init__', 'pkg.module'] create = ['top_level', 'pkg.__init__', 'pkg.module']
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'} globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
def callback(global_): def callback(global_):
import_('pkg') util.import_('pkg')
self.assertRaises(ValueError, import_, '', global_, self.assertRaises(ValueError, util.import_, '', global_,
fromlist=['top_level'], level=2) fromlist=['top_level'], level=2)
self.relative_import_test(create, globals_, callback) self.relative_import_test(create, globals_, callback)
def test_empty_name_w_level_0(self): def test_empty_name_w_level_0(self):
# [empty name] # [empty name]
self.assertRaises(ValueError, import_, '') self.assertRaises(ValueError, util.import_, '')
def test_import_from_different_package(self): def test_import_from_different_package(self):
# Test importing from a different package than the caller. # Test importing from a different package than the caller.
...@@ -183,8 +181,9 @@ class RelativeImports(unittest.TestCase): ...@@ -183,8 +181,9 @@ class RelativeImports(unittest.TestCase):
'__runpy_pkg__.uncle.cousin.nephew'] '__runpy_pkg__.uncle.cousin.nephew']
globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'} globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'}
def callback(global_): def callback(global_):
import_('__runpy_pkg__.__runpy_pkg__') util.import_('__runpy_pkg__.__runpy_pkg__')
module = import_('uncle.cousin', globals_, {}, fromlist=['nephew'], module = util.import_('uncle.cousin', globals_, {},
fromlist=['nephew'],
level=2) level=2)
self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin') self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin')
self.relative_import_test(create, globals_, callback) self.relative_import_test(create, globals_, callback)
......
"""Test case-sensitivity (PEP 235).""" """Test case-sensitivity (PEP 235)."""
import importlib import importlib
from .. import support from .. import util
from . import util as source_util from . import util as source_util
import os import os
import sys import sys
...@@ -8,7 +8,7 @@ from test import support as test_support ...@@ -8,7 +8,7 @@ from test import support as test_support
import unittest import unittest
@support.case_insensitive_tests @util.case_insensitive_tests
class CaseSensitivityTest(unittest.TestCase): class CaseSensitivityTest(unittest.TestCase):
"""PEP 235 dictates that on case-preserving, case-insensitive file systems """PEP 235 dictates that on case-preserving, case-insensitive file systems
......
import importlib import importlib
from .. import abc from .. import abc
from .. import support
from . import util as source_util from . import util as source_util
import os import os
import py_compile import py_compile
......
import importlib import importlib
from .. import abc from .. import abc
from .. import support
from . import util as source_util from . import util as source_util
import imp import imp
......
import importlib import importlib
from . import util from . import util as source_util
import unittest import unittest
...@@ -9,7 +9,7 @@ class PathHookTest(unittest.TestCase): ...@@ -9,7 +9,7 @@ class PathHookTest(unittest.TestCase):
def test_success(self): def test_success(self):
# XXX Only work on existing directories? # 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']), self.assert_(hasattr(importlib.FileImporter(mapping['.root']),
'find_module')) 'find_module'))
......
import importlib import importlib
from .. import support
from . import util as source_util from . import util as source_util
import codecs import codecs
......
from .. import support as util from .. import util
import contextlib import contextlib
import imp import imp
import os import os
import os.path import os.path
import sys import sys
import tempfile import tempfile
from test import support as support from test import support
def writes_bytecode(fxn): def writes_bytecode(fxn):
......
import unittest import unittest
import importlib import importlib
from . import support from . import util
class ImportModuleTests(unittest.TestCase): class ImportModuleTests(unittest.TestCase):
...@@ -9,8 +9,8 @@ class ImportModuleTests(unittest.TestCase): ...@@ -9,8 +9,8 @@ class ImportModuleTests(unittest.TestCase):
def test_module_import(self): def test_module_import(self):
# Test importing a top-level module. # Test importing a top-level module.
with support.mock_modules('top_level') as mock: with util.mock_modules('top_level') as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = importlib.import_module('top_level') module = importlib.import_module('top_level')
self.assertEqual(module.__name__, 'top_level') self.assertEqual(module.__name__, 'top_level')
...@@ -19,8 +19,8 @@ class ImportModuleTests(unittest.TestCase): ...@@ -19,8 +19,8 @@ class ImportModuleTests(unittest.TestCase):
pkg_name = 'pkg' pkg_name = 'pkg'
pkg_long_name = '{0}.__init__'.format(pkg_name) pkg_long_name = '{0}.__init__'.format(pkg_name)
name = '{0}.mod'.format(pkg_name) name = '{0}.mod'.format(pkg_name)
with support.mock_modules(pkg_long_name, name) as mock: with util.mock_modules(pkg_long_name, name) as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = importlib.import_module(name) module = importlib.import_module(name)
self.assertEqual(module.__name__, name) self.assertEqual(module.__name__, name)
...@@ -31,8 +31,8 @@ class ImportModuleTests(unittest.TestCase): ...@@ -31,8 +31,8 @@ class ImportModuleTests(unittest.TestCase):
module_name = 'mod' module_name = 'mod'
absolute_name = '{0}.{1}'.format(pkg_name, module_name) absolute_name = '{0}.{1}'.format(pkg_name, module_name)
relative_name = '.{0}'.format(module_name) relative_name = '.{0}'.format(module_name)
with support.mock_modules(pkg_long_name, absolute_name) as mock: with util.mock_modules(pkg_long_name, absolute_name) as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = importlib.import_module(relative_name, pkg_name) module = importlib.import_module(relative_name, pkg_name)
self.assertEqual(module.__name__, absolute_name) self.assertEqual(module.__name__, absolute_name)
...@@ -42,8 +42,8 @@ class ImportModuleTests(unittest.TestCase): ...@@ -42,8 +42,8 @@ class ImportModuleTests(unittest.TestCase):
pkg_name = 'pkg' pkg_name = 'pkg'
pkg_long_name = '{0}.__init__'.format(pkg_name) pkg_long_name = '{0}.__init__'.format(pkg_name)
name = '{0}.mod'.format(pkg_name) name = '{0}.mod'.format(pkg_name)
with support.mock_modules(pkg_long_name, name) as mock: with util.mock_modules(pkg_long_name, name) as mock:
with support.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = importlib.import_module(name, pkg_name) module = importlib.import_module(name, pkg_name)
self.assertEqual(module.__name__, name) self.assertEqual(module.__name__, name)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment