]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-145754: Update signature retrieval in unittest.mock to use forwardref annotation...
authorMatthias Schoettle <git@mattsch.com>
Fri, 20 Mar 2026 02:39:41 +0000 (22:39 -0400)
committerGitHub <noreply@github.com>
Fri, 20 Mar 2026 02:39:41 +0000 (19:39 -0700)
Lib/test/test_unittest/testmock/testmock.py
Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2026-03-10-14-57-15.gh-issue-145754.YBL5Ko.rst [new file with mode: 0644]

index 386d53bf5a5c63a89622bfff84cc88b26d617511..764585ec5d54688b483dca510d6fa187a9fc2531 100644 (file)
@@ -1743,6 +1743,13 @@ class MockTest(unittest.TestCase):
                 mock_method.assert_called_once_with()
                 self.assertRaises(TypeError, mock_method, 'extra_arg')
 
+    # gh-145754
+    def test_create_autospec_type_hints_typechecking(self):
+        def foo(x: Tuple[int, ...]) -> None:
+            pass
+
+        mock.create_autospec(foo)
+
     #Issue21238
     def test_mock_unsafe(self):
         m = Mock()
index 64a01a0b713c61da2609711ac27bc6ce148bf9fb..1cee67fa5d709463567dddec94d9de5837be88da 100644 (file)
@@ -34,6 +34,7 @@ import builtins
 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 (file)
index 0000000..7de81ac
--- /dev/null
@@ -0,0 +1,2 @@
+Request signature during mock autospec with ``FORWARDREF`` annotation format.
+This prevents runtime errors when an annotation uses a name that is not defined at runtime.