Commit 9674a762 authored by Eric Snow's avatar Eric Snow

Issue 19713: Add PEP 451-related deprecations.

parent c7570bf7
...@@ -12,6 +12,7 @@ __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] ...@@ -12,6 +12,7 @@ __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload']
import _imp # Just the builtin component, NOT the full Python module import _imp # Just the builtin component, NOT the full Python module
import sys import sys
import types import types
import warnings
try: try:
import _frozen_importlib as _bootstrap import _frozen_importlib as _bootstrap
...@@ -77,13 +78,16 @@ def find_spec(name, path=None): ...@@ -77,13 +78,16 @@ def find_spec(name, path=None):
return spec return spec
# XXX Deprecate...
def find_loader(name, path=None): def find_loader(name, path=None):
"""Return the loader for the specified module. """Return the loader for the specified module.
This is a backward-compatible wrapper around find_spec(). This is a backward-compatible wrapper around find_spec().
This function is deprecated in favor of importlib.find_spec().
""" """
warnings.warn('Use importlib.find_spec() instead.', DeprecationWarning,
stacklevel=2)
try: try:
loader = sys.modules[name].__loader__ loader = sys.modules[name].__loader__
if loader is None: if loader is None:
......
...@@ -564,7 +564,11 @@ def _requires_frozen(fxn): ...@@ -564,7 +564,11 @@ def _requires_frozen(fxn):
def _find_module_shim(self, fullname): def _find_module_shim(self, fullname):
"""Try to find a loader for the specified module by delegating to """Try to find a loader for the specified module by delegating to
self.find_loader().""" self.find_loader().
This method is deprecated in favor of finder.find_spec().
"""
# Call find_loader(). If it returns a string (indicating this # Call find_loader(). If it returns a string (indicating this
# is a namespace package portion), generate a warning and # is a namespace package portion), generate a warning and
# return None. # return None.
...@@ -576,8 +580,11 @@ def _find_module_shim(self, fullname): ...@@ -576,8 +580,11 @@ def _find_module_shim(self, fullname):
def _load_module_shim(self, fullname): def _load_module_shim(self, fullname):
"""Load the specified module into sys.modules and return it.""" """Load the specified module into sys.modules and return it.
# XXX Deprecation Warning here...
This method is deprecated. Use loader.exec_module instead.
"""
spec = spec_from_loader(fullname, self) spec = spec_from_loader(fullname, self)
methods = _SpecMethods(spec) methods = _SpecMethods(spec)
if fullname in sys.modules: if fullname in sys.modules:
...@@ -683,7 +690,9 @@ def _module_repr(module): ...@@ -683,7 +690,9 @@ def _module_repr(module):
# The implementation of ModuleType__repr__(). # The implementation of ModuleType__repr__().
loader = getattr(module, '__loader__', None) loader = getattr(module, '__loader__', None)
if hasattr(loader, 'module_repr'): if hasattr(loader, 'module_repr'):
# XXX Deprecation Warning here... # As soon as BuiltinImporter, FrozenImporter, and NamespaceLoader
# drop their implementations for module_repr. we can add a
# deprecation warning here.
try: try:
return loader.module_repr(module) return loader.module_repr(module)
except Exception: except Exception:
...@@ -1149,17 +1158,27 @@ class _SpecMethods: ...@@ -1149,17 +1158,27 @@ class _SpecMethods:
return module return module
self.init_module_attrs(module, _override=True) self.init_module_attrs(module, _override=True)
if not hasattr(self.spec.loader, 'exec_module'): if not hasattr(self.spec.loader, 'exec_module'):
# XXX DeprecationWarning goes here... # (issue19713) Once BuiltinImporter and ExtensionFileLoader
# have exec_module() implemented, we can add a deprecation
# warning here.
self.spec.loader.load_module(name) self.spec.loader.load_module(name)
else: else:
self._exec(module) self._exec(module)
return sys.modules[name] return sys.modules[name]
def _load_backward_compatible(self): def _load_backward_compatible(self):
# XXX DeprecationWarning goes here... # (issue19713) Once BuiltinImporter and ExtensionFileLoader
# have exec_module() implemented, we can add a deprecation
# warning here.
spec = self.spec spec = self.spec
# The module must be in sys.modules! # The module must be in sys.modules!
spec.loader.load_module(spec.name) try:
_warnings
except NameError:
# We must be importing builtins in setup().
spec.loader.load_module(spec.name)
else:
spec.loader.load_module(spec.name)
module = sys.modules[spec.name] module = sys.modules[spec.name]
if getattr(module, '__loader__', None) is None: if getattr(module, '__loader__', None) is None:
try: try:
...@@ -1233,7 +1252,11 @@ class BuiltinImporter: ...@@ -1233,7 +1252,11 @@ class BuiltinImporter:
@staticmethod @staticmethod
def module_repr(module): def module_repr(module):
# XXX deprecate """Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
return '<module {!r} (built-in)>'.format(module.__name__) return '<module {!r} (built-in)>'.format(module.__name__)
@classmethod @classmethod
...@@ -1251,6 +1274,8 @@ class BuiltinImporter: ...@@ -1251,6 +1274,8 @@ class BuiltinImporter:
If 'path' is ever specified then the search is considered a failure. If 'path' is ever specified then the search is considered a failure.
This method is deprecated. Use find_spec() instead.
""" """
spec = cls.find_spec(fullname, path) spec = cls.find_spec(fullname, path)
return spec.loader if spec is not None else None return spec.loader if spec is not None else None
...@@ -1259,6 +1284,8 @@ class BuiltinImporter: ...@@ -1259,6 +1284,8 @@ class BuiltinImporter:
@_requires_builtin @_requires_builtin
def load_module(cls, fullname): def load_module(cls, fullname):
"""Load a built-in module.""" """Load a built-in module."""
# Once an exec_module() implementation is added we can also
# add a deprecation warning here.
with _ManageReload(fullname): with _ManageReload(fullname):
module = _call_with_frames_removed(_imp.init_builtin, fullname) module = _call_with_frames_removed(_imp.init_builtin, fullname)
module.__loader__ = cls module.__loader__ = cls
...@@ -1281,7 +1308,6 @@ class BuiltinImporter: ...@@ -1281,7 +1308,6 @@ class BuiltinImporter:
@_requires_builtin @_requires_builtin
def is_package(cls, fullname): def is_package(cls, fullname):
"""Return False as built-in modules are never packages.""" """Return False as built-in modules are never packages."""
# XXX DeprecationWarning here...
return False return False
...@@ -1296,7 +1322,11 @@ class FrozenImporter: ...@@ -1296,7 +1322,11 @@ class FrozenImporter:
@staticmethod @staticmethod
def module_repr(m): def module_repr(m):
# XXX deprecate """Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
return '<module {!r} (frozen)>'.format(m.__name__) return '<module {!r} (frozen)>'.format(m.__name__)
@classmethod @classmethod
...@@ -1308,7 +1338,11 @@ class FrozenImporter: ...@@ -1308,7 +1338,11 @@ class FrozenImporter:
@classmethod @classmethod
def find_module(cls, fullname, path=None): def find_module(cls, fullname, path=None):
"""Find a frozen module.""" """Find a frozen module.
This method is deprecated. Use find_spec() instead.
"""
return cls if _imp.is_frozen(fullname) else None return cls if _imp.is_frozen(fullname) else None
@staticmethod @staticmethod
...@@ -1322,7 +1356,11 @@ class FrozenImporter: ...@@ -1322,7 +1356,11 @@ class FrozenImporter:
@classmethod @classmethod
def load_module(cls, fullname): def load_module(cls, fullname):
"""Load a frozen module.""" """Load a frozen module.
This method is deprecated. Use exec_module() instead.
"""
return _load_module_shim(cls, fullname) return _load_module_shim(cls, fullname)
@classmethod @classmethod
...@@ -1395,7 +1433,11 @@ class WindowsRegistryFinder: ...@@ -1395,7 +1433,11 @@ class WindowsRegistryFinder:
@classmethod @classmethod
def find_module(cls, fullname, path=None): def find_module(cls, fullname, path=None):
"""Find module named in the registry.""" """Find module named in the registry.
This method is deprecated. Use exec_module() instead.
"""
spec = cls.find_spec(fullname, path) spec = cls.find_spec(fullname, path)
if spec is not None: if spec is not None:
return spec.loader return spec.loader
...@@ -1408,7 +1450,6 @@ class _LoaderBasics: ...@@ -1408,7 +1450,6 @@ class _LoaderBasics:
"""Base class of common code needed by both SourceLoader and """Base class of common code needed by both SourceLoader and
SourcelessFileLoader.""" SourcelessFileLoader."""
# XXX deprecate?
def is_package(self, fullname): def is_package(self, fullname):
"""Concrete implementation of InspectLoader.is_package by checking if """Concrete implementation of InspectLoader.is_package by checking if
the path returned by get_filename has a filename of '__init__.py'.""" the path returned by get_filename has a filename of '__init__.py'."""
...@@ -1558,9 +1599,12 @@ class FileLoader: ...@@ -1558,9 +1599,12 @@ class FileLoader:
@_check_name @_check_name
def load_module(self, fullname): def load_module(self, fullname):
"""Load a module from a file.""" """Load a module from a file.
# The only reason for this method is for the name check.
This method is deprecated. Use exec_module() instead.
"""
# The only reason for this method is for the name check.
# Issue #14857: Avoid the zero-argument form of super so the implementation # Issue #14857: Avoid the zero-argument form of super so the implementation
# of that form can be updated without breaking the frozen module # of that form can be updated without breaking the frozen module
return super(FileLoader, self).load_module(fullname) return super(FileLoader, self).load_module(fullname)
...@@ -1660,6 +1704,8 @@ class ExtensionFileLoader: ...@@ -1660,6 +1704,8 @@ class ExtensionFileLoader:
@_check_name @_check_name
def load_module(self, fullname): def load_module(self, fullname):
"""Load an extension module.""" """Load an extension module."""
# Once an exec_module() implementation is added we can also
# add a deprecation warning here.
with _ManageReload(fullname): with _ManageReload(fullname):
module = _call_with_frames_removed(_imp.load_dynamic, module = _call_with_frames_removed(_imp.load_dynamic,
fullname, self.path) fullname, self.path)
...@@ -1754,9 +1800,13 @@ class _NamespaceLoader: ...@@ -1754,9 +1800,13 @@ class _NamespaceLoader:
def __init__(self, name, path, path_finder): def __init__(self, name, path, path_finder):
self._path = _NamespacePath(name, path, path_finder) self._path = _NamespacePath(name, path, path_finder)
# XXX Deprecate
@classmethod @classmethod
def module_repr(cls, module): def module_repr(cls, module):
"""Return repr for the module.
The method is deprecated. The import machinery does the job itself.
"""
return '<module {!r} (namespace)>'.format(module.__name__) return '<module {!r} (namespace)>'.format(module.__name__)
def is_package(self, fullname): def is_package(self, fullname):
...@@ -1768,9 +1818,16 @@ class _NamespaceLoader: ...@@ -1768,9 +1818,16 @@ class _NamespaceLoader:
def get_code(self, fullname): def get_code(self, fullname):
return compile('', '<string>', 'exec', dont_inherit=True) return compile('', '<string>', 'exec', dont_inherit=True)
# XXX Deprecate def exec_module(self, module):
pass
def load_module(self, fullname): def load_module(self, fullname):
"""Load a namespace module.""" """Load a namespace module.
This method is deprecated. Use exec_module() instead.
"""
# The import system never calls this method.
_verbose_message('namespace module loaded with path {!r}', self._path) _verbose_message('namespace module loaded with path {!r}', self._path)
return _load_module_shim(self, fullname) return _load_module_shim(self, fullname)
...@@ -1825,6 +1882,8 @@ class PathFinder: ...@@ -1825,6 +1882,8 @@ class PathFinder:
@classmethod @classmethod
def _legacy_get_spec(cls, fullname, finder): def _legacy_get_spec(cls, fullname, finder):
# This would be a good place for a DeprecationWarning if
# we ended up going that route.
if hasattr(finder, 'find_loader'): if hasattr(finder, 'find_loader'):
loader, portions = finder.find_loader(fullname) loader, portions = finder.find_loader(fullname)
else: else:
...@@ -1893,8 +1952,11 @@ class PathFinder: ...@@ -1893,8 +1952,11 @@ class PathFinder:
@classmethod @classmethod
def find_module(cls, fullname, path=None): def find_module(cls, fullname, path=None):
"""find the module on sys.path or 'path' based on sys.path_hooks and """find the module on sys.path or 'path' based on sys.path_hooks and
sys.path_importer_cache.""" sys.path_importer_cache.
# XXX Deprecation warning here.
This method is deprecated. Use find_spec() instead.
"""
spec = cls.find_spec(fullname, path) spec = cls.find_spec(fullname, path)
if spec is None: if spec is None:
return None return None
...@@ -1932,7 +1994,11 @@ class FileFinder: ...@@ -1932,7 +1994,11 @@ class FileFinder:
def find_loader(self, fullname): def find_loader(self, fullname):
"""Try to find a loader for the specified module, or the namespace """Try to find a loader for the specified module, or the namespace
package portions. Returns (loader, list-of-portions).""" package portions. Returns (loader, list-of-portions).
This method is deprecated. Use find_spec() instead.
"""
spec = self.find_spec(fullname) spec = self.find_spec(fullname)
if spec is None: if spec is None:
return None, [] return None, []
...@@ -2065,6 +2131,15 @@ def _resolve_name(name, package, level): ...@@ -2065,6 +2131,15 @@ def _resolve_name(name, package, level):
return '{}.{}'.format(base, name) if name else base return '{}.{}'.format(base, name) if name else base
def _find_spec_legacy(finder, name, path):
# This would be a good place for a DeprecationWarning if
# we ended up going that route.
loader = finder.find_module(name, path)
if loader is None:
return None
return spec_from_loader(name, loader)
def _find_spec(name, path, target=None): def _find_spec(name, path, target=None):
"""Find a module's loader.""" """Find a module's loader."""
if not sys.meta_path: if not sys.meta_path:
...@@ -2078,10 +2153,9 @@ def _find_spec(name, path, target=None): ...@@ -2078,10 +2153,9 @@ def _find_spec(name, path, target=None):
try: try:
find_spec = finder.find_spec find_spec = finder.find_spec
except AttributeError: except AttributeError:
loader = finder.find_module(name, path) spec = _find_spec_legacy(finder, name, path)
if loader is None: if spec is None:
continue continue
spec = spec_from_loader(name, loader)
else: else:
spec = find_spec(name, path, target) spec = find_spec(name, path, target)
if spec is not None: if spec is not None:
......
...@@ -43,13 +43,14 @@ class MetaPathFinder(Finder): ...@@ -43,13 +43,14 @@ class MetaPathFinder(Finder):
# We don't define find_spec() here since that would break # We don't define find_spec() here since that would break
# hasattr checks we do to support backward compatibility. # hasattr checks we do to support backward compatibility.
# XXX Deprecate
def find_module(self, fullname, path): def find_module(self, fullname, path):
"""Return a loader for the module. """Return a loader for the module.
If no module is found, return None. The fullname is a str and If no module is found, return None. The fullname is a str and
the path is a list of strings or None. the path is a list of strings or None.
This method is deprecated in favor of finder.find_spec().
""" """
return None return None
...@@ -69,7 +70,6 @@ class PathEntryFinder(Finder): ...@@ -69,7 +70,6 @@ class PathEntryFinder(Finder):
# We don't define find_spec() here since that would break # We don't define find_spec() here since that would break
# hasattr checks we do to support backward compatibility. # hasattr checks we do to support backward compatibility.
# XXX Deprecate.
def find_loader(self, fullname): def find_loader(self, fullname):
"""Return (loader, namespace portion) for the path entry. """Return (loader, namespace portion) for the path entry.
...@@ -81,10 +81,11 @@ class PathEntryFinder(Finder): ...@@ -81,10 +81,11 @@ class PathEntryFinder(Finder):
The portion will be discarded if another path entry finder The portion will be discarded if another path entry finder
locates the module as a normal module or package. locates the module as a normal module or package.
This method is deprecated in favor of finder.find_spec().
""" """
return None, [] return None, []
# XXX Deprecate.
find_module = _bootstrap._find_module_shim find_module = _bootstrap._find_module_shim
def invalidate_caches(self): def invalidate_caches(self):
...@@ -115,7 +116,6 @@ class Loader(metaclass=abc.ABCMeta): ...@@ -115,7 +116,6 @@ class Loader(metaclass=abc.ABCMeta):
# We don't define exec_module() here since that would break # We don't define exec_module() here since that would break
# hasattr checks we do to support backward compatibility. # hasattr checks we do to support backward compatibility.
# XXX Deprecate.
def load_module(self, fullname): def load_module(self, fullname):
"""Return the loaded module. """Return the loaded module.
...@@ -124,16 +124,19 @@ class Loader(metaclass=abc.ABCMeta): ...@@ -124,16 +124,19 @@ class Loader(metaclass=abc.ABCMeta):
ImportError is raised on failure. ImportError is raised on failure.
This method is deprecated in favor of loader.exec_module().
""" """
raise ImportError raise ImportError
# XXX Deprecate.
def module_repr(self, module): def module_repr(self, module):
"""Return a module's repr. """Return a module's repr.
Used by the module type when the method does not raise Used by the module type when the method does not raise
NotImplementedError. NotImplementedError.
This method is deprecated.
""" """
# The exception will cause ModuleType.__repr__ to ignore this method. # The exception will cause ModuleType.__repr__ to ignore this method.
raise NotImplementedError raise NotImplementedError
......
...@@ -55,11 +55,16 @@ def _module_to_load(name): ...@@ -55,11 +55,16 @@ def _module_to_load(name):
module.__initializing__ = False module.__initializing__ = False
# XXX deprecate
def set_package(fxn): def set_package(fxn):
"""Set __package__ on the returned module.""" """Set __package__ on the returned module.
This function is deprecated.
"""
@functools.wraps(fxn) @functools.wraps(fxn)
def set_package_wrapper(*args, **kwargs): def set_package_wrapper(*args, **kwargs):
warnings.warn('The import system now takes care of this automatically.',
DeprecationWarning, stacklevel=2)
module = fxn(*args, **kwargs) module = fxn(*args, **kwargs)
if getattr(module, '__package__', None) is None: if getattr(module, '__package__', None) is None:
module.__package__ = module.__name__ module.__package__ = module.__name__
...@@ -69,11 +74,16 @@ def set_package(fxn): ...@@ -69,11 +74,16 @@ def set_package(fxn):
return set_package_wrapper return set_package_wrapper
# XXX deprecate
def set_loader(fxn): def set_loader(fxn):
"""Set __loader__ on the returned module.""" """Set __loader__ on the returned module.
This function is deprecated.
"""
@functools.wraps(fxn) @functools.wraps(fxn)
def set_loader_wrapper(self, *args, **kwargs): def set_loader_wrapper(self, *args, **kwargs):
warnings.warn('The import system now takes care of this automatically.',
DeprecationWarning, stacklevel=2)
module = fxn(self, *args, **kwargs) module = fxn(self, *args, **kwargs)
if getattr(module, '__loader__', None) is None: if getattr(module, '__loader__', None) is None:
module.__loader__ = self module.__loader__ = self
...@@ -100,7 +110,7 @@ def module_for_loader(fxn): ...@@ -100,7 +110,7 @@ def module_for_loader(fxn):
""" """
warnings.warn('The import system now takes care of this automatically.', warnings.warn('The import system now takes care of this automatically.',
PendingDeprecationWarning, stacklevel=2) DeprecationWarning, stacklevel=2)
@functools.wraps(fxn) @functools.wraps(fxn)
def module_for_loader_wrapper(self, fullname, *args, **kwargs): def module_for_loader_wrapper(self, fullname, *args, **kwargs):
with _module_to_load(fullname) as module: with _module_to_load(fullname) as module:
......
...@@ -5,6 +5,7 @@ from . import util ...@@ -5,6 +5,7 @@ from . import util
machinery = test_util.import_importlib('importlib.machinery') machinery = test_util.import_importlib('importlib.machinery')
import unittest import unittest
import warnings
# XXX find_spec tests # XXX find_spec tests
...@@ -16,7 +17,9 @@ class FinderTests(abc.FinderTests): ...@@ -16,7 +17,9 @@ class FinderTests(abc.FinderTests):
importer = self.machinery.FileFinder(util.PATH, importer = self.machinery.FileFinder(util.PATH,
(self.machinery.ExtensionFileLoader, (self.machinery.ExtensionFileLoader,
self.machinery.EXTENSION_SUFFIXES)) self.machinery.EXTENSION_SUFFIXES))
return importer.find_module(fullname) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
return importer.find_module(fullname)
def test_module(self): def test_module(self):
self.assertTrue(self.find_module(util.NAME)) self.assertTrue(self.find_module(util.NAME))
......
...@@ -8,6 +8,7 @@ import sys ...@@ -8,6 +8,7 @@ import sys
from test.support import captured_stdout from test.support import captured_stdout
import types import types
import unittest import unittest
import warnings
class ExecModuleTests(abc.LoaderTests): class ExecModuleTests(abc.LoaderTests):
...@@ -60,8 +61,16 @@ class ExecModuleTests(abc.LoaderTests): ...@@ -60,8 +61,16 @@ class ExecModuleTests(abc.LoaderTests):
expected=value)) expected=value))
self.assertEqual(output, 'Hello world!\n') self.assertEqual(output, 'Hello world!\n')
def test_module_repr(self): def test_module_repr(self):
name = '__hello__'
module, output = self.exec_module(name)
with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
repr_str = self.machinery.FrozenImporter.module_repr(module)
self.assertEqual(repr_str,
"<module '__hello__' (frozen)>")
def test_module_repr_indirect(self):
name = '__hello__' name = '__hello__'
module, output = self.exec_module(name) module, output = self.exec_module(name)
self.assertEqual(repr(module), self.assertEqual(repr(module),
...@@ -84,7 +93,9 @@ class LoaderTests(abc.LoaderTests): ...@@ -84,7 +93,9 @@ class LoaderTests(abc.LoaderTests):
def test_module(self): def test_module(self):
with util.uncache('__hello__'), captured_stdout() as stdout: with util.uncache('__hello__'), captured_stdout() as stdout:
module = self.machinery.FrozenImporter.load_module('__hello__') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = self.machinery.FrozenImporter.load_module('__hello__')
check = {'__name__': '__hello__', check = {'__name__': '__hello__',
'__package__': '', '__package__': '',
'__loader__': self.machinery.FrozenImporter, '__loader__': self.machinery.FrozenImporter,
...@@ -96,7 +107,9 @@ class LoaderTests(abc.LoaderTests): ...@@ -96,7 +107,9 @@ class LoaderTests(abc.LoaderTests):
def test_package(self): def test_package(self):
with util.uncache('__phello__'), captured_stdout() as stdout: with util.uncache('__phello__'), captured_stdout() as stdout:
module = self.machinery.FrozenImporter.load_module('__phello__') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = self.machinery.FrozenImporter.load_module('__phello__')
check = {'__name__': '__phello__', check = {'__name__': '__phello__',
'__package__': '__phello__', '__package__': '__phello__',
'__path__': [], '__path__': [],
...@@ -113,7 +126,9 @@ class LoaderTests(abc.LoaderTests): ...@@ -113,7 +126,9 @@ class LoaderTests(abc.LoaderTests):
def test_lacking_parent(self): def test_lacking_parent(self):
with util.uncache('__phello__', '__phello__.spam'), \ with util.uncache('__phello__', '__phello__.spam'), \
captured_stdout() as stdout: captured_stdout() as stdout:
module = self.machinery.FrozenImporter.load_module('__phello__.spam') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = self.machinery.FrozenImporter.load_module('__phello__.spam')
check = {'__name__': '__phello__.spam', check = {'__name__': '__phello__.spam',
'__package__': '__phello__', '__package__': '__phello__',
'__loader__': self.machinery.FrozenImporter, '__loader__': self.machinery.FrozenImporter,
...@@ -128,18 +143,29 @@ class LoaderTests(abc.LoaderTests): ...@@ -128,18 +143,29 @@ class LoaderTests(abc.LoaderTests):
def test_module_reuse(self): def test_module_reuse(self):
with util.uncache('__hello__'), captured_stdout() as stdout: with util.uncache('__hello__'), captured_stdout() as stdout:
module1 = self.machinery.FrozenImporter.load_module('__hello__') with warnings.catch_warnings():
module2 = self.machinery.FrozenImporter.load_module('__hello__') warnings.simplefilter('ignore', DeprecationWarning)
module1 = self.machinery.FrozenImporter.load_module('__hello__')
module2 = self.machinery.FrozenImporter.load_module('__hello__')
self.assertIs(module1, module2) self.assertIs(module1, module2)
self.assertEqual(stdout.getvalue(), self.assertEqual(stdout.getvalue(),
'Hello world!\nHello world!\n') 'Hello world!\nHello world!\n')
def test_module_repr(self): def test_module_repr(self):
with util.uncache('__hello__'), captured_stdout(): with util.uncache('__hello__'), captured_stdout():
module = self.machinery.FrozenImporter.load_module('__hello__') with warnings.catch_warnings():
self.assertEqual(repr(module), warnings.simplefilter('ignore', DeprecationWarning)
module = self.machinery.FrozenImporter.load_module('__hello__')
repr_str = self.machinery.FrozenImporter.module_repr(module)
self.assertEqual(repr_str,
"<module '__hello__' (frozen)>") "<module '__hello__' (frozen)>")
def test_module_repr_indirect(self):
with util.uncache('__hello__'), captured_stdout():
module = self.machinery.FrozenImporter.load_module('__hello__')
self.assertEqual(repr(module),
"<module '__hello__' (frozen)>")
# No way to trigger an error in a frozen module. # No way to trigger an error in a frozen module.
test_state_after_failure = None test_state_after_failure = None
......
...@@ -16,6 +16,7 @@ import stat ...@@ -16,6 +16,7 @@ import stat
import sys import sys
import types import types
import unittest import unittest
import warnings
from test.support import make_legacy_pyc, unload from test.support import make_legacy_pyc, unload
...@@ -39,7 +40,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -39,7 +40,9 @@ class SimpleTest(abc.LoaderTests):
loader = Tester('blah', 'blah.py') loader = Tester('blah', 'blah.py')
self.addCleanup(unload, 'blah') self.addCleanup(unload, 'blah')
module = loader.load_module() # Should not raise an exception. with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module() # Should not raise an exception.
def test_get_filename_API(self): def test_get_filename_API(self):
# If fullname is not set then assume self.path is desired. # If fullname is not set then assume self.path is desired.
...@@ -70,7 +73,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -70,7 +73,9 @@ class SimpleTest(abc.LoaderTests):
def test_module(self): def test_module(self):
with source_util.create_modules('_temp') as mapping: with source_util.create_modules('_temp') as mapping:
loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) loader = self.machinery.SourceFileLoader('_temp', mapping['_temp'])
module = loader.load_module('_temp') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module('_temp')
self.assertIn('_temp', sys.modules) self.assertIn('_temp', sys.modules)
check = {'__name__': '_temp', '__file__': mapping['_temp'], check = {'__name__': '_temp', '__file__': mapping['_temp'],
'__package__': ''} '__package__': ''}
...@@ -81,7 +86,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -81,7 +86,9 @@ class SimpleTest(abc.LoaderTests):
with source_util.create_modules('_pkg.__init__') as mapping: with source_util.create_modules('_pkg.__init__') as mapping:
loader = self.machinery.SourceFileLoader('_pkg', loader = self.machinery.SourceFileLoader('_pkg',
mapping['_pkg.__init__']) mapping['_pkg.__init__'])
module = loader.load_module('_pkg') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module('_pkg')
self.assertIn('_pkg', sys.modules) self.assertIn('_pkg', sys.modules)
check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'], check = {'__name__': '_pkg', '__file__': mapping['_pkg.__init__'],
'__path__': [os.path.dirname(mapping['_pkg.__init__'])], '__path__': [os.path.dirname(mapping['_pkg.__init__'])],
...@@ -94,7 +101,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -94,7 +101,9 @@ class SimpleTest(abc.LoaderTests):
with source_util.create_modules('_pkg.__init__', '_pkg.mod')as mapping: with source_util.create_modules('_pkg.__init__', '_pkg.mod')as mapping:
loader = self.machinery.SourceFileLoader('_pkg.mod', loader = self.machinery.SourceFileLoader('_pkg.mod',
mapping['_pkg.mod']) mapping['_pkg.mod'])
module = loader.load_module('_pkg.mod') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module('_pkg.mod')
self.assertIn('_pkg.mod', sys.modules) self.assertIn('_pkg.mod', sys.modules)
check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'], check = {'__name__': '_pkg.mod', '__file__': mapping['_pkg.mod'],
'__package__': '_pkg'} '__package__': '_pkg'}
...@@ -108,12 +117,16 @@ class SimpleTest(abc.LoaderTests): ...@@ -108,12 +117,16 @@ class SimpleTest(abc.LoaderTests):
def test_module_reuse(self): def test_module_reuse(self):
with source_util.create_modules('_temp') as mapping: with source_util.create_modules('_temp') as mapping:
loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) loader = self.machinery.SourceFileLoader('_temp', mapping['_temp'])
module = loader.load_module('_temp') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module('_temp')
module_id = id(module) module_id = id(module)
module_dict_id = id(module.__dict__) module_dict_id = id(module.__dict__)
with open(mapping['_temp'], 'w') as file: with open(mapping['_temp'], 'w') as file:
file.write("testing_var = 42\n") file.write("testing_var = 42\n")
module = loader.load_module('_temp') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module('_temp')
self.assertIn('testing_var', module.__dict__, self.assertIn('testing_var', module.__dict__,
"'testing_var' not in " "'testing_var' not in "
"{0}".format(list(module.__dict__.keys()))) "{0}".format(list(module.__dict__.keys())))
...@@ -138,7 +151,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -138,7 +151,9 @@ class SimpleTest(abc.LoaderTests):
for attr in attributes: for attr in attributes:
self.assertEqual(getattr(orig_module, attr), value) self.assertEqual(getattr(orig_module, attr), value)
with self.assertRaises(SyntaxError): with self.assertRaises(SyntaxError):
loader.load_module(name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
loader.load_module(name)
for attr in attributes: for attr in attributes:
self.assertEqual(getattr(orig_module, attr), value) self.assertEqual(getattr(orig_module, attr), value)
...@@ -149,7 +164,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -149,7 +164,9 @@ class SimpleTest(abc.LoaderTests):
file.write('=') file.write('=')
loader = self.machinery.SourceFileLoader('_temp', mapping['_temp']) loader = self.machinery.SourceFileLoader('_temp', mapping['_temp'])
with self.assertRaises(SyntaxError): with self.assertRaises(SyntaxError):
loader.load_module('_temp') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
loader.load_module('_temp')
self.assertNotIn('_temp', sys.modules) self.assertNotIn('_temp', sys.modules)
def test_file_from_empty_string_dir(self): def test_file_from_empty_string_dir(self):
...@@ -161,7 +178,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -161,7 +178,9 @@ class SimpleTest(abc.LoaderTests):
try: try:
with util.uncache('_temp'): with util.uncache('_temp'):
loader = self.machinery.SourceFileLoader('_temp', file_path) loader = self.machinery.SourceFileLoader('_temp', file_path)
mod = loader.load_module('_temp') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
mod = loader.load_module('_temp')
self.assertEqual(file_path, mod.__file__) self.assertEqual(file_path, mod.__file__)
self.assertEqual(self.util.cache_from_source(file_path), self.assertEqual(self.util.cache_from_source(file_path),
mod.__cached__) mod.__cached__)
...@@ -196,7 +215,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -196,7 +215,9 @@ class SimpleTest(abc.LoaderTests):
self.assertTrue(os.path.exists(compiled)) self.assertTrue(os.path.exists(compiled))
os.unlink(compiled) os.unlink(compiled)
# PEP 302 # PEP 302
mod = loader.load_module('_temp') # XXX with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
mod = loader.load_module('_temp') # XXX
# Sanity checks. # Sanity checks.
self.assertEqual(mod.__cached__, compiled) self.assertEqual(mod.__cached__, compiled)
self.assertEqual(mod.x, 5) self.assertEqual(mod.x, 5)
...@@ -210,7 +231,9 @@ class SimpleTest(abc.LoaderTests): ...@@ -210,7 +231,9 @@ class SimpleTest(abc.LoaderTests):
with self.assertRaises(ImportError): with self.assertRaises(ImportError):
loader.exec_module(module) loader.exec_module(module)
with self.assertRaises(ImportError): with self.assertRaises(ImportError):
loader.load_module('bad name') with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
loader.load_module('bad name')
Frozen_SimpleTest, Source_SimpleTest = util.test_both( Frozen_SimpleTest, Source_SimpleTest = util.test_both(
SimpleTest, importlib=importlib, machinery=machinery, abc=importlib_abc, SimpleTest, importlib=importlib, machinery=machinery, abc=importlib_abc,
...@@ -221,7 +244,10 @@ class BadBytecodeTest: ...@@ -221,7 +244,10 @@ class BadBytecodeTest:
def import_(self, file, module_name): def import_(self, file, module_name):
loader = self.loader(module_name, file) loader = self.loader(module_name, file)
module = loader.load_module(module_name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
# XXX Change to use exec_module().
module = loader.load_module(module_name)
self.assertIn(module_name, sys.modules) self.assertIn(module_name, sys.modules)
def manipulate_bytecode(self, name, mapping, manipulator, *, def manipulate_bytecode(self, name, mapping, manipulator, *,
...@@ -332,7 +358,9 @@ class BadBytecodeTestPEP302(BadBytecodeTest): ...@@ -332,7 +358,9 @@ class BadBytecodeTestPEP302(BadBytecodeTest):
def import_(self, file, module_name): def import_(self, file, module_name):
loader = self.loader(module_name, file) loader = self.loader(module_name, file)
module = loader.load_module(module_name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = loader.load_module(module_name)
self.assertIn(module_name, sys.modules) self.assertIn(module_name, sys.modules)
......
...@@ -46,6 +46,10 @@ class FinderTests(abc.FinderTests): ...@@ -46,6 +46,10 @@ class FinderTests(abc.FinderTests):
self.machinery.BYTECODE_SUFFIXES)] self.machinery.BYTECODE_SUFFIXES)]
return self.machinery.FileFinder(root, *loader_details) return self.machinery.FileFinder(root, *loader_details)
def import_(self, root, module):
finder = self.get_finder(root)
return self._find(finder, module, loader_only=True)
def run_test(self, test, create=None, *, compile_=None, unlink=None): def run_test(self, test, create=None, *, compile_=None, unlink=None):
"""Test the finding of 'test' with the creation of modules listed in """Test the finding of 'test' with the creation of modules listed in
'create'. 'create'.
...@@ -127,7 +131,7 @@ class FinderTests(abc.FinderTests): ...@@ -127,7 +131,7 @@ class FinderTests(abc.FinderTests):
with open('mod.py', 'w') as file: with open('mod.py', 'w') as file:
file.write("# test file for importlib") file.write("# test file for importlib")
try: try:
loader = finder.find_module('mod') loader = self._find(finder, 'mod', loader_only=True)
self.assertTrue(hasattr(loader, 'load_module')) self.assertTrue(hasattr(loader, 'load_module'))
finally: finally:
os.unlink('mod.py') os.unlink('mod.py')
...@@ -145,8 +149,10 @@ class FinderTests(abc.FinderTests): ...@@ -145,8 +149,10 @@ class FinderTests(abc.FinderTests):
mod = 'mod' mod = 'mod'
with source_util.create_modules(mod) as mapping: with source_util.create_modules(mod) as mapping:
finder = self.get_finder(mapping['.root']) finder = self.get_finder(mapping['.root'])
self.assertIsNotNone(finder.find_module(mod)) found = self._find(finder, 'mod', loader_only=True)
self.assertIsNone(finder.find_module(mod)) self.assertIsNotNone(found)
found = self._find(finder, 'mod', loader_only=True)
self.assertIsNone(found)
@unittest.skipUnless(sys.platform != 'win32', @unittest.skipUnless(sys.platform != 'win32',
'os.chmod() does not support the needed arguments under Windows') 'os.chmod() does not support the needed arguments under Windows')
...@@ -170,29 +176,52 @@ class FinderTests(abc.FinderTests): ...@@ -170,29 +176,52 @@ class FinderTests(abc.FinderTests):
self.addCleanup(cleanup, tempdir) self.addCleanup(cleanup, tempdir)
os.chmod(tempdir.name, stat.S_IWUSR | stat.S_IXUSR) os.chmod(tempdir.name, stat.S_IWUSR | stat.S_IXUSR)
finder = self.get_finder(tempdir.name) finder = self.get_finder(tempdir.name)
self.assertEqual((None, []), finder.find_loader('doesnotexist')) found = self._find(finder, 'doesnotexist')
self.assertEqual(found, self.NOT_FOUND)
def test_ignore_file(self): def test_ignore_file(self):
# If a directory got changed to a file from underneath us, then don't # If a directory got changed to a file from underneath us, then don't
# worry about looking for submodules. # worry about looking for submodules.
with tempfile.NamedTemporaryFile() as file_obj: with tempfile.NamedTemporaryFile() as file_obj:
finder = self.get_finder(file_obj.name) finder = self.get_finder(file_obj.name)
self.assertEqual((None, []), finder.find_loader('doesnotexist')) found = self._find(finder, 'doesnotexist')
self.assertEqual(found, self.NOT_FOUND)
class FinderTestsPEP451(FinderTests): class FinderTestsPEP451(FinderTests):
def import_(self, root, module): NOT_FOUND = None
found = self.get_finder(root).find_spec(module)
return found.loader if found is not None else found def _find(self, finder, name, loader_only=False):
spec = finder.find_spec(name)
return spec.loader if spec is not None else spec
Frozen_FinderTestsPEP451, Source_FinderTestsPEP451 = util.test_both( Frozen_FinderTestsPEP451, Source_FinderTestsPEP451 = util.test_both(
FinderTestsPEP451, machinery=machinery) FinderTestsPEP451, machinery=machinery)
class FinderTestsPEP420(FinderTests):
NOT_FOUND = (None, [])
def _find(self, finder, name, loader_only=False):
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
loader_portions = finder.find_loader(name)
return loader_portions[0] if loader_only else loader_portions
Frozen_FinderTestsPEP420, Source_FinderTestsPEP420 = util.test_both(
FinderTestsPEP420, machinery=machinery)
class FinderTestsPEP302(FinderTests): class FinderTestsPEP302(FinderTests):
def import_(self, root, module): NOT_FOUND = None
return self.get_finder(root).find_module(module)
def _find(self, finder, name, loader_only=False):
with warnings.catch_warnings():
warnings.simplefilter("ignore", DeprecationWarning)
return finder.find_module(name)
Frozen_FinderTestsPEP302, Source_FinderTestsPEP302 = util.test_both( Frozen_FinderTestsPEP302, Source_FinderTestsPEP302 = util.test_both(
FinderTestsPEP302, machinery=machinery) FinderTestsPEP302, machinery=machinery)
......
...@@ -12,6 +12,7 @@ import types ...@@ -12,6 +12,7 @@ import types
# imported for the parser to use. # imported for the parser to use.
import unicodedata import unicodedata
import unittest import unittest
import warnings
CODING_RE = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII) CODING_RE = re.compile(r'^[ \t\f]*#.*coding[:=][ \t]*([-\w.]+)', re.ASCII)
...@@ -102,7 +103,9 @@ Frozen_EncodingTestPEP451, Source_EncodingTestPEP451 = util.test_both( ...@@ -102,7 +103,9 @@ Frozen_EncodingTestPEP451, Source_EncodingTestPEP451 = util.test_both(
class EncodingTestPEP302(EncodingTest): class EncodingTestPEP302(EncodingTest):
def load(self, loader): def load(self, loader):
return loader.load_module(self.module_name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
return loader.load_module(self.module_name)
Frozen_EncodingTestPEP302, Source_EncodingTestPEP302 = util.test_both( Frozen_EncodingTestPEP302, Source_EncodingTestPEP302 = util.test_both(
EncodingTestPEP302, machinery=machinery) EncodingTestPEP302, machinery=machinery)
...@@ -121,8 +124,8 @@ class LineEndingTest: ...@@ -121,8 +124,8 @@ class LineEndingTest:
with open(mapping[module_name], 'wb') as file: with open(mapping[module_name], 'wb') as file:
file.write(source) file.write(source)
loader = self.machinery.SourceFileLoader(module_name, loader = self.machinery.SourceFileLoader(module_name,
mapping[module_name]) mapping[module_name])
return loader.load_module(module_name) return self.load(loader, module_name)
# [cr] # [cr]
def test_cr(self): def test_cr(self):
...@@ -138,9 +141,9 @@ class LineEndingTest: ...@@ -138,9 +141,9 @@ class LineEndingTest:
class LineEndingTestPEP451(LineEndingTest): class LineEndingTestPEP451(LineEndingTest):
def load(self, loader): def load(self, loader, module_name):
module = types.ModuleType(self.module_name) module = types.ModuleType(module_name)
module.__spec__ = importlib.util.spec_from_loader(self.module_name, loader) module.__spec__ = importlib.util.spec_from_loader(module_name, loader)
loader.exec_module(module) loader.exec_module(module)
return module return module
...@@ -149,8 +152,10 @@ Frozen_LineEndingTestPEP451, Source_LineEndingTestPEP451 = util.test_both( ...@@ -149,8 +152,10 @@ Frozen_LineEndingTestPEP451, Source_LineEndingTestPEP451 = util.test_both(
class LineEndingTestPEP302(LineEndingTest): class LineEndingTestPEP302(LineEndingTest):
def load(self, loader): def load(self, loader, module_name):
return loader.load_module(self.module_name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
return loader.load_module(module_name)
Frozen_LineEndingTestPEP302, Source_LineEndingTestPEP302 = util.test_both( Frozen_LineEndingTestPEP302, Source_LineEndingTestPEP302 = util.test_both(
LineEndingTestPEP302, machinery=machinery) LineEndingTestPEP302, machinery=machinery)
......
...@@ -8,6 +8,7 @@ from test import support ...@@ -8,6 +8,7 @@ from test import support
import types import types
import unittest import unittest
from unittest import mock from unittest import mock
import warnings
from . import util from . import util
...@@ -388,7 +389,9 @@ class InspectLoaderLoadModuleTests: ...@@ -388,7 +389,9 @@ class InspectLoaderLoadModuleTests:
mocked_get_code.side_effect = ImportError mocked_get_code.side_effect = ImportError
with self.assertRaises(ImportError): with self.assertRaises(ImportError):
loader = self.InspectLoaderSubclass() loader = self.InspectLoaderSubclass()
loader.load_module(self.module_name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
loader.load_module(self.module_name)
def test_get_code_None(self): def test_get_code_None(self):
# If get_code() returns None, raise ImportError. # If get_code() returns None, raise ImportError.
...@@ -631,7 +634,9 @@ class SourceOnlyLoaderTests(SourceLoaderTestHarness): ...@@ -631,7 +634,9 @@ class SourceOnlyLoaderTests(SourceLoaderTestHarness):
# __path__ (for packages), __file__, and __cached__. # __path__ (for packages), __file__, and __cached__.
# The module should also be put into sys.modules. # The module should also be put into sys.modules.
with util.uncache(self.name): with util.uncache(self.name):
module = self.loader.load_module(self.name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = self.loader.load_module(self.name)
self.verify_module(module) self.verify_module(module)
self.assertEqual(module.__path__, [os.path.dirname(self.path)]) self.assertEqual(module.__path__, [os.path.dirname(self.path)])
self.assertIn(self.name, sys.modules) self.assertIn(self.name, sys.modules)
...@@ -642,7 +647,9 @@ class SourceOnlyLoaderTests(SourceLoaderTestHarness): ...@@ -642,7 +647,9 @@ class SourceOnlyLoaderTests(SourceLoaderTestHarness):
# Testing the values for a package are covered by test_load_module. # Testing the values for a package are covered by test_load_module.
self.setUp(is_package=False) self.setUp(is_package=False)
with util.uncache(self.name): with util.uncache(self.name):
module = self.loader.load_module(self.name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
module = self.loader.load_module(self.name)
self.verify_module(module) self.verify_module(module)
self.assertTrue(not hasattr(module, '__path__')) self.assertTrue(not hasattr(module, '__path__'))
......
...@@ -10,6 +10,7 @@ import sys ...@@ -10,6 +10,7 @@ import sys
from test import support from test import support
import types import types
import unittest import unittest
import warnings
@contextmanager @contextmanager
...@@ -143,7 +144,9 @@ class FindLoaderTests: ...@@ -143,7 +144,9 @@ class FindLoaderTests:
loader = 'a loader!' loader = 'a loader!'
module.__loader__ = loader module.__loader__ = loader
sys.modules[name] = module sys.modules[name] = module
found = self.init.find_loader(name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
found = self.init.find_loader(name)
self.assertEqual(loader, found) self.assertEqual(loader, found)
def test_sys_modules_loader_is_None(self): def test_sys_modules_loader_is_None(self):
...@@ -154,7 +157,9 @@ class FindLoaderTests: ...@@ -154,7 +157,9 @@ class FindLoaderTests:
module.__loader__ = None module.__loader__ = None
sys.modules[name] = module sys.modules[name] = module
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
self.init.find_loader(name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.init.find_loader(name)
def test_sys_modules_loader_is_not_set(self): def test_sys_modules_loader_is_not_set(self):
# Should raise ValueError # Should raise ValueError
...@@ -168,14 +173,18 @@ class FindLoaderTests: ...@@ -168,14 +173,18 @@ class FindLoaderTests:
pass pass
sys.modules[name] = module sys.modules[name] = module
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
self.init.find_loader(name) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.init.find_loader(name)
def test_success(self): def test_success(self):
# Return the loader found on sys.meta_path. # Return the loader found on sys.meta_path.
name = 'some_mod' name = 'some_mod'
with util.uncache(name): with util.uncache(name):
with util.import_state(meta_path=[self.FakeMetaFinder]): with util.import_state(meta_path=[self.FakeMetaFinder]):
self.assertEqual((name, None), self.init.find_loader(name)) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.assertEqual((name, None), self.init.find_loader(name))
def test_success_path(self): def test_success_path(self):
# Searching on a path should work. # Searching on a path should work.
...@@ -183,12 +192,16 @@ class FindLoaderTests: ...@@ -183,12 +192,16 @@ class FindLoaderTests:
path = 'path to some place' path = 'path to some place'
with util.uncache(name): with util.uncache(name):
with util.import_state(meta_path=[self.FakeMetaFinder]): with util.import_state(meta_path=[self.FakeMetaFinder]):
self.assertEqual((name, path), with warnings.catch_warnings():
self.init.find_loader(name, path)) warnings.simplefilter('ignore', DeprecationWarning)
self.assertEqual((name, path),
self.init.find_loader(name, path))
def test_nothing(self): def test_nothing(self):
# None is returned upon failure to find a loader. # None is returned upon failure to find a loader.
self.assertIsNone(self.init.find_loader('nevergoingtofindthismodule')) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.assertIsNone(self.init.find_loader('nevergoingtofindthismodule'))
class Frozen_FindLoaderTests(FindLoaderTests, unittest.TestCase): class Frozen_FindLoaderTests(FindLoaderTests, unittest.TestCase):
init = frozen_init init = frozen_init
......
...@@ -50,7 +50,7 @@ class LegacyLoader(TestLoader): ...@@ -50,7 +50,7 @@ class LegacyLoader(TestLoader):
HAM = -1 HAM = -1
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore", PendingDeprecationWarning) warnings.simplefilter("ignore", DeprecationWarning)
@frozen_util.module_for_loader @frozen_util.module_for_loader
def load_module(self, module): def load_module(self, module):
......
...@@ -41,14 +41,14 @@ class ModuleForLoaderTests: ...@@ -41,14 +41,14 @@ class ModuleForLoaderTests:
@classmethod @classmethod
def module_for_loader(cls, func): def module_for_loader(cls, func):
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter('ignore', PendingDeprecationWarning) warnings.simplefilter('ignore', DeprecationWarning)
return cls.util.module_for_loader(func) return cls.util.module_for_loader(func)
def test_warning(self): def test_warning(self):
# Should raise a PendingDeprecationWarning when used. # Should raise a PendingDeprecationWarning when used.
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter('error', PendingDeprecationWarning) warnings.simplefilter('error', DeprecationWarning)
with self.assertRaises(PendingDeprecationWarning): with self.assertRaises(DeprecationWarning):
func = self.util.module_for_loader(lambda x: x) func = self.util.module_for_loader(lambda x: x)
def return_module(self, name): def return_module(self, name):
...@@ -172,7 +172,9 @@ class SetPackageTests: ...@@ -172,7 +172,9 @@ class SetPackageTests:
passing through set_package.""" passing through set_package."""
fxn = lambda: module fxn = lambda: module
wrapped = self.util.set_package(fxn) wrapped = self.util.set_package(fxn)
wrapped() with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
wrapped()
self.assertTrue(hasattr(module, '__package__')) self.assertTrue(hasattr(module, '__package__'))
self.assertEqual(expect, module.__package__) self.assertEqual(expect, module.__package__)
...@@ -212,7 +214,9 @@ class SetPackageTests: ...@@ -212,7 +214,9 @@ class SetPackageTests:
def test_decorator_attrs(self): def test_decorator_attrs(self):
def fxn(module): pass def fxn(module): pass
wrapped = self.util.set_package(fxn) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
wrapped = self.util.set_package(fxn)
self.assertEqual(wrapped.__name__, fxn.__name__) self.assertEqual(wrapped.__name__, fxn.__name__)
self.assertEqual(wrapped.__qualname__, fxn.__qualname__) self.assertEqual(wrapped.__qualname__, fxn.__qualname__)
...@@ -236,19 +240,25 @@ class SetLoaderTests: ...@@ -236,19 +240,25 @@ class SetLoaderTests:
del loader.module.__loader__ del loader.module.__loader__
except AttributeError: except AttributeError:
pass pass
self.assertEqual(loader, loader.load_module('blah').__loader__) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.assertEqual(loader, loader.load_module('blah').__loader__)
def test_attribute_is_None(self): def test_attribute_is_None(self):
loader = self.DummyLoader() loader = self.DummyLoader()
loader.module = types.ModuleType('blah') loader.module = types.ModuleType('blah')
loader.module.__loader__ = None loader.module.__loader__ = None
self.assertEqual(loader, loader.load_module('blah').__loader__) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.assertEqual(loader, loader.load_module('blah').__loader__)
def test_not_reset(self): def test_not_reset(self):
loader = self.DummyLoader() loader = self.DummyLoader()
loader.module = types.ModuleType('blah') loader.module = types.ModuleType('blah')
loader.module.__loader__ = 42 loader.module.__loader__ = 42
self.assertEqual(42, loader.load_module('blah').__loader__) with warnings.catch_warnings():
warnings.simplefilter('ignore', DeprecationWarning)
self.assertEqual(42, loader.load_module('blah').__loader__)
class Frozen_SetLoaderTests(SetLoaderTests, unittest.TestCase): class Frozen_SetLoaderTests(SetLoaderTests, unittest.TestCase):
class DummyLoader: class DummyLoader:
......
...@@ -283,7 +283,8 @@ Library ...@@ -283,7 +283,8 @@ Library
- Issue #6477: Added support for pickling the types of built-in singletons - Issue #6477: Added support for pickling the types of built-in singletons
(i.e., Ellipsis, NotImplemented, None). (i.e., Ellipsis, NotImplemented, None).
- Issue #19713: Move away from using find_module/load_module. - Issue #19713: Add remaining PEP 451-related deprecations and move away
from using find_module/find_loaer/load_module.
- Issue #19708: Update pkgutil to use the new importer APIs. - Issue #19708: Update pkgutil to use the new importer APIs.
......
This diff is collapsed.
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