Skip to content

Commit

Permalink
Add Mock.assert_called()
Browse files Browse the repository at this point in the history
Issue #26323: Add assert_called() and assert_called_once() methods to
unittest.mock.Mock.
  • Loading branch information
vstinner authored and rbtcollins committed Mar 23, 2016
1 parent e966658 commit 7ca5d3a
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
3 changes: 3 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
Library
-------

- Issue #26323: Add Mock.assert_called() and Mock.assert_called_once()
methods to unittest.mock. Patch written by Amit Saha.

- Issue #22138: Fix mock.patch behavior when patching descriptors. Restore
original values after patching. Patch contributed by Sean McCully.

Expand Down
18 changes: 18 additions & 0 deletions mock/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -911,6 +911,24 @@ def assert_not_called(_mock_self):
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg)

def assert_called(_mock_self):
"""assert that the mock was called at least once
"""
self = _mock_self
if self.call_count == 0:
msg = ("Expected '%s' to have been called." %
self._mock_name or 'mock')
raise AssertionError(msg)

def assert_called_once(_mock_self):
"""assert that the mock was called only once.
"""
self = _mock_self
if not self.call_count == 1:
msg = ("Expected '%s' to have been called once. Called %s times." %
(self._mock_name or 'mock', self.call_count))
raise AssertionError(msg)

def assert_called_with(_mock_self, *args, **kwargs):
"""assert that the mock was called with the specified arguments.
Expand Down
21 changes: 21 additions & 0 deletions mock/tests/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1288,6 +1288,27 @@ def test_assert_not_called(self):
with self.assertRaises(AssertionError):
m.hello.assert_not_called()

def test_assert_called(self):
m = Mock()
with self.assertRaises(AssertionError):
m.hello.assert_called()
m.hello()
m.hello.assert_called()

m.hello()
m.hello.assert_called()

def test_assert_called_once(self):
m = Mock()
with self.assertRaises(AssertionError):
m.hello.assert_called_once()
m.hello()
m.hello.assert_called_once()

m.hello()
with self.assertRaises(AssertionError):
m.hello.assert_called_once()

#Issue21256 printout of keyword args should be in deterministic order
def test_sorted_call_signature(self):
m = Mock()
Expand Down

0 comments on commit 7ca5d3a

Please sign in to comment.