Skip to content

Commit d9c74a3

Browse files
committed
pythongh-96127: Fix inspect.signature call on mocks
1 parent 26ff436 commit d9c74a3

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
@@ -3283,6 +3283,25 @@ def test_signature_on_lambdas(self):
32833283
((('a', 10, ..., "positional_or_keyword"),),
32843284
...))
32853285

3286+
def test_signature_on_mocks(self):
3287+
# https://github.com/python/cpython/issues/96127
3288+
for mock in (
3289+
unittest.mock.Mock(),
3290+
unittest.mock.AsyncMock(),
3291+
unittest.mock.MagicMock(),
3292+
):
3293+
with self.subTest(mock=mock):
3294+
self.assertEqual(str(inspect.signature(mock)), '(*args, **kwargs)')
3295+
3296+
def test_signature_on_noncallable_mocks(self):
3297+
for mock in (
3298+
unittest.mock.NonCallableMock(),
3299+
unittest.mock.NonCallableMagicMock(),
3300+
):
3301+
with self.subTest(mock=mock):
3302+
with self.assertRaises(TypeError):
3303+
inspect.signature(mock)
3304+
32863305
def test_signature_equality(self):
32873306
def foo(a, *, b:int) -> float: pass
32883307
self.assertFalse(inspect.signature(foo) == 42)

Lib/unittest/mock.py

+9-1
Original file line numberDiff line numberDiff line change
@@ -2213,7 +2213,15 @@ def __init__(self, /, *args, **kwargs):
22132213
code_mock = NonCallableMock(spec_set=_CODE_ATTRS)
22142214
code_mock.__dict__["_spec_class"] = CodeType
22152215
code_mock.__dict__["_spec_signature"] = _CODE_SIG
2216-
code_mock.co_flags = inspect.CO_COROUTINE
2216+
code_mock.co_flags = (
2217+
inspect.CO_COROUTINE
2218+
+ inspect.CO_VARARGS
2219+
+ inspect.CO_VARKEYWORDS
2220+
)
2221+
code_mock.co_argcount = 0
2222+
code_mock.co_varnames = ('args', 'kwargs')
2223+
code_mock.co_posonlyargcount = 0
2224+
code_mock.co_kwonlyargcount = 0
22172225
self.__dict__['__code__'] = code_mock
22182226
self.__dict__['__name__'] = 'AsyncMock'
22192227
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)