For code that uses annotations / signature, wrapping a callable in a Mock
object does not work correctly:
>>> import typing, inspect, functools
>>> from unittest.mock import Mock
>>>
>>> def incr(i: int) -> int:
... return i+1
...
>>> wrapped = Mock(wraps=incr)
>>> inspect.signature(wrapped)
<Signature (*args, **kwargs)>
>>> typing.get_type_hints(wrapped)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/lib/python3.11/typing.py", line 2330, in get_type_hints
raise TypeError('{!r} is not a module, class, method, '
TypeError: <Mock id='140078552596944'> is not a module, class, method, or
function.
>>> functools.update_wrapper(wrapped, incr)
<Mock id='140078552596944'>
>>> inspect.signature(wrapped)
<Signature (i: int) -> int>
>>> typing.get_type_hints(wrapped)
{'i': <class 'int'>, 'return': <class 'int'>}
It's relatively simple to call update_wrapper on your own, but it seems
like it would be better if the mock "just worked" for code that tries to
use signature and annotations at runtime. I think all that's required would
be adding `if wraps is not None: functools.update_wrapper(self, wraps)`
after the line here:
https://github.com/python/cpython/blob/f4fcfdf8c593611f98b9358cc0c5604c15306465/Lib/unittest/mock.py#L1107
Does anyone see any problems with implementing this?
Thanks & best wishes,
Lucas Wiman
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/25EGYHN3OYUFDJYZLEUZPLZUTMYWW5R5/
Code of Conduct: http://python.org/psf/codeofconduct/