Issue45756
Created on 2021-11-08 19:47 by kjamieson, last changed 2022-04-11 14:59 by admin.
| Pull Requests | |||
|---|---|---|---|
| URL | Status | Linked | Edit |
| PR 29901 | open | sobolevn, 2021-12-03 08:22 | |
| PR 31348 | open | hongweipeng, 2022-02-15 06:36 | |
| Messages (3) | |||
|---|---|---|---|
| msg405982 - (view) | Author: Kevin Jamieson (kjamieson) | Date: 2021-11-08 19:47 | |
In Python 3.8 and later creating a mock with a spec specifying an object containing a property that happens to raise an exception when accessed will fail, because _mock_add_spec calls getattr() on every attribute of the spec. This did not happen in Python 3.6/3.7.
This is likely a fairly unusual scenario (and in the particular case where I encountered this I could just use a class instead of an instance for the spec), but it was surprising.
For example:
# cat test.py
from unittest import mock
class Foo:
@property
def bar(self) -> str:
raise Exception('xxx')
m = mock.MagicMock(spec=Foo())
# python3.11 test.py
Traceback (most recent call last):
File "/root/test.py", line 8, in <module>
m = mock.MagicMock(spec=Foo())
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/unittest/mock.py", line 2069, in __init__
_safe_super(MagicMixin, self).__init__(*args, **kw)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/unittest/mock.py", line 1087, in __init__
_safe_super(CallableMixin, self).__init__(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/unittest/mock.py", line 442, in __init__
self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/unittest/mock.py", line 497, in _mock_add_spec
if iscoroutinefunction(getattr(spec, attr, None)):
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/test.py", line 6, in bar
raise Exception('xxx')
^^^^^^^^^^^^^^^^^^^^^^
Exception: xxx
|
|||
| msg406284 - (view) | Author: Jaap Roes (jaap3) | Date: 2021-11-13 16:00 | |
I think I encountered this when trying to mock `requests.Response`: https://github.com/psf/requests/issues/5944 |
|||
| msg406452 - (view) | Author: Karthikeyan Singaravelan (xtreak) * ![]() |
Date: 2021-11-17 04:38 | |
This seems to be similar to https://bugs.python.org/issue41768 . |
|||
| History | |||
|---|---|---|---|
| Date | User | Action | Args |
| 2022-04-11 14:59:52 | admin | set | github: 89917 |
| 2022-02-15 06:36:26 | hongweipeng | set | nosy:
+ hongweipeng pull_requests: + pull_request29497 |
| 2021-12-03 08:46:16 | AlexWaygood | set | nosy:
+ lukasz.langa |
| 2021-12-03 08:22:21 | sobolevn | set | keywords:
+ patch nosy: + sobolevn pull_requests:
+ pull_request28125 |
| 2021-11-17 04:38:10 | xtreak | set | nosy:
+ xtreak messages: + msg406452 |
| 2021-11-13 16:00:51 | jaap3 | set | nosy:
+ jaap3 messages: + msg406284 |
| 2021-11-08 19:47:53 | kjamieson | create | |
