Skip to content

Commit 4662fa9

Browse files
authored
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.
1 parent 133aa2d commit 4662fa9

File tree

3 files changed

+14
-3
lines changed

3 files changed

+14
-3
lines changed

Lib/unittest/mock.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -631,9 +631,9 @@ def __getattr__(self, name):
631631
elif _is_magic(name):
632632
raise AttributeError(name)
633633
if not self._mock_unsafe:
634-
if name.startswith(('assert', 'assret')):
634+
if name.startswith(('assert', 'assret', 'asert', 'aseert', 'assrt')):
635635
raise AttributeError("Attributes cannot start with 'assert' "
636-
"or 'assret'")
636+
"or its misspellings")
637637

638638
result = self._mock_children.get(name)
639639
if result is _deleted:

Lib/unittest/test/testmock/testmock.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1598,14 +1598,23 @@ def static_method(): pass
15981598
#Issue21238
15991599
def test_mock_unsafe(self):
16001600
m = Mock()
1601-
msg = "Attributes cannot start with 'assert' or 'assret'"
1601+
msg = "Attributes cannot start with 'assert' or its misspellings"
16021602
with self.assertRaisesRegex(AttributeError, msg):
16031603
m.assert_foo_call()
16041604
with self.assertRaisesRegex(AttributeError, msg):
16051605
m.assret_foo_call()
1606+
with self.assertRaisesRegex(AttributeError, msg):
1607+
m.asert_foo_call()
1608+
with self.assertRaisesRegex(AttributeError, msg):
1609+
m.aseert_foo_call()
1610+
with self.assertRaisesRegex(AttributeError, msg):
1611+
m.assrt_foo_call()
16061612
m = Mock(unsafe=True)
16071613
m.assert_foo_call()
16081614
m.assret_foo_call()
1615+
m.asert_foo_call()
1616+
m.aseert_foo_call()
1617+
m.assrt_foo_call()
16091618

16101619
#Issue21262
16111620
def test_assert_not_called(self):
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.

0 commit comments

Comments
 (0)