Skip to content

Commit ca9f3e9

Browse files
sobolevnarhadthedev
authored andcommitted
pythongh-96127: Fix inspect.signature call on mocks (python#96335)
(cherry picked from commit 9e7d726)
1 parent 25196d6 commit ca9f3e9

File tree

3 files changed

+32
-1
lines changed

3 files changed

+32
-1
lines changed

Lib/test/test_inspect.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3235,6 +3235,25 @@ def test_signature_on_lambdas(self):
32353235
((('a', 10, ..., "positional_or_keyword"),),
32363236
...))
32373237

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

Lib/unittest/mock.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2212,7 +2212,17 @@ def __init__(self, /, *args, **kwargs):
22122212
self.__dict__['_mock_await_args'] = None
22132213
self.__dict__['_mock_await_args_list'] = _CallList()
22142214
code_mock = NonCallableMock(spec_set=CodeType)
2215-
code_mock.co_flags = inspect.CO_COROUTINE
2215+
code_mock.__dict__["_spec_class"] = CodeType
2216+
code_mock.__dict__["_spec_signature"] = _CODE_SIG
2217+
code_mock.co_flags = (
2218+
inspect.CO_COROUTINE
2219+
+ inspect.CO_VARARGS
2220+
+ inspect.CO_VARKEYWORDS
2221+
)
2222+
code_mock.co_argcount = 0
2223+
code_mock.co_varnames = ('args', 'kwargs')
2224+
code_mock.co_posonlyargcount = 0
2225+
code_mock.co_kwonlyargcount = 0
22162226
self.__dict__['__code__'] = code_mock
22172227
self.__dict__['__name__'] = 'AsyncMock'
22182228
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)