Skip to content

Commit 75b75df

Browse files
authored
[3.11] gh-100287: Fix unittest.mock.seal with AsyncMock (GH-100496) (#100506)
(cherry picked from commit e4b43eb) Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
1 parent 44b664e commit 75b75df

File tree

3 files changed

+18
-5
lines changed

3 files changed

+18
-5
lines changed

Lib/unittest/mock.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -1014,15 +1014,15 @@ def _get_child_mock(self, /, **kw):
10141014
10151015
For non-callable mocks the callable variant will be used (rather than
10161016
any custom subclass)."""
1017-
_new_name = kw.get("_new_name")
1018-
if _new_name in self.__dict__['_spec_asyncs']:
1019-
return AsyncMock(**kw)
1020-
10211017
if self._mock_sealed:
10221018
attribute = f".{kw['name']}" if "name" in kw else "()"
10231019
mock_name = self._extract_mock_name() + attribute
10241020
raise AttributeError(mock_name)
10251021

1022+
_new_name = kw.get("_new_name")
1023+
if _new_name in self.__dict__['_spec_asyncs']:
1024+
return AsyncMock(**kw)
1025+
10261026
_type = type(self)
10271027
if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
10281028
# Any asynchronous magic becomes an AsyncMock

Lib/unittest/test/testmock/testasync.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from asyncio import run, iscoroutinefunction
1212
from unittest import IsolatedAsyncioTestCase
1313
from unittest.mock import (ANY, call, AsyncMock, patch, MagicMock, Mock,
14-
create_autospec, sentinel, _CallList)
14+
create_autospec, sentinel, _CallList, seal)
1515

1616

1717
def tearDownModule():
@@ -300,6 +300,14 @@ def test_spec_normal_methods_on_class_with_mock(self):
300300
self.assertIsInstance(mock.async_method, AsyncMock)
301301
self.assertIsInstance(mock.normal_method, Mock)
302302

303+
def test_spec_normal_methods_on_class_with_mock_seal(self):
304+
mock = Mock(AsyncClass)
305+
seal(mock)
306+
with self.assertRaises(AttributeError):
307+
mock.normal_method
308+
with self.assertRaises(AttributeError):
309+
mock.async_method
310+
303311
def test_spec_mock_type_kw(self):
304312
def inner_test(mock_type):
305313
async_mock = mock_type(spec=async_func)
@@ -1076,3 +1084,7 @@ async def f(x=None): pass
10761084
'Actual: [call(1)]'))) as cm:
10771085
self.mock.assert_has_awaits([call(), call(1, 2)])
10781086
self.assertIsInstance(cm.exception.__cause__, TypeError)
1087+
1088+
1089+
if __name__ == '__main__':
1090+
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix the interaction of :func:`unittest.mock.seal` with :class:`unittest.mock.AsyncMock`.

0 commit comments

Comments
 (0)