This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: unittest.mock.create_autospec(Obj, instance=True) has self keyword in _spec_signature if Obj implements __call__
Type: Stage:
Components: Library (Lib) Versions: Python 3.6
process
Status: open Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: CendioOssman, ettang, xtreak
Priority: normal Keywords:

Created on 2020-10-03 01:23 by ettang, last changed 2022-04-11 14:59 by admin.

Messages (2)
msg377846 - (view) Author: Ethan Tang US (ettang) Date: 2020-10-03 01:23
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`.
msg382470 - (view) Author: Pierre Ossman (CendioOssman) Date: 2020-12-04 08:06
autospec's behaviour for methods is currently needed to work around Issue42556, so be careful with any fixes here so they don't break that workaround.
History
Date User Action Args
2022-04-11 14:59:36adminsetgithub: 86081
2020-12-04 08:06:53CendioOssmansetnosy: + CendioOssman
messages: + msg382470
2020-12-03 17:57:15xtreaksetnosy: + xtreak
2020-10-03 01:23:47ettangcreate