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.

Author kjamieson
Recipients kjamieson
Date 2021-11-08.19:47:53
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <>
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
from unittest import mock

class Foo:
    def bar(self) -> str:
        raise Exception('xxx')

m = mock.MagicMock(spec=Foo())

# python3.11
Traceback (most recent call last):
  File "/root/", line 8, in <module>
    m = mock.MagicMock(spec=Foo())
  File "/usr/lib/python3.11/unittest/", line 2069, in __init__
    _safe_super(MagicMixin, self).__init__(*args, **kw)
  File "/usr/lib/python3.11/unittest/", line 1087, in __init__
    _safe_super(CallableMixin, self).__init__(
  File "/usr/lib/python3.11/unittest/", line 442, in __init__
    self._mock_add_spec(spec, spec_set, _spec_as_instance, _eat_self)
  File "/usr/lib/python3.11/unittest/", line 497, in _mock_add_spec
    if iscoroutinefunction(getattr(spec, attr, None)):
  File "/root/", line 6, in bar
    raise Exception('xxx')
Exception: xxx
Date User Action Args
2021-11-08 19:47:53kjamiesonsetrecipients: + kjamieson
2021-11-08 19:47:53kjamiesonsetmessageid: <>
2021-11-08 19:47:53kjamiesonlinkissue45756 messages
2021-11-08 19:47:53kjamiesoncreate