Skip to content

Commit

Permalink
Add the awaited and await_count attributes to CoroutineMock.
Browse files Browse the repository at this point in the history
Refs #64.
  • Loading branch information
Kentzo committed Dec 8, 2017
1 parent 6df2676 commit 312a6a8
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 2 deletions.
28 changes: 26 additions & 2 deletions asynctest/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,9 @@ class CoroutineMock(Mock):
:class:`unittest.mock.Mock` object: the wrapped object may have methods
defined as coroutine functions.
"""
awaited = unittest.mock._delegating_property('awaited')
await_count = unittest.mock._delegating_property('await_count')

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)

Expand All @@ -413,15 +416,31 @@ def __init__(self, *args, **kwargs):
# It is set through __dict__ because when spec_set is True, this
# attribute is likely undefined.
self.__dict__['_is_coroutine'] = _is_coroutine
self.__dict__['_mock_awaited'] = asyncio.Event()
self.__dict__['_mock_await_count'] = 0

def _mock_call(_mock_self, *args, **kwargs):
try:
result = super()._mock_call(*args, **kwargs)

if asyncio.iscoroutine(result):
return result
@asyncio.coroutine
def proxy():
try:
return (yield from result)
finally:
_mock_self.await_count += 1
_mock_self.awaited.set()
else:
return asyncio.coroutine(lambda *a, **kw: result)()
@asyncio.coroutine
def proxy():
try:
return result
finally:
_mock_self.await_count += 1
_mock_self.awaited.set()

return proxy()
except StopIteration as e:
side_effect = _mock_self.side_effect
if side_effect is not None and not callable(side_effect):
Expand All @@ -431,6 +450,11 @@ def _mock_call(_mock_self, *args, **kwargs):
except BaseException as e:
return asyncio.coroutine(_raise)(e)

def reset_mock(self, *args, **kwargs):
super().reset_mock(*args, **kwargs)
self.awaited = asyncio.Event()
self.await_count = 0


def mock_open(mock=None, read_data=''):
"""
Expand Down
17 changes: 17 additions & 0 deletions test/test_mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,23 @@ def test_called_CoroutineMock_returns_MagicMock(self):
mock = asynctest.mock.CoroutineMock()
self.assertIsInstance(run_coroutine(mock()), asynctest.mock.MagicMock)

def test_awaited_CoroutineMock_sets_awaited(self):
mock = asynctest.mock.CoroutineMock()
run_coroutine(mock())
self.assertTrue(mock.awaited.is_set())

mock.reset_mock()
self.assertFalse(mock.awaited.is_set())

def test_awaited_CoroutineMock_counts(self):
mock = asynctest.mock.CoroutineMock()
run_coroutine(mock())
run_coroutine(mock())
self.assertEqual(mock.await_count, 2)

mock.reset_mock()
self.assertEqual(mock.await_count, 0)


class TestMockInheritanceModel(unittest.TestCase):
to_test = {
Expand Down

0 comments on commit 312a6a8

Please sign in to comment.