summaryrefslogtreecommitdiff
path: root/Lib/test/test_importlib/import_
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test/test_importlib/import_')
-rw-r--r--Lib/test/test_importlib/import_/test___package__.py55
-rw-r--r--Lib/test/test_importlib/import_/test_api.py4
-rw-r--r--Lib/test/test_importlib/import_/test_fromlist.py10
-rw-r--r--Lib/test/test_importlib/import_/test_packages.py1
-rw-r--r--Lib/test/test_importlib/import_/test_path.py68
-rw-r--r--Lib/test/test_importlib/import_/test_relative_imports.py24
6 files changed, 119 insertions, 43 deletions
diff --git a/Lib/test/test_importlib/import_/test___package__.py b/Lib/test/test_importlib/import_/test___package__.py
index c7d3a2a204..7f64548748 100644
--- a/Lib/test/test_importlib/import_/test___package__.py
+++ b/Lib/test/test_importlib/import_/test___package__.py
@@ -5,6 +5,7 @@ of using the typical __path__/__name__ test).
"""
import unittest
+import warnings
from .. import util
@@ -33,31 +34,50 @@ class Using__package__:
"""
- def test_using___package__(self):
- # [__package__]
+ def import_module(self, globals_):
with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
with util.import_state(meta_path=[importer]):
self.__import__('pkg.fake')
module = self.__import__('',
- globals={'__package__': 'pkg.fake'},
- fromlist=['attr'], level=2)
+ globals=globals_,
+ fromlist=['attr'], level=2)
+ return module
+
+ def test_using___package__(self):
+ # [__package__]
+ module = self.import_module({'__package__': 'pkg.fake'})
self.assertEqual(module.__name__, 'pkg')
- def test_using___name__(self, package_as_None=False):
+ def test_using___name__(self):
# [__name__]
- globals_ = {'__name__': 'pkg.fake', '__path__': []}
- if package_as_None:
- globals_['__package__'] = None
- with self.mock_modules('pkg.__init__', 'pkg.fake') as importer:
- with util.import_state(meta_path=[importer]):
- self.__import__('pkg.fake')
- module = self.__import__('', globals= globals_,
- fromlist=['attr'], level=2)
- self.assertEqual(module.__name__, 'pkg')
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ module = self.import_module({'__name__': 'pkg.fake',
+ '__path__': []})
+ self.assertEqual(module.__name__, 'pkg')
+
+ def test_warn_when_using___name__(self):
+ with self.assertWarns(ImportWarning):
+ self.import_module({'__name__': 'pkg.fake', '__path__': []})
def test_None_as___package__(self):
# [None]
- self.test_using___name__(package_as_None=True)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ module = self.import_module({
+ '__name__': 'pkg.fake', '__path__': [], '__package__': None })
+ self.assertEqual(module.__name__, 'pkg')
+
+ def test_spec_fallback(self):
+ # If __package__ isn't defined, fall back on __spec__.parent.
+ module = self.import_module({'__spec__': FakeSpec('pkg.fake')})
+ self.assertEqual(module.__name__, 'pkg')
+
+ def test_warn_when_package_and_spec_disagree(self):
+ # Raise an ImportWarning if __package__ != __spec__.parent.
+ with self.assertWarns(ImportWarning):
+ self.import_module({'__package__': 'pkg.fake',
+ '__spec__': FakeSpec('pkg.fakefake')})
def test_bad__package__(self):
globals = {'__package__': '<not real>'}
@@ -70,6 +90,11 @@ class Using__package__:
self.__import__('', globals, {}, ['relimport'], 1)
+class FakeSpec:
+ def __init__(self, parent):
+ self.parent = parent
+
+
class Using__package__PEP302(Using__package__):
mock_modules = util.mock_modules
diff --git a/Lib/test/test_importlib/import_/test_api.py b/Lib/test/test_importlib/import_/test_api.py
index 7069d9e58d..a7bf2749cf 100644
--- a/Lib/test/test_importlib/import_/test_api.py
+++ b/Lib/test/test_importlib/import_/test_api.py
@@ -43,6 +43,10 @@ class APITest:
"""Test API-specific details for __import__ (e.g. raising the right
exception when passing in an int for the module name)."""
+ def test_raises_ModuleNotFoundError(self):
+ with self.assertRaises(ModuleNotFoundError):
+ util.import_importlib('some module that does not exist')
+
def test_name_requires_rparition(self):
# Raise TypeError if a non-string is passed in for the module name.
with self.assertRaises(TypeError):
diff --git a/Lib/test/test_importlib/import_/test_fromlist.py b/Lib/test/test_importlib/import_/test_fromlist.py
index 80454655ad..14640032b4 100644
--- a/Lib/test/test_importlib/import_/test_fromlist.py
+++ b/Lib/test/test_importlib/import_/test_fromlist.py
@@ -73,16 +73,16 @@ class HandlingFromlist:
self.assertTrue(hasattr(module, 'module'))
self.assertEqual(module.module.__name__, 'pkg.module')
- def test_module_from_package_triggers_ImportError(self):
- # If a submodule causes an ImportError because it tries to import
- # a module which doesn't exist, that should let the ImportError
- # propagate.
+ def test_module_from_package_triggers_ModuleNotFoundError(self):
+ # If a submodule causes an ModuleNotFoundError because it tries
+ # to import a module which doesn't exist, that should let the
+ # ModuleNotFoundError propagate.
def module_code():
import i_do_not_exist
with util.mock_modules('pkg.__init__', 'pkg.mod',
module_code={'pkg.mod': module_code}) as importer:
with util.import_state(meta_path=[importer]):
- with self.assertRaises(ImportError) as exc:
+ with self.assertRaises(ModuleNotFoundError) as exc:
self.__import__('pkg', fromlist=['mod'])
self.assertEqual('i_do_not_exist', exc.exception.name)
diff --git a/Lib/test/test_importlib/import_/test_packages.py b/Lib/test/test_importlib/import_/test_packages.py
index 3755b84a1a..24396044a5 100644
--- a/Lib/test/test_importlib/import_/test_packages.py
+++ b/Lib/test/test_importlib/import_/test_packages.py
@@ -1,7 +1,6 @@
from .. import util
import sys
import unittest
-import importlib
from test import support
diff --git a/Lib/test/test_importlib/import_/test_path.py b/Lib/test/test_importlib/import_/test_path.py
index b32a876f89..7aa26b0eee 100644
--- a/Lib/test/test_importlib/import_/test_path.py
+++ b/Lib/test/test_importlib/import_/test_path.py
@@ -16,11 +16,14 @@ class FinderTests:
"""Tests for PathFinder."""
+ find = None
+ check_found = None
+
def test_failure(self):
# Test None returned upon not finding a suitable loader.
module = '<test module>'
with util.import_state():
- self.assertIsNone(self.machinery.PathFinder.find_module(module))
+ self.assertIsNone(self.find(module))
def test_sys_path(self):
# Test that sys.path is used when 'path' is None.
@@ -30,8 +33,8 @@ class FinderTests:
importer = util.mock_spec(module)
with util.import_state(path_importer_cache={path: importer},
path=[path]):
- loader = self.machinery.PathFinder.find_module(module)
- self.assertIs(loader, importer)
+ found = self.find(module)
+ self.check_found(found, importer)
def test_path(self):
# Test that 'path' is used when set.
@@ -40,8 +43,8 @@ class FinderTests:
path = '<test path>'
importer = util.mock_spec(module)
with util.import_state(path_importer_cache={path: importer}):
- loader = self.machinery.PathFinder.find_module(module, [path])
- self.assertIs(loader, importer)
+ found = self.find(module, [path])
+ self.check_found(found, importer)
def test_empty_list(self):
# An empty list should not count as asking for sys.path.
@@ -50,7 +53,7 @@ class FinderTests:
importer = util.mock_spec(module)
with util.import_state(path_importer_cache={path: importer},
path=[path]):
- self.assertIsNone(self.machinery.PathFinder.find_module('module', []))
+ self.assertIsNone(self.find('module', []))
def test_path_hooks(self):
# Test that sys.path_hooks is used.
@@ -60,8 +63,8 @@ class FinderTests:
importer = util.mock_spec(module)
hook = util.mock_path_hook(path, importer=importer)
with util.import_state(path_hooks=[hook]):
- loader = self.machinery.PathFinder.find_module(module, [path])
- self.assertIs(loader, importer)
+ found = self.find(module, [path])
+ self.check_found(found, importer)
self.assertIn(path, sys.path_importer_cache)
self.assertIs(sys.path_importer_cache[path], importer)
@@ -73,7 +76,7 @@ class FinderTests:
path=[path_entry]):
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter('always')
- self.assertIsNone(self.machinery.PathFinder.find_module('os'))
+ self.assertIsNone(self.find('os'))
self.assertIsNone(sys.path_importer_cache[path_entry])
self.assertEqual(len(w), 1)
self.assertTrue(issubclass(w[-1].category, ImportWarning))
@@ -85,8 +88,8 @@ class FinderTests:
importer = util.mock_spec(module)
hook = util.mock_path_hook(os.getcwd(), importer=importer)
with util.import_state(path=[path], path_hooks=[hook]):
- loader = self.machinery.PathFinder.find_module(module)
- self.assertIs(loader, importer)
+ found = self.find(module)
+ self.check_found(found, importer)
self.assertIn(os.getcwd(), sys.path_importer_cache)
def test_None_on_sys_path(self):
@@ -182,16 +185,33 @@ class FinderTests:
self.assertIsNone(self.machinery.PathFinder.find_spec('whatever'))
+class FindModuleTests(FinderTests):
+ def find(self, *args, **kwargs):
+ return self.machinery.PathFinder.find_module(*args, **kwargs)
+ def check_found(self, found, importer):
+ self.assertIs(found, importer)
+
+
+(Frozen_FindModuleTests,
+ Source_FindModuleTests
+) = util.test_both(FindModuleTests, importlib=importlib, machinery=machinery)
-(Frozen_FinderTests,
- Source_FinderTests
- ) = util.test_both(FinderTests, importlib=importlib, machinery=machinery)
+class FindSpecTests(FinderTests):
+ def find(self, *args, **kwargs):
+ return self.machinery.PathFinder.find_spec(*args, **kwargs)
+ def check_found(self, found, importer):
+ self.assertIs(found.loader, importer)
+
+
+(Frozen_FindSpecTests,
+ Source_FindSpecTests
+ ) = util.test_both(FindSpecTests, importlib=importlib, machinery=machinery)
class PathEntryFinderTests:
- def test_finder_with_failing_find_module(self):
+ def test_finder_with_failing_find_spec(self):
# PathEntryFinder with find_module() defined should work.
# Issue #20763.
class Finder:
@@ -209,6 +229,24 @@ class PathEntryFinderTests:
path_hooks=[Finder]):
self.machinery.PathFinder.find_spec('importlib')
+ def test_finder_with_failing_find_module(self):
+ # PathEntryFinder with find_module() defined should work.
+ # Issue #20763.
+ class Finder:
+ path_location = 'test_finder_with_find_module'
+ def __init__(self, path):
+ if path != self.path_location:
+ raise ImportError
+
+ @staticmethod
+ def find_module(fullname):
+ return None
+
+
+ with util.import_state(path=[Finder.path_location]+sys.path[:],
+ path_hooks=[Finder]):
+ self.machinery.PathFinder.find_module('importlib')
+
(Frozen_PEFTests,
Source_PEFTests
diff --git a/Lib/test/test_importlib/import_/test_relative_imports.py b/Lib/test/test_importlib/import_/test_relative_imports.py
index 3bb819f906..8a95a32109 100644
--- a/Lib/test/test_importlib/import_/test_relative_imports.py
+++ b/Lib/test/test_importlib/import_/test_relative_imports.py
@@ -1,7 +1,8 @@
"""Test relative imports (PEP 328)."""
from .. import util
-import sys
import unittest
+import warnings
+
class RelativeImports:
@@ -65,9 +66,11 @@ class RelativeImports:
uncache_names.append(name[:-len('.__init__')])
with util.mock_spec(*create) as importer:
with util.import_state(meta_path=[importer]):
- for global_ in globals_:
- with util.uncache(*uncache_names):
- callback(global_)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ for global_ in globals_:
+ with util.uncache(*uncache_names):
+ callback(global_)
def test_module_from_module(self):
@@ -204,11 +207,18 @@ class RelativeImports:
def test_relative_import_no_globals(self):
# No globals for a relative import is an error.
- with self.assertRaises(KeyError):
- self.__import__('sys', level=1)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore")
+ with self.assertRaises(KeyError):
+ self.__import__('sys', level=1)
+
+ def test_relative_import_no_package(self):
+ with self.assertRaises(ImportError):
+ self.__import__('a', {'__package__': '', '__spec__': None},
+ level=1)
def test_relative_import_no_package_exists_absolute(self):
- with self.assertRaises(SystemError):
+ with self.assertRaises(ImportError):
self.__import__('sys', {'__package__': '', '__spec__': None},
level=1)