Skip to content

Commit

Permalink
gh-100287: Fix unittest.mock.seal with AsyncMock (#100496)
Browse files Browse the repository at this point in the history
Backports: e4b43ebb3afbd231a4e5630e7e358aa3093f8677
Signed-off-by: Chris Withers <[email protected]>
  • Loading branch information
hauntsaninja authored and cjw296 committed Dec 28, 2022
1 parent 36e4a68 commit 78fed8a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 5 deletions.
1 change: 1 addition & 0 deletions NEWS.d/2022-12-24-08-42-05.gh-issue-100287.n0oEuG.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix the interaction of :func:`unittest.mock.seal` with :class:`unittest.mock.AsyncMock`.
8 changes: 4 additions & 4 deletions mock/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1027,15 +1027,15 @@ def _get_child_mock(self, **kw):
For non-callable mocks the callable variant will be used (rather than
any custom subclass)."""
_new_name = kw.get("_new_name")
if _new_name in self.__dict__['_spec_asyncs']:
return AsyncMock(**kw)

if self._mock_sealed:
attribute = f".{kw['name']}" if "name" in kw else "()"
mock_name = self._extract_mock_name() + attribute
raise AttributeError(mock_name)

_new_name = kw.get("_new_name")
if _new_name in self.__dict__['_spec_asyncs']:
return AsyncMock(**kw)

_type = type(self)
if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
# Any asynchronous magic becomes an AsyncMock
Expand Down
14 changes: 13 additions & 1 deletion mock/tests/testasync.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from contextlib import contextmanager

from mock import (ANY, call, AsyncMock, patch, MagicMock, Mock,
create_autospec, sentinel)
create_autospec, sentinel, seal)
from mock.backports import IsolatedAsyncioTestCase, iscoroutinefunction
from mock.mock import _CallList

Expand Down Expand Up @@ -306,6 +306,14 @@ def test_spec_normal_methods_on_class_with_mock(self):
self.assertIsInstance(mock.async_method, AsyncMock)
self.assertIsInstance(mock.normal_method, Mock)

def test_spec_normal_methods_on_class_with_mock_seal(self):
mock = Mock(AsyncClass)
seal(mock)
with self.assertRaises(AttributeError):
mock.normal_method
with self.assertRaises(AttributeError):
mock.async_method

def test_spec_async_attributes_instance(self):
async_instance = AsyncClass()
async_instance.async_func_attr = async_func
Expand Down Expand Up @@ -1097,3 +1105,7 @@ async def f(x=None): pass
)) as cm:
self.mock.assert_has_awaits([call(), call(1, 2)])
self.assertIsInstance(cm.exception.__cause__, TypeError)


if __name__ == '__main__':
unittest.main()

0 comments on commit 78fed8a

Please sign in to comment.