You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
mock raises exception when using a spec with an attribute that raises exception on access #89917
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee=Noneclosed_at=Nonecreated_at=<Date2021-11-08.19:47:53.494>labels= ['type-bug', '3.8', '3.9', '3.10', '3.11']
title='mock raises exception when using a spec with an attribute that raises exception on access'updated_at=<Date2022-02-15.06:36:26.841>user='https://bugs.python.org/kjamieson'
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.
# 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_specif iscoroutinefunction(getattr(spec, attr, None)):
^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/test.py", line 6, in barraiseException('xxx')
^^^^^^^^^^^^^^^^^^^^^^Exception: xxx
Activity
kjamieson commentedon Nov 8, 2021
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:
jaap3 commentedon Nov 13, 2021
I think I encountered this when trying to mock
requests.Response: psf/requests#5944tirkarthi commentedon Nov 17, 2021
This seems to be similar to https://bugs.python.org/issue41768 .
carljm commentedon May 5, 2023
Closing as duplicate of #85934