Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 8af9db3

Browse files
committed
Closes Issue 21262: New method assert_not_called for Mock.
It raises AssertionError if the mock has been called.
1 parent 8c14534 commit 8af9db3

4 files changed

Lines changed: 34 additions & 0 deletions

File tree

Doc/library/unittest.mock.rst

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,20 @@ the `new_callable` argument to `patch`.
321321
>>> calls = [call(4), call(2), call(3)]
322322
>>> mock.assert_has_calls(calls, any_order=True)
323323

324+
.. method:: assert_not_called(*args, **kwargs)
325+
326+
Assert the mock was never called.
327+
328+
>>> m = Mock()
329+
>>> m.hello.assert_not_called()
330+
>>> obj = m.hello()
331+
>>> m.hello.assert_not_called()
332+
Traceback (most recent call last):
333+
...
334+
AssertionError: Expected 'hello' to not have been called. Called 1 times.
335+
336+
.. versionadded:: 3.5
337+
324338

325339
.. method:: reset_mock()
326340

Lib/unittest/mock.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -758,6 +758,14 @@ def _call_matcher(self, _call):
758758
else:
759759
return _call
760760

761+
def assert_not_called(_mock_self, *args, **kwargs):
762+
"""assert that the mock was never called.
763+
"""
764+
self = _mock_self
765+
if self.call_count != 0:
766+
msg = ("Expected '%s' to not have been called. Called %s times." %
767+
(self._mock_name or 'mock', self.call_count))
768+
raise AssertionError(msg)
761769

762770
def assert_called_with(_mock_self, *args, **kwargs):
763771
"""assert that the mock was called with the specified arguments.

Lib/unittest/test/testmock/testmock.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1198,6 +1198,15 @@ def test_mock_unsafe(self):
11981198
m.assert_foo_call()
11991199
m.assret_foo_call()
12001200

1201+
#Issue21262
1202+
def test_assert_not_called(self):
1203+
m = Mock()
1204+
m.hello.assert_not_called()
1205+
m.hello()
1206+
with self.assertRaises(AssertionError):
1207+
m.hello.assert_not_called()
1208+
1209+
12011210
def test_mock_add_spec(self):
12021211
class _One(object):
12031212
one = 1

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@ Core and Builtins
5050
Library
5151
-------
5252

53+
- Issue #21262: New method assert_not_called for Mock.
54+
It raises AssertionError if the mock has been called.
55+
5356
- Issue #21238: New keyword argument `unsafe` to Mock. It raises
5457
`AttributeError` incase of an attribute startswith assert or assret.
5558

0 commit comments

Comments
 (0)