bpo-45156: Fixes inifite loop on unittest.mock.seal() (GH-28300) (GH-28326)
Fixes infinite loop on unittest.mock.seal() of mocks created by
unittest.create_autospec().
Co-authored-by: Dong-hee Na <donghee.na92@gmail.com>
(cherry picked from commit 7f60c9e1c6e22cc0e846a872c318570926cd3094)
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index c606715..6226bd4 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -1004,6 +1004,11 @@ def _get_child_mock(self, /, **kw):
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)
+
_type = type(self)
if issubclass(_type, MagicMock) and _new_name in _async_method_magics:
# Any asynchronous magic becomes an AsyncMock
@@ -1022,12 +1027,6 @@ def _get_child_mock(self, /, **kw):
klass = Mock
else:
klass = _type.__mro__[1]
-
- if self._mock_sealed:
- attribute = "." + kw["name"] if "name" in kw else "()"
- mock_name = self._extract_mock_name() + attribute
- raise AttributeError(mock_name)
-
return klass(**kw)
@@ -2927,6 +2926,8 @@ def seal(mock):
continue
if not isinstance(m, NonCallableMock):
continue
+ if isinstance(m._mock_children.get(attr), _SpecState):
+ continue
if m._mock_new_parent is mock:
seal(m)