[Python-checkins] bpo-37828: Fix default mock_name in unittest.mock.assert_called error (GH-16166)

Pablo Galindo webhook-mailer at python.org
Tue Sep 17 07:16:12 EDT 2019


https://github.com/python/cpython/commit/5f5f11faf9de0d8dcbe1a8a4eb35d2a4232d6eaa
commit: 5f5f11faf9de0d8dcbe1a8a4eb35d2a4232d6eaa
branch: master
author: Abraham Toriz Cruz <awonderfulcode at gmail.com>
committer: Pablo Galindo <Pablogsal at gmail.com>
date: 2019-09-17T12:16:08+01:00
summary:

bpo-37828: Fix default mock_name in unittest.mock.assert_called error (GH-16166)

In the format string for assert_called the evaluation order is incorrect and hence for mock's without name, 'None' is printed whereas it should be 'mock' like for other messages. The error message is ("Expected '%s' to have been called." % self._mock_name or 'mock').

files:
A Misc/NEWS.d/next/Library/2019-09-15-21-31-18.bpo-37828.gLLDX7.rst
M Lib/unittest/mock.py
M Lib/unittest/test/testmock/testmock.py

diff --git a/Lib/unittest/mock.py b/Lib/unittest/mock.py
index 74d32af9bf99..4cf8e60ccc15 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -868,7 +868,7 @@ def assert_called(self):
         """
         if self.call_count == 0:
             msg = ("Expected '%s' to have been called." %
-                   self._mock_name or 'mock')
+                   (self._mock_name or 'mock'))
             raise AssertionError(msg)
 
     def assert_called_once(self):
diff --git a/Lib/unittest/test/testmock/testmock.py b/Lib/unittest/test/testmock/testmock.py
index 581afaaeb815..2bafa8266b63 100644
--- a/Lib/unittest/test/testmock/testmock.py
+++ b/Lib/unittest/test/testmock/testmock.py
@@ -396,6 +396,14 @@ def _check(mock):
         _check(mock)
 
 
+    def test_assert_called_exception_message(self):
+        msg = "Expected '{0}' to have been called"
+        with self.assertRaisesRegex(AssertionError, msg.format('mock')):
+            Mock().assert_called()
+        with self.assertRaisesRegex(AssertionError, msg.format('test_name')):
+            Mock(name="test_name").assert_called()
+
+
     def test_assert_called_once_with(self):
         mock = Mock()
         mock()
diff --git a/Misc/NEWS.d/next/Library/2019-09-15-21-31-18.bpo-37828.gLLDX7.rst b/Misc/NEWS.d/next/Library/2019-09-15-21-31-18.bpo-37828.gLLDX7.rst
new file mode 100644
index 000000000000..c364009b2408
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-09-15-21-31-18.bpo-37828.gLLDX7.rst
@@ -0,0 +1,2 @@
+Fix default mock name in :meth:`unittest.mock.Mock.assert_called` exceptions.
+Patch by Abraham Toriz Cruz.



More information about the Python-checkins mailing list