Skip to content

Commit

Permalink
Respect mock spec when checking for unsafe prefixes
Browse files Browse the repository at this point in the history
  • Loading branch information
cklein authored and Christian Klein committed Jan 2, 2023
1 parent 68ecf80 commit 37aa291
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
12 changes: 12 additions & 0 deletions Lib/test/test_unittest/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1655,6 +1655,18 @@ def test_mock_unsafe(self):
m.assrt_foo_call()
m.called_once_with()

def test_mock_safe_with_spec(self):
class Foo(object):
def called_frobnicate(self):
pass

m = Mock(spec=Foo)
m.called_frobnicate()

msg = "is not a valid assertion. Use a spec for the mock"
with self.assertRaisesRegex(AttributeError, msg):
m.called_frognicate()

#Issue21262
def test_assert_not_called(self):
m = Mock()
Expand Down
2 changes: 1 addition & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,7 +652,7 @@ def __getattr__(self, name):
raise AttributeError("Mock object has no attribute %r" % name)
elif _is_magic(name):
raise AttributeError(name)
if not self._mock_unsafe:
if not self._mock_unsafe and name not in self._mock_methods:
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt', 'called_')):
raise AttributeError(
f"{name!r} is not a valid assertion. Use a spec "
Expand Down

0 comments on commit 37aa291

Please sign in to comment.