Skip to content

Commit efcab38

Browse files
[3.11] gh-96127: Fix inspect.signature call on mocks (#96335) (#101646)
(cherry picked from commit 9e7d726) Co-authored-by: Nikita Sobolev <[email protected]>
1 parent c38b4e7 commit efcab38

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

Lib/test/test_inspect.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3238,6 +3238,25 @@ def test_signature_on_lambdas(self):
32383238
((('a', 10, ..., "positional_or_keyword"),),
32393239
...))
32403240

3241+
def test_signature_on_mocks(self):
3242+
# https://github.com/python/cpython/issues/96127
3243+
for mock in (
3244+
unittest.mock.Mock(),
3245+
unittest.mock.AsyncMock(),
3246+
unittest.mock.MagicMock(),
3247+
):
3248+
with self.subTest(mock=mock):
3249+
self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)')
3250+
3251+
def test_signature_on_noncallable_mocks(self):
3252+
for mock in (
3253+
unittest.mock.NonCallableMock(),
3254+
unittest.mock.NonCallableMagicMock(),
3255+
):
3256+
with self.subTest(mock=mock):
3257+
with self.assertRaises(TypeError):
3258+
inspect.signature(mock)
3259+
32413260
def test_signature_equality(self):
32423261
def foo(a, *, b:int) -> float: pass
32433262
self.assertFalse(inspect.signature(foo) == 42)

Lib/unittest/mock.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2201,7 +2201,15 @@ def __init__(self, /, *args, **kwargs):
22012201
self.__dict__['_mock_await_args'] = None
22022202
self.__dict__['_mock_await_args_list'] = _CallList()
22032203
code_mock = NonCallableMock(spec_set=CodeType)
2204-
code_mock.co_flags = inspect.CO_COROUTINE
2204+
code_mock.co_flags = (
2205+
inspect.CO_COROUTINE
2206+
+ inspect.CO_VARARGS
2207+
+ inspect.CO_VARKEYWORDS
2208+
)
2209+
code_mock.co_argcount = 0
2210+
code_mock.co_varnames = ('args', 'kwargs')
2211+
code_mock.co_posonlyargcount = 0
2212+
code_mock.co_kwonlyargcount = 0
22052213
self.__dict__['__code__'] = code_mock
22062214
self.__dict__['__name__'] = 'AsyncMock'
22072215
self.__dict__['__defaults__'] = tuple()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
``inspect.signature`` was raising ``TypeError`` on call with mock objects.
2+
Now it correctly returns ``(*args, **kwargs)`` as infered signature.

0 commit comments

Comments
 (0)