Skip to content

Commit 66b00a9

Browse files
tirkarthicjw296
authored andcommitted
bpo-38473: Handle autospecced functions and methods used with attach_mock (GH-16784)
1 parent b8d1262 commit 66b00a9

File tree

3 files changed

+35
-0
lines changed

3 files changed

+35
-0
lines changed

Lib/unittest/mock.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -817,6 +817,10 @@ def _get_call_signature_from_name(self, name):
817817
if child is None or isinstance(child, _SpecState):
818818
break
819819
else:
820+
# If an autospecced object is attached using attach_mock the
821+
# child would be a function with mock object as attribute from
822+
# which signature has to be derived.
823+
child = _extract_mock(child)
820824
children = child._mock_children
821825
sig = child._spec_signature
822826

Lib/unittest/test/testmock/testmock.py

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1922,6 +1922,35 @@ def test_attach_mock_patch_autospec(self):
19221922
self.assertEqual(mock_func.mock._extract_mock_name(), 'mock.child')
19231923

19241924

1925+
def test_attach_mock_patch_autospec_signature(self):
1926+
with mock.patch(f'{__name__}.Something.meth', autospec=True) as mocked:
1927+
manager = Mock()
1928+
manager.attach_mock(mocked, 'attach_meth')
1929+
obj = Something()
1930+
obj.meth(1, 2, 3, d=4)
1931+
manager.assert_has_calls([call.attach_meth(mock.ANY, 1, 2, 3, d=4)])
1932+
obj.meth.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
1933+
mocked.assert_has_calls([call(mock.ANY, 1, 2, 3, d=4)])
1934+
1935+
with mock.patch(f'{__name__}.something', autospec=True) as mocked:
1936+
manager = Mock()
1937+
manager.attach_mock(mocked, 'attach_func')
1938+
something(1)
1939+
manager.assert_has_calls([call.attach_func(1)])
1940+
something.assert_has_calls([call(1)])
1941+
mocked.assert_has_calls([call(1)])
1942+
1943+
with mock.patch(f'{__name__}.Something', autospec=True) as mocked:
1944+
manager = Mock()
1945+
manager.attach_mock(mocked, 'attach_obj')
1946+
obj = Something()
1947+
obj.meth(1, 2, 3, d=4)
1948+
manager.assert_has_calls([call.attach_obj(),
1949+
call.attach_obj().meth(1, 2, 3, d=4)])
1950+
obj.meth.assert_has_calls([call(1, 2, 3, d=4)])
1951+
mocked.assert_has_calls([call(), call().meth(1, 2, 3, d=4)])
1952+
1953+
19251954
def test_attribute_deletion(self):
19261955
for mock in (Mock(), MagicMock(), NonCallableMagicMock(),
19271956
NonCallableMock()):
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Use signature from inner mock for autospecced methods attached with
2+
:func:`unittest.mock.attach_mock`. Patch by Karthikeyan Singaravelan.

0 commit comments

Comments
 (0)