Issue #16803: test.test_importlib.import_ now tests frozen and source code

This commit is contained in:
Brett Cannon 2013-11-08 13:34:59 -05:00
parent a3c6963467
commit 330f71b617
11 changed files with 146 additions and 154 deletions

View File

@ -15,6 +15,4 @@ if __name__ == '__main__':
parser.add_argument('-b', '--builtin', action='store_true', default=False,
help='use builtins.__import__() instead of importlib')
args = parser.parse_args()
if args.builtin:
util.using___import__ = True
test_main()

View File

@ -16,7 +16,7 @@ class LoaderMock:
return self.module
class LoaderAttributeTests(unittest.TestCase):
class LoaderAttributeTests:
def test___loader___missing(self):
module = types.ModuleType('blah')
@ -27,7 +27,7 @@ class LoaderAttributeTests(unittest.TestCase):
loader = LoaderMock()
loader.module = module
with util.uncache('blah'), util.import_state(meta_path=[loader]):
module = import_util.import_('blah')
module = self.__import__('blah')
self.assertEqual(loader, module.__loader__)
def test___loader___is_None(self):
@ -36,9 +36,13 @@ class LoaderAttributeTests(unittest.TestCase):
loader = LoaderMock()
loader.module = module
with util.uncache('blah'), util.import_state(meta_path=[loader]):
returned_module = import_util.import_('blah')
returned_module = self.__import__('blah')
self.assertEqual(loader, module.__loader__)
Frozen_Tests, Source_Tests = util.test_both(LoaderAttributeTests,
__import__=import_util.__import__)
if __name__ == '__main__':
unittest.main()

View File

@ -9,7 +9,7 @@ from .. import util
from . import util as import_util
class Using__package__(unittest.TestCase):
class Using__package__:
"""Use of __package__ supercedes the use of __name__/__path__ to calculate
what package a module belongs to. The basic algorithm is [__package__]::
@ -38,8 +38,8 @@ class Using__package__(unittest.TestCase):
# [__package__]
with util.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with util.import_state(meta_path=[importer]):
import_util.import_('pkg.fake')
module = import_util.import_('',
self.__import__('pkg.fake')
module = self.__import__('',
globals={'__package__': 'pkg.fake'},
fromlist=['attr'], level=2)
self.assertEqual(module.__name__, 'pkg')
@ -51,8 +51,8 @@ class Using__package__(unittest.TestCase):
globals_['__package__'] = None
with util.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with util.import_state(meta_path=[importer]):
import_util.import_('pkg.fake')
module = import_util.import_('', globals= globals_,
self.__import__('pkg.fake')
module = self.__import__('', globals= globals_,
fromlist=['attr'], level=2)
self.assertEqual(module.__name__, 'pkg')
@ -63,15 +63,17 @@ class Using__package__(unittest.TestCase):
def test_bad__package__(self):
globals = {'__package__': '<not real>'}
with self.assertRaises(SystemError):
import_util.import_('', globals, {}, ['relimport'], 1)
self.__import__('', globals, {}, ['relimport'], 1)
def test_bunk__package__(self):
globals = {'__package__': 42}
with self.assertRaises(TypeError):
import_util.import_('', globals, {}, ['relimport'], 1)
self.__import__('', globals, {}, ['relimport'], 1)
Frozen_UsingPackage, Source_UsingPackage = util.test_both(
Using__package__, __import__=import_util.__import__)
@import_util.importlib_only
class Setting__package__(unittest.TestCase):
"""Because __package__ is a new feature, it is not always set by a loader.
@ -84,12 +86,14 @@ class Setting__package__(unittest.TestCase):
"""
__import__ = import_util.__import__[1]
# [top-level]
def test_top_level(self):
with util.mock_modules('top_level') as mock:
with util.import_state(meta_path=[mock]):
del mock['top_level'].__package__
module = import_util.import_('top_level')
module = self.__import__('top_level')
self.assertEqual(module.__package__, '')
# [package]
@ -97,7 +101,7 @@ class Setting__package__(unittest.TestCase):
with util.mock_modules('pkg.__init__') as mock:
with util.import_state(meta_path=[mock]):
del mock['pkg'].__package__
module = import_util.import_('pkg')
module = self.__import__('pkg')
self.assertEqual(module.__package__, 'pkg')
# [submodule]
@ -105,15 +109,10 @@ class Setting__package__(unittest.TestCase):
with util.mock_modules('pkg.__init__', 'pkg.mod') as mock:
with util.import_state(meta_path=[mock]):
del mock['pkg.mod'].__package__
pkg = import_util.import_('pkg.mod')
pkg = self.__import__('pkg.mod')
module = getattr(pkg, 'mod')
self.assertEqual(module.__package__, 'pkg')
def test_main():
from test.support import run_unittest
run_unittest(Using__package__, Setting__package__)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -1,5 +1,5 @@
from .. import util as importlib_test_util
from . import util
from .. import util
from . import util as import_util
import sys
import types
import unittest
@ -17,7 +17,7 @@ class BadLoaderFinder:
raise ImportError('I cannot be loaded!')
class APITest(unittest.TestCase):
class APITest:
"""Test API-specific details for __import__ (e.g. raising the right
exception when passing in an int for the module name)."""
@ -25,24 +25,24 @@ class APITest(unittest.TestCase):
def test_name_requires_rparition(self):
# Raise TypeError if a non-string is passed in for the module name.
with self.assertRaises(TypeError):
util.import_(42)
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):
util.import_('os', globals(), level=-1)
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('fine')
mod.__path__ = ['XXX']
with importlib_test_util.import_state(meta_path=[BadLoaderFinder]):
with importlib_test_util.uncache('fine'):
with util.import_state(meta_path=[BadLoaderFinder]):
with util.uncache('fine'):
sys.modules['fine'] = mod
util.import_('fine', fromlist=['not here'])
self.__import__('fine', fromlist=['not here'])
def test_fromlist_load_error_propagates(self):
# If something in fromlist triggers an exception not related to not
@ -50,18 +50,15 @@ class APITest(unittest.TestCase):
# issue15316
mod = types.ModuleType('fine')
mod.__path__ = ['XXX']
with importlib_test_util.import_state(meta_path=[BadLoaderFinder]):
with importlib_test_util.uncache('fine'):
with util.import_state(meta_path=[BadLoaderFinder]):
with util.uncache('fine'):
sys.modules['fine'] = mod
with self.assertRaises(ImportError):
util.import_('fine', fromlist=['bogus'])
self.__import__('fine', fromlist=['bogus'])
def test_main():
from test.support import run_unittest
run_unittest(APITest)
Frozen_APITests, Source_APITests = util.test_both(
APITest, __import__=import_util.__import__)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -6,7 +6,7 @@ from types import MethodType
import unittest
class UseCache(unittest.TestCase):
class UseCache:
"""When it comes to sys.modules, import prefers it over anything else.
@ -21,12 +21,13 @@ class UseCache(unittest.TestCase):
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 = import_util.import_('some_module')
module = self.__import__('some_module')
self.assertEqual(id(module_to_use), id(module))
def test_None_in_cache(self):
@ -35,7 +36,7 @@ class UseCache(unittest.TestCase):
with util.uncache(name):
sys.modules[name] = None
with self.assertRaises(ImportError) as cm:
import_util.import_(name)
self.__import__(name)
self.assertEqual(cm.exception.name, name)
def create_mock(self, *names, return_=None):
@ -47,42 +48,43 @@ class UseCache(unittest.TestCase):
mock.load_module = MethodType(load_module, mock)
return mock
Frozen_UseCache, Source_UseCache = util.test_both(
UseCache, __import__=import_util.__import__)
class ImportlibUseCache(UseCache, unittest.TestCase):
__import__ = import_util.__import__[1]
# __import__ inconsistent between loaders and built-in import when it comes
# to when to use the module in sys.modules and when not to.
@import_util.importlib_only
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 = import_util.import_('module')
module = self.__import__('module')
self.assertEqual(id(module), id(sys.modules['module']))
# See test_using_cache_after_loader() for reasoning.
@import_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 util.import_state(meta_path=[importer]):
module = import_util.import_('pkg.module')
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.
@import_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 util.import_state(meta_path=[importer]):
module = import_util.import_('pkg', fromlist=['module'])
module = self.__import__('pkg', fromlist=['module'])
self.assertTrue(hasattr(module, 'module'))
self.assertEqual(id(module.module),
id(sys.modules['pkg.module']))
def test_main():
from test.support import run_unittest
run_unittest(UseCache)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -3,7 +3,8 @@ from .. import util
from . import util as import_util
import unittest
class ReturnValue(unittest.TestCase):
class ReturnValue:
"""The use of fromlist influences what import returns.
@ -18,18 +19,21 @@ class ReturnValue(unittest.TestCase):
# [import return]
with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg.module')
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 = import_util.import_('pkg.module', fromlist=['attr'])
module = self.__import__('pkg.module', fromlist=['attr'])
self.assertEqual(module.__name__, 'pkg.module')
Frozen_ReturnValue, Source_ReturnValue = util.test_both(
ReturnValue, __import__=import_util.__import__)
class HandlingFromlist(unittest.TestCase):
class HandlingFromlist:
"""Using fromlist triggers different actions based on what is being asked
of it.
@ -48,14 +52,14 @@ class HandlingFromlist(unittest.TestCase):
# [object case]
with util.mock_modules('module') as importer:
with util.import_state(meta_path=[importer]):
module = import_util.import_('module', fromlist=['attr'])
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 = import_util.import_('module', fromlist=['non_existent'])
module = self.__import__('module', fromlist=['non_existent'])
self.assertEqual(module.__name__, 'module')
self.assertTrue(not hasattr(module, 'non_existent'))
@ -63,7 +67,7 @@ class HandlingFromlist(unittest.TestCase):
# [module]
with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg', fromlist=['module'])
module = self.__import__('pkg', fromlist=['module'])
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module'))
self.assertEqual(module.module.__name__, 'pkg.module')
@ -78,13 +82,13 @@ class HandlingFromlist(unittest.TestCase):
module_code={'pkg.mod': module_code}) as importer:
with util.import_state(meta_path=[importer]):
with self.assertRaises(ImportError) as exc:
import_util.import_('pkg', fromlist=['mod'])
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 = import_util.import_('pkg.mod', fromlist=[''])
module = self.__import__('pkg.mod', fromlist=[''])
self.assertEqual(module.__name__, 'pkg.mod')
def basic_star_test(self, fromlist=['*']):
@ -92,7 +96,7 @@ class HandlingFromlist(unittest.TestCase):
with util.mock_modules('pkg.__init__', 'pkg.module') as mock:
with util.import_state(meta_path=[mock]):
mock['pkg'].__all__ = ['module']
module = import_util.import_('pkg', fromlist=fromlist)
module = self.__import__('pkg', fromlist=fromlist)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module'))
self.assertEqual(module.module.__name__, 'pkg.module')
@ -110,17 +114,16 @@ class HandlingFromlist(unittest.TestCase):
with context as mock:
with util.import_state(meta_path=[mock]):
mock['pkg'].__all__ = ['module1']
module = import_util.import_('pkg', fromlist=['module2', '*'])
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')
Frozen_FromList, Source_FromList = util.test_both(
HandlingFromlist, __import__=import_util.__import__)
def test_main():
from test.support import run_unittest
run_unittest(ReturnValue, HandlingFromlist)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -7,7 +7,7 @@ import unittest
import warnings
class CallingOrder(unittest.TestCase):
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
@ -24,7 +24,7 @@ class CallingOrder(unittest.TestCase):
first.modules[mod] = 42
second.modules[mod] = -13
with util.import_state(meta_path=[first, second]):
self.assertEqual(import_util.import_(mod), 42)
self.assertEqual(self.__import__(mod), 42)
def test_continuing(self):
# [continuing]
@ -34,7 +34,7 @@ class CallingOrder(unittest.TestCase):
first.find_module = lambda self, fullname, path=None: None
second.modules[mod_name] = 42
with util.import_state(meta_path=[first, second]):
self.assertEqual(import_util.import_(mod_name), 42)
self.assertEqual(self.__import__(mod_name), 42)
def test_empty(self):
# Raise an ImportWarning if sys.meta_path is empty.
@ -51,8 +51,11 @@ class CallingOrder(unittest.TestCase):
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, ImportWarning))
Frozen_CallingOrder, Source_CallingOrder = util.test_both(
CallingOrder, __import__=import_util.__import__)
class CallSignature(unittest.TestCase):
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'
@ -74,7 +77,7 @@ class CallSignature(unittest.TestCase):
log, wrapped_call = self.log(importer.find_module)
importer.find_module = MethodType(wrapped_call, importer)
with util.import_state(meta_path=[importer]):
import_util.import_(mod_name)
self.__import__(mod_name)
assert len(log) == 1
args = log[0][0]
kwargs = log[0][1]
@ -95,7 +98,7 @@ class CallSignature(unittest.TestCase):
log, wrapped_call = self.log(importer.find_module)
importer.find_module = MethodType(wrapped_call, importer)
with util.import_state(meta_path=[importer]):
import_util.import_(mod_name)
self.__import__(mod_name)
assert len(log) == 2
args = log[1][0]
kwargs = log[1][1]
@ -104,12 +107,9 @@ class CallSignature(unittest.TestCase):
self.assertEqual(args[0], mod_name)
self.assertIs(args[1], path)
def test_main():
from test.support import run_unittest
run_unittest(CallingOrder, CallSignature)
Frozen_CallSignature, Source_CallSignature = util.test_both(
CallSignature, __import__=import_util.__import__)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -6,21 +6,21 @@ import importlib
from test import support
class ParentModuleTests(unittest.TestCase):
class ParentModuleTests:
"""Importing a submodule should import the parent modules."""
def test_import_parent(self):
with util.mock_modules('pkg.__init__', 'pkg.module') as mock:
with util.import_state(meta_path=[mock]):
module = import_util.import_('pkg.module')
module = self.__import__('pkg.module')
self.assertIn('pkg', sys.modules)
def test_bad_parent(self):
with util.mock_modules('pkg.module') as mock:
with util.import_state(meta_path=[mock]):
with self.assertRaises(ImportError) as cm:
import_util.import_('pkg.module')
self.__import__('pkg.module')
self.assertEqual(cm.exception.name, 'pkg')
def test_raising_parent_after_importing_child(self):
@ -32,11 +32,11 @@ class ParentModuleTests(unittest.TestCase):
with mock:
with util.import_state(meta_path=[mock]):
with self.assertRaises(ZeroDivisionError):
import_util.import_('pkg')
self.__import__('pkg')
self.assertNotIn('pkg', sys.modules)
self.assertIn('pkg.module', sys.modules)
with self.assertRaises(ZeroDivisionError):
import_util.import_('pkg.module')
self.__import__('pkg.module')
self.assertNotIn('pkg', sys.modules)
self.assertIn('pkg.module', sys.modules)
@ -51,10 +51,10 @@ class ParentModuleTests(unittest.TestCase):
with self.assertRaises((ZeroDivisionError, ImportError)):
# This raises ImportError on the "from . import module"
# line, not sure why.
import_util.import_('pkg')
self.__import__('pkg')
self.assertNotIn('pkg', sys.modules)
with self.assertRaises((ZeroDivisionError, ImportError)):
import_util.import_('pkg.module')
self.__import__('pkg.module')
self.assertNotIn('pkg', sys.modules)
# XXX False
#self.assertIn('pkg.module', sys.modules)
@ -71,10 +71,10 @@ class ParentModuleTests(unittest.TestCase):
with self.assertRaises((ZeroDivisionError, ImportError)):
# This raises ImportError on the "from ..subpkg import module"
# line, not sure why.
import_util.import_('pkg.subpkg')
self.__import__('pkg.subpkg')
self.assertNotIn('pkg.subpkg', sys.modules)
with self.assertRaises((ZeroDivisionError, ImportError)):
import_util.import_('pkg.subpkg.module')
self.__import__('pkg.subpkg.module')
self.assertNotIn('pkg.subpkg', sys.modules)
# XXX False
#self.assertIn('pkg.subpkg.module', sys.modules)
@ -83,7 +83,7 @@ class ParentModuleTests(unittest.TestCase):
# Try to import a submodule from a non-package should raise ImportError.
assert not hasattr(sys, '__path__')
with self.assertRaises(ImportError) as cm:
import_util.import_('sys.no_submodules_here')
self.__import__('sys.no_submodules_here')
self.assertEqual(cm.exception.name, 'sys.no_submodules_here')
def test_module_not_package_but_side_effects(self):
@ -98,15 +98,13 @@ class ParentModuleTests(unittest.TestCase):
with mock_modules as mock:
with util.import_state(meta_path=[mock]):
try:
submodule = import_util.import_(subname)
submodule = self.__import__(subname)
finally:
support.unload(subname)
def test_main():
from test.support import run_unittest
run_unittest(ParentModuleTests)
Frozen_ParentTests, Source_ParentTests = util.test_both(
ParentModuleTests, __import__=import_util.__import__)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -1,8 +1,9 @@
from importlib import _bootstrap
from importlib import machinery
from importlib import import_module
from .. import util
from . import util as import_util
importlib = util.import_importlib('importlib')
machinery = util.import_importlib('importlib.machinery')
import os
import sys
from types import ModuleType
@ -11,7 +12,7 @@ import warnings
import zipimport
class FinderTests(unittest.TestCase):
class FinderTests:
"""Tests for PathFinder."""
@ -19,7 +20,7 @@ class FinderTests(unittest.TestCase):
# Test None returned upon not finding a suitable finder.
module = '<test module>'
with util.import_state():
self.assertIsNone(machinery.PathFinder.find_module(module))
self.assertIsNone(self.machinery.PathFinder.find_module(module))
def test_sys_path(self):
# Test that sys.path is used when 'path' is None.
@ -29,7 +30,7 @@ class FinderTests(unittest.TestCase):
importer = util.mock_modules(module)
with util.import_state(path_importer_cache={path: importer},
path=[path]):
loader = machinery.PathFinder.find_module(module)
loader = self.machinery.PathFinder.find_module(module)
self.assertIs(loader, importer)
def test_path(self):
@ -39,7 +40,7 @@ class FinderTests(unittest.TestCase):
path = '<test path>'
importer = util.mock_modules(module)
with util.import_state(path_importer_cache={path: importer}):
loader = machinery.PathFinder.find_module(module, [path])
loader = self.machinery.PathFinder.find_module(module, [path])
self.assertIs(loader, importer)
def test_empty_list(self):
@ -49,7 +50,7 @@ class FinderTests(unittest.TestCase):
importer = util.mock_modules(module)
with util.import_state(path_importer_cache={path: importer},
path=[path]):
self.assertIsNone(machinery.PathFinder.find_module('module', []))
self.assertIsNone(self.machinery.PathFinder.find_module('module', []))
def test_path_hooks(self):
# Test that sys.path_hooks is used.
@ -59,7 +60,7 @@ class FinderTests(unittest.TestCase):
importer = util.mock_modules(module)
hook = import_util.mock_path_hook(path, importer=importer)
with util.import_state(path_hooks=[hook]):
loader = machinery.PathFinder.find_module(module, [path])
loader = self.machinery.PathFinder.find_module(module, [path])
self.assertIs(loader, importer)
self.assertIn(path, sys.path_importer_cache)
self.assertIs(sys.path_importer_cache[path], importer)
@ -72,7 +73,7 @@ class FinderTests(unittest.TestCase):
path=[path_entry]):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
self.assertIsNone(machinery.PathFinder.find_module('os'))
self.assertIsNone(self.machinery.PathFinder.find_module('os'))
self.assertIsNone(sys.path_importer_cache[path_entry])
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, ImportWarning))
@ -84,7 +85,7 @@ class FinderTests(unittest.TestCase):
importer = util.mock_modules(module)
hook = import_util.mock_path_hook(os.getcwd(), importer=importer)
with util.import_state(path=[path], path_hooks=[hook]):
loader = machinery.PathFinder.find_module(module)
loader = self.machinery.PathFinder.find_module(module)
self.assertIs(loader, importer)
self.assertIn(os.getcwd(), sys.path_importer_cache)
@ -96,8 +97,8 @@ class FinderTests(unittest.TestCase):
new_path_importer_cache = sys.path_importer_cache.copy()
new_path_importer_cache.pop(None, None)
new_path_hooks = [zipimport.zipimporter,
_bootstrap.FileFinder.path_hook(
*_bootstrap._get_supported_file_loaders())]
self.machinery.FileFinder.path_hook(
*self.importlib._bootstrap._get_supported_file_loaders())]
missing = object()
email = sys.modules.pop('email', missing)
try:
@ -105,16 +106,15 @@ class FinderTests(unittest.TestCase):
path=new_path,
path_importer_cache=new_path_importer_cache,
path_hooks=new_path_hooks):
module = import_module('email')
module = self.importlib.import_module('email')
self.assertIsInstance(module, ModuleType)
finally:
if email is not missing:
sys.modules['email'] = email
Frozen_FinderTests, Source_FinderTests = util.test_both(
FinderTests, importlib=importlib, machinery=machinery)
def test_main():
from test.support import run_unittest
run_unittest(FinderTests)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -4,7 +4,7 @@ from . import util as import_util
import sys
import unittest
class RelativeImports(unittest.TestCase):
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.
@ -76,8 +76,8 @@ class RelativeImports(unittest.TestCase):
create = 'pkg.__init__', 'pkg.mod2'
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
def callback(global_):
import_util.import_('pkg') # For __import__().
module = import_util.import_('', global_, fromlist=['mod2'], level=1)
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')
@ -88,8 +88,8 @@ class RelativeImports(unittest.TestCase):
create = 'pkg.__init__', 'pkg.mod2'
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.mod1'}
def callback(global_):
import_util.import_('pkg') # For __import__().
module = import_util.import_('mod2', global_, fromlist=['attr'],
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')
@ -101,8 +101,8 @@ class RelativeImports(unittest.TestCase):
globals_ = ({'__package__': 'pkg'},
{'__name__': 'pkg', '__path__': ['blah']})
def callback(global_):
import_util.import_('pkg') # For __import__().
module = import_util.import_('', global_, fromlist=['module'],
self.__import__('pkg') # For __import__().
module = self.__import__('', global_, fromlist=['module'],
level=1)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module'))
@ -114,8 +114,8 @@ class RelativeImports(unittest.TestCase):
create = 'pkg.__init__', 'pkg.module'
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
def callback(global_):
import_util.import_('pkg') # For __import__().
module = import_util.import_('', global_, fromlist=['attr'], level=1)
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)
@ -126,7 +126,7 @@ class RelativeImports(unittest.TestCase):
globals_ = ({'__package__': 'pkg.subpkg1'},
{'__name__': 'pkg.subpkg1', '__path__': ['blah']})
def callback(global_):
module = import_util.import_('', global_, fromlist=['subpkg2'],
module = self.__import__('', global_, fromlist=['subpkg2'],
level=2)
self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'subpkg2'))
@ -142,8 +142,8 @@ class RelativeImports(unittest.TestCase):
{'__name__': 'pkg.pkg1.pkg2.pkg3.pkg4.pkg5',
'__path__': ['blah']})
def callback(global_):
import_util.import_(globals_[0]['__package__'])
module = import_util.import_('', global_, fromlist=['attr'], level=6)
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)
@ -153,9 +153,9 @@ class RelativeImports(unittest.TestCase):
globals_ = ({'__package__': 'pkg'},
{'__name__': 'pkg', '__path__': ['blah']})
def callback(global_):
import_util.import_('pkg')
self.__import__('pkg')
with self.assertRaises(ValueError):
import_util.import_('', global_, fromlist=['top_level'],
self.__import__('', global_, fromlist=['top_level'],
level=2)
self.relative_import_test(create, globals_, callback)
@ -164,16 +164,16 @@ class RelativeImports(unittest.TestCase):
create = ['top_level', 'pkg.__init__', 'pkg.module']
globals_ = {'__package__': 'pkg'}, {'__name__': 'pkg.module'}
def callback(global_):
import_util.import_('pkg')
self.__import__('pkg')
with self.assertRaises(ValueError):
import_util.import_('', global_, fromlist=['top_level'],
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):
import_util.import_('')
self.__import__('')
def test_import_from_different_package(self):
# Test importing from a different package than the caller.
@ -186,8 +186,8 @@ class RelativeImports(unittest.TestCase):
'__runpy_pkg__.uncle.cousin.nephew']
globals_ = {'__package__': '__runpy_pkg__.__runpy_pkg__'}
def callback(global_):
import_util.import_('__runpy_pkg__.__runpy_pkg__')
module = import_util.import_('uncle.cousin', globals_, {},
self.__import__('__runpy_pkg__.__runpy_pkg__')
module = self.__import__('uncle.cousin', globals_, {},
fromlist=['nephew'],
level=2)
self.assertEqual(module.__name__, '__runpy_pkg__.uncle.cousin')
@ -198,20 +198,19 @@ class RelativeImports(unittest.TestCase):
create = ['crash.__init__', 'crash.mod']
globals_ = [{'__package__': 'crash', '__name__': 'crash'}]
def callback(global_):
import_util.import_('crash')
mod = import_util.import_('mod', global_, {}, [], 1)
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 self.assertRaises(KeyError):
import_util.import_('sys', level=1)
self.__import__('sys', level=1)
Frozen_RelativeImports, Source_RelativeImports = util.test_both(
RelativeImports, __import__=import_util.__import__)
def test_main():
from test.support import run_unittest
run_unittest(RelativeImports)
if __name__ == '__main__':
test_main()
unittest.main()

View File

@ -1,22 +1,14 @@
from .. import util
frozen_importlib, source_importlib = util.import_importlib('importlib')
import builtins
import functools
import importlib
import unittest
using___import__ = False
def import_(*args, **kwargs):
"""Delegate to allow for injecting different implementations of import."""
if using___import__:
return __import__(*args, **kwargs)
else:
return importlib.__import__(*args, **kwargs)
def importlib_only(fxn):
"""Decorator to skip a test if using __builtins__.__import__."""
return unittest.skipIf(using___import__, "importlib-specific test")(fxn)
__import__ = staticmethod(builtins.__import__), staticmethod(source_importlib.__import__)
def mock_path_hook(*entries, importer):