Skip to content

Commit e5d7551

Browse files
vabr-gcjw296
authored andcommitted
bpo-41877 Check for asert, aseert, assrt in mocks (GH-23165)
Currently, a Mock object which is not unsafe will raise an AttributeError if an attribute with the prefix assert or assret is accessed on it. This protects against misspellings of real assert method calls, which lead to tests passing silently even if the tested code does not satisfy the intended assertion. Recently a check was done in a large code base (Google) and three more frequent ways of misspelling assert were found causing harm: asert, aseert, assrt. These are now added to the existing check. Backports: 4662fa9bfe4a849fe87bfb321d8ef0956c89a772 Signed-off-by: Chris Withers <[email protected]>
1 parent c627515 commit e5d7551

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Mock objects which are not unsafe will now raise an AttributeError if an attribute with the prefix asert, aseert,
2+
or assrt is accessed, in addition to this already happening for the prefixes assert or assret.

mock/mock.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -633,9 +633,9 @@ def __getattr__(self, name):
633633
elif _is_magic(name):
634634
raise AttributeError(name)
635635
if not self._mock_unsafe:
636-
if name.startswith(('assert', 'assret')):
636+
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
637637
raise AttributeError("Attributes cannot start with 'assert' "
638-
"or 'assret'")
638+
"or its misspellings")
639639

640640
result = self._mock_children.get(name)
641641
if result is _deleted:

mock/tests/testmock.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1600,14 +1600,23 @@ def static_method(): pass
16001600
#Issue21238
16011601
def test_mock_unsafe(self):
16021602
m = Mock()
1603-
msg = "Attributes cannot start with 'assert' or 'assret'"
1603+
msg = "Attributes cannot start with 'assert' or its misspellings"
16041604
with self.assertRaisesRegex(AttributeError, msg):
16051605
m.assert_foo_call()
16061606
with self.assertRaisesRegex(AttributeError, msg):
16071607
m.assret_foo_call()
1608+
with self.assertRaisesRegex(AttributeError, msg):
1609+
m.asert_foo_call()
1610+
with self.assertRaisesRegex(AttributeError, msg):
1611+
m.aseert_foo_call()
1612+
with self.assertRaisesRegex(AttributeError, msg):
1613+
m.assrt_foo_call()
16081614
m = Mock(unsafe=True)
16091615
m.assert_foo_call()
16101616
m.assret_foo_call()
1617+
m.asert_foo_call()
1618+
m.aseert_foo_call()
1619+
m.assrt_foo_call()
16111620

16121621
#Issue21262
16131622
def test_assert_not_called(self):

0 commit comments

Comments
 (0)