title: How to make asyncio cancel() to actually cancel the task?
body: <p>This code is stuck in an infinite loop, the <code>self.task.cancel()</code> seems to have no effect:</p>
  <pre><code>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(&quot;asyncio.sleep&quot;, 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__ == &quot;__main__&quot;:
      main()
  </code></pre>
  <p>The goal is to make a mock of <code>asyncio.sleep()</code> that can break out from that infinite <code>loop()</code> that the application under test has. How to do that?</p>