summaryrefslogtreecommitdiffstatshomepage
path: root/tests/extmod/uasyncio_cancel_task.py
diff options
context:
space:
mode:
authorDamien George <damien.p.george@gmail.com>2019-11-13 21:08:22 +1100
committerDamien George <damien.p.george@gmail.com>2020-03-26 01:25:45 +1100
commitc4935f30490d0446e16a51dbf7a6397b771cf804 (patch)
treeb095dd91914950939d4d0cdc10e7be3625fff00d /tests/extmod/uasyncio_cancel_task.py
parent63b99443820f53afbdab5201044629d2bfecd73b (diff)
downloadmicropython-c4935f30490d0446e16a51dbf7a6397b771cf804.tar.gz
micropython-c4935f30490d0446e16a51dbf7a6397b771cf804.zip
tests/extmod: Add uasyncio tests.
All .exp files are included because they require CPython 3.8 which may not always be available.
Diffstat (limited to 'tests/extmod/uasyncio_cancel_task.py')
-rw-r--r--tests/extmod/uasyncio_cancel_task.py85
1 files changed, 85 insertions, 0 deletions
diff --git a/tests/extmod/uasyncio_cancel_task.py b/tests/extmod/uasyncio_cancel_task.py
new file mode 100644
index 0000000000..ec60d85545
--- /dev/null
+++ b/tests/extmod/uasyncio_cancel_task.py
@@ -0,0 +1,85 @@
+# Test cancelling a task
+
+try:
+ import uasyncio as asyncio
+except ImportError:
+ try:
+ import asyncio
+ except ImportError:
+ print("SKIP")
+ raise SystemExit
+
+
+async def task(s, allow_cancel):
+ try:
+ print("task start")
+ await asyncio.sleep(s)
+ print("task done")
+ except asyncio.CancelledError as er:
+ print("task cancel")
+ if allow_cancel:
+ raise er
+
+
+async def task2(allow_cancel):
+ print("task 2")
+ try:
+ await asyncio.create_task(task(0.05, allow_cancel))
+ except asyncio.CancelledError as er:
+ print("task 2 cancel")
+ raise er
+ print("task 2 done")
+
+
+async def main():
+ # Cancel task immediately
+ t = asyncio.create_task(task(2, True))
+ print(t.cancel())
+
+ # Cancel task after it has started
+ t = asyncio.create_task(task(2, True))
+ await asyncio.sleep(0.01)
+ print(t.cancel())
+ print("main sleep")
+ await asyncio.sleep(0.01)
+
+ # Cancel task multiple times after it has started
+ t = asyncio.create_task(task(2, True))
+ await asyncio.sleep(0.01)
+ for _ in range(4):
+ print(t.cancel())
+ print("main sleep")
+ await asyncio.sleep(0.01)
+
+ # Await on a cancelled task
+ print("main wait")
+ try:
+ await t
+ except asyncio.CancelledError:
+ print("main got CancelledError")
+
+ # Cancel task after it has finished
+ t = asyncio.create_task(task(0.01, False))
+ await asyncio.sleep(0.05)
+ print(t.cancel())
+
+ # Nested: task2 waits on task, task2 is cancelled (should cancel task then task2)
+ print("----")
+ t = asyncio.create_task(task2(True))
+ await asyncio.sleep(0.01)
+ print("main cancel")
+ t.cancel()
+ print("main sleep")
+ await asyncio.sleep(0.1)
+
+ # Nested: task2 waits on task, task2 is cancelled but task doesn't allow it (task2 should continue)
+ print("----")
+ t = asyncio.create_task(task2(False))
+ await asyncio.sleep(0.01)
+ print("main cancel")
+ t.cancel()
+ print("main sleep")
+ await asyncio.sleep(0.1)
+
+
+asyncio.run(main())