Skip to content

Commit 4b9459d

Browse files
miss-islingtontirkarthi
authored andcommitted
Autospec functions should propagate mock calls to parent GH-11273 (#12039)
(cherry picked from commit 9c3f284) Co-authored-by: Xtreak <[email protected]>
1 parent cd04164 commit 4b9459d

File tree

3 files changed

+23
-0
lines changed

3 files changed

+23
-0
lines changed

Lib/unittest/mock.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,14 @@ def __repr__(self):
320320

321321

322322
def _check_and_set_parent(parent, value, name, new_name):
323+
# function passed to create_autospec will have mock
324+
# attribute attached to which parent must be set
325+
if isinstance(value, FunctionTypes):
326+
try:
327+
value = value.mock
328+
except AttributeError:
329+
pass
330+
323331
if not _is_instance_mock(value):
324332
return False
325333
if ((value._mock_name or value._mock_new_name) or

Lib/unittest/test/testmock/testmock.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1799,5 +1799,18 @@ def test_parent_attribute_of_call(self):
17991799
self.assertEqual(type(call.parent().parent), _Call)
18001800

18011801

1802+
def test_parent_propagation_with_create_autospec(self):
1803+
1804+
def foo(a, b):
1805+
pass
1806+
1807+
mock = Mock()
1808+
mock.child = create_autospec(foo)
1809+
mock.child(1, 2)
1810+
1811+
self.assertRaises(TypeError, mock.child, 1)
1812+
self.assertEqual(mock.mock_calls, [call.child(1, 2)])
1813+
1814+
18021815
if __name__ == '__main__':
18031816
unittest.main()
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Calls to a child function created with :func:`unittest.mock.create_autospec`
2+
should propagate to the parent. Patch by Karthikeyan Singaravelan.

0 commit comments

Comments
 (0)