This code is stuck in an infinite loop, the self.task.cancel()
seems to have no effect:
import asyncio
from unittest.mock import AsyncMock, patch
async def loop():
while True:
await asyncio.sleep(1)
class AsyncSleepMock(AsyncMock):
def __init__(self):
super(AsyncMock, self).__init__()
self.task = None
async def __call__(self, delay, *args, **kwargs):
self.task.cancel()
return await super(AsyncMock, self).__call__(delay, *args, **kwargs)
def create_async_sleep_mock():
return AsyncSleepMock()
@patch("asyncio.sleep", new_callable=create_async_sleep_mock)
def main(async_sleep_mock):
loop_task = asyncio.get_event_loop().create_task(loop())
async_sleep_mock.task = loop_task
asyncio.get_event_loop().run_until_complete(loop_task)
if __name__ == "__main__":
main()
The goal is to make a mock of asyncio.sleep()
that can break out from that infinite loop()
that the application under test has. How to do that?