Skip to content

Commit b1c6e20

Browse files
committed
pythongh-96127: Fix inspect.signature call on mocks
1 parent 0ace820 commit b1c6e20

File tree

3 files changed

+30
-1
lines changed

3 files changed

+30
-1
lines changed

Lib/test/test_inspect.py

+19
Original file line numberDiff line numberDiff line change
@@ -3220,6 +3220,25 @@ def test_signature_on_lambdas(self):
32203220
((('a', 10, ..., "positional_or_keyword"),),
32213221
...))
32223222

3223+
def test_signature_on_mocks(self):
3224+
# https://github.com/python/cpython/issues/96127
3225+
for mock in (
3226+
unittest.mock.Mock(),
3227+
unittest.mock.AsyncMock(),
3228+
unittest.mock.MagicMock(),
3229+
):
3230+
with self.subTest(mock=mock):
3231+
self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)')
3232+
3233+
def test_signature_on_noncallable_mocks(self):
3234+
for mock in (
3235+
unittest.mock.NonCallableMock(),
3236+
unittest.mock.NonCallableMagicMock(),
3237+
):
3238+
with self.subTest(mock=mock):
3239+
with self.assertRaises(TypeError):
3240+
inspect.signature(mock)
3241+
32233242
def test_signature_equality(self):
32243243
def foo(a, *, b:int) -> float: pass
32253244
self.assertFalse(inspect.signature(foo) == 42)

Lib/unittest/mock.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -2173,7 +2173,15 @@ def __init__(self, /, *args, **kwargs):
21732173
self.__dict__['_mock_await_args'] = None
21742174
self.__dict__['_mock_await_args_list'] = _CallList()
21752175
code_mock = NonCallableMock(spec_set=CodeType)
2176-
code_mock.co_flags = inspect.CO_COROUTINE
2176+
code_mock.co_flags = (
2177+
inspect.CO_COROUTINE
2178+
+ inspect.CO_VARARGS
2179+
+ inspect.CO_VARKEYWORDS
2180+
)
2181+
code_mock.co_argcount = 0
2182+
code_mock.co_varnames = ('args', 'kwargs')
2183+
code_mock.co_posonlyargcount = 0
2184+
code_mock.co_kwonlyargcount = 0
21772185
self.__dict__['__code__'] = code_mock
21782186
self.__dict__['__name__'] = 'AsyncMock'
21792187
self.__dict__['__defaults__'] = tuple()
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)