Skip to content

Commit 541e7b8

Browse files
miss-islingtonckleinsobolevn
authored
gh-100739: Respect mock spec when checking for unsafe prefixes (GH-100740)
(cherry picked from commit 7f1eefc) Co-authored-by: Christian Klein <[email protected]> Co-authored-by: Nikita Sobolev <[email protected]>
1 parent eba6b00 commit 541e7b8

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

Lib/unittest/mock.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -647,7 +647,7 @@ def __getattr__(self, name):
647647
raise AttributeError("Mock object has no attribute %r" % name)
648648
elif _is_magic(name):
649649
raise AttributeError(name)
650-
if not self._mock_unsafe:
650+
if not self._mock_unsafe and (not self._mock_methods or name not in self._mock_methods):
651651
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
652652
raise AttributeError(
653653
f"{name!r} is not a valid assertion. Use a spec "

Lib/unittest/test/testmock/testmock.py

+16
Original file line numberDiff line numberDiff line change
@@ -1652,6 +1652,22 @@ def test_mock_unsafe(self):
16521652
m.aseert_foo_call()
16531653
m.assrt_foo_call()
16541654

1655+
# gh-100739
1656+
def test_mock_safe_with_spec(self):
1657+
class Foo(object):
1658+
def assert_bar(self):
1659+
pass
1660+
1661+
def assertSome(self):
1662+
pass
1663+
1664+
m = Mock(spec=Foo)
1665+
m.assert_bar()
1666+
m.assertSome()
1667+
1668+
m.assert_bar.assert_called_once()
1669+
m.assertSome.assert_called_once()
1670+
16551671
#Issue21262
16561672
def test_assert_not_called(self):
16571673
m = Mock()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix ``unittest.mock.Mock`` not respecting the spec for attribute names prefixed with ``assert``.

0 commit comments

Comments
 (0)