How do I mock async call from one native coroutine to other one using unittest.mock.patch
?
I currently have quite an awkward solution:
JavaScript
x
7
1
class CoroutineMock(MagicMock):
2
def __await__(self, *args, **kwargs):
3
future = Future()
4
future.set_result(self)
5
result = yield from future
6
return result
7
Then
JavaScript
1
6
1
class TestCoroutines(TestCase):
2
@patch('some.path', new_callable=CoroutineMock)
3
def test(self, mock):
4
some_action()
5
mock.assert_called_with(1,2,3)
6
This works but looks ugly. Is there more pythonic way to do this?
Advertisement
Answer
The solution was actually quite simple:
I just needed to convert __call__
method of mock into coroutine:
JavaScript
1
4
1
class AsyncMock(MagicMock):
2
async def __call__(self, *args, **kwargs):
3
return super(AsyncMock, self).__call__(*args, **kwargs)
4
This works perfectly, when mock is called, code receives native coroutine
Example usage:
JavaScript
1
4
1
@mock.patch('my.path.asyncio.sleep', new_callable=AsyncMock)
2
def test_stuff(sleep):
3
# code
4