Skip to content

Commit b1a8138

Browse files
committed
Enhance cancel test
Now verifies that coroutines can catch CancelledError and return a value.
1 parent 62ef0b5 commit b1a8138

File tree

1 file changed

+21
-11
lines changed

1 file changed

+21
-11
lines changed

tests/test_base.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -86,18 +86,27 @@ async def wrk(*arg, **kw):
8686
await aio.sleep(0.5)
8787
return 1
8888

89-
pool = AioPool(size=2)
89+
async def wrk_safe(*arg, **kw):
90+
try:
91+
await aio.sleep(0.5)
92+
except aio.CancelledError:
93+
await aio.sleep(0.1) # simulate cleanup
94+
pass
95+
return 1
96+
97+
pool = AioPool(size=5)
9098

9199
f_quick = pool.spawn_n(aio.sleep(0.15))
92-
f12 = await pool.spawn(wrk()), pool.spawn_n(wrk())
93-
f35 = pool.map_n(wrk, range(3))
100+
f_safe = await pool.spawn(wrk_safe())
101+
f3 = await pool.spawn(wrk())
102+
pool.spawn_n(wrk())
103+
f567 = pool.map_n(wrk, range(3))
94104

95105
# cancel some
96106
await aio.sleep(0.1)
97-
cancelled, results = await pool.cancel(f12[0], f35[2]) # running and waiting
98-
assert 2 == cancelled # none of them had time to finish
99-
assert 2 == len(results) and \
100-
all(isinstance(res, aio.CancelledError) for res in results)
107+
cancelled, results = await pool.cancel(f3, f567[2]) # running and waiting
108+
assert cancelled == len(results) == 2 # none of them had time to finish
109+
assert all(isinstance(res, aio.CancelledError) for res in results)
101110

102111
# cancel all others
103112
await aio.sleep(0.1)
@@ -106,11 +115,12 @@ async def wrk(*arg, **kw):
106115
assert f_quick.done() and f_quick.result() is None
107116

108117
cancelled, results = await pool.cancel() # all
109-
assert 3 == cancelled
110-
assert len(results) == 3 and \
111-
all(isinstance(res, aio.CancelledError) for res in results)
118+
assert cancelled == len(results) == 4
119+
assert f_safe.done() and f_safe.result() == 1 # could recover
120+
# the others could not
121+
assert sum(isinstance(res, aio.CancelledError) for res in results) == 3
112122

113-
assert await pool.join() # joins successfully
123+
assert await pool.join() # joins successfully (basically no-op)
114124

115125

116126
@pytest.mark.asyncio

0 commit comments

Comments
 (0)