giambio/tests/count.py

56 lines
1.6 KiB
Python
Raw Normal View History

import giambio
2020-11-14 10:42:46 +01:00
# A test for context managers
async def countdown(n: int):
while n > 0:
print(f"Down {n}")
n -= 1
await giambio.sleep(1)
2020-11-14 10:42:46 +01:00
# raise Exception("oh no man") # Uncomment to test propagation
print("Countdown over")
return 0
2020-07-13 22:02:31 +02:00
async def countup(stop: int, step: int = 1):
2020-11-14 12:59:58 +01:00
x = 0
while x < stop:
print(f"Up {x}")
x += 1
await giambio.sleep(step)
print("Countup over")
return 1
async def main():
2020-11-14 10:42:46 +01:00
try:
print("Creating an async pool")
async with giambio.create_pool() as pool:
print("Starting counters")
pool.spawn(countdown, 10)
2020-11-14 12:59:58 +01:00
count_up = pool.spawn(countup, 5, 2)
# raise Exception
# Raising an exception here has a weird
# Behavior: The exception is propagated
# *after* all the child tasks complete,
# which is not what we want
# print("Sleeping for 2 seconds before cancelling")
# await giambio.sleep(2)
# await count_up.cancel() # TODO: Cancel _is_ broken, this does not re-schedule the parent!
# print("Cancelled countup")
2020-11-14 10:42:46 +01:00
print("Task execution complete")
except Exception as e:
print(f"Caught this bad boy in here, propagating it -> {type(e).__name__}: {e}")
raise
2020-07-13 22:02:31 +02:00
if __name__ == "__main__":
2020-11-14 10:42:46 +01:00
print("Starting event loop")
2020-11-12 23:35:01 +01:00
try:
giambio.run(main)
2020-11-14 12:59:58 +01:00
except BaseException as error:
print(f"Exception caught from main event loop! -> {type(error).__name__}: {error}")
2020-11-14 10:42:46 +01:00
print("Event loop done")