Skip to content

Commit

Permalink
Prevent calling assert functions without the prefix "assert_" in safe…
Browse files Browse the repository at this point in the history
… mode

Raise an AttributeError when calling e.g. `mock_obj.called_once` instead of
`mock_obj.assert_called_once`.
  • Loading branch information
cklein committed Jan 3, 2023
1 parent d7e7f79 commit 154012f
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
6 changes: 6 additions & 0 deletions Lib/test/test_unittest/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1645,12 +1645,18 @@ def test_mock_unsafe(self):
m.aseert_foo_call()
with self.assertRaisesRegex(AttributeError, msg):
m.assrt_foo_call()
with self.assertRaisesRegex(AttributeError, msg):
m.called_once_with()
with self.assertRaisesRegex(AttributeError, msg):
m.has_calls()
m = Mock(unsafe=True)
m.assert_foo_call()
m.assret_foo_call()
m.asert_foo_call()
m.aseert_foo_call()
m.assrt_foo_call()
m.called_once_with()
m.has_calls()

#Issue21262
def test_assert_not_called(self):
Expand Down
8 changes: 6 additions & 2 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,7 @@ def __getattr__(self, name):
elif _is_magic(name):
raise AttributeError(name)
if not self._mock_unsafe:
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')) or name in ATTRIB_DENY_LIST:
raise AttributeError(
f"{name!r} is not a valid assertion. Use a spec "
f"for the mock if {name!r} is meant to be an attribute.")
Expand Down Expand Up @@ -1062,6 +1062,10 @@ def _calls_repr(self, prefix="Calls"):
return f"\n{prefix}: {safe_repr(self.mock_calls)}."


# gh-100690 Denylist for forbidden method names in safe mode
ATTRIB_DENY_LIST = {name.removeprefix("assert_") for name in dir(NonCallableMock) if name.startswith("assert_")}


class _AnyComparer(list):
"""A list which checks if it contains a call which may have an
argument of ANY, flipping the components of item and self from
Expand Down Expand Up @@ -1231,7 +1235,7 @@ class or instance) that acts as the specification for the mock object. If
`return_value` attribute.
* `unsafe`: By default, accessing any attribute whose name starts with
*assert*, *assret*, *asert*, *aseert* or *assrt* will raise an
*assert*, *assret*, *asert*, *aseert*, *assrt*, or *called_* will raise an
AttributeError. Passing `unsafe=True` will allow access to
these attributes.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Mock objects which are not unsafe will now raise an AttributeError if an
attribute with the prefix ``called_`` is accessed, in addition to this already
happening for the prefixes assert, assret, asert, aseert, assrt.

0 comments on commit 154012f

Please sign in to comment.