bpo-44686 replace unittest.mock._importer with pkgutil.resolve_name (GH-18544)

Automerge-Triggered-By: GH:cjw296
This commit is contained in:
Thomas Grainger 2021-07-21 12:47:44 +01:00 committed by GitHub
parent 64f54b7ccd
commit ab7fcc8fbd
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 5 additions and 23 deletions

View file

@ -30,6 +30,7 @@ import inspect
import pprint import pprint
import sys import sys
import builtins import builtins
import pkgutil
from asyncio import iscoroutinefunction from asyncio import iscoroutinefunction
from types import CodeType, ModuleType, MethodType from types import CodeType, ModuleType, MethodType
from unittest.util import safe_repr from unittest.util import safe_repr
@ -1239,25 +1240,6 @@ class Mock(CallableMixin, NonCallableMock):
""" """
def _dot_lookup(thing, comp, import_path):
try:
return getattr(thing, comp)
except AttributeError:
__import__(import_path)
return getattr(thing, comp)
def _importer(target):
components = target.split('.')
import_path = components.pop(0)
thing = __import__(import_path)
for comp in components:
import_path += ".%s" % comp
thing = _dot_lookup(thing, comp, import_path)
return thing
# _check_spec_arg_typos takes kwargs from commands like patch and checks that # _check_spec_arg_typos takes kwargs from commands like patch and checks that
# they don't contain common misspellings of arguments related to autospeccing. # they don't contain common misspellings of arguments related to autospeccing.
def _check_spec_arg_typos(kwargs_to_check): def _check_spec_arg_typos(kwargs_to_check):
@ -1611,8 +1593,7 @@ def _get_target(target):
except (TypeError, ValueError): except (TypeError, ValueError):
raise TypeError("Need a valid target to patch. You supplied: %r" % raise TypeError("Need a valid target to patch. You supplied: %r" %
(target,)) (target,))
getter = lambda: _importer(target) return partial(pkgutil.resolve_name, target), attribute
return getter, attribute
def _patch_object( def _patch_object(
@ -1667,7 +1648,7 @@ def _patch_multiple(target, spec=None, create=False, spec_set=None,
for choosing which methods to wrap. for choosing which methods to wrap.
""" """
if type(target) is str: if type(target) is str:
getter = lambda: _importer(target) getter = partial(pkgutil.resolve_name, target)
else: else:
getter = lambda: target getter = lambda: target
@ -1847,7 +1828,7 @@ class _patch_dict(object):
def _patch_dict(self): def _patch_dict(self):
values = self.values values = self.values
if isinstance(self.in_dict, str): if isinstance(self.in_dict, str):
self.in_dict = _importer(self.in_dict) self.in_dict = pkgutil.resolve_name(self.in_dict)
in_dict = self.in_dict in_dict = self.in_dict
clear = self.clear clear = self.clear

View file

@ -0,0 +1 @@
Replace ``unittest.mock._importer`` with ``pkgutil.resolve_name``.