[Python-checkins] Autospec functions should propagate mock calls to parent GH-11273

Chris Withers webhook-mailer at python.org
Mon Feb 25 16:45:22 EST 2019


https://github.com/python/cpython/commit/9c3f284de598550be6687964c23fd7599e53b20e
commit: 9c3f284de598550be6687964c23fd7599e53b20e
branch: master
author: Xtreak <tir.karthi at gmail.com>
committer: Chris Withers <chris at withers.org>
date: 2019-02-25T21:46:34Z
summary:

Autospec functions should propagate mock calls to parent GH-11273

files:
A Misc/NEWS.d/next/Library/2018-12-21-09-54-30.bpo-21478.5gsXtc.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 ccbcd355ce31..2ccf0d82ce23 100644
--- a/Lib/unittest/mock.py
+++ b/Lib/unittest/mock.py
@@ -321,6 +321,14 @@ def __repr__(self):
 
 
 def _check_and_set_parent(parent, value, name, new_name):
+    # function passed to create_autospec will have mock
+    # attribute attached to which parent must be set
+    if isinstance(value, FunctionTypes):
+        try:
+            value = value.mock
+        except AttributeError:
+            pass
+
     if not _is_instance_mock(value):
         return False
     if ((value._mock_name or value._mock_new_name) or
diff --git a/Lib/unittest/test/testmock/testmock.py b/Lib/unittest/test/testmock/testmock.py
index 04ab52271578..2ad90ea81ec7 100644
--- a/Lib/unittest/test/testmock/testmock.py
+++ b/Lib/unittest/test/testmock/testmock.py
@@ -1830,5 +1830,18 @@ def test_parent_attribute_of_call(self):
         self.assertEqual(type(call.parent().parent), _Call)
 
 
+    def test_parent_propagation_with_create_autospec(self):
+
+        def foo(a, b):
+            pass
+
+        mock = Mock()
+        mock.child = create_autospec(foo)
+        mock.child(1, 2)
+
+        self.assertRaises(TypeError, mock.child, 1)
+        self.assertEqual(mock.mock_calls, [call.child(1, 2)])
+
+
 if __name__ == '__main__':
     unittest.main()
diff --git a/Misc/NEWS.d/next/Library/2018-12-21-09-54-30.bpo-21478.5gsXtc.rst b/Misc/NEWS.d/next/Library/2018-12-21-09-54-30.bpo-21478.5gsXtc.rst
new file mode 100644
index 000000000000..1000748c9c48
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2018-12-21-09-54-30.bpo-21478.5gsXtc.rst
@@ -0,0 +1,2 @@
+Calls to a child function created with :func:`unittest.mock.create_autospec`
+should propagate to the parent. Patch by Karthikeyan Singaravelan.



More information about the Python-checkins mailing list