Skip to content
8 changes: 8 additions & 0 deletions Lib/test/test_unittest/testmock/testpatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
builtin_string = 'builtins'

PTModule = sys.modules[__name__]
lazy from json import dumps as lazy_dumps # noqa: F401
MODNAME = '%s.PTModule' % __name__


Expand Down Expand Up @@ -2101,5 +2102,12 @@ def test(_):
test()


def test_patch_autospec_lazy_import(self):
self.assertIn("lazy_dumps", globals())

with patch(f"{__name__}.lazy_dumps", autospec=True) as mock_dumps:
mock_dumps({})
mock_dumps.assert_called_once_with({})

if __name__ == '__main__':
unittest.main()
5 changes: 4 additions & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import sys
import builtins
import pkgutil
import types
from inspect import iscoroutinefunction
import threading
from annotationlib import Format
Expand Down Expand Up @@ -1469,7 +1470,9 @@ def get_original(self):
except (AttributeError, KeyError):
original = getattr(target, name, DEFAULT)
else:
local = True
local = True
if isinstance(original, types.LazyImportType):
original = original.resolve()

if name in _builtins and isinstance(target, ModuleType):
self.create = True
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`unittest.mock.patch` with ``autospec``, ``spec``, or ``spec_set``
when used with lazy-imported objects.
Loading