Skip to content

Commit 06a2aba

Browse files
committed
uasyncio.core: Add test for cancel(coro) function.
1 parent 17a432c commit 06a2aba

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

uasyncio.core/test_cancel.py

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import time
2+
try:
3+
import uasyncio.core as asyncio
4+
is_uasyncio = True
5+
except ImportError:
6+
import asyncio
7+
is_uasyncio = False
8+
import logging
9+
#logging.basicConfig(level=logging.DEBUG)
10+
#asyncio.set_debug(True)
11+
12+
13+
output = []
14+
cancelled = False
15+
16+
def print1(msg):
17+
print(msg)
18+
output.append(msg)
19+
20+
def looper1(iters):
21+
global cancelled
22+
try:
23+
for i in range(iters):
24+
print1("ping1")
25+
# sleep() isn't properly cancellable
26+
#yield from asyncio.sleep(1.0)
27+
t = time.time()
28+
while time.time() - t < 1:
29+
yield from asyncio.sleep(0)
30+
return 10
31+
except asyncio.CancelledError:
32+
print1("cancelled")
33+
cancelled = True
34+
35+
def looper2(iters):
36+
for i in range(iters):
37+
print1("ping2")
38+
# sleep() isn't properly cancellable
39+
#yield from asyncio.sleep(1.0)
40+
t = time.time()
41+
while time.time() - t < 1:
42+
yield from asyncio.sleep(0)
43+
return 10
44+
45+
46+
def run_to():
47+
coro = looper1(10)
48+
task = loop.create_task(coro)
49+
yield from asyncio.sleep(3)
50+
if is_uasyncio:
51+
asyncio.cancel(coro)
52+
else:
53+
task.cancel()
54+
# Need another eventloop iteration for cancellation to be actually
55+
# processed and to see side effects of the cancellation.
56+
yield from asyncio.sleep(0)
57+
assert cancelled
58+
59+
coro = looper2(10)
60+
task = loop.create_task(coro)
61+
yield from asyncio.sleep(2)
62+
if is_uasyncio:
63+
asyncio.cancel(coro)
64+
else:
65+
task.cancel()
66+
yield from asyncio.sleep(0)
67+
68+
# Once saw 3 ping3's output on CPython 3.5.2
69+
assert output == ['ping1', 'ping1', 'ping1', 'cancelled', 'ping2', 'ping2']
70+
71+
72+
loop = asyncio.get_event_loop()
73+
loop.run_until_complete(run_to())

0 commit comments

Comments
 (0)