Skip to content

Commit 8710b95

Browse files
committed
add race test
1 parent e8617b4 commit 8710b95

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

Lib/test/test_asyncio/test_taskgroups.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1190,6 +1190,43 @@ async def test_taskgroup_body_cancel_after_exception(self):
11901190
finally:
11911191
tg.cancel()
11921192

1193+
async def test_taskgroup_cancel_one_winner(self):
1194+
async def race(*fns):
1195+
outcome = None
1196+
async def run(fn):
1197+
nonlocal outcome
1198+
outcome = await fn()
1199+
tg.cancel()
1200+
1201+
async with asyncio.TaskGroup() as tg:
1202+
for fn in fns:
1203+
tg.create_task(run(fn))
1204+
return outcome
1205+
1206+
event = asyncio.Event()
1207+
record = []
1208+
async def fn_1():
1209+
record.append("1 started")
1210+
await event.wait()
1211+
record.append("1 finished")
1212+
return 1
1213+
1214+
async def fn_2():
1215+
record.append("2 started")
1216+
await event.wait()
1217+
record.append("2 finished")
1218+
return 2
1219+
1220+
async def fn_3():
1221+
record.append("3 started")
1222+
event.set()
1223+
await asyncio.sleep(10)
1224+
record.append("3 finished")
1225+
return 3
1226+
1227+
self.assertEqual(await race(fn_1, fn_2, fn_3), 1)
1228+
self.assertListEqual(record, ["1 started", "2 started", "3 started", "1 finished"])
1229+
11931230

11941231
class TestTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase):
11951232
loop_factory = asyncio.EventLoop

0 commit comments

Comments
 (0)