Skip to content

Commit ab7fcc8

Browse files
authored
bpo-44686 replace unittest.mock._importer with pkgutil.resolve_name (GH-18544)
Automerge-Triggered-By: GH:cjw296
1 parent 64f54b7 commit ab7fcc8

File tree

2 files changed

+5
-23
lines changed

2 files changed

+5
-23
lines changed

Lib/unittest/mock.py

Lines changed: 4 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import pprint
3131
import sys
3232
import builtins
33+
import pkgutil
3334
from asyncio import iscoroutinefunction
3435
from types import CodeType, ModuleType, MethodType
3536
from unittest.util import safe_repr
@@ -1239,25 +1240,6 @@ class or instance) that acts as the specification for the mock object. If
12391240
"""
12401241

12411242

1242-
def _dot_lookup(thing, comp, import_path):
1243-
try:
1244-
return getattr(thing, comp)
1245-
except AttributeError:
1246-
__import__(import_path)
1247-
return getattr(thing, comp)
1248-
1249-
1250-
def _importer(target):
1251-
components = target.split('.')
1252-
import_path = components.pop(0)
1253-
thing = __import__(import_path)
1254-
1255-
for comp in components:
1256-
import_path += ".%s" % comp
1257-
thing = _dot_lookup(thing, comp, import_path)
1258-
return thing
1259-
1260-
12611243
# _check_spec_arg_typos takes kwargs from commands like patch and checks that
12621244
# they don't contain common misspellings of arguments related to autospeccing.
12631245
def _check_spec_arg_typos(kwargs_to_check):
@@ -1611,8 +1593,7 @@ def _get_target(target):
16111593
except (TypeError, ValueError):
16121594
raise TypeError("Need a valid target to patch. You supplied: %r" %
16131595
(target,))
1614-
getter = lambda: _importer(target)
1615-
return getter, attribute
1596+
return partial(pkgutil.resolve_name, target), attribute
16161597

16171598

16181599
def _patch_object(
@@ -1667,7 +1648,7 @@ def _patch_multiple(target, spec=None, create=False, spec_set=None,
16671648
for choosing which methods to wrap.
16681649
"""
16691650
if type(target) is str:
1670-
getter = lambda: _importer(target)
1651+
getter = partial(pkgutil.resolve_name, target)
16711652
else:
16721653
getter = lambda: target
16731654

@@ -1847,7 +1828,7 @@ def __enter__(self):
18471828
def _patch_dict(self):
18481829
values = self.values
18491830
if isinstance(self.in_dict, str):
1850-
self.in_dict = _importer(self.in_dict)
1831+
self.in_dict = pkgutil.resolve_name(self.in_dict)
18511832
in_dict = self.in_dict
18521833
clear = self.clear
18531834

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Replace ``unittest.mock._importer`` with ``pkgutil.resolve_name``.

0 commit comments

Comments
 (0)