[New-bugs-announce] [issue41915] unittest.mock.create_autospec(Obj, instance=True) has self keyword in _spec_signature if Obj implements __call__

Ethan Tang US report at bugs.python.org
Fri Oct 2 21:23:47 EDT 2020


New submission from Ethan Tang US <ettang at nvidia.com>:

When an `unittest.mock.create_autospec(Obj, instance=True)` is used, and said Obj implements the `__call__(self, ...)` function, the mocked instance of it will take the full function signature including the `self` argument.

This will then cause an issue when `assert_called_once_with()` or `assert_called_with()` is used. Those two assertions will fail regardless if the arguments used were correct or not. The error message will contain the error: `TypeError: missing a required argument: 'self'`

Here an example of this issue happening

```
from unittest import mock

def Foo(object):

    def __call__(self, a):
        pass

    def bar(self, b):
        ```This is to just compare it with a regular function.```
        pass

foo_mock = mock.create_autospec(Foo, instance=True)
foo_mock(a=1)

foo_mock.assert_called_once_with(a=1)
```

In the example above, the assertion will then fail and raise an error even though the assertion should be correct.

upon inspecting further to understand the issue, this is because `foo_mock._spec_signature` will be `<Signature (self, a)>`.

The existence of `self` in `foo_mock._spec_signature` will cause this error.

As compared to the method `foo_mock.bar._spec_signature`, it will only be `<Signature (b)>`.

The reason for me posting this issue is that development with the Keras library heavily uses __call__ in their API and therefore it is hard to mock the APIs if such issue exists. One work around would be iterating through its `called_args_list`.

----------
components: Library (Lib)
messages: 377846
nosy: ettang
priority: normal
severity: normal
status: open
title: unittest.mock.create_autospec(Obj, instance=True) has self keyword in _spec_signature if Obj implements __call__
versions: Python 3.6

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue41915>
_______________________________________


More information about the New-bugs-announce mailing list