Skip to content

Commit

Permalink
gh-100739: Respect mock spec when checking for unsafe prefixes (GH-10…
Browse files Browse the repository at this point in the history
…0740)

(cherry picked from commit 7f1eefc)

Co-authored-by: Christian Klein <167265+cklein@users.noreply.github.com>
Co-authored-by: Nikita Sobolev <mail@sobolevn.me>
  • Loading branch information
3 people authored Jan 4, 2023
1 parent fee4059 commit f49cc3c
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -643,7 +643,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
16 changes: 16 additions & 0 deletions Lib/unittest/test/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1644,6 +1644,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
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``.

0 comments on commit f49cc3c

Please sign in to comment.