]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.11] gh-96127: Fix `inspect.signature` call on mocks (#96335) (#101646)
authorOleg Iarygin <oleg@arhadthedev.net>
Wed, 8 Feb 2023 10:05:57 +0000 (14:05 +0400)
committerGitHub <noreply@github.com>
Wed, 8 Feb 2023 10:05:57 +0000 (11:05 +0100)
(cherry picked from commit 9e7d7266ecdcccc02385fe4ccb094f3444102e26)

Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
Lib/test/test_inspect.py
Lib/unittest/mock.py
Misc/NEWS.d/next/Library/2022-08-27-10-35-50.gh-issue-96127.8RdLre.rst [new file with mode: 0644]

index 9ea49854cbc636273dc540670f4456b5407af274..c50486003a4dabd836106abd7a6b4929c056c3ee 100644 (file)
@@ -3238,6 +3238,25 @@ class TestSignatureObject(unittest.TestCase):
                          ((('a', 10, ..., "positional_or_keyword"),),
                           ...))
 
+    def test_signature_on_mocks(self):
+        # https://github.com/python/cpython/issues/96127
+        for mock in (
+            unittest.mock.Mock(),
+            unittest.mock.AsyncMock(),
+            unittest.mock.MagicMock(),
+        ):
+            with self.subTest(mock=mock):
+                self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)')
+
+    def test_signature_on_noncallable_mocks(self):
+        for mock in (
+            unittest.mock.NonCallableMock(),
+            unittest.mock.NonCallableMagicMock(),
+        ):
+            with self.subTest(mock=mock):
+                with self.assertRaises(TypeError):
+                    inspect.signature(mock)
+
     def test_signature_equality(self):
         def foo(a, *, b:int) -> float: pass
         self.assertFalse(inspect.signature(foo) == 42)
index fa0bd9131a21e7c88ad64c740e356a08abd5ad53..54bd3ecdd76f14e3dc1e193c2286c73133de3b3a 100644 (file)
@@ -2201,7 +2201,15 @@ class AsyncMockMixin(Base):
         self.__dict__['_mock_await_args'] = None
         self.__dict__['_mock_await_args_list'] = _CallList()
         code_mock = NonCallableMock(spec_set=CodeType)
-        code_mock.co_flags = inspect.CO_COROUTINE
+        code_mock.co_flags = (
+            inspect.CO_COROUTINE
+            + inspect.CO_VARARGS
+            + inspect.CO_VARKEYWORDS
+        )
+        code_mock.co_argcount = 0
+        code_mock.co_varnames = ('args', 'kwargs')
+        code_mock.co_posonlyargcount = 0
+        code_mock.co_kwonlyargcount = 0
         self.__dict__['__code__'] = code_mock
         self.__dict__['__name__'] = 'AsyncMock'
         self.__dict__['__defaults__'] = tuple()
diff --git a/Misc/NEWS.d/next/Library/2022-08-27-10-35-50.gh-issue-96127.8RdLre.rst b/Misc/NEWS.d/next/Library/2022-08-27-10-35-50.gh-issue-96127.8RdLre.rst
new file mode 100644 (file)
index 0000000..79edd8f
--- /dev/null
@@ -0,0 +1,2 @@
+``inspect.signature`` was raising ``TypeError`` on call with mock objects.
+Now it correctly returns ``(*args, **kwargs)`` as infered signature.