Skip to content

Commit b5a7a4f

Browse files
sfreilichmiss-islington
authored andcommitted
bpo-36871: Handle spec errors in assert_has_calls (GH-16005)
The fix in PR 13261 handled the underlying issue about the spec for specific methods not being applied correctly, but it didn't fix the issue that was causing the misleading error message. The code currently grabs a list of responses from _call_matcher (which may include exceptions). But it doesn't reach inside the list when checking if the result is an exception. This results in a misleading error message when one of the provided calls does not match the spec. https://bugs.python.org/issue36871 Automerge-Triggered-By: @gpshead
1 parent bb6bf7d commit b5a7a4f

File tree

4 files changed

+64
-5
lines changed

4 files changed

+64
-5
lines changed

Lib/unittest/mock.py

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -926,13 +926,21 @@ def assert_has_calls(self, calls, any_order=False):
926926
If `any_order` is True then the calls can be in any order, but
927927
they must all appear in `mock_calls`."""
928928
expected = [self._call_matcher(c) for c in calls]
929-
cause = expected if isinstance(expected, Exception) else None
929+
cause = next((e for e in expected if isinstance(e, Exception)), None)
930930
all_calls = _CallList(self._call_matcher(c) for c in self.mock_calls)
931931
if not any_order:
932932
if expected not in all_calls:
933+
if cause is None:
934+
problem = 'Calls not found.'
935+
else:
936+
problem = ('Error processing expected calls.\n'
937+
'Errors: {}').format(
938+
[e if isinstance(e, Exception) else None
939+
for e in expected])
933940
raise AssertionError(
934-
'Calls not found.\nExpected: %r%s'
935-
% (_CallList(calls), self._calls_repr(prefix="Actual"))
941+
f'{problem}\n'
942+
f'Expected: {_CallList(calls)}\n'
943+
f'Actual: {self._calls_repr(prefix="Actual")}'
936944
) from cause
937945
return
938946

@@ -2244,12 +2252,20 @@ def assert_has_awaits(self, calls, any_order=False):
22442252
they must all appear in :attr:`await_args_list`.
22452253
"""
22462254
expected = [self._call_matcher(c) for c in calls]
2247-
cause = expected if isinstance(expected, Exception) else None
2255+
cause = next((e for e in expected if isinstance(e, Exception)), None)
22482256
all_awaits = _CallList(self._call_matcher(c) for c in self.await_args_list)
22492257
if not any_order:
22502258
if expected not in all_awaits:
2259+
if cause is None:
2260+
problem = 'Awaits not found.'
2261+
else:
2262+
problem = ('Error processing expected awaits.\n'
2263+
'Errors: {}').format(
2264+
[e if isinstance(e, Exception) else None
2265+
for e in expected])
22512266
raise AssertionError(
2252-
f'Awaits not found.\nExpected: {_CallList(calls)}\n'
2267+
f'{problem}\n'
2268+
f'Expected: {_CallList(calls)}\n'
22532269
f'Actual: {self.await_args_list}'
22542270
) from cause
22552271
return

Lib/unittest/test/testmock/testasync.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import asyncio
22
import inspect
3+
import re
34
import unittest
45

56
from unittest.mock import (ANY, call, AsyncMock, patch, MagicMock,
@@ -889,3 +890,23 @@ def test_assert_not_awaited(self):
889890
asyncio.run(self._runnable_test())
890891
with self.assertRaises(AssertionError):
891892
self.mock.assert_not_awaited()
893+
894+
def test_assert_has_awaits_not_matching_spec_error(self):
895+
async def f(): pass
896+
897+
mock = AsyncMock(spec=f)
898+
899+
with self.assertRaisesRegex(
900+
AssertionError,
901+
re.escape('Awaits not found.\nExpected:')) as cm:
902+
mock.assert_has_awaits([call()])
903+
self.assertIsNone(cm.exception.__cause__)
904+
905+
with self.assertRaisesRegex(
906+
AssertionError,
907+
re.escape('Error processing expected awaits.\n'
908+
"Errors: [None, TypeError('too many positional "
909+
"arguments')]\n"
910+
'Expected:')) as cm:
911+
mock.assert_has_awaits([call(), call('wrong')])
912+
self.assertIsInstance(cm.exception.__cause__, TypeError)

Lib/unittest/test/testmock/testmock.py

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1435,6 +1435,25 @@ def f(a, b, c, d=None): pass
14351435
mock.assert_has_calls(calls[:-1])
14361436
mock.assert_has_calls(calls[:-1], any_order=True)
14371437

1438+
def test_assert_has_calls_not_matching_spec_error(self):
1439+
def f(): pass
1440+
1441+
mock = Mock(spec=f)
1442+
1443+
with self.assertRaisesRegex(
1444+
AssertionError,
1445+
re.escape('Calls not found.\nExpected:')) as cm:
1446+
mock.assert_has_calls([call()])
1447+
self.assertIsNone(cm.exception.__cause__)
1448+
1449+
with self.assertRaisesRegex(
1450+
AssertionError,
1451+
re.escape('Error processing expected calls.\n'
1452+
"Errors: [None, TypeError('too many positional "
1453+
"arguments')]\n"
1454+
'Expected:')) as cm:
1455+
mock.assert_has_calls([call(), call('wrong')])
1456+
self.assertIsInstance(cm.exception.__cause__, TypeError)
14381457

14391458
def test_assert_any_call(self):
14401459
mock = Mock()
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Improve error handling for the assert_has_calls and assert_has_awaits methods of
2+
mocks. Fixed a bug where any errors encountered while binding the expected calls
3+
to the mock's spec were silently swallowed, leading to misleading error output.

0 commit comments

Comments
 (0)