aboutsummaryrefslogtreecommitdiff
path: root/tests/net_inet/uasyncio_cancel_stream.py
blob: 6b6b845b0f7a844a02346ced7a02569fdef10fd7 (plain)
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
# Test cancelling a task waiting on stream IO

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


async def get(reader):
    print("start")
    try:
        await reader.read(10)
        print("fail")
    except asyncio.CancelledError:
        print("cancelled")


async def main(url):
    reader, writer = await asyncio.open_connection(url, 80)
    task = asyncio.create_task(get(reader))
    await asyncio.sleep(0)
    print("cancelling")
    task.cancel()
    print("waiting")
    await task
    print("done")
    writer.close()
    await writer.wait_closed()


asyncio.run(main("micropython.org"))