]> granicus.if.org Git - python/commitdiff
Closes Issue 21262: New method assert_not_called for Mock.
authorKushal Das <kushaldas@gmail.com>
Wed, 16 Apr 2014 20:06:14 +0000 (01:36 +0530)
committerKushal Das <kushaldas@gmail.com>
Wed, 16 Apr 2014 20:06:14 +0000 (01:36 +0530)
It raises AssertionError if the mock has been called.

Doc/library/unittest.mock.rst
Lib/unittest/mock.py
Lib/unittest/test/testmock/testmock.py
Misc/NEWS

index e6ca908816ef881c128eaf144469362b5ed667fb..4f588924433db6be8a774f08924ba586f64ae99a 100644 (file)
@@ -321,6 +321,20 @@ the `new_callable` argument to `patch`.
             >>> calls = [call(4), call(2), call(3)]
             >>> mock.assert_has_calls(calls, any_order=True)
 
+    .. method:: assert_not_called(*args, **kwargs)
+
+        Assert the mock was never called.
+
+            >>> m = Mock()
+            >>> m.hello.assert_not_called()
+            >>> obj = m.hello()
+            >>> m.hello.assert_not_called()
+            Traceback (most recent call last):
+              ...
+            AssertionError: Expected 'hello' to not have been called. Called 1 times.
+
+        .. versionadded:: 3.5
+
 
     .. method:: reset_mock()
 
index 48e7dd078f24e9b6d689ca8c9a6f5c56abb6068b..6c00bc66f8fbe5f349a363d034fc43b254e93bb4 100644 (file)
@@ -758,6 +758,14 @@ class NonCallableMock(Base):
         else:
             return _call
 
+    def assert_not_called(_mock_self, *args, **kwargs):
+        """assert that the mock was never called.
+        """
+        self = _mock_self
+        if self.call_count != 0:
+            msg = ("Expected '%s' to not have been called. 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.
index 59353a095b6efef54092253602576230a87a6f8c..b65dc321cff655e63066d15782f19504bd6924b9 100644 (file)
@@ -1198,6 +1198,15 @@ class MockTest(unittest.TestCase):
         m.assert_foo_call()
         m.assret_foo_call()
 
+    #Issue21262
+    def test_assert_not_called(self):
+        m = Mock()
+        m.hello.assert_not_called()
+        m.hello()
+        with self.assertRaises(AssertionError):
+            m.hello.assert_not_called()
+
+
     def test_mock_add_spec(self):
         class _One(object):
             one = 1
index dd1c4afb3a6223374011338c8f7171be6008f2bb..4bef2992c1587a4a696cf2f1e9f3e5f981479012 100644 (file)
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -50,6 +50,9 @@ Core and Builtins
 Library
 -------
 
+- Issue #21262: New method assert_not_called for Mock.
+  It raises AssertionError if the mock has been called.
+
 - Issue #21238: New keyword argument `unsafe` to Mock. It raises
   `AttributeError` incase of an attribute startswith assert or assret.