summaryrefslogtreecommitdiff
path: root/tests/extmod/uasyncio_lock_cancel.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_lock_cancel.py
parent63b99443820f53afbdab5201044629d2bfecd73b (diff)
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_lock_cancel.py')
-rw-r--r--tests/extmod/uasyncio_lock_cancel.py55
1 files changed, 55 insertions, 0 deletions
diff --git a/tests/extmod/uasyncio_lock_cancel.py b/tests/extmod/uasyncio_lock_cancel.py
new file mode 100644
index 000000000..85b8df848
--- /dev/null
+++ b/tests/extmod/uasyncio_lock_cancel.py
@@ -0,0 +1,55 @@
+# Test that locks work when cancelling multiple waiters on the lock
+
+try:
+ import uasyncio as asyncio
+except ImportError:
+ try:
+ import asyncio
+ except ImportError:
+ print("SKIP")
+ raise SystemExit
+
+
+async def task(i, lock, lock_flag):
+ print("task", i, "start")
+ try:
+ await lock.acquire()
+ except asyncio.CancelledError:
+ print("task", i, "cancel")
+ return
+ print("task", i, "lock_flag", lock_flag[0])
+ lock_flag[0] = True
+ await asyncio.sleep(0)
+ lock.release()
+ lock_flag[0] = False
+ print("task", i, "done")
+
+
+async def main():
+ # Create a lock and acquire it so the tasks below must wait
+ lock = asyncio.Lock()
+ await lock.acquire()
+ lock_flag = [True]
+
+ # Create 4 tasks and let them all run
+ t0 = asyncio.create_task(task(0, lock, lock_flag))
+ t1 = asyncio.create_task(task(1, lock, lock_flag))
+ t2 = asyncio.create_task(task(2, lock, lock_flag))
+ t3 = asyncio.create_task(task(3, lock, lock_flag))
+ await asyncio.sleep(0)
+
+ # Cancel 2 of the tasks (which are waiting on the lock) and release the lock
+ t1.cancel()
+ t2.cancel()
+ lock.release()
+ lock_flag[0] = False
+
+ # Let the tasks run to completion
+ for _ in range(4):
+ await asyncio.sleep(0)
+
+ # The locke should be unlocked
+ print(lock.locked())
+
+
+asyncio.run(main())