Skip to content

bpo-21478: Autospec functions should propagate mock calls to parent #11273

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 25, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/unittest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions Lib/unittest/test/testmock/testmock.py
Original file line number Diff line number Diff line change
Expand Up @@ -1802,5 +1802,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)])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What was the outcome here before your fix?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

mock.mock_calls would be an empty list though the child mock was called. It's a case where create_autospec returns a function object with mock attached to it in the mock attribute instead of a mock.



if __name__ == '__main__':
unittest.main()
Original file line number Diff line number Diff line change
@@ -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.