diff --git a/Lib/test/test_unittest/testmock/testmock.py b/Lib/test/test_unittest/testmock/testmock.py index 386d53bf5a5c63..7b828e275d9a9a 100644 --- a/Lib/test/test_unittest/testmock/testmock.py +++ b/Lib/test/test_unittest/testmock/testmock.py @@ -1743,6 +1743,17 @@ def static_method(): pass mock_method.assert_called_once_with() self.assertRaises(TypeError, mock_method, 'extra_arg') + #Issue145754 + def test_create_autospec_type_hints_typechecking(self): + from typing import TYPE_CHECKING + if TYPE_CHECKING: + from typing import Tuple + + def foo(x: Tuple[int, ...]) -> None: + pass + + mock.create_autospec(foo) + #Issue21238 def test_mock_unsafe(self): m = Mock() diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py index 64a01a0b713c61..1cee67fa5d7094 100644 --- a/Lib/unittest/mock.py +++ b/Lib/unittest/mock.py @@ -34,6 +34,7 @@ import pkgutil from inspect import iscoroutinefunction import threading +from annotationlib import Format from dataclasses import fields, is_dataclass from types import CodeType, ModuleType, MethodType from unittest.util import safe_repr @@ -119,7 +120,7 @@ def _get_signature_object(func, as_instance, eat_self): else: sig_func = func try: - return func, inspect.signature(sig_func) + return func, inspect.signature(sig_func, annotation_format=Format.FORWARDREF) except ValueError: # Certain callable types are not supported by inspect.signature() return None diff --git a/Misc/NEWS.d/next/Library/2026-03-10-14-57-15.gh-issue-145754.YBL5Ko.rst b/Misc/NEWS.d/next/Library/2026-03-10-14-57-15.gh-issue-145754.YBL5Ko.rst new file mode 100644 index 00000000000000..10539af74f8bfe --- /dev/null +++ b/Misc/NEWS.d/next/Library/2026-03-10-14-57-15.gh-issue-145754.YBL5Ko.rst @@ -0,0 +1,3 @@ +Request signature during mock autospec with ``FORWARDREF`` annotation format. +This prevents runtime errors when a type referred in a type hint is +imported within a ``TYPE_CHECKING`` block.