Skip to content

Commit 7f1eefc

Browse files
ckleinsobolevn
andauthored
gh-100739: Respect mock spec when checking for unsafe prefixes (#100740)
Co-authored-by: Nikita Sobolev <[email protected]>
1 parent 52017db commit 7f1eefc

File tree

3 files changed

+18
-1
lines changed

3 files changed

+18
-1
lines changed

Lib/test/test_unittest/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()

Lib/unittest/mock.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -652,7 +652,7 @@ def __getattr__(self, name):
652652
raise AttributeError("Mock object has no attribute %r" % name)
653653
elif _is_magic(name):
654654
raise AttributeError(name)
655-
if not self._mock_unsafe:
655+
if not self._mock_unsafe and (not self._mock_methods or name not in self._mock_methods):
656656
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
657657
raise AttributeError(
658658
f"{name!r} is not a valid assertion. Use a spec "
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)