Debian Codegraph @

Lib/test/test_asyncio/test_taskgroups.py

raw
1 # Adapted with permission from the EdgeDB project;
2 # license: PSFL.
3
4 import weakref
5 import sys
6 import gc
7 import asyncio
8 import contextvars
9 import contextlib
10 from asyncio import taskgroups
11 import unittest
12 import warnings
13
14 from test.test_asyncio.utils import await_without_task
15
16 # To prevent a warning "test altered the execution environment"
17 def tearDownModule():
18 asyncio.set_event_loop_policy(None)
19
20
21 class MyExc(Exception):
22 pass
23
24
25 class MyBaseExc(BaseException):
26 pass
27
28
29 def get_error_types(eg):
30 return {type(exc) for exc in eg.exceptions}
31
32
33 def set_gc_state(enabled):
34 was_enabled = gc.isenabled()
35 if enabled:
36 gc.enable()
37 else:
38 gc.disable()
39 return was_enabled
40
41
42 @contextlib.contextmanager
43 def disable_gc():
44 was_enabled = set_gc_state(enabled=False)
45 try:
46 yield
47 finally:
48 set_gc_state(enabled=was_enabled)
49
50
51 class BaseTestTaskGroup:
52
53 async def test_taskgroup_01(self):
54
55 async def foo1():
56 await asyncio.sleep(0.1)
57 return 42
58
59 async def foo2():
60 await asyncio.sleep(0.2)
61 return 11
62
63 async with taskgroups.TaskGroup() as g:
64 t1 = g.create_task(foo1())
65 t2 = g.create_task(foo2())
66
67 self.assertEqual(t1.result(), 42)
68 self.assertEqual(t2.result(), 11)
69
70 async def test_taskgroup_02(self):
71
72 async def foo1():
73 await asyncio.sleep(0.1)
74 return 42
75
76 async def foo2():
77 await asyncio.sleep(0.2)
78 return 11
79
80 async with taskgroups.TaskGroup() as g:
81 t1 = g.create_task(foo1())
82 await asyncio.sleep(0.15)
83 t2 = g.create_task(foo2())
84
85 self.assertEqual(t1.result(), 42)
86 self.assertEqual(t2.result(), 11)
87
88 async def test_taskgroup_03(self):
89
90 async def foo1():
91 await asyncio.sleep(1)
92 return 42
93
94 async def foo2():
95 await asyncio.sleep(0.2)
96 return 11
97
98 async with taskgroups.TaskGroup() as g:
99 t1 = g.create_task(foo1())
100 await asyncio.sleep(0.15)
101 # cancel t1 explicitly, i.e. everything should continue
102 # working as expected.
103 t1.cancel()
104
105 t2 = g.create_task(foo2())
106
107 self.assertTrue(t1.cancelled())
108 self.assertEqual(t2.result(), 11)
109
110 async def test_taskgroup_04(self):
111
112 NUM = 0
113 t2_cancel = False
114 t2 = None
115
116 async def foo1():
117 await asyncio.sleep(0.1)
118 1 / 0
119
120 async def foo2():
121 nonlocal NUM, t2_cancel
122 try:
123 await asyncio.sleep(1)
124 except asyncio.CancelledError:
125 t2_cancel = True
126 raise
127 NUM += 1
128
129 async def runner():
130 nonlocal NUM, t2
131
132 async with taskgroups.TaskGroup() as g:
133 g.create_task(foo1())
134 t2 = g.create_task(foo2())
135
136 NUM += 10
137
138 with self.assertRaises(ExceptionGroup) as cm:
139 await asyncio.create_task(runner())
140
141 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
142
143 self.assertEqual(NUM, 0)
144 self.assertTrue(t2_cancel)
145 self.assertTrue(t2.cancelled())
146
147 async def test_cancel_children_on_child_error(self):
148 # When a child task raises an error, the rest of the children
149 # are cancelled and the errors are gathered into an EG.
150
151 NUM = 0
152 t2_cancel = False
153 runner_cancel = False
154
155 async def foo1():
156 await asyncio.sleep(0.1)
157 1 / 0
158
159 async def foo2():
160 nonlocal NUM, t2_cancel
161 try:
162 await asyncio.sleep(5)
163 except asyncio.CancelledError:
164 t2_cancel = True
165 raise
166 NUM += 1
167
168 async def runner():
169 nonlocal NUM, runner_cancel
170
171 async with taskgroups.TaskGroup() as g:
172 g.create_task(foo1())
173 g.create_task(foo1())
174 g.create_task(foo1())
175 g.create_task(foo2())
176 try:
177 await asyncio.sleep(10)
178 except asyncio.CancelledError:
179 runner_cancel = True
180 raise
181
182 NUM += 10
183
184 # The 3 foo1 sub tasks can be racy when the host is busy - if the
185 # cancellation happens in the middle, we'll see partial sub errors here
186 with self.assertRaises(ExceptionGroup) as cm:
187 await asyncio.create_task(runner())
188
189 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
190 self.assertEqual(NUM, 0)
191 self.assertTrue(t2_cancel)
192 self.assertTrue(runner_cancel)
193
194 async def test_cancellation(self):
195
196 NUM = 0
197
198 async def foo():
199 nonlocal NUM
200 try:
201 await asyncio.sleep(5)
202 except asyncio.CancelledError:
203 NUM += 1
204 raise
205
206 async def runner():
207 async with taskgroups.TaskGroup() as g:
208 for _ in range(5):
209 g.create_task(foo())
210
211 r = asyncio.create_task(runner())
212 await asyncio.sleep(0.1)
213
214 self.assertFalse(r.done())
215 r.cancel()
216 with self.assertRaises(asyncio.CancelledError) as cm:
217 await r
218
219 self.assertEqual(NUM, 5)
220
221 async def test_taskgroup_07(self):
222
223 NUM = 0
224
225 async def foo():
226 nonlocal NUM
227 try:
228 await asyncio.sleep(5)
229 except asyncio.CancelledError:
230 NUM += 1
231 raise
232
233 async def runner():
234 nonlocal NUM
235 async with taskgroups.TaskGroup() as g:
236 for _ in range(5):
237 g.create_task(foo())
238
239 try:
240 await asyncio.sleep(10)
241 except asyncio.CancelledError:
242 NUM += 10
243 raise
244
245 r = asyncio.create_task(runner())
246 await asyncio.sleep(0.1)
247
248 self.assertFalse(r.done())
249 r.cancel()
250 with self.assertRaises(asyncio.CancelledError):
251 await r
252
253 self.assertEqual(NUM, 15)
254
255 async def test_taskgroup_08(self):
256
257 async def foo():
258 try:
259 await asyncio.sleep(10)
260 finally:
261 1 / 0
262
263 async def runner():
264 async with taskgroups.TaskGroup() as g:
265 for _ in range(5):
266 g.create_task(foo())
267
268 await asyncio.sleep(10)
269
270 r = asyncio.create_task(runner())
271 await asyncio.sleep(0.1)
272
273 self.assertFalse(r.done())
274 r.cancel()
275 with self.assertRaises(ExceptionGroup) as cm:
276 await r
277 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
278
279 async def test_taskgroup_09(self):
280
281 t1 = t2 = None
282
283 async def foo1():
284 await asyncio.sleep(1)
285 return 42
286
287 async def foo2():
288 await asyncio.sleep(2)
289 return 11
290
291 async def runner():
292 nonlocal t1, t2
293 async with taskgroups.TaskGroup() as g:
294 t1 = g.create_task(foo1())
295 t2 = g.create_task(foo2())
296 await asyncio.sleep(0.1)
297 1 / 0
298
299 try:
300 await runner()
301 except ExceptionGroup as t:
302 self.assertEqual(get_error_types(t), {ZeroDivisionError})
303 else:
304 self.fail('ExceptionGroup was not raised')
305
306 self.assertTrue(t1.cancelled())
307 self.assertTrue(t2.cancelled())
308
309 async def test_taskgroup_10(self):
310
311 t1 = t2 = None
312
313 async def foo1():
314 await asyncio.sleep(1)
315 return 42
316
317 async def foo2():
318 await asyncio.sleep(2)
319 return 11
320
321 async def runner():
322 nonlocal t1, t2
323 async with taskgroups.TaskGroup() as g:
324 t1 = g.create_task(foo1())
325 t2 = g.create_task(foo2())
326 1 / 0
327
328 try:
329 await runner()
330 except ExceptionGroup as t:
331 self.assertEqual(get_error_types(t), {ZeroDivisionError})
332 else:
333 self.fail('ExceptionGroup was not raised')
334
335 self.assertTrue(t1.cancelled())
336 self.assertTrue(t2.cancelled())
337
338 async def test_taskgroup_11(self):
339
340 async def foo():
341 try:
342 await asyncio.sleep(10)
343 finally:
344 1 / 0
345
346 async def runner():
347 async with taskgroups.TaskGroup():
348 async with taskgroups.TaskGroup() as g2:
349 for _ in range(5):
350 g2.create_task(foo())
351
352 await asyncio.sleep(10)
353
354 r = asyncio.create_task(runner())
355 await asyncio.sleep(0.1)
356
357 self.assertFalse(r.done())
358 r.cancel()
359 with self.assertRaises(ExceptionGroup) as cm:
360 await r
361
362 self.assertEqual(get_error_types(cm.exception), {ExceptionGroup})
363 self.assertEqual(get_error_types(cm.exception.exceptions[0]), {ZeroDivisionError})
364
365 async def test_taskgroup_12(self):
366
367 async def foo():
368 try:
369 await asyncio.sleep(10)
370 finally:
371 1 / 0
372
373 async def runner():
374 async with taskgroups.TaskGroup() as g1:
375 g1.create_task(asyncio.sleep(10))
376
377 async with taskgroups.TaskGroup() as g2:
378 for _ in range(5):
379 g2.create_task(foo())
380
381 await asyncio.sleep(10)
382
383 r = asyncio.create_task(runner())
384 await asyncio.sleep(0.1)
385
386 self.assertFalse(r.done())
387 r.cancel()
388 with self.assertRaises(ExceptionGroup) as cm:
389 await r
390
391 self.assertEqual(get_error_types(cm.exception), {ExceptionGroup})
392 self.assertEqual(get_error_types(cm.exception.exceptions[0]), {ZeroDivisionError})
393
394 async def test_taskgroup_13(self):
395
396 async def crash_after(t):
397 await asyncio.sleep(t)
398 raise ValueError(t)
399
400 async def runner():
401 async with taskgroups.TaskGroup() as g1:
402 g1.create_task(crash_after(0.1))
403
404 async with taskgroups.TaskGroup() as g2:
405 g2.create_task(crash_after(10))
406
407 r = asyncio.create_task(runner())
408 with self.assertRaises(ExceptionGroup) as cm:
409 await r
410
411 self.assertEqual(get_error_types(cm.exception), {ValueError})
412
413 async def test_taskgroup_14(self):
414
415 async def crash_after(t):
416 await asyncio.sleep(t)
417 raise ValueError(t)
418
419 async def runner():
420 async with taskgroups.TaskGroup() as g1:
421 g1.create_task(crash_after(10))
422
423 async with taskgroups.TaskGroup() as g2:
424 g2.create_task(crash_after(0.1))
425
426 r = asyncio.create_task(runner())
427 with self.assertRaises(ExceptionGroup) as cm:
428 await r
429
430 self.assertEqual(get_error_types(cm.exception), {ExceptionGroup})
431 self.assertEqual(get_error_types(cm.exception.exceptions[0]), {ValueError})
432
433 async def test_taskgroup_15(self):
434
435 async def crash_soon():
436 await asyncio.sleep(0.3)
437 1 / 0
438
439 async def runner():
440 async with taskgroups.TaskGroup() as g1:
441 g1.create_task(crash_soon())
442 try:
443 await asyncio.sleep(10)
444 except asyncio.CancelledError:
445 await asyncio.sleep(0.5)
446 raise
447
448 r = asyncio.create_task(runner())
449 await asyncio.sleep(0.1)
450
451 self.assertFalse(r.done())
452 r.cancel()
453 with self.assertRaises(ExceptionGroup) as cm:
454 await r
455 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
456
457 async def test_taskgroup_16(self):
458
459 async def crash_soon():
460 await asyncio.sleep(0.3)
461 1 / 0
462
463 async def nested_runner():
464 async with taskgroups.TaskGroup() as g1:
465 g1.create_task(crash_soon())
466 try:
467 await asyncio.sleep(10)
468 except asyncio.CancelledError:
469 await asyncio.sleep(0.5)
470 raise
471
472 async def runner():
473 t = asyncio.create_task(nested_runner())
474 await t
475
476 r = asyncio.create_task(runner())
477 await asyncio.sleep(0.1)
478
479 self.assertFalse(r.done())
480 r.cancel()
481 with self.assertRaises(ExceptionGroup) as cm:
482 await r
483 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
484
485 async def test_taskgroup_17(self):
486 NUM = 0
487
488 async def runner():
489 nonlocal NUM
490 async with taskgroups.TaskGroup():
491 try:
492 await asyncio.sleep(10)
493 except asyncio.CancelledError:
494 NUM += 10
495 raise
496
497 r = asyncio.create_task(runner())
498 await asyncio.sleep(0.1)
499
500 self.assertFalse(r.done())
501 r.cancel()
502 with self.assertRaises(asyncio.CancelledError):
503 await r
504
505 self.assertEqual(NUM, 10)
506
507 async def test_taskgroup_18(self):
508 NUM = 0
509
510 async def runner():
511 nonlocal NUM
512 async with taskgroups.TaskGroup():
513 try:
514 await asyncio.sleep(10)
515 except asyncio.CancelledError:
516 NUM += 10
517 # This isn't a good idea, but we have to support
518 # this weird case.
519 raise MyExc
520
521 r = asyncio.create_task(runner())
522 await asyncio.sleep(0.1)
523
524 self.assertFalse(r.done())
525 r.cancel()
526
527 try:
528 await r
529 except ExceptionGroup as t:
530 self.assertEqual(get_error_types(t),{MyExc})
531 else:
532 self.fail('ExceptionGroup was not raised')
533
534 self.assertEqual(NUM, 10)
535
536 async def test_taskgroup_19(self):
537 async def crash_soon():
538 await asyncio.sleep(0.1)
539 1 / 0
540
541 async def nested():
542 try:
543 await asyncio.sleep(10)
544 finally:
545 raise MyExc
546
547 async def runner():
548 async with taskgroups.TaskGroup() as g:
549 g.create_task(crash_soon())
550 await nested()
551
552 r = asyncio.create_task(runner())
553 try:
554 await r
555 except ExceptionGroup as t:
556 self.assertEqual(get_error_types(t), {MyExc, ZeroDivisionError})
557 else:
558 self.fail('TasgGroupError was not raised')
559
560 async def test_taskgroup_20(self):
561 async def crash_soon():
562 await asyncio.sleep(0.1)
563 1 / 0
564
565 async def nested():
566 try:
567 await asyncio.sleep(10)
568 finally:
569 raise KeyboardInterrupt
570
571 async def runner():
572 async with taskgroups.TaskGroup() as g:
573 g.create_task(crash_soon())
574 await nested()
575
576 with self.assertRaises(KeyboardInterrupt):
577 await runner()
578
579 async def test_taskgroup_20a(self):
580 async def crash_soon():
581 await asyncio.sleep(0.1)
582 1 / 0
583
584 async def nested():
585 try:
586 await asyncio.sleep(10)
587 finally:
588 raise MyBaseExc
589
590 async def runner():
591 async with taskgroups.TaskGroup() as g:
592 g.create_task(crash_soon())
593 await nested()
594
595 with self.assertRaises(BaseExceptionGroup) as cm:
596 await runner()
597
598 self.assertEqual(
599 get_error_types(cm.exception), {MyBaseExc, ZeroDivisionError}
600 )
601
602 async def _test_taskgroup_21(self):
603 # This test doesn't work as asyncio, currently, doesn't
604 # correctly propagate KeyboardInterrupt (or SystemExit) --
605 # those cause the event loop itself to crash.
606 # (Compare to the previous (passing) test -- that one raises
607 # a plain exception but raises KeyboardInterrupt in nested();
608 # this test does it the other way around.)
609
610 async def crash_soon():
611 await asyncio.sleep(0.1)
612 raise KeyboardInterrupt
613
614 async def nested():
615 try:
616 await asyncio.sleep(10)
617 finally:
618 raise TypeError
619
620 async def runner():
621 async with taskgroups.TaskGroup() as g:
622 g.create_task(crash_soon())
623 await nested()
624
625 with self.assertRaises(KeyboardInterrupt):
626 await runner()
627
628 async def test_taskgroup_21a(self):
629
630 async def crash_soon():
631 await asyncio.sleep(0.1)
632 raise MyBaseExc
633
634 async def nested():
635 try:
636 await asyncio.sleep(10)
637 finally:
638 raise TypeError
639
640 async def runner():
641 async with taskgroups.TaskGroup() as g:
642 g.create_task(crash_soon())
643 await nested()
644
645 with self.assertRaises(BaseExceptionGroup) as cm:
646 await runner()
647
648 self.assertEqual(get_error_types(cm.exception), {MyBaseExc, TypeError})
649
650 async def test_taskgroup_22(self):
651
652 async def foo1():
653 await asyncio.sleep(1)
654 return 42
655
656 async def foo2():
657 await asyncio.sleep(2)
658 return 11
659
660 async def runner():
661 async with taskgroups.TaskGroup() as g:
662 g.create_task(foo1())
663 g.create_task(foo2())
664
665 r = asyncio.create_task(runner())
666 await asyncio.sleep(0.05)
667 r.cancel()
668
669 with self.assertRaises(asyncio.CancelledError):
670 await r
671
672 async def test_taskgroup_23(self):
673
674 async def do_job(delay):
675 await asyncio.sleep(delay)
676
677 async with taskgroups.TaskGroup() as g:
678 for count in range(10):
679 await asyncio.sleep(0.1)
680 g.create_task(do_job(0.3))
681 if count == 5:
682 self.assertLess(len(g._tasks), 5)
683 await asyncio.sleep(1.35)
684 self.assertEqual(len(g._tasks), 0)
685
686 async def test_taskgroup_24(self):
687
688 async def root(g):
689 await asyncio.sleep(0.1)
690 g.create_task(coro1(0.1))
691 g.create_task(coro1(0.2))
692
693 async def coro1(delay):
694 await asyncio.sleep(delay)
695
696 async def runner():
697 async with taskgroups.TaskGroup() as g:
698 g.create_task(root(g))
699
700 await runner()
701
702 async def test_taskgroup_25(self):
703 nhydras = 0
704
705 async def hydra(g):
706 nonlocal nhydras
707 nhydras += 1
708 await asyncio.sleep(0.01)
709 g.create_task(hydra(g))
710 g.create_task(hydra(g))
711
712 async def hercules():
713 while nhydras < 10:
714 await asyncio.sleep(0.015)
715 1 / 0
716
717 async def runner():
718 async with taskgroups.TaskGroup() as g:
719 g.create_task(hydra(g))
720 g.create_task(hercules())
721
722 with self.assertRaises(ExceptionGroup) as cm:
723 await runner()
724
725 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
726 self.assertGreaterEqual(nhydras, 10)
727
728 async def test_taskgroup_task_name(self):
729 async def coro():
730 await asyncio.sleep(0)
731 async with taskgroups.TaskGroup() as g:
732 t = g.create_task(coro(), name="yolo")
733 self.assertEqual(t.get_name(), "yolo")
734
735 async def test_taskgroup_task_context(self):
736 cvar = contextvars.ContextVar('cvar')
737
738 async def coro(val):
739 await asyncio.sleep(0)
740 cvar.set(val)
741
742 async with taskgroups.TaskGroup() as g:
743 ctx = contextvars.copy_context()
744 self.assertIsNone(ctx.get(cvar))
745 t1 = g.create_task(coro(1), context=ctx)
746 await t1
747 self.assertEqual(1, ctx.get(cvar))
748 t2 = g.create_task(coro(2), context=ctx)
749 await t2
750 self.assertEqual(2, ctx.get(cvar))
751
752 async def test_taskgroup_no_create_task_after_failure(self):
753 async def coro1():
754 await asyncio.sleep(0.001)
755 1 / 0
756 async def coro2(g):
757 try:
758 await asyncio.sleep(1)
759 except asyncio.CancelledError:
760 with self.assertRaises(RuntimeError):
761 g.create_task(coro1())
762
763 with self.assertRaises(ExceptionGroup) as cm:
764 async with taskgroups.TaskGroup() as g:
765 g.create_task(coro1())
766 g.create_task(coro2(g))
767
768 self.assertEqual(get_error_types(cm.exception), {ZeroDivisionError})
769
770 async def test_taskgroup_context_manager_exit_raises(self):
771 # See https://github.com/python/cpython/issues/95289
772 class CustomException(Exception):
773 pass
774
775 async def raise_exc():
776 raise CustomException
777
778 @contextlib.asynccontextmanager
779 async def database():
780 try:
781 yield
782 finally:
783 raise CustomException
784
785 async def main():
786 task = asyncio.current_task()
787 try:
788 async with taskgroups.TaskGroup() as tg:
789 async with database():
790 tg.create_task(raise_exc())
791 await asyncio.sleep(1)
792 except* CustomException as err:
793 self.assertEqual(task.cancelling(), 0)
794 self.assertEqual(len(err.exceptions), 2)
795
796 else:
797 self.fail('CustomException not raised')
798
799 await asyncio.create_task(main())
800
801 async def test_taskgroup_already_entered(self):
802 tg = taskgroups.TaskGroup()
803 async with tg:
804 with self.assertRaisesRegex(RuntimeError, "has already been entered"):
805 async with tg:
806 pass
807
808 async def test_taskgroup_double_enter(self):
809 tg = taskgroups.TaskGroup()
810 async with tg:
811 pass
812 with self.assertRaisesRegex(RuntimeError, "has already been entered"):
813 async with tg:
814 pass
815
816 async def test_taskgroup_finished(self):
817 async def create_task_after_tg_finish():
818 tg = taskgroups.TaskGroup()
819 async with tg:
820 pass
821 coro = asyncio.sleep(0)
822 with self.assertRaisesRegex(RuntimeError, "is finished"):
823 tg.create_task(coro)
824
825 # Make sure the coroutine was closed when submitted to the inactive tg
826 # (if not closed, a RuntimeWarning should have been raised)
827 with warnings.catch_warnings(record=True) as w:
828 await create_task_after_tg_finish()
829 self.assertEqual(len(w), 0)
830
831 async def test_taskgroup_not_entered(self):
832 tg = taskgroups.TaskGroup()
833 coro = asyncio.sleep(0)
834 with self.assertRaisesRegex(RuntimeError, "has not been entered"):
835 tg.create_task(coro)
836
837 async def test_taskgroup_without_parent_task(self):
838 tg = taskgroups.TaskGroup()
839 with self.assertRaisesRegex(RuntimeError, "parent task"):
840 await await_without_task(tg.__aenter__())
841 coro = asyncio.sleep(0)
842 with self.assertRaisesRegex(RuntimeError, "has not been entered"):
843 tg.create_task(coro)
844
845 async def test_coro_closed_when_tg_closed(self):
846 async def run_coro_after_tg_closes():
847 async with taskgroups.TaskGroup() as tg:
848 pass
849 coro = asyncio.sleep(0)
850 with self.assertRaisesRegex(RuntimeError, "is finished"):
851 tg.create_task(coro)
852
853 await run_coro_after_tg_closes()
854
855 async def test_cancelling_level_preserved(self):
856 async def raise_after(t, e):
857 await asyncio.sleep(t)
858 raise e()
859
860 try:
861 async with asyncio.TaskGroup() as tg:
862 tg.create_task(raise_after(0.0, RuntimeError))
863 except* RuntimeError:
864 pass
865 self.assertEqual(asyncio.current_task().cancelling(), 0)
866
867 async def test_nested_groups_both_cancelled(self):
868 async def raise_after(t, e):
869 await asyncio.sleep(t)
870 raise e()
871
872 try:
873 async with asyncio.TaskGroup() as outer_tg:
874 try:
875 async with asyncio.TaskGroup() as inner_tg:
876 inner_tg.create_task(raise_after(0, RuntimeError))
877 outer_tg.create_task(raise_after(0, ValueError))
878 except* RuntimeError:
879 pass
880 else:
881 self.fail("RuntimeError not raised")
882 self.assertEqual(asyncio.current_task().cancelling(), 1)
883 except* ValueError:
884 pass
885 else:
886 self.fail("ValueError not raised")
887 self.assertEqual(asyncio.current_task().cancelling(), 0)
888
889 async def test_error_and_cancel(self):
890 event = asyncio.Event()
891
892 async def raise_error():
893 event.set()
894 await asyncio.sleep(0)
895 raise RuntimeError()
896
897 async def inner():
898 try:
899 async with taskgroups.TaskGroup() as tg:
900 tg.create_task(raise_error())
901 await asyncio.sleep(1)
902 self.fail("Sleep in group should have been cancelled")
903 except* RuntimeError:
904 self.assertEqual(asyncio.current_task().cancelling(), 1)
905 self.assertEqual(asyncio.current_task().cancelling(), 1)
906 await asyncio.sleep(1)
907 self.fail("Sleep after group should have been cancelled")
908
909 async def outer():
910 t = asyncio.create_task(inner())
911 await event.wait()
912 self.assertEqual(t.cancelling(), 0)
913 t.cancel()
914 self.assertEqual(t.cancelling(), 1)
915 with self.assertRaises(asyncio.CancelledError):
916 await t
917 self.assertTrue(t.cancelled())
918
919 await outer()
920
921 async def test_exception_refcycles_direct(self):
922 """Test that TaskGroup doesn't keep a reference to the raised ExceptionGroup"""
923 tg = asyncio.TaskGroup()
924 exc = None
925
926 class _Done(Exception):
927 pass
928
929 try:
930 async with tg:
931 raise _Done
932 except ExceptionGroup as e:
933 exc = e
934
935 self.assertIsNotNone(exc)
936 self.assertListEqual(gc.get_referrers(exc), [])
937
938
939 async def test_exception_refcycles_errors(self):
940 """Test that TaskGroup deletes self._errors, and __aexit__ args"""
941 tg = asyncio.TaskGroup()
942 exc = None
943
944 class _Done(Exception):
945 pass
946
947 try:
948 async with tg:
949 raise _Done
950 except* _Done as excs:
951 exc = excs.exceptions[0]
952
953 self.assertIsInstance(exc, _Done)
954 self.assertListEqual(gc.get_referrers(exc), [])
955
956
957 async def test_exception_refcycles_parent_task(self):
958 """Test that TaskGroup deletes self._parent_task"""
959 tg = asyncio.TaskGroup()
960 exc = None
961
962 class _Done(Exception):
963 pass
964
965 async def coro_fn():
966 async with tg:
967 raise _Done
968
969 try:
970 async with asyncio.TaskGroup() as tg2:
971 tg2.create_task(coro_fn())
972 except* _Done as excs:
973 exc = excs.exceptions[0].exceptions[0]
974
975 self.assertIsInstance(exc, _Done)
976 self.assertListEqual(gc.get_referrers(exc), [])
977
978
979 async def test_exception_refcycles_parent_task_wr(self):
980 """Test that TaskGroup deletes self._parent_task and create_task() deletes task"""
981 tg = asyncio.TaskGroup()
982 exc = None
983
984 class _Done(Exception):
985 pass
986
987 async def coro_fn():
988 async with tg:
989 raise _Done
990
991 with disable_gc():
992 try:
993 async with asyncio.TaskGroup() as tg2:
994 task_wr = weakref.ref(tg2.create_task(coro_fn()))
995 except* _Done as excs:
996 exc = excs.exceptions[0].exceptions[0]
997
998 self.assertIsNone(task_wr())
999 self.assertIsInstance(exc, _Done)
1000 self.assertListEqual(gc.get_referrers(exc), [])
1001
1002 async def test_exception_refcycles_propagate_cancellation_error(self):
1003 """Test that TaskGroup deletes propagate_cancellation_error"""
1004 tg = asyncio.TaskGroup()
1005 exc = None
1006
1007 try:
1008 async with asyncio.timeout(-1):
1009 async with tg:
1010 await asyncio.sleep(0)
1011 except TimeoutError as e:
1012 exc = e.__cause__
1013
1014 self.assertIsInstance(exc, asyncio.CancelledError)
1015 self.assertListEqual(gc.get_referrers(exc), [])
1016
1017 async def test_exception_refcycles_base_error(self):
1018 """Test that TaskGroup deletes self._base_error"""
1019 class MyKeyboardInterrupt(KeyboardInterrupt):
1020 pass
1021
1022 tg = asyncio.TaskGroup()
1023 exc = None
1024
1025 try:
1026 async with tg:
1027 raise MyKeyboardInterrupt
1028 except MyKeyboardInterrupt as e:
1029 exc = e
1030
1031 self.assertIsNotNone(exc)
1032 self.assertListEqual(gc.get_referrers(exc), [])
1033
1034
1035 async def test_cancels_task_if_created_during_creation(self):
1036 # regression test for gh-128550
1037 ran = False
1038 class MyError(Exception):
1039 pass
1040
1041 exc = None
1042 try:
1043 async with asyncio.TaskGroup() as tg:
1044 async def third_task():
1045 raise MyError("third task failed")
1046
1047 async def second_task():
1048 nonlocal ran
1049 tg.create_task(third_task())
1050 with self.assertRaises(asyncio.CancelledError):
1051 await asyncio.sleep(0) # eager tasks cancel here
1052 await asyncio.sleep(0) # lazy tasks cancel here
1053 ran = True
1054
1055 tg.create_task(second_task())
1056 except* MyError as excs:
1057 exc = excs.exceptions[0]
1058
1059 self.assertTrue(ran)
1060 self.assertIsInstance(exc, MyError)
1061
1062
1063 async def test_cancellation_does_not_leak_out_of_tg(self):
1064 class MyError(Exception):
1065 pass
1066
1067 async def throw_error():
1068 raise MyError
1069
1070 try:
1071 async with asyncio.TaskGroup() as tg:
1072 tg.create_task(throw_error())
1073 except* MyError:
1074 pass
1075 else:
1076 self.fail("should have raised one MyError in group")
1077
1078 # if this test fails this current task will be cancelled
1079 # outside the task group and inside unittest internals
1080 # we yield to the event loop with sleep(0) so that
1081 # cancellation happens here and error is more understandable
1082 await asyncio.sleep(0)
1083
1084
1085 class TestTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase):
1086 loop_factory = asyncio.EventLoop
1087
1088 class TestEagerTaskTaskGroup(BaseTestTaskGroup, unittest.IsolatedAsyncioTestCase):
1089 @staticmethod
1090 def loop_factory():
1091 loop = asyncio.EventLoop()
1092 loop.set_task_factory(asyncio.eager_task_factory)
1093 return loop
1094
1095
1096 if __name__ == "__main__":
1097 unittest.main()