summaryrefslogtreecommitdiffstatshomepage
path: root/tests/extmod/uasyncio_set_exception_handler.py
blob: fe7b83eb4d81a6e79f00c0fcb678e79dfe9e310e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# Test that tasks return their value correctly to the caller

try:
    import uasyncio as asyncio
except ImportError:
    try:
        import asyncio
    except ImportError:
        print("SKIP")
        raise SystemExit


def custom_handler(loop, context):
    print("custom_handler", repr(context["exception"]))


async def task(i):
    # Raise with 2 args so exception prints the same in uPy and CPython
    raise ValueError(i, i + 1)


async def main():
    loop = asyncio.get_event_loop()

    # Check default exception handler, should be None
    print(loop.get_exception_handler())

    # Set exception handler and test it was set
    loop.set_exception_handler(custom_handler)
    print(loop.get_exception_handler() == custom_handler)

    # Create a task that raises and uses the custom exception handler
    asyncio.create_task(task(0))
    print("sleep")
    for _ in range(2):
        await asyncio.sleep(0)

    # Create 2 tasks to test order of printing exception
    asyncio.create_task(task(1))
    asyncio.create_task(task(2))
    print("sleep")
    for _ in range(2):
        await asyncio.sleep(0)

    # Create a task, let it run, then await it (no exception should be printed)
    t = asyncio.create_task(task(3))
    await asyncio.sleep(0)
    try:
        await t
    except ValueError as er:
        print(repr(er))

    print("done")


asyncio.run(main())