bpo-41877: Improve docs for assert misspellings check in mock (GH-23729)

This is a follow-up to
4662fa9bfe.
That original commit expanded guards against misspelling assertions on
mocks. This follow-up updates the documentation and improves the error
message by pointing out the potential cause and solution.

Automerge-Triggered-By: GH:gpshead
This commit is contained in:
vabr-g 2020-12-10 19:35:28 +01:00 committed by GitHub
parent b5c7b38f5e
commit 9fc571359a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 9 additions and 6 deletions

View File

@ -262,9 +262,10 @@ the *new_callable* argument to :func:`patch`.
this is a new Mock (created on first access). See the this is a new Mock (created on first access). See the
:attr:`return_value` attribute. :attr:`return_value` attribute.
* *unsafe*: By default if any attribute starts with *assert* or * *unsafe*: By default, accessing any attribute with name starting with
*assret* will raise an :exc:`AttributeError`. Passing ``unsafe=True`` *assert*, *assret*, *asert*, *aseert* or *assrt* will raise an
will allow access to these attributes. :exc:`AttributeError`. Passing ``unsafe=True`` will allow access to
these attributes.
.. versionadded:: 3.5 .. versionadded:: 3.5

View File

@ -632,8 +632,9 @@ class NonCallableMock(Base):
raise AttributeError(name) raise AttributeError(name)
if not self._mock_unsafe: if not self._mock_unsafe:
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')): if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
raise AttributeError("Attributes cannot start with 'assert' " raise AttributeError(
"or its misspellings") f"{name} is not a valid assertion. Use a spec "
f"for the mock if {name} is meant to be an attribute.")
result = self._mock_children.get(name) result = self._mock_children.get(name)
if result is _deleted: if result is _deleted:

View File

@ -1598,7 +1598,7 @@ class MockTest(unittest.TestCase):
#Issue21238 #Issue21238
def test_mock_unsafe(self): def test_mock_unsafe(self):
m = Mock() m = Mock()
msg = "Attributes cannot start with 'assert' or its misspellings" msg = "is not a valid assertion. Use a spec for the mock"
with self.assertRaisesRegex(AttributeError, msg): with self.assertRaisesRegex(AttributeError, msg):
m.assert_foo_call() m.assert_foo_call()
with self.assertRaisesRegex(AttributeError, msg): with self.assertRaisesRegex(AttributeError, msg):

View File

@ -0,0 +1 @@
AttributeError for suspected misspellings of assertions on mocks are now pointing out that the cause are misspelled assertions and also what to do if the misspelling is actually an intended attribute name. The unittest.mock document is also updated to reflect the current set of recognised misspellings.