/tests/extmod/uasyncio_wait_for_fwd.py

https://github.com/mcauser/micropython · Python · 60 lines · 48 code · 10 blank · 2 comment · 15 complexity · dacc3fc3104be06bdfa760bf30a55bab MD5 · raw file

  1. # Test asyncio.wait_for, with forwarding cancellation
  2. try:
  3. import uasyncio as asyncio
  4. except ImportError:
  5. try:
  6. import asyncio
  7. except ImportError:
  8. print("SKIP")
  9. raise SystemExit
  10. async def awaiting(t, return_if_fail):
  11. try:
  12. print("awaiting started")
  13. await asyncio.sleep(t)
  14. except asyncio.CancelledError as er:
  15. # CPython wait_for raises CancelledError inside task but TimeoutError in wait_for
  16. print("awaiting canceled")
  17. if return_if_fail:
  18. return False # return has no effect if Cancelled
  19. else:
  20. raise er
  21. except Exception as er:
  22. print("caught exception", er)
  23. raise er
  24. async def test_cancellation_forwarded(catch, catch_inside):
  25. print("----------")
  26. async def wait():
  27. try:
  28. await asyncio.wait_for(awaiting(2, catch_inside), 1)
  29. except asyncio.TimeoutError as er:
  30. print("Got timeout error")
  31. raise er
  32. except asyncio.CancelledError as er:
  33. print("Got canceled")
  34. if not catch:
  35. raise er
  36. async def cancel(t):
  37. print("cancel started")
  38. await asyncio.sleep(0.01)
  39. print("cancel wait()")
  40. t.cancel()
  41. t = asyncio.create_task(wait())
  42. k = asyncio.create_task(cancel(t))
  43. try:
  44. await t
  45. except asyncio.CancelledError:
  46. print("waiting got cancelled")
  47. asyncio.run(test_cancellation_forwarded(False, False))
  48. asyncio.run(test_cancellation_forwarded(False, True))
  49. asyncio.run(test_cancellation_forwarded(True, True))
  50. asyncio.run(test_cancellation_forwarded(True, False))