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 @@ -13,6 +13,7 @@

from test.support.import_helper import DirsOnSysPath
from test.test_importlib.util import uncache
lazy from json import dumps as lazy_dumps # noqa: F401
from unittest.mock import (
NonCallableMock, CallableMixin, sentinel,
MagicMock, Mock, NonCallableMagicMock, patch, _patch,
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()
3 changes: 3 additions & 0 deletions 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 @@ -1470,6 +1471,8 @@ def get_original(self):
original = getattr(target, name, DEFAULT)
else:
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