Skip to content

Commit 37aa291

Browse files
ckleinChristian Klein
authored andcommitted
Respect mock spec when checking for unsafe prefixes
1 parent 68ecf80 commit 37aa291

2 files changed

Lines changed: 13 additions & 1 deletion

File tree

Lib/test/test_unittest/testmock/testmock.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1655,6 +1655,18 @@ def test_mock_unsafe(self):
16551655
m.assrt_foo_call()
16561656
m.called_once_with()
16571657

1658+
def test_mock_safe_with_spec(self):
1659+
class Foo(object):
1660+
def called_frobnicate(self):
1661+
pass
1662+
1663+
m = Mock(spec=Foo)
1664+
m.called_frobnicate()
1665+
1666+
msg = "is not a valid assertion. Use a spec for the mock"
1667+
with self.assertRaisesRegex(AttributeError, msg):
1668+
m.called_frognicate()
1669+
16581670
#Issue21262
16591671
def test_assert_not_called(self):
16601672
m = Mock()

Lib/unittest/mock.py

Lines changed: 1 addition & 1 deletion
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 name not in self._mock_methods:
656656
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt', 'called_')):
657657
raise AttributeError(
658658
f"{name!r} is not a valid assertion. Use a spec "

0 commit comments

Comments
 (0)