Skip to content

Commit 9975d4e

Browse files
authored
[3.10] pythongh-100287: Fix unittest.mock.seal with AsyncMock (pythonGH-100496) (python#100508)
(cherry picked from commit e4b43eb) Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
1 parent ad8d2ef commit 9975d4e

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
@@ -1010,15 +1010,15 @@ def _get_child_mock(self, /, **kw):
10101010
10111011
For non-callable mocks the callable variant will be used (rather than
10121012
any custom subclass)."""
1013-
_new_name = kw.get("_new_name")
1014-
if _new_name in self.__dict__['_spec_asyncs']:
1015-
return AsyncMock(**kw)
1016-
10171013
if self._mock_sealed:
10181014
attribute = f".{kw['name']}" if "name" in kw else "()"
10191015
mock_name = self._extract_mock_name() + attribute
10201016
raise AttributeError(mock_name)
10211017

1018+
_new_name = kw.get("_new_name")
1019+
if _new_name in self.__dict__['_spec_asyncs']:
1020+
return AsyncMock(**kw)
1021+
10221022
_type = type(self)
10231023
if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
10241024
# Any asynchronous magic becomes an AsyncMock

Lib/unittest/test/testmock/testasync.py

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

1313

1414
def tearDownModule():
@@ -298,6 +298,14 @@ def test_spec_normal_methods_on_class_with_mock(self):
298298
self.assertIsInstance(mock.async_method, AsyncMock)
299299
self.assertIsInstance(mock.normal_method, Mock)
300300

301+
def test_spec_normal_methods_on_class_with_mock_seal(self):
302+
mock = Mock(AsyncClass)
303+
seal(mock)
304+
with self.assertRaises(AttributeError):
305+
mock.normal_method
306+
with self.assertRaises(AttributeError):
307+
mock.async_method
308+
301309
def test_spec_mock_type_kw(self):
302310
def inner_test(mock_type):
303311
async_mock = mock_type(spec=async_func)
@@ -1074,3 +1082,7 @@ async def f(x=None): pass
10741082
'Actual: [call(1)]'))) as cm:
10751083
self.mock.assert_has_awaits([call(), call(1, 2)])
10761084
self.assertIsInstance(cm.exception.__cause__, TypeError)
1085+
1086+
1087+
if __name__ == '__main__':
1088+
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)