Skip to content

gh-96127: Fix inspect.signature call on mocks #96335

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions Lib/test/test_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -3283,6 +3283,25 @@ def test_signature_on_lambdas(self):
((('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)
Expand Down
10 changes: 9 additions & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -2213,7 +2213,15 @@ def __init__(self, /, *args, **kwargs):
code_mock = NonCallableMock(spec_set=_CODE_ATTRS)
code_mock.__dict__["_spec_class"] = CodeType
code_mock.__dict__["_spec_signature"] = _CODE_SIG
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()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
``inspect.signature`` was raising ``TypeError`` on call with mock objects.
Now it correctly returns ``(*args, **kwargs)`` as infered signature.