Skip to content

gh-100739: Respect mock spec when checking for unsafe prefixes #100740

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions Lib/test/test_unittest/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1652,6 +1652,22 @@ def test_mock_unsafe(self):
m.aseert_foo_call()
m.assrt_foo_call()

# gh-100739
def test_mock_safe_with_spec(self):
class Foo(object):
def assert_bar(self):
pass

def assertSome(self):
pass

m = Mock(spec=Foo)
m.assert_bar()
m.assertSome()

m.assert_bar.assert_called_once()
m.assertSome.assert_called_once()

#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 (not self._mock_methods or name not in self._mock_methods):
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
raise AttributeError(
f"{name!r} is not a valid assertion. Use a spec "
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix ``unittest.mock.Mock`` not respecting the spec for attribute names prefixed with ``assert``.