Debian Codegraph @

src/trio/_core/_tests/test_run.py

raw
1 from __future__ import annotations
2
3 import contextvars
4 import functools
5 import gc
6 import sys
7 import threading
8 import time
9 import types
10 import weakref
11 from contextlib import (
12 AsyncExitStack,
13 ExitStack,
14 asynccontextmanager,
15 contextmanager,
16 suppress,
17 )
18 from math import inf, nan
19 from typing import TYPE_CHECKING, NoReturn, TypeVar
20 from unittest import mock
21
22 import outcome
23 import pytest
24 import sniffio
25
26 from ... import _core
27 from ..._threads import to_thread_run_sync
28 from ..._timeouts import fail_after, sleep
29 from ...testing import (
30 Sequencer,
31 assert_checkpoints,
32 wait_all_tasks_blocked,
33 )
34 from .._run import DEADLINE_HEAP_MIN_PRUNE_THRESHOLD, _count_context_run_tb_frames
35 from .tutil import (
36 check_sequence_matches,
37 create_asyncio_future_in_new_loop,
38 gc_collect_harder,
39 ignore_coroutine_never_awaited_warnings,
40 restore_unraisablehook,
41 slow,
42 )
43
44 if TYPE_CHECKING:
45 from collections.abc import (
46 AsyncGenerator,
47 AsyncIterator,
48 Awaitable,
49 Callable,
50 Generator,
51 )
52
53 if sys.version_info < (3, 11):
54 from exceptiongroup import BaseExceptionGroup, ExceptionGroup
55
56
57 T = TypeVar("T")
58
59
60 # slightly different from _timeouts.sleep_forever because it returns the value
61 # its rescheduled with, which is really only useful for tests of
62 # rescheduling...
63 async def sleep_forever() -> object:
64 return await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED)
65
66
67 def not_none(x: T | None) -> T:
68 """Assert that this object is not None.
69
70 This is just to satisfy type checkers, if this ever fails the test is broken.
71 """
72 assert x is not None
73 return x
74
75
76 def test_basic() -> None:
77 async def trivial(x: T) -> T:
78 return x
79
80 assert _core.run(trivial, 8) == 8
81
82 with pytest.raises(TypeError):
83 # Missing an argument
84 _core.run(trivial) # type: ignore[arg-type]
85
86 with pytest.raises(TypeError):
87 # Not an async function
88 _core.run(lambda: None) # type: ignore
89
90 async def trivial2(x: T) -> T:
91 await _core.checkpoint()
92 return x
93
94 assert _core.run(trivial2, 1) == 1
95
96
97 def test_initial_task_error() -> None:
98 async def main(x: object) -> NoReturn:
99 raise ValueError(x)
100
101 with pytest.raises(ValueError, match=r"^17$") as excinfo:
102 _core.run(main, 17)
103 assert excinfo.value.args == (17,)
104
105
106 def test_run_nesting() -> None:
107 async def inception() -> None:
108 async def main() -> None: # pragma: no cover
109 pass
110
111 return _core.run(main)
112
113 with pytest.raises(RuntimeError) as excinfo:
114 _core.run(inception)
115 assert "from inside" in str(excinfo.value)
116
117
118 async def test_nursery_warn_use_async_with() -> None:
119 on = _core.open_nursery()
120 with pytest.raises(RuntimeError) as excinfo:
121 with on: # type: ignore
122 pass # pragma: no cover
123 excinfo.match(
124 r"use 'async with open_nursery\(...\)', not 'with open_nursery\(...\)'",
125 )
126
127 # avoid unawaited coro.
128 async with on:
129 pass
130
131
132 async def test_nursery_main_block_error_basic() -> None:
133 exc = ValueError("whoops")
134
135 with pytest.RaisesGroup(pytest.RaisesExc(check=lambda e: e is exc)):
136 async with _core.open_nursery():
137 raise exc
138
139
140 async def test_child_crash_basic() -> None:
141 my_exc = ValueError("uh oh")
142
143 async def erroring() -> NoReturn:
144 raise my_exc
145
146 with pytest.RaisesGroup(pytest.RaisesExc(check=lambda e: e is my_exc)):
147 # nursery.__aexit__ propagates exception from child back to parent
148 async with _core.open_nursery() as nursery:
149 nursery.start_soon(erroring)
150
151
152 async def test_basic_interleave() -> None:
153 async def looper(whoami: str, record: list[tuple[str, int]]) -> None:
154 for i in range(3):
155 record.append((whoami, i))
156 await _core.checkpoint()
157
158 record: list[tuple[str, int]] = []
159 async with _core.open_nursery() as nursery:
160 nursery.start_soon(looper, "a", record)
161 nursery.start_soon(looper, "b", record)
162
163 check_sequence_matches(
164 record,
165 [{("a", 0), ("b", 0)}, {("a", 1), ("b", 1)}, {("a", 2), ("b", 2)}],
166 )
167
168
169 def test_task_crash_propagation() -> None:
170 looper_record: list[str] = []
171
172 async def looper() -> None:
173 try:
174 while True:
175 await _core.checkpoint()
176 except _core.Cancelled:
177 print("looper cancelled")
178 looper_record.append("cancelled")
179
180 async def crasher() -> NoReturn:
181 raise ValueError("argh")
182
183 async def main() -> None:
184 async with _core.open_nursery() as nursery:
185 nursery.start_soon(looper)
186 nursery.start_soon(crasher)
187
188 with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="^argh$")):
189 _core.run(main)
190
191 assert looper_record == ["cancelled"]
192
193
194 def test_main_and_task_both_crash() -> None:
195 # If main crashes and there's also a task crash, then we get both in an
196 # ExceptionGroup
197 async def crasher() -> NoReturn:
198 raise ValueError
199
200 async def main() -> NoReturn:
201 async with _core.open_nursery() as nursery:
202 nursery.start_soon(crasher)
203 raise KeyError
204
205 with pytest.RaisesGroup(ValueError, KeyError):
206 _core.run(main)
207
208
209 def test_two_child_crashes() -> None:
210 async def crasher(etype: type[Exception]) -> NoReturn:
211 raise etype
212
213 async def main() -> None:
214 async with _core.open_nursery() as nursery:
215 nursery.start_soon(crasher, KeyError)
216 nursery.start_soon(crasher, ValueError)
217
218 with pytest.RaisesGroup(ValueError, KeyError):
219 _core.run(main)
220
221
222 async def test_child_crash_wakes_parent() -> None:
223 async def crasher() -> NoReturn:
224 raise ValueError("this is a crash")
225
226 with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="^this is a crash$")):
227 async with _core.open_nursery() as nursery:
228 nursery.start_soon(crasher)
229 await sleep_forever()
230
231
232 async def test_reschedule() -> None:
233 t1: _core.Task | None = None
234 t2: _core.Task | None = None
235
236 async def child1() -> None:
237 nonlocal t1, t2
238 t1 = _core.current_task()
239 print("child1 start")
240 x = await sleep_forever()
241 print("child1 woke")
242 assert x == 0
243 print("child1 rescheduling t2")
244 _core.reschedule(not_none(t2), outcome.Error(ValueError("error message")))
245 print("child1 exit")
246
247 async def child2() -> None:
248 nonlocal t1, t2
249 print("child2 start")
250 t2 = _core.current_task()
251 _core.reschedule(not_none(t1), outcome.Value(0))
252 print("child2 sleep")
253 with pytest.raises(ValueError, match=r"^error message$"):
254 await sleep_forever()
255 print("child2 successful exit")
256
257 async with _core.open_nursery() as nursery:
258 nursery.start_soon(child1)
259 # let t1 run and fall asleep
260 await _core.checkpoint()
261 nursery.start_soon(child2)
262
263
264 async def test_current_time() -> None:
265 t1 = _core.current_time()
266 # Windows clock is pretty low-resolution -- appveyor tests fail unless we
267 # sleep for a bit here.
268 time.sleep(time.get_clock_info("perf_counter").resolution) # noqa: ASYNC251
269 t2 = _core.current_time()
270 assert t1 < t2
271
272
273 async def test_current_time_with_mock_clock(mock_clock: _core.MockClock) -> None:
274 start = mock_clock.current_time()
275 assert mock_clock.current_time() == _core.current_time()
276 assert mock_clock.current_time() == _core.current_time()
277 mock_clock.jump(3.15)
278 assert start + 3.15 == mock_clock.current_time() == _core.current_time()
279
280
281 async def test_current_clock(mock_clock: _core.MockClock) -> None:
282 assert mock_clock is _core.current_clock()
283
284
285 async def test_current_task() -> None:
286 parent_task = _core.current_task()
287
288 async def child() -> None:
289 assert not_none(_core.current_task().parent_nursery).parent_task is parent_task
290
291 async with _core.open_nursery() as nursery:
292 nursery.start_soon(child)
293
294
295 async def test_root_task() -> None:
296 root = not_none(_core.current_root_task())
297 assert root.parent_nursery is root.eventual_parent_nursery is None
298
299
300 def test_out_of_context() -> None:
301 with pytest.raises(RuntimeError):
302 _core.current_task()
303 with pytest.raises(RuntimeError):
304 _core.current_time()
305
306
307 async def test_current_statistics(mock_clock: _core.MockClock) -> None:
308 # Make sure all the early startup stuff has settled down
309 await wait_all_tasks_blocked()
310
311 # A child that sticks around to make some interesting stats:
312 async def child() -> None:
313 with suppress(_core.Cancelled):
314 await sleep_forever()
315
316 stats = _core.current_statistics()
317 print(stats)
318 # 2 system tasks + us
319 assert stats.tasks_living == 3
320 assert stats.run_sync_soon_queue_size == 0
321
322 async with _core.open_nursery() as nursery:
323 nursery.start_soon(child)
324 await wait_all_tasks_blocked()
325 token = _core.current_trio_token()
326 token.run_sync_soon(lambda: None)
327 token.run_sync_soon(lambda: None, idempotent=True)
328 stats = _core.current_statistics()
329 print(stats)
330 # 2 system tasks + us + child
331 assert stats.tasks_living == 4
332 # the exact value here might shift if we change how we do accounting
333 # (currently it only counts tasks that we already know will be
334 # runnable on the next pass), but still useful to at least test the
335 # difference between now and after we wake up the child:
336 assert stats.tasks_runnable == 0
337 assert stats.run_sync_soon_queue_size == 2
338
339 nursery.cancel_scope.cancel()
340 stats = _core.current_statistics()
341 print(stats)
342 assert stats.tasks_runnable == 1
343
344 # Give the child a chance to die and the run_sync_soon a chance to clear
345 await _core.checkpoint()
346 await _core.checkpoint()
347
348 with _core.CancelScope(deadline=_core.current_time() + 5):
349 stats = _core.current_statistics()
350 print(stats)
351 assert stats.seconds_to_next_deadline == 5
352 stats = _core.current_statistics()
353 print(stats)
354 assert stats.seconds_to_next_deadline == inf
355
356
357 async def test_cancel_scope_repr(mock_clock: _core.MockClock) -> None:
358 scope = _core.CancelScope()
359 assert "unbound" in repr(scope)
360 with scope:
361 assert "active" in repr(scope)
362 scope.deadline = _core.current_time() - 1
363 assert "deadline is 1.00 seconds ago" in repr(scope)
364 scope.deadline = _core.current_time() + 10
365 assert "deadline is 10.00 seconds from now" in repr(scope)
366 # when not in async context, can't get the current time
367 assert "deadline" not in await to_thread_run_sync(repr, scope)
368 scope.cancel()
369 assert "cancelled" in repr(scope)
370 assert "exited" in repr(scope)
371
372
373 async def test_cancel_scope_validation() -> None:
374 with pytest.raises(
375 ValueError,
376 match=r"^Cannot specify both a deadline and a relative deadline$",
377 ):
378 _core.CancelScope(deadline=7, relative_deadline=3)
379
380 with pytest.raises(ValueError, match=r"^deadline must not be NaN$"):
381 _core.CancelScope(deadline=nan)
382 with pytest.raises(ValueError, match=r"^relative deadline must not be NaN$"):
383 _core.CancelScope(relative_deadline=nan)
384
385 with pytest.raises(ValueError, match=r"^timeout must be non-negative$"):
386 _core.CancelScope(relative_deadline=-3)
387
388 scope = _core.CancelScope()
389
390 with pytest.raises(ValueError, match=r"^deadline must not be NaN$"):
391 scope.deadline = nan
392 with pytest.raises(ValueError, match=r"^relative deadline must not be NaN$"):
393 scope.relative_deadline = nan
394
395 with pytest.raises(ValueError, match=r"^relative deadline must be non-negative$"):
396 scope.relative_deadline = -3
397 scope.relative_deadline = 5
398 assert scope.relative_deadline == 5
399
400 # several related tests of CancelScope are implicitly handled by test_timeouts.py
401
402
403 def test_cancel_points() -> None:
404 async def main1() -> None:
405 with _core.CancelScope() as scope:
406 await _core.checkpoint_if_cancelled()
407 scope.cancel()
408 with pytest.raises(_core.Cancelled):
409 await _core.checkpoint_if_cancelled()
410
411 _core.run(main1)
412
413 async def main2() -> None:
414 with _core.CancelScope() as scope:
415 await _core.checkpoint()
416 scope.cancel()
417 with pytest.raises(_core.Cancelled):
418 await _core.checkpoint()
419
420 _core.run(main2)
421
422 async def main3() -> None:
423 with _core.CancelScope() as scope:
424 scope.cancel()
425 with pytest.raises(_core.Cancelled):
426 await sleep_forever()
427
428 _core.run(main3)
429
430 async def main4() -> None:
431 with _core.CancelScope() as scope:
432 scope.cancel()
433 await _core.cancel_shielded_checkpoint()
434 await _core.cancel_shielded_checkpoint()
435 with pytest.raises(_core.Cancelled):
436 await _core.checkpoint()
437
438 _core.run(main4)
439
440
441 async def test_cancel_edge_cases() -> None:
442 with _core.CancelScope() as scope:
443 # Two cancels in a row -- idempotent
444 scope.cancel()
445 scope.cancel()
446 await _core.checkpoint()
447 assert scope.cancel_called
448 assert scope.cancelled_caught
449
450 with _core.CancelScope() as scope:
451 # Check level-triggering
452 scope.cancel()
453 with pytest.raises(_core.Cancelled):
454 await sleep_forever()
455 with pytest.raises(_core.Cancelled):
456 await sleep_forever()
457
458
459 async def test_cancel_scope_exceptiongroup_filtering() -> None:
460 async def crasher() -> NoReturn:
461 raise KeyError
462
463 # This is outside the outer scope, so all the Cancelled
464 # exceptions should have been absorbed, leaving just a regular
465 # KeyError from crasher(), wrapped in an ExceptionGroup
466 with pytest.RaisesGroup(KeyError):
467 with _core.CancelScope() as outer:
468 # Since the outer scope became cancelled before the
469 # nursery block exited, all cancellations inside the
470 # nursery block continue propagating to reach the
471 # outer scope.
472 with pytest.RaisesGroup(
473 _core.Cancelled,
474 _core.Cancelled,
475 _core.Cancelled,
476 KeyError,
477 ) as excinfo:
478 async with _core.open_nursery() as nursery:
479 # Two children that get cancelled by the nursery scope
480 nursery.start_soon(sleep_forever) # t1
481 nursery.start_soon(sleep_forever) # t2
482 nursery.cancel_scope.cancel()
483 with _core.CancelScope(shield=True):
484 await wait_all_tasks_blocked()
485 # One child that gets cancelled by the outer scope
486 nursery.start_soon(sleep_forever) # t3
487 outer.cancel()
488 # And one that raises a different error
489 nursery.start_soon(crasher) # t4
490 # and then our __aexit__ also receives an outer Cancelled
491 # reraise the exception caught by pytest.RaisesGroup for the
492 # CancelScope to handle
493 raise excinfo.value
494
495
496 async def test_precancelled_task() -> None:
497 # a task that gets spawned into an already-cancelled nursery should begin
498 # execution (https://github.com/python-trio/trio/issues/41), but get a
499 # cancelled error at its first blocking call.
500 record: list[str] = []
501
502 async def blocker() -> None:
503 record.append("started")
504 await sleep_forever()
505
506 async with _core.open_nursery() as nursery:
507 nursery.cancel_scope.cancel()
508 nursery.start_soon(blocker)
509 assert record == ["started"]
510
511
512 async def test_cancel_shielding() -> None:
513 with _core.CancelScope() as outer:
514 with _core.CancelScope() as inner:
515 await _core.checkpoint()
516 outer.cancel()
517 with pytest.raises(_core.Cancelled):
518 await _core.checkpoint()
519
520 assert inner.shield is False
521 with pytest.raises(TypeError):
522 inner.shield = "hello" # type: ignore
523 assert inner.shield is False
524
525 inner.shield = True
526 assert inner.shield is True
527 # shield protects us from 'outer'
528 await _core.checkpoint()
529
530 with _core.CancelScope() as innerest:
531 innerest.cancel()
532 # but it doesn't protect us from scope inside inner
533 with pytest.raises(_core.Cancelled):
534 await _core.checkpoint()
535 await _core.checkpoint()
536
537 inner.shield = False
538 # can disable shield again
539 with pytest.raises(_core.Cancelled):
540 await _core.checkpoint()
541
542 # re-enable shield
543 inner.shield = True
544 await _core.checkpoint()
545 # shield doesn't protect us from inner itself
546 inner.cancel()
547 # This should now raise, but be absorbed by the inner scope
548 await _core.checkpoint()
549 assert inner.cancelled_caught
550
551
552 # make sure that cancellation propagates immediately to all children
553 async def test_cancel_inheritance() -> None:
554 record: set[str] = set()
555
556 async def leaf(ident: str) -> None:
557 try:
558 await sleep_forever()
559 except _core.Cancelled:
560 record.add(ident)
561
562 async def worker(ident: str) -> None:
563 async with _core.open_nursery() as nursery:
564 nursery.start_soon(leaf, ident + "-l1")
565 nursery.start_soon(leaf, ident + "-l2")
566
567 async with _core.open_nursery() as nursery:
568 nursery.start_soon(worker, "w1")
569 nursery.start_soon(worker, "w2")
570 nursery.cancel_scope.cancel()
571
572 assert record == {"w1-l1", "w1-l2", "w2-l1", "w2-l2"}
573
574
575 async def test_cancel_shield_abort() -> None:
576 with _core.CancelScope() as outer:
577 async with _core.open_nursery() as nursery:
578 outer.cancel()
579 nursery.cancel_scope.shield = True
580 # The outer scope is cancelled, but this task is protected by the
581 # shield, so it manages to get to sleep
582 record = []
583
584 async def sleeper() -> None:
585 record.append("sleeping")
586 try:
587 await sleep_forever()
588 except _core.Cancelled:
589 record.append("cancelled")
590
591 nursery.start_soon(sleeper)
592 await wait_all_tasks_blocked()
593 assert record == ["sleeping"]
594 # now when we unshield, it should abort the sleep.
595 nursery.cancel_scope.shield = False
596 # wait for the task to finish before entering the nursery
597 # __aexit__, because __aexit__ could make it spuriously look like
598 # this worked by cancelling the nursery scope. (When originally
599 # written, without these last few lines, the test spuriously
600 # passed, even though shield assignment was buggy.)
601 with _core.CancelScope(shield=True):
602 await wait_all_tasks_blocked()
603 assert record == ["sleeping", "cancelled"]
604
605
606 async def test_basic_timeout(mock_clock: _core.MockClock) -> None:
607 start = _core.current_time()
608 with _core.CancelScope() as scope:
609 assert scope.deadline == inf
610 scope.deadline = start + 1
611 assert scope.deadline == start + 1
612 assert not scope.cancel_called
613 mock_clock.jump(2)
614 await _core.checkpoint()
615 await _core.checkpoint()
616 await _core.checkpoint()
617 assert not scope.cancel_called
618
619 start = _core.current_time()
620 with _core.CancelScope(deadline=start + 1) as scope:
621 mock_clock.jump(2)
622 await sleep_forever()
623 # But then the scope swallowed the exception... but we can still see it
624 # here:
625 assert scope.cancel_called
626 assert scope.cancelled_caught
627
628 # changing deadline
629 start = _core.current_time()
630 with _core.CancelScope() as scope:
631 await _core.checkpoint()
632 scope.deadline = start + 10
633 await _core.checkpoint()
634 mock_clock.jump(5)
635 await _core.checkpoint()
636 scope.deadline = start + 1
637 with pytest.raises(_core.Cancelled):
638 await _core.checkpoint()
639 with pytest.raises(_core.Cancelled):
640 await _core.checkpoint()
641
642
643 async def test_cancel_scope_nesting() -> None:
644 # Nested scopes: if two triggering at once, the outer one wins
645 with _core.CancelScope() as scope1:
646 with _core.CancelScope() as scope2:
647 with _core.CancelScope() as scope3:
648 scope3.cancel()
649 scope2.cancel()
650 await sleep_forever()
651 assert scope3.cancel_called
652 assert not scope3.cancelled_caught
653 assert scope2.cancel_called
654 assert scope2.cancelled_caught
655 assert not scope1.cancel_called
656 assert not scope1.cancelled_caught
657
658 # shielding
659 with _core.CancelScope() as scope1:
660 with _core.CancelScope() as scope2:
661 scope1.cancel()
662 with pytest.raises(_core.Cancelled):
663 await _core.checkpoint()
664 with pytest.raises(_core.Cancelled):
665 await _core.checkpoint()
666 scope2.shield = True
667 await _core.checkpoint()
668 scope2.cancel()
669 with pytest.raises(_core.Cancelled):
670 await _core.checkpoint()
671
672 # if a scope is pending, but then gets popped off the stack, then it
673 # isn't delivered
674 with _core.CancelScope() as scope:
675 scope.cancel()
676 await _core.cancel_shielded_checkpoint()
677 await _core.checkpoint()
678 assert not scope.cancelled_caught
679
680
681 # Regression test for https://github.com/python-trio/trio/issues/1175
682 async def test_unshield_while_cancel_propagating() -> None:
683 with _core.CancelScope() as outer:
684 with _core.CancelScope() as inner:
685 outer.cancel()
686 try:
687 await _core.checkpoint()
688 finally:
689 inner.shield = True
690 assert outer.cancelled_caught
691 assert not inner.cancelled_caught
692
693
694 async def test_cancel_unbound() -> None:
695 async def sleep_until_cancelled(scope: _core.CancelScope) -> None:
696 with scope, fail_after(1):
697 await sleep_forever()
698
699 # Cancel before entry
700 scope = _core.CancelScope()
701 scope.cancel()
702 async with _core.open_nursery() as nursery:
703 nursery.start_soon(sleep_until_cancelled, scope)
704
705 # Cancel after entry
706 scope = _core.CancelScope()
707 async with _core.open_nursery() as nursery:
708 nursery.start_soon(sleep_until_cancelled, scope)
709 await wait_all_tasks_blocked()
710 scope.cancel()
711
712 # Shield before entry
713 scope = _core.CancelScope()
714 scope.shield = True
715 with _core.CancelScope() as outer, scope:
716 outer.cancel()
717 await _core.checkpoint()
718 scope.shield = False
719 with pytest.raises(_core.Cancelled):
720 await _core.checkpoint()
721
722 # Can't reuse
723 with _core.CancelScope() as scope:
724 await _core.checkpoint()
725 scope.cancel()
726 await _core.checkpoint()
727 assert scope.cancel_called
728 assert not scope.cancelled_caught
729 with pytest.raises(RuntimeError) as exc_info:
730 with scope:
731 pass # pragma: no cover
732 assert "single 'with' block" in str(exc_info.value)
733
734 # Can't reenter
735 with _core.CancelScope() as scope:
736 with pytest.raises(RuntimeError) as exc_info:
737 with scope:
738 pass # pragma: no cover
739 assert "single 'with' block" in str(exc_info.value)
740
741 # Can't enter from multiple tasks simultaneously
742 scope = _core.CancelScope()
743
744 async def enter_scope() -> None:
745 with scope:
746 await sleep_forever()
747
748 async with _core.open_nursery() as nursery:
749 nursery.start_soon(enter_scope, name="this one")
750 await wait_all_tasks_blocked()
751
752 with pytest.raises(RuntimeError) as exc_info:
753 with scope:
754 pass # pragma: no cover
755 assert "single 'with' block" in str(exc_info.value)
756 nursery.cancel_scope.cancel()
757
758 # If not yet entered, cancel_called is true when the deadline has passed
759 # even if cancel() hasn't been called yet
760 scope = _core.CancelScope(deadline=_core.current_time() + 1)
761 assert not scope.cancel_called
762 scope.deadline -= 1
763 assert scope.cancel_called
764 scope.deadline += 1
765 assert scope.cancel_called # never become un-cancelled
766
767
768 async def test_cancel_scope_misnesting_1() -> None:
769 outer = _core.CancelScope()
770 inner = _core.CancelScope()
771 with ExitStack() as stack:
772 stack.enter_context(outer)
773 with inner:
774 with pytest.raises(RuntimeError, match="still within its child"):
775 stack.close()
776 # No further error is raised when exiting the inner context
777
778
779 async def test_cancel_scope_misnesting_2() -> None:
780 # If there are other tasks inside the abandoned part of the cancel tree,
781 # they get cancelled when the misnesting is detected
782 async def task1() -> None:
783 with pytest.raises(_core.Cancelled):
784 await sleep_forever()
785
786 # Even if inside another cancel scope
787 async def task2() -> None:
788 with _core.CancelScope():
789 with pytest.raises(
790 _core.Cancelled,
791 match=r"^cancelled due to unknown with reason 'misnesting'$",
792 ):
793 await sleep_forever()
794
795 with ExitStack() as stack:
796 stack.enter_context(_core.CancelScope())
797 async with _core.open_nursery() as nursery:
798 nursery.start_soon(task1)
799 nursery.start_soon(task2)
800 await wait_all_tasks_blocked()
801 with pytest.raises(RuntimeError, match="still within its child"):
802 stack.close()
803
804 # Variant that makes the child tasks direct children of the scope
805 # that noticed the misnesting:
806 nursery_mgr = _core.open_nursery()
807 nursery = await nursery_mgr.__aenter__()
808 try:
809 nursery.start_soon(task1)
810 nursery.start_soon(task2)
811 nursery.start_soon(sleep_forever)
812 await wait_all_tasks_blocked()
813 nursery.cancel_scope.__exit__(None, None, None)
814 finally:
815 with pytest.raises(
816 RuntimeError,
817 match="which had already been exited",
818 ) as exc_info:
819 await nursery_mgr.__aexit__(*sys.exc_info())
820
821 def no_context(exc: RuntimeError) -> bool:
822 return exc.__context__ is None
823
824 msg = "closed before the task exited"
825 group = pytest.RaisesGroup(
826 pytest.RaisesExc(RuntimeError, match=msg, check=no_context),
827 pytest.RaisesExc(RuntimeError, match=msg, check=no_context),
828 # sleep_forever
829 pytest.RaisesExc(
830 RuntimeError,
831 match=msg,
832 check=lambda x: isinstance(x.__context__, _core.Cancelled),
833 ),
834 )
835 assert group.matches(exc_info.value.__context__)
836
837
838 async def test_cancel_scope_misnesting_3() -> None:
839 # Trying to exit a cancel scope from an unrelated task raises an error
840 # without affecting any state
841 async def task3(task_status: _core.TaskStatus[_core.CancelScope]) -> None:
842 with _core.CancelScope() as scope:
843 task_status.started(scope)
844 await sleep_forever()
845
846 async with _core.open_nursery() as nursery:
847 value = await nursery.start(task3)
848 assert isinstance(value, _core.CancelScope)
849 scope: _core.CancelScope = value
850 with pytest.raises(RuntimeError, match="from unrelated"):
851 scope.__exit__(None, None, None)
852 scope.cancel()
853
854
855 # helper to check we're not outputting overly verbose tracebacks
856 def no_cause_or_context(e: BaseException) -> bool:
857 return e.__cause__ is None and e.__context__ is None
858
859
860 async def test_nursery_misnest() -> None:
861 # See https://github.com/python-trio/trio/issues/3298
862 async def inner_func() -> None:
863 inner_nursery = await inner_cm.__aenter__()
864 inner_nursery.start_soon(sleep, 1)
865
866 with pytest.RaisesGroup(
867 pytest.RaisesExc(
868 RuntimeError, match="Nursery stack corrupted", check=no_cause_or_context
869 ),
870 check=no_cause_or_context,
871 ):
872 async with _core.open_nursery() as outer_nursery:
873 inner_cm = _core.open_nursery()
874 outer_nursery.start_soon(inner_func)
875
876
877 def test_nursery_nested_child_misnest() -> None:
878 # Note that this example does *not* raise an exception group.
879 async def main() -> None:
880 async with _core.open_nursery():
881 inner_cm = _core.open_nursery()
882 await inner_cm.__aenter__()
883
884 with pytest.raises(RuntimeError, match="Nursery stack corrupted") as excinfo:
885 _core.run(main)
886 assert excinfo.value.__cause__ is None
887 # This AssertionError is kind of redundant, but I don't think we want to remove
888 # the assertion and don't think we care enough to suppress it in this specific case.
889 assert pytest.RaisesExc(
890 AssertionError, match="^Nursery misnesting detected!$"
891 ).matches(excinfo.value.__context__)
892 assert excinfo.value.__context__.__cause__ is None
893 assert excinfo.value.__context__.__context__ is None
894
895
896 async def test_asyncexitstack_nursery_misnest() -> None:
897 # This example is trickier than the above ones, and is the one that requires
898 # special logic of abandoned nurseries to avoid nasty internal errors that masks
899 # the RuntimeError.
900 @asynccontextmanager
901 async def asynccontextmanager_that_creates_a_nursery_internally() -> (
902 AsyncGenerator[None]
903 ):
904 async with _core.open_nursery() as nursery:
905 await nursery.start(started_sleeper)
906 nursery.start_soon(unstarted_task)
907 yield
908
909 async def started_sleeper(task_status: _core.TaskStatus[None]) -> None:
910 task_status.started()
911 await sleep_forever()
912
913 async def unstarted_task() -> None:
914 await _core.checkpoint()
915
916 with pytest.RaisesGroup(
917 pytest.RaisesGroup(
918 pytest.RaisesExc(
919 RuntimeError, match="Nursery stack corrupted", check=no_cause_or_context
920 ),
921 check=no_cause_or_context,
922 ),
923 check=no_cause_or_context,
924 ):
925 async with AsyncExitStack() as stack, _core.open_nursery() as nursery:
926 # The asynccontextmanager is going to create a nursery that outlives this nursery!
927 nursery.start_soon(
928 stack.enter_async_context,
929 asynccontextmanager_that_creates_a_nursery_internally(),
930 )
931
932
933 def test_asyncexitstack_nursery_misnest_cleanup() -> None:
934 # We guarantee that abandoned tasks get to do cleanup *eventually*, but exceptions
935 # are lost. With more effort it's possible we could reschedule child tasks to exit
936 # promptly.
937 finally_entered = []
938
939 async def main() -> None:
940 async def unstarted_task() -> None:
941 try:
942 await _core.checkpoint()
943 finally:
944 finally_entered.append(True)
945 raise ValueError("this exception is lost")
946
947 # rest of main() is ~identical to the above test
948 @asynccontextmanager
949 async def asynccontextmanager_that_creates_a_nursery_internally() -> (
950 AsyncGenerator[None]
951 ):
952 async with _core.open_nursery() as nursery:
953 nursery.start_soon(unstarted_task)
954 yield
955
956 with pytest.RaisesGroup(
957 pytest.RaisesGroup(
958 pytest.RaisesExc(
959 RuntimeError,
960 match="Nursery stack corrupted",
961 check=no_cause_or_context,
962 ),
963 check=no_cause_or_context,
964 ),
965 check=no_cause_or_context,
966 ):
967 async with AsyncExitStack() as stack, _core.open_nursery() as nursery:
968 # The asynccontextmanager is going to create a nursery that outlives this nursery!
969 nursery.start_soon(
970 stack.enter_async_context,
971 asynccontextmanager_that_creates_a_nursery_internally(),
972 )
973 assert not finally_entered # abandoned task still hasn't been cleaned up
974
975 _core.run(main)
976 assert finally_entered # now it has
977
978
979 @slow
980 async def test_timekeeping() -> None:
981 # probably a good idea to use a real clock for *one* test anyway...
982 TARGET = 1.0
983 # give it a few tries in case of random CI server flakiness
984 for _ in range(4):
985 real_start = time.perf_counter()
986 with _core.CancelScope() as scope:
987 scope.deadline = _core.current_time() + TARGET
988 await sleep_forever()
989 real_duration = time.perf_counter() - real_start
990 accuracy = real_duration / TARGET
991 print(accuracy)
992 # Actual time elapsed should always be >= target time
993 # (== is possible depending on system behavior for time.perf_counter resolution
994 if 1.0 <= accuracy < 2: # pragma: no branch
995 break
996 else: # pragma: no cover
997 raise AssertionError()
998
999
1000 async def test_failed_abort() -> None:
1001 stubborn_task: _core.Task | None = None
1002 stubborn_scope: _core.CancelScope | None = None
1003 record: list[str] = []
1004
1005 async def stubborn_sleeper() -> None:
1006 nonlocal stubborn_task, stubborn_scope
1007 stubborn_task = _core.current_task()
1008 with _core.CancelScope() as scope:
1009 stubborn_scope = scope
1010 record.append("sleep")
1011 x = await _core.wait_task_rescheduled(lambda _: _core.Abort.FAILED)
1012 assert x == 1
1013 record.append("woke")
1014 try:
1015 await _core.checkpoint_if_cancelled()
1016 except _core.Cancelled:
1017 record.append("cancelled")
1018
1019 async with _core.open_nursery() as nursery:
1020 nursery.start_soon(stubborn_sleeper)
1021 await wait_all_tasks_blocked()
1022 assert record == ["sleep"]
1023 not_none(stubborn_scope).cancel()
1024 await wait_all_tasks_blocked()
1025 # cancel didn't wake it up
1026 assert record == ["sleep"]
1027 # wake it up again by hand
1028 _core.reschedule(not_none(stubborn_task), outcome.Value(1))
1029 assert record == ["sleep", "woke", "cancelled"]
1030
1031
1032 @restore_unraisablehook()
1033 def test_broken_abort() -> None:
1034 async def main() -> None:
1035 # These yields are here to work around an annoying warning -- we're
1036 # going to crash the main loop, and if we (by chance) do this before
1037 # the run_sync_soon task runs for the first time, then Python gives us
1038 # a spurious warning about it not being awaited. (I mean, the warning
1039 # is correct, but here we're testing our ability to deliver a
1040 # semi-meaningful error after things have gone totally pear-shaped, so
1041 # it's not relevant.) By letting the run_sync_soon_task run first, we
1042 # avoid the warning.
1043 await _core.checkpoint()
1044 await _core.checkpoint()
1045 with _core.CancelScope() as scope:
1046 scope.cancel()
1047 # None is not a legal return value here
1048 await _core.wait_task_rescheduled(lambda _: None) # type: ignore
1049
1050 with pytest.raises(_core.TrioInternalError):
1051 _core.run(main)
1052
1053 # Because this crashes, various __del__ methods print complaints on
1054 # stderr. Make sure that they get run now, so the output is attached to
1055 # this test.
1056 gc_collect_harder()
1057
1058
1059 @restore_unraisablehook()
1060 def test_error_in_run_loop() -> None:
1061 # Blow stuff up real good to check we at least get a TrioInternalError
1062 async def main() -> None:
1063 task = _core.current_task()
1064 task._schedule_points = "hello!" # type: ignore
1065 await _core.checkpoint()
1066
1067 with ignore_coroutine_never_awaited_warnings():
1068 with pytest.raises(_core.TrioInternalError):
1069 _core.run(main)
1070
1071
1072 async def test_spawn_system_task() -> None:
1073 record: list[tuple[str, int]] = []
1074
1075 async def system_task(x: int) -> None:
1076 record.append(("x", x))
1077 record.append(("ki", _core.currently_ki_protected()))
1078 await _core.checkpoint()
1079
1080 _core.spawn_system_task(system_task, 1)
1081 await wait_all_tasks_blocked()
1082 assert record == [("x", 1), ("ki", True)]
1083
1084
1085 # intentionally make a system task crash
1086 def test_system_task_crash() -> None:
1087 async def crasher() -> NoReturn:
1088 raise KeyError
1089
1090 async def main() -> None:
1091 _core.spawn_system_task(crasher)
1092 await sleep_forever()
1093
1094 with pytest.raises(_core.TrioInternalError):
1095 _core.run(main)
1096
1097
1098 def test_system_task_crash_ExceptionGroup() -> None:
1099 async def crasher1() -> NoReturn:
1100 raise KeyError
1101
1102 async def crasher2() -> NoReturn:
1103 raise ValueError
1104
1105 async def system_task() -> None:
1106 async with _core.open_nursery() as nursery:
1107 nursery.start_soon(crasher1)
1108 nursery.start_soon(crasher2)
1109
1110 async def main() -> None:
1111 _core.spawn_system_task(system_task)
1112 await sleep_forever()
1113
1114 # TrioInternalError is not wrapped
1115 with pytest.raises(_core.TrioInternalError) as excinfo:
1116 _core.run(main)
1117
1118 # the first exceptiongroup is from the first nursery opened in Runner.init()
1119 # the second exceptiongroup is from the second nursery opened in Runner.init()
1120 # the third exceptongroup is from the nursery defined in `system_task` above
1121 assert pytest.RaisesGroup(
1122 pytest.RaisesGroup(pytest.RaisesGroup(KeyError, ValueError))
1123 ).matches(
1124 excinfo.value.__cause__,
1125 )
1126
1127
1128 def test_system_task_crash_plus_Cancelled() -> None:
1129 # Set up a situation where a system task crashes with a
1130 # ExceptionGroup([Cancelled, ValueError])
1131 async def crasher() -> None:
1132 try:
1133 await sleep_forever()
1134 except _core.Cancelled:
1135 raise ValueError from None
1136
1137 async def cancelme() -> None:
1138 await sleep_forever()
1139
1140 async def system_task() -> None:
1141 async with _core.open_nursery() as nursery:
1142 nursery.start_soon(crasher)
1143 nursery.start_soon(cancelme)
1144
1145 async def main() -> None:
1146 _core.spawn_system_task(system_task)
1147 # then we exit, triggering a cancellation
1148
1149 with pytest.raises(_core.TrioInternalError) as excinfo:
1150 _core.run(main)
1151
1152 # See explanation for triple-wrap in test_system_task_crash_ExceptionGroup
1153 assert pytest.RaisesGroup(
1154 pytest.RaisesGroup(pytest.RaisesGroup(ValueError))
1155 ).matches(
1156 excinfo.value.__cause__,
1157 )
1158
1159
1160 def test_system_task_crash_KeyboardInterrupt() -> None:
1161 async def ki() -> NoReturn:
1162 raise KeyboardInterrupt
1163
1164 async def main() -> None:
1165 _core.spawn_system_task(ki)
1166 await sleep_forever()
1167
1168 with pytest.raises(_core.TrioInternalError) as excinfo:
1169 _core.run(main)
1170 # "Only" double-wrapped since ki() doesn't create an exceptiongroup
1171 assert pytest.RaisesGroup(pytest.RaisesGroup(KeyboardInterrupt)).matches(
1172 excinfo.value.__cause__
1173 )
1174
1175
1176 # This used to fail because checkpoint was a yield followed by an immediate
1177 # reschedule. So we had:
1178 # 1) this task yields
1179 # 2) this task is rescheduled
1180 # ...
1181 # 3) next iteration of event loop starts, runs timeouts
1182 # 4) this task has timed out
1183 # 5) ...but it's on the run queue, so the timeout is queued to be delivered
1184 # the next time that it's blocked.
1185 async def test_yield_briefly_checks_for_timeout(mock_clock: _core.MockClock) -> None:
1186 with _core.CancelScope(deadline=_core.current_time() + 5):
1187 await _core.checkpoint()
1188 mock_clock.jump(10)
1189 with pytest.raises(_core.Cancelled):
1190 await _core.checkpoint()
1191
1192
1193 # This tests that sys.exc_info is properly saved/restored as we swap between
1194 # tasks. It turns out that the interpreter automagically handles this for us
1195 # so there's no special code in Trio required to pass this test, but it's
1196 # still nice to know that it works :-).
1197 #
1198 # Update: it turns out I was right to be nervous! see the next test...
1199 async def test_exc_info() -> None:
1200 record: list[str] = []
1201 seq = Sequencer()
1202
1203 async def child1() -> None:
1204 async with seq(0):
1205 pass # we don't yield until seq(2) below
1206 record.append("child1 raise")
1207 with pytest.raises(ValueError, match=r"^child1$") as excinfo:
1208 try:
1209 raise ValueError("child1")
1210 except ValueError:
1211 record.append("child1 sleep")
1212 async with seq(2):
1213 pass
1214 assert "child2 wake" in record
1215 record.append("child1 re-raise")
1216 raise
1217 assert excinfo.value.__context__ is None
1218 record.append("child1 success")
1219
1220 async def child2() -> None:
1221 async with seq(1):
1222 pass # we don't yield until seq(3) below
1223 assert "child1 sleep" in record
1224 record.append("child2 wake")
1225 assert sys.exc_info() == (None, None, None)
1226 with pytest.raises(KeyError) as excinfo:
1227 try:
1228 raise KeyError("child2")
1229 except KeyError:
1230 record.append("child2 sleep again")
1231 async with seq(3):
1232 pass
1233 assert "child1 re-raise" in record
1234 record.append("child2 re-raise")
1235 raise
1236 assert excinfo.value.__context__ is None
1237 record.append("child2 success")
1238
1239 async with _core.open_nursery() as nursery:
1240 nursery.start_soon(child1)
1241 nursery.start_soon(child2)
1242
1243 assert record == [
1244 "child1 raise",
1245 "child1 sleep",
1246 "child2 wake",
1247 "child2 sleep again",
1248 "child1 re-raise",
1249 "child1 success",
1250 "child2 re-raise",
1251 "child2 success",
1252 ]
1253
1254
1255 # On all CPython versions (at time of writing), using .throw() to raise an
1256 # exception inside a coroutine/generator can cause the original `exc_info` state
1257 # to be lost, so things like re-raising and exception chaining are broken unless
1258 # Trio implements its workaround. At time of writing, CPython main (3.13-dev)
1259 # and every CPython release (excluding releases for old Python versions not
1260 # supported by Trio) is affected (albeit in differing ways).
1261 #
1262 # If the `ValueError()` gets sent in via `throw` and is suppressed, then CPython
1263 # loses track of the original `exc_info`:
1264 # https://bugs.python.org/issue25612 (Example 1)
1265 # https://bugs.python.org/issue29587 (Example 2)
1266 # This is fixed in CPython >= 3.7.
1267 async def test_exc_info_after_throw_suppressed() -> None:
1268 child_task: _core.Task | None = None
1269
1270 async def child() -> None:
1271 nonlocal child_task
1272 child_task = _core.current_task()
1273
1274 try:
1275 raise KeyError
1276 except KeyError:
1277 with suppress(ValueError):
1278 await sleep_forever()
1279 raise
1280
1281 with pytest.RaisesGroup(
1282 pytest.RaisesExc(KeyError, check=lambda e: e.__context__ is None)
1283 ):
1284 async with _core.open_nursery() as nursery:
1285 nursery.start_soon(child)
1286 await wait_all_tasks_blocked()
1287 _core.reschedule(not_none(child_task), outcome.Error(ValueError()))
1288
1289
1290 # Similar to previous test -- if the `ValueError()` gets sent in via 'throw' and
1291 # propagates out, then CPython doesn't set its `__context__` so normal implicit
1292 # exception chaining is broken:
1293 # https://bugs.python.org/issue25612 (Example 2)
1294 # https://bugs.python.org/issue25683
1295 # https://bugs.python.org/issue29587 (Example 1)
1296 # This is fixed in CPython >= 3.9, but kept as a regression test.
1297 async def test_exception_chaining_after_throw() -> None:
1298 child_task: _core.Task | None = None
1299
1300 async def child() -> None:
1301 nonlocal child_task
1302 child_task = _core.current_task()
1303
1304 try:
1305 raise KeyError
1306 except KeyError:
1307 await sleep_forever()
1308
1309 with pytest.RaisesGroup(
1310 pytest.RaisesExc(
1311 ValueError,
1312 match="error text",
1313 check=lambda e: isinstance(e.__context__, KeyError),
1314 ),
1315 ):
1316 async with _core.open_nursery() as nursery:
1317 nursery.start_soon(child)
1318 await wait_all_tasks_blocked()
1319 _core.reschedule(
1320 not_none(child_task),
1321 outcome.Error(ValueError("error text")),
1322 )
1323
1324
1325 # Similar to previous tests -- if the `ValueError()` gets sent into an inner
1326 # `await` via 'throw' and is suppressed there, then CPython loses track of
1327 # `exc_info` in the inner coroutine:
1328 # https://github.com/python/cpython/issues/108668
1329 # This is unfixed in CPython at time of writing.
1330 async def test_exc_info_after_throw_to_inner_suppressed() -> None:
1331 child_task: _core.Task | None = None
1332
1333 async def child() -> None:
1334 nonlocal child_task
1335 child_task = _core.current_task()
1336
1337 try:
1338 raise KeyError
1339 except KeyError as exc:
1340 await inner(exc)
1341 raise
1342
1343 async def inner(exc: BaseException) -> None:
1344 with suppress(ValueError):
1345 await sleep_forever()
1346 assert not_none(sys.exc_info()[1]) is exc
1347
1348 with pytest.RaisesGroup(
1349 pytest.RaisesExc(KeyError, check=lambda e: e.__context__ is None)
1350 ):
1351 async with _core.open_nursery() as nursery:
1352 nursery.start_soon(child)
1353 await wait_all_tasks_blocked()
1354 _core.reschedule(not_none(child_task), outcome.Error(ValueError()))
1355
1356
1357 # Similar to previous tests -- if the `ValueError()` gets sent into an inner
1358 # `await` via `throw` and propagates out, then CPython incorrectly sets its
1359 # `__context__` so normal implicit exception chaining is broken:
1360 # https://bugs.python.org/issue40694
1361 # This is unfixed in CPython at time of writing.
1362 async def test_exception_chaining_after_throw_to_inner() -> None:
1363 child_task: _core.Task | None = None
1364
1365 async def child() -> None:
1366 nonlocal child_task
1367 child_task = _core.current_task()
1368
1369 try:
1370 raise KeyError
1371 except KeyError:
1372 await inner()
1373
1374 async def inner() -> None:
1375 try:
1376 raise IndexError
1377 except IndexError:
1378 await sleep_forever()
1379
1380 with pytest.RaisesGroup(
1381 pytest.RaisesExc(
1382 ValueError,
1383 match="^Unique Text$",
1384 check=lambda e: isinstance(e.__context__, IndexError)
1385 and isinstance(e.__context__.__context__, KeyError),
1386 ),
1387 ):
1388 async with _core.open_nursery() as nursery:
1389 nursery.start_soon(child)
1390 await wait_all_tasks_blocked()
1391 _core.reschedule(
1392 not_none(child_task),
1393 outcome.Error(ValueError("Unique Text")),
1394 )
1395
1396
1397 async def test_nursery_exception_chaining_doesnt_make_context_loops() -> None:
1398 async def crasher() -> NoReturn:
1399 raise KeyError
1400
1401 # the ExceptionGroup should not have the KeyError or ValueError as context
1402 with pytest.RaisesGroup(
1403 ValueError, KeyError, check=lambda x: x.__context__ is None
1404 ):
1405 async with _core.open_nursery() as nursery:
1406 nursery.start_soon(crasher)
1407 raise ValueError
1408
1409
1410 def test_TrioToken_identity() -> None:
1411 async def get_and_check_token() -> _core.TrioToken:
1412 token = _core.current_trio_token()
1413 # Two calls in the same run give the same object
1414 assert token is _core.current_trio_token()
1415 return token
1416
1417 t1 = _core.run(get_and_check_token)
1418 t2 = _core.run(get_and_check_token)
1419 assert t1 is not t2
1420 assert t1 != t2
1421 assert hash(t1) != hash(t2)
1422
1423
1424 async def test_TrioToken_run_sync_soon_basic() -> None:
1425 record: list[tuple[str, int]] = []
1426
1427 def cb(x: int) -> None:
1428 record.append(("cb", x))
1429
1430 token = _core.current_trio_token()
1431 token.run_sync_soon(cb, 1)
1432 assert not record
1433 await wait_all_tasks_blocked()
1434 assert record == [("cb", 1)]
1435
1436
1437 def test_TrioToken_run_sync_soon_too_late() -> None:
1438 token: _core.TrioToken | None = None
1439
1440 async def main() -> None:
1441 nonlocal token
1442 token = _core.current_trio_token()
1443
1444 _core.run(main)
1445 with pytest.raises(_core.RunFinishedError):
1446 not_none(token).run_sync_soon(lambda: None) # pragma: no branch
1447
1448
1449 async def test_TrioToken_run_sync_soon_idempotent() -> None:
1450 record: list[int] = []
1451
1452 def cb(x: int) -> None:
1453 record.append(x)
1454
1455 token = _core.current_trio_token()
1456 token.run_sync_soon(cb, 1)
1457 token.run_sync_soon(cb, 1, idempotent=True)
1458 token.run_sync_soon(cb, 1, idempotent=True)
1459 token.run_sync_soon(cb, 1, idempotent=True)
1460 token.run_sync_soon(cb, 2, idempotent=True)
1461 token.run_sync_soon(cb, 2, idempotent=True)
1462 await wait_all_tasks_blocked()
1463 assert len(record) == 3
1464 assert sorted(record) == [1, 1, 2]
1465
1466 # ordering test
1467 record = []
1468 for _ in range(3):
1469 for i in range(100):
1470 token.run_sync_soon(cb, i, idempotent=True)
1471 await wait_all_tasks_blocked()
1472 # We guarantee FIFO
1473 assert record == list(range(100))
1474
1475
1476 def test_TrioToken_run_sync_soon_idempotent_requeue() -> None:
1477 # We guarantee that if a call has finished, queueing it again will call it
1478 # again. Due to the lack of synchronization, this effectively means that
1479 # we have to guarantee that once a call has *started*, queueing it again
1480 # will call it again. Also this is much easier to test :-)
1481 record: list[None] = []
1482
1483 def redo(token: _core.TrioToken) -> None:
1484 record.append(None)
1485 with suppress(_core.RunFinishedError):
1486 token.run_sync_soon(redo, token, idempotent=True)
1487
1488 async def main() -> None:
1489 token = _core.current_trio_token()
1490 token.run_sync_soon(redo, token, idempotent=True)
1491 await _core.checkpoint()
1492 await _core.checkpoint()
1493 await _core.checkpoint()
1494
1495 _core.run(main)
1496
1497 assert len(record) >= 2
1498
1499
1500 def test_TrioToken_run_sync_soon_after_main_crash() -> None:
1501 record: list[str] = []
1502
1503 async def main() -> None:
1504 token = _core.current_trio_token()
1505 # After main exits but before finally cleaning up, callback processed
1506 # normally
1507 token.run_sync_soon(lambda: record.append("sync-cb"))
1508 raise ValueError("error text")
1509
1510 with pytest.raises(ValueError, match=r"^error text$"):
1511 _core.run(main)
1512
1513 assert record == ["sync-cb"]
1514
1515
1516 def test_TrioToken_run_sync_soon_crashes() -> None:
1517 record: set[str] = set()
1518
1519 async def main() -> None:
1520 token = _core.current_trio_token()
1521 token.run_sync_soon(lambda: {}["nope"]) # type: ignore[index]
1522 # check that a crashing run_sync_soon callback doesn't stop further
1523 # calls to run_sync_soon
1524 token.run_sync_soon(lambda: record.add("2nd run_sync_soon ran"))
1525 try:
1526 await sleep_forever()
1527 except _core.Cancelled:
1528 record.add("cancelled!")
1529
1530 with pytest.raises(_core.TrioInternalError) as excinfo:
1531 _core.run(main)
1532 # the first exceptiongroup is from the first nursery opened in Runner.init()
1533 # the second exceptiongroup is from the second nursery opened in Runner.init()
1534 assert pytest.RaisesGroup(pytest.RaisesGroup(KeyError)).matches(
1535 excinfo.value.__cause__
1536 )
1537 assert record == {"2nd run_sync_soon ran", "cancelled!"}
1538
1539
1540 async def test_TrioToken_run_sync_soon_FIFO() -> None:
1541 N = 100
1542 record = []
1543 token = _core.current_trio_token()
1544 for i in range(N):
1545 token.run_sync_soon(lambda j: record.append(j), i)
1546 await wait_all_tasks_blocked()
1547 assert record == list(range(N))
1548
1549
1550 def test_TrioToken_run_sync_soon_starvation_resistance() -> None:
1551 # Even if we push callbacks in from callbacks, so that the callback queue
1552 # never empties out, then we still can't starve out other tasks from
1553 # running.
1554 token: _core.TrioToken | None = None
1555 record: list[tuple[str, int]] = []
1556
1557 def naughty_cb(i: int) -> None:
1558 try:
1559 not_none(token).run_sync_soon(naughty_cb, i + 1)
1560 except _core.RunFinishedError:
1561 record.append(("run finished", i))
1562
1563 async def main() -> None:
1564 nonlocal token
1565 token = _core.current_trio_token()
1566 token.run_sync_soon(naughty_cb, 0)
1567 record.append(("starting", 0))
1568 for _ in range(20):
1569 await _core.checkpoint()
1570
1571 _core.run(main)
1572 assert len(record) == 2
1573 assert record[0] == ("starting", 0)
1574 assert record[1][0] == "run finished"
1575 assert record[1][1] >= 19
1576
1577
1578 def test_TrioToken_run_sync_soon_threaded_stress_test() -> None:
1579 cb_counter = 0
1580
1581 def cb() -> None:
1582 nonlocal cb_counter
1583 cb_counter += 1
1584
1585 def stress_thread(token: _core.TrioToken) -> None:
1586 try:
1587 while True:
1588 token.run_sync_soon(cb)
1589 time.sleep(0)
1590 except _core.RunFinishedError:
1591 pass
1592
1593 async def main() -> None:
1594 token = _core.current_trio_token()
1595 thread = threading.Thread(target=stress_thread, args=(token,))
1596 thread.start()
1597 for _ in range(10):
1598 start_value = cb_counter
1599 while cb_counter == start_value:
1600 await sleep(0.01)
1601
1602 _core.run(main)
1603 print(cb_counter)
1604
1605
1606 async def test_TrioToken_run_sync_soon_massive_queue() -> None:
1607 # There are edge cases in the wakeup fd code when the wakeup fd overflows,
1608 # so let's try to make that happen. This is also just a good stress test
1609 # in general. (With the current-as-of-2017-02-14 code using a socketpair
1610 # with minimal buffer, Linux takes 6 wakeups to fill the buffer and macOS
1611 # takes 1 wakeup. So 1000 is overkill if anything. Windows OTOH takes
1612 # ~600,000 wakeups, but has the same code paths...)
1613 COUNT = 1000
1614 token = _core.current_trio_token()
1615 counter = [0]
1616
1617 def cb(i: int) -> None:
1618 # This also tests FIFO ordering of callbacks
1619 assert counter[0] == i
1620 counter[0] += 1
1621
1622 for i in range(COUNT):
1623 token.run_sync_soon(cb, i)
1624 await wait_all_tasks_blocked()
1625 assert counter[0] == COUNT
1626
1627
1628 def test_TrioToken_run_sync_soon_late_crash() -> None:
1629 # Crash after system nursery is closed -- easiest way to do that is
1630 # from an async generator finalizer.
1631 record: list[str] = []
1632 saved: list[AsyncGenerator[int, None]] = []
1633
1634 async def agen() -> AsyncGenerator[int, None]:
1635 token = _core.current_trio_token()
1636 try:
1637 yield 1
1638 finally:
1639 token.run_sync_soon(lambda: {}["nope"]) # type: ignore[index]
1640 token.run_sync_soon(lambda: record.append("2nd ran"))
1641
1642 async def main() -> None:
1643 saved.append(agen())
1644 await saved[-1].asend(None)
1645 record.append("main exiting")
1646
1647 with pytest.raises(_core.TrioInternalError) as excinfo:
1648 _core.run(main)
1649
1650 assert pytest.RaisesGroup(KeyError).matches(excinfo.value.__cause__)
1651 assert record == ["main exiting", "2nd ran"]
1652
1653
1654 async def test_slow_abort_basic() -> None:
1655 with _core.CancelScope() as scope:
1656 scope.cancel()
1657
1658 task = _core.current_task()
1659 token = _core.current_trio_token()
1660
1661 def slow_abort(raise_cancel: _core.RaiseCancelT) -> _core.Abort:
1662 result = outcome.capture(raise_cancel)
1663 token.run_sync_soon(_core.reschedule, task, result)
1664 return _core.Abort.FAILED
1665
1666 with pytest.raises(_core.Cancelled):
1667 await _core.wait_task_rescheduled(slow_abort)
1668
1669
1670 async def test_slow_abort_edge_cases() -> None:
1671 record: list[str] = []
1672
1673 async def slow_aborter() -> None:
1674 task = _core.current_task()
1675 token = _core.current_trio_token()
1676
1677 def slow_abort(raise_cancel: _core.RaiseCancelT) -> _core.Abort:
1678 record.append("abort-called")
1679 result = outcome.capture(raise_cancel)
1680 token.run_sync_soon(_core.reschedule, task, result)
1681 return _core.Abort.FAILED
1682
1683 record.append("sleeping")
1684 with pytest.raises(_core.Cancelled):
1685 await _core.wait_task_rescheduled(slow_abort)
1686 record.append("cancelled")
1687 # blocking again, this time it's okay, because we're shielded
1688 await _core.checkpoint()
1689 record.append("done")
1690
1691 with _core.CancelScope() as outer1:
1692 with _core.CancelScope() as outer2:
1693 async with _core.open_nursery() as nursery:
1694 # So we have a task blocked on an operation that can't be
1695 # aborted immediately
1696 nursery.start_soon(slow_aborter)
1697 await wait_all_tasks_blocked()
1698 assert record == ["sleeping"]
1699 # And then we cancel it, so the abort callback gets run
1700 outer1.cancel()
1701 assert record == ["sleeping", "abort-called"]
1702 # In fact that happens twice! (This used to cause the abort
1703 # callback to be run twice)
1704 outer2.cancel()
1705 assert record == ["sleeping", "abort-called"]
1706 # But then before the abort finishes, the task gets shielded!
1707 nursery.cancel_scope.shield = True
1708 # Now we wait for the task to finish...
1709 # The cancellation was delivered, even though it was shielded
1710 assert record == ["sleeping", "abort-called", "cancelled", "done"]
1711
1712
1713 async def test_task_tree_introspection() -> None:
1714 tasks: dict[str, _core.Task] = {}
1715 nurseries: dict[str, _core.Nursery] = {}
1716
1717 async def parent(
1718 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
1719 ) -> None:
1720 tasks["parent"] = _core.current_task()
1721
1722 assert tasks["parent"].child_nurseries == []
1723
1724 async with _core.open_nursery() as nursery1:
1725 async with _core.open_nursery() as nursery2:
1726 assert tasks["parent"].child_nurseries == [nursery1, nursery2]
1727
1728 assert tasks["parent"].child_nurseries == []
1729
1730 nursery: _core.Nursery | None
1731 async with _core.open_nursery() as nursery:
1732 nurseries["parent"] = nursery
1733 await nursery.start(child1)
1734
1735 # Upward links survive after tasks/nurseries exit
1736 assert nurseries["parent"].parent_task is tasks["parent"]
1737 assert tasks["child1"].parent_nursery is nurseries["parent"]
1738 assert nurseries["child1"].parent_task is tasks["child1"]
1739 assert tasks["child2"].parent_nursery is nurseries["child1"]
1740
1741 nursery = _core.current_task().parent_nursery
1742 # Make sure that chaining eventually gives a nursery of None (and not,
1743 # for example, an error)
1744 while nursery is not None:
1745 t = nursery.parent_task
1746 nursery = t.parent_nursery
1747
1748 async def child2() -> None:
1749 tasks["child2"] = _core.current_task()
1750 assert tasks["parent"].child_nurseries == [nurseries["parent"]]
1751 assert nurseries["parent"].child_tasks == frozenset({tasks["child1"]})
1752 assert tasks["child1"].child_nurseries == [nurseries["child1"]]
1753 assert nurseries["child1"].child_tasks == frozenset({tasks["child2"]})
1754 assert tasks["child2"].child_nurseries == []
1755
1756 async def child1(
1757 *,
1758 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
1759 ) -> None:
1760 me = tasks["child1"] = _core.current_task()
1761 assert not_none(me.parent_nursery).parent_task is tasks["parent"]
1762 assert me.parent_nursery is not nurseries["parent"]
1763 assert me.eventual_parent_nursery is nurseries["parent"]
1764 task_status.started()
1765 assert me.parent_nursery is nurseries["parent"]
1766 assert me.eventual_parent_nursery is None
1767
1768 # Wait for the start() call to return and close its internal nursery, to
1769 # ensure consistent results in child2:
1770 await _core.wait_all_tasks_blocked()
1771
1772 async with _core.open_nursery() as nursery:
1773 nurseries["child1"] = nursery
1774 nursery.start_soon(child2)
1775
1776 async with _core.open_nursery() as nursery:
1777 nursery.start_soon(parent)
1778
1779 # There are no pending starts, so no one should have a non-None
1780 # eventual_parent_nursery
1781 for task in tasks.values():
1782 assert task.eventual_parent_nursery is None
1783
1784
1785 async def test_nursery_closure() -> None:
1786 async def child1(nursery: _core.Nursery) -> None:
1787 # We can add new tasks to the nursery even after entering __aexit__,
1788 # so long as there are still tasks running
1789 nursery.start_soon(child2)
1790
1791 async def child2() -> None:
1792 pass
1793
1794 async with _core.open_nursery() as nursery:
1795 nursery.start_soon(child1, nursery)
1796
1797 # But once we've left __aexit__, the nursery is closed
1798 with pytest.raises(RuntimeError):
1799 nursery.start_soon(child2)
1800
1801
1802 async def test_spawn_name() -> None:
1803 async def func1(expected: str) -> None:
1804 task = _core.current_task()
1805 assert expected in task.name
1806
1807 async def func2() -> None: # pragma: no cover
1808 pass
1809
1810 async def check( # type: ignore[explicit-any]
1811 spawn_fn: Callable[..., object],
1812 ) -> None:
1813 spawn_fn(func1, "func1")
1814 spawn_fn(func1, "func2", name=func2)
1815 spawn_fn(func1, "func3", name="func3")
1816 spawn_fn(functools.partial(func1, "func1"))
1817 spawn_fn(func1, "object", name=object())
1818
1819 async with _core.open_nursery() as nursery:
1820 await check(nursery.start_soon)
1821 await check(_core.spawn_system_task)
1822
1823
1824 async def test_current_effective_deadline(mock_clock: _core.MockClock) -> None:
1825 assert _core.current_effective_deadline() == inf
1826
1827 with _core.CancelScope(deadline=5) as scope1:
1828 with _core.CancelScope(deadline=10) as scope2:
1829 assert _core.current_effective_deadline() == 5
1830 scope2.deadline = 3
1831 assert _core.current_effective_deadline() == 3
1832 scope2.deadline = 10
1833 assert _core.current_effective_deadline() == 5
1834 scope2.shield = True
1835 assert _core.current_effective_deadline() == 10
1836 scope2.shield = False
1837 assert _core.current_effective_deadline() == 5
1838 scope1.cancel()
1839 assert _core.current_effective_deadline() == -inf
1840 scope2.shield = True
1841 assert _core.current_effective_deadline() == 10
1842 assert _core.current_effective_deadline() == -inf
1843 assert _core.current_effective_deadline() == inf
1844
1845
1846 def test_nice_error_on_bad_calls_to_run_or_spawn() -> None:
1847 def bad_call_run( # type: ignore[explicit-any]
1848 func: Callable[..., Awaitable[object]],
1849 *args: tuple[object, ...],
1850 ) -> None:
1851 _core.run(func, *args)
1852
1853 def bad_call_spawn( # type: ignore[explicit-any]
1854 func: Callable[..., Awaitable[object]],
1855 *args: tuple[object, ...],
1856 ) -> None:
1857 async def main() -> None:
1858 async with _core.open_nursery() as nursery:
1859 nursery.start_soon(func, *args)
1860
1861 _core.run(main)
1862
1863 async def f() -> None: # pragma: no cover
1864 pass
1865
1866 async def async_gen(arg: T) -> AsyncGenerator[T, None]: # pragma: no cover
1867 yield arg
1868
1869 # If/when RaisesGroup/Matcher is added to pytest in some form this test can be
1870 # rewritten to use a loop again, and avoid specifying the exceptions twice in
1871 # different ways
1872 with pytest.raises(
1873 TypeError,
1874 match=r"^Trio was expecting an async function, but instead it got a coroutine object <.*>",
1875 ):
1876 bad_call_run(f()) # type: ignore[arg-type]
1877 with pytest.raises(
1878 TypeError,
1879 match=r"expected an async function but got an async generator",
1880 ):
1881 bad_call_run(async_gen, 0) # type: ignore
1882
1883 # bad_call_spawn calls the function inside a nursery, so the exception will be
1884 # wrapped in an exceptiongroup
1885 with pytest.RaisesGroup(
1886 pytest.RaisesExc(TypeError, match="expecting an async function")
1887 ):
1888 bad_call_spawn(f()) # type: ignore[arg-type]
1889
1890 with pytest.RaisesGroup(
1891 pytest.RaisesExc(
1892 TypeError, match="expected an async function but got an async generator"
1893 ),
1894 ):
1895 bad_call_spawn(async_gen, 0) # type: ignore
1896
1897
1898 def test_calling_asyncio_function_gives_nice_error() -> None:
1899 async def child_xyzzy() -> None:
1900 await create_asyncio_future_in_new_loop()
1901
1902 async def misguided() -> None:
1903 await child_xyzzy()
1904
1905 with pytest.raises(TypeError, match="asyncio") as excinfo:
1906 _core.run(misguided)
1907
1908 # The traceback should point to the location of the foreign await
1909 assert any( # pragma: no branch
1910 entry.name == "child_xyzzy" for entry in excinfo.traceback
1911 )
1912
1913
1914 async def test_asyncio_function_inside_nursery_does_not_explode() -> None:
1915 # Regression test for https://github.com/python-trio/trio/issues/552
1916 with pytest.RaisesGroup(pytest.RaisesExc(TypeError, match="asyncio")):
1917 async with _core.open_nursery() as nursery:
1918 nursery.start_soon(sleep_forever)
1919 await create_asyncio_future_in_new_loop()
1920
1921
1922 async def test_trivial_yields() -> None:
1923 with assert_checkpoints():
1924 await _core.checkpoint()
1925
1926 with assert_checkpoints():
1927 await _core.checkpoint_if_cancelled()
1928 await _core.cancel_shielded_checkpoint()
1929
1930 # Weird case: opening and closing a nursery schedules, but doesn't check
1931 # for cancellation (unless something inside the nursery does)
1932 task = _core.current_task()
1933 before_schedule_points = task._schedule_points
1934 with _core.CancelScope() as cs:
1935 cs.cancel()
1936 async with _core.open_nursery():
1937 pass
1938 assert not cs.cancelled_caught
1939 assert task._schedule_points > before_schedule_points
1940
1941 before_schedule_points = task._schedule_points
1942
1943 async def noop_with_no_checkpoint() -> None:
1944 pass
1945
1946 with _core.CancelScope() as cs:
1947 cs.cancel()
1948 async with _core.open_nursery() as nursery:
1949 nursery.start_soon(noop_with_no_checkpoint)
1950 assert not cs.cancelled_caught
1951
1952 assert task._schedule_points > before_schedule_points
1953
1954 with _core.CancelScope() as cancel_scope:
1955 cancel_scope.cancel()
1956 with pytest.RaisesGroup(KeyError):
1957 async with _core.open_nursery():
1958 raise KeyError
1959
1960
1961 async def test_nursery_start(autojump_clock: _core.MockClock) -> None:
1962 async def no_args() -> None: # pragma: no cover
1963 pass
1964
1965 # Errors in calling convention get raised immediately from start
1966 async with _core.open_nursery() as nursery:
1967 with pytest.raises(TypeError):
1968 await nursery.start(no_args)
1969
1970 async def sleep_then_start(
1971 seconds: int,
1972 *,
1973 task_status: _core.TaskStatus[int] = _core.TASK_STATUS_IGNORED,
1974 ) -> None:
1975 repr(task_status) # smoke test
1976 await sleep(seconds)
1977 task_status.started(seconds)
1978 await sleep(seconds)
1979
1980 # Basic happy-path check: start waits for the task to call started(), then
1981 # returns, passes back the value, and the given nursery then waits for it
1982 # to exit.
1983 for seconds in [1, 2]:
1984 async with _core.open_nursery() as nursery:
1985 assert len(nursery.child_tasks) == 0
1986 t0 = _core.current_time()
1987 assert await nursery.start(sleep_then_start, seconds) == seconds
1988 assert _core.current_time() - t0 == seconds
1989 assert len(nursery.child_tasks) == 1
1990 assert _core.current_time() - t0 == 2 * seconds
1991
1992 # Make sure TASK_STATUS_IGNORED works so task function can be called
1993 # directly
1994 t0 = _core.current_time()
1995 await sleep_then_start(3)
1996 assert _core.current_time() - t0 == 2 * 3
1997
1998 # calling started twice
1999 async def double_started(
2000 *,
2001 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2002 ) -> None:
2003 task_status.started()
2004 with pytest.raises(RuntimeError):
2005 task_status.started()
2006
2007 async with _core.open_nursery() as nursery:
2008 await nursery.start(double_started)
2009
2010 # child crashes before calling started -> error comes out of .start()
2011 async def raise_keyerror(
2012 *,
2013 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2014 ) -> None:
2015 raise KeyError("oops")
2016
2017 async with _core.open_nursery() as nursery:
2018 with pytest.raises(KeyError):
2019 await nursery.start(raise_keyerror)
2020
2021 # child exiting cleanly before calling started -> triggers a RuntimeError
2022 async def nothing(
2023 *,
2024 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2025 ) -> None:
2026 return
2027
2028 async with _core.open_nursery() as nursery:
2029 with pytest.raises(RuntimeError) as excinfo1:
2030 await nursery.start(nothing)
2031 assert "exited without calling" in str(excinfo1.value)
2032
2033 # if the call to start() is cancelled, then the call to started() does
2034 # nothing -- the child keeps executing under start(). The value it passed
2035 # is ignored; start() raises Cancelled.
2036 async def just_started(
2037 *,
2038 task_status: _core.TaskStatus[str] = _core.TASK_STATUS_IGNORED,
2039 ) -> None:
2040 task_status.started("hi")
2041 await _core.checkpoint()
2042
2043 async with _core.open_nursery() as nursery:
2044 with _core.CancelScope() as cs:
2045 cs.cancel()
2046 with pytest.raises(_core.Cancelled):
2047 await nursery.start(just_started)
2048
2049 # but if the task does not execute any checkpoints, and exits, then start()
2050 # doesn't raise Cancelled, since the task completed successfully.
2051 async def started_with_no_checkpoint(
2052 *,
2053 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2054 ) -> None:
2055 task_status.started(None)
2056
2057 async with _core.open_nursery() as nursery:
2058 with _core.CancelScope() as cs:
2059 cs.cancel()
2060 await nursery.start(started_with_no_checkpoint)
2061 assert not cs.cancelled_caught
2062
2063 # and since starting in a cancelled context makes started() a no-op, if
2064 # the child crashes after calling started(), the error can *still* come
2065 # out of start()
2066 async def raise_keyerror_after_started(
2067 *,
2068 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2069 ) -> None:
2070 task_status.started()
2071 raise KeyError("whoopsiedaisy")
2072
2073 async with _core.open_nursery() as nursery:
2074 with _core.CancelScope() as cs:
2075 cs.cancel()
2076 with pytest.raises(KeyError):
2077 await nursery.start(raise_keyerror_after_started)
2078
2079 # trying to start in a closed nursery raises an error immediately
2080 async with _core.open_nursery() as closed_nursery:
2081 pass
2082 t0 = _core.current_time()
2083 with pytest.raises(RuntimeError):
2084 await closed_nursery.start(sleep_then_start, 7)
2085 # sub-second delays can be caused by unrelated multitasking by an OS
2086 assert int(_core.current_time()) == int(t0)
2087
2088
2089 async def test_task_nursery_stack() -> None:
2090 task = _core.current_task()
2091 assert task._child_nurseries == []
2092 async with _core.open_nursery() as nursery1:
2093 assert task._child_nurseries == [nursery1]
2094 with pytest.RaisesGroup(KeyError):
2095 async with _core.open_nursery() as nursery2:
2096 assert task._child_nurseries == [nursery1, nursery2]
2097 raise KeyError
2098 assert task._child_nurseries == [nursery1]
2099 assert task._child_nurseries == []
2100
2101
2102 async def test_nursery_start_with_cancelled_nursery() -> None:
2103 # This function isn't testing task_status, it's using task_status as a
2104 # convenient way to get a nursery that we can test spawning stuff into.
2105 async def setup_nursery(
2106 task_status: _core.TaskStatus[_core.Nursery] = _core.TASK_STATUS_IGNORED,
2107 ) -> None:
2108 async with _core.open_nursery() as nursery:
2109 task_status.started(nursery)
2110 await sleep_forever()
2111
2112 # Calls started() while children are asleep, so we can make sure
2113 # that the cancellation machinery notices and aborts when a sleeping task
2114 # is moved into a cancelled scope.
2115 async def sleeping_children(
2116 fn: Callable[[], object],
2117 *,
2118 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2119 ) -> None:
2120 async with _core.open_nursery() as nursery:
2121 nursery.start_soon(sleep_forever)
2122 nursery.start_soon(sleep_forever)
2123 await wait_all_tasks_blocked()
2124 fn()
2125 task_status.started()
2126
2127 # Cancelling the setup_nursery just *before* calling started()
2128 async with _core.open_nursery() as nursery:
2129 value = await nursery.start(setup_nursery)
2130 assert isinstance(value, _core.Nursery)
2131 target_nursery: _core.Nursery = value
2132 await target_nursery.start(
2133 sleeping_children,
2134 target_nursery.cancel_scope.cancel,
2135 )
2136
2137 # Cancelling the setup_nursery just *after* calling started()
2138 async with _core.open_nursery() as nursery:
2139 value = await nursery.start(setup_nursery)
2140 assert isinstance(value, _core.Nursery)
2141 target_nursery = value
2142 await target_nursery.start(sleeping_children, lambda: None)
2143 target_nursery.cancel_scope.cancel()
2144
2145
2146 async def test_nursery_start_keeps_nursery_open(
2147 autojump_clock: _core.MockClock,
2148 ) -> None:
2149 async def sleep_a_bit(
2150 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2151 ) -> None:
2152 await sleep(2)
2153 task_status.started()
2154 await sleep(3)
2155
2156 async with _core.open_nursery() as nursery1:
2157 t0 = _core.current_time()
2158 async with _core.open_nursery() as nursery2:
2159 # Start the 'start' call running in the background
2160 nursery1.start_soon(nursery2.start, sleep_a_bit)
2161 # Sleep a bit
2162 await sleep(1)
2163 # Start another one.
2164 nursery1.start_soon(nursery2.start, sleep_a_bit)
2165 # Then exit this nursery. At this point, there are no tasks
2166 # present in this nursery -- the only thing keeping it open is
2167 # that the tasks will be placed into it soon, when they call
2168 # started().
2169 assert _core.current_time() - t0 == 6
2170
2171 # Check that it still works even if the task that the nursery is waiting
2172 # for ends up crashing, and never actually enters the nursery.
2173 async def sleep_then_crash(
2174 task_status: _core.TaskStatus[None] = _core.TASK_STATUS_IGNORED,
2175 ) -> None:
2176 await sleep(7)
2177 raise KeyError
2178
2179 async def start_sleep_then_crash(nursery: _core.Nursery) -> None:
2180 with pytest.raises(KeyError):
2181 await nursery.start(sleep_then_crash)
2182
2183 async with _core.open_nursery() as nursery1:
2184 t0 = _core.current_time()
2185 async with _core.open_nursery() as nursery2:
2186 nursery1.start_soon(start_sleep_then_crash, nursery2)
2187 await wait_all_tasks_blocked()
2188 assert _core.current_time() - t0 == 7
2189
2190
2191 async def test_nursery_explicit_exception() -> None:
2192 with pytest.RaisesGroup(KeyError):
2193 async with _core.open_nursery():
2194 raise KeyError()
2195
2196
2197 async def test_nursery_stop_iteration() -> None:
2198 async def fail() -> NoReturn:
2199 raise ValueError
2200
2201 with pytest.RaisesGroup(StopIteration, ValueError):
2202 async with _core.open_nursery() as nursery:
2203 nursery.start_soon(fail)
2204 raise StopIteration
2205
2206
2207 async def test_nursery_stop_async_iteration() -> None:
2208 class it:
2209 def __init__(self, count: int) -> None:
2210 self.count = count
2211 self.val = 0
2212
2213 async def __anext__(self) -> int:
2214 await sleep(0)
2215 val = self.val
2216 if val >= self.count:
2217 raise StopAsyncIteration
2218 self.val += 1
2219 return val
2220
2221 class async_zip:
2222 def __init__(self, *largs: it) -> None:
2223 self.nexts = [obj.__anext__ for obj in largs]
2224
2225 async def _accumulate(
2226 self,
2227 f: Callable[[], Awaitable[int]],
2228 items: list[int],
2229 i: int,
2230 ) -> None:
2231 items[i] = await f()
2232
2233 def __aiter__(self) -> async_zip:
2234 return self
2235
2236 async def __anext__(self) -> list[int]:
2237 nexts = self.nexts
2238 items: list[int] = [-1] * len(nexts)
2239
2240 try:
2241 async with _core.open_nursery() as nursery:
2242 for i, f in enumerate(nexts):
2243 nursery.start_soon(self._accumulate, f, items, i)
2244 except ExceptionGroup as e:
2245 # With strict_exception_groups enabled, users now need to unwrap
2246 # StopAsyncIteration and re-raise it.
2247 # This would be relatively clean on python3.11+ with except*.
2248 # We could also use pytest.RaisesGroup, but that's primarily meant as
2249 # test infra, not as a runtime tool.
2250 if len(e.exceptions) == 1 and isinstance(
2251 e.exceptions[0],
2252 StopAsyncIteration,
2253 ):
2254 raise e.exceptions[0] from None
2255 else: # pragma: no cover
2256 raise AssertionError("unknown error in _accumulate") from e
2257
2258 return items
2259
2260 result: list[list[int]] = [vals async for vals in async_zip(it(4), it(2))]
2261 assert result == [[0, 0], [1, 1]]
2262
2263
2264 async def test_traceback_frame_removal() -> None:
2265 async def my_child_task() -> NoReturn:
2266 raise KeyError()
2267
2268 def check_traceback(exc: KeyError) -> bool:
2269 # The top frame in the exception traceback should be inside the child
2270 # task, not trio/contextvars internals. And there's only one frame
2271 # inside the child task, so this will also detect if our frame-removal
2272 # is too eager.
2273 tb = exc.__traceback__
2274 assert tb is not None
2275 return tb.tb_frame.f_code is my_child_task.__code__
2276
2277 with pytest.RaisesGroup(pytest.RaisesExc(KeyError, check=check_traceback)):
2278 # For now cancel/nursery scopes still leave a bunch of tb gunk behind.
2279 # But if there's an Exceptiongroup, they leave it on the group,
2280 # which lets us get a clean look at the KeyError itself.
2281 async with _core.open_nursery() as nursery:
2282 nursery.start_soon(my_child_task)
2283
2284
2285 def test_contextvar_support() -> None:
2286 var: contextvars.ContextVar[str] = contextvars.ContextVar("test")
2287 var.set("before")
2288
2289 assert var.get() == "before"
2290
2291 async def inner() -> None:
2292 task = _core.current_task()
2293 assert task.context.get(var) == "before"
2294 assert var.get() == "before"
2295 var.set("after")
2296 assert var.get() == "after"
2297 assert var in task.context
2298 assert task.context.get(var) == "after"
2299
2300 _core.run(inner)
2301 assert var.get() == "before"
2302
2303
2304 async def test_contextvar_multitask() -> None:
2305 var = contextvars.ContextVar("test", default="hmmm")
2306
2307 async def t1() -> None:
2308 assert var.get() == "hmmm"
2309 var.set("hmmmm")
2310 assert var.get() == "hmmmm"
2311
2312 async def t2() -> None:
2313 assert var.get() == "hmmmm"
2314
2315 async with _core.open_nursery() as n:
2316 n.start_soon(t1)
2317 await wait_all_tasks_blocked()
2318 assert var.get() == "hmmm"
2319 var.set("hmmmm")
2320 n.start_soon(t2)
2321 await wait_all_tasks_blocked()
2322
2323
2324 def test_system_task_contexts() -> None:
2325 cvar: contextvars.ContextVar[str] = contextvars.ContextVar("qwilfish")
2326 cvar.set("water")
2327
2328 async def system_task() -> None:
2329 assert cvar.get() == "water"
2330
2331 async def regular_task() -> None:
2332 assert cvar.get() == "poison"
2333
2334 async def inner() -> None:
2335 async with _core.open_nursery() as nursery:
2336 cvar.set("poison")
2337 nursery.start_soon(regular_task)
2338 _core.spawn_system_task(system_task)
2339 await wait_all_tasks_blocked()
2340
2341 _core.run(inner)
2342
2343
2344 async def test_Nursery_init() -> None:
2345 """Test that nurseries cannot be constructed directly."""
2346 # This function is async so that we have access to a task object we can
2347 # pass in. It should never be accessed though.
2348 task = _core.current_task()
2349 scope = _core.CancelScope()
2350 with pytest.raises(TypeError):
2351 _core._run.Nursery(task, scope, True)
2352
2353
2354 async def test_Nursery_private_init() -> None:
2355 # context manager creation should not raise
2356 async with _core.open_nursery() as nursery:
2357 assert not nursery._closed
2358
2359
2360 def test_Nursery_subclass() -> None:
2361 with pytest.raises(TypeError):
2362 type("Subclass", (_core._run.Nursery,), {})
2363
2364
2365 def test_CancelScope_subclass() -> None:
2366 with pytest.raises(TypeError):
2367 type("Subclass", (_core.CancelScope,), {})
2368
2369
2370 def test_sniffio_integration() -> None:
2371 with pytest.raises(sniffio.AsyncLibraryNotFoundError):
2372 sniffio.current_async_library()
2373
2374 async def check_inside_trio() -> None:
2375 assert sniffio.current_async_library() == "trio"
2376
2377 def check_function_returning_coroutine() -> Awaitable[object]:
2378 assert sniffio.current_async_library() == "trio"
2379 return check_inside_trio()
2380
2381 _core.run(check_inside_trio)
2382
2383 with pytest.raises(sniffio.AsyncLibraryNotFoundError):
2384 sniffio.current_async_library()
2385
2386 @contextmanager
2387 def alternate_sniffio_library() -> Generator[None, None, None]:
2388 prev_token = sniffio.current_async_library_cvar.set("nullio")
2389 prev_library, sniffio.thread_local.name = sniffio.thread_local.name, "nullio"
2390 try:
2391 yield
2392 assert sniffio.current_async_library() == "nullio"
2393 finally:
2394 sniffio.thread_local.name = prev_library
2395 sniffio.current_async_library_cvar.reset(prev_token)
2396
2397 async def check_new_task_resets_sniffio_library() -> None:
2398 with alternate_sniffio_library():
2399 _core.spawn_system_task(check_inside_trio)
2400 async with _core.open_nursery() as nursery:
2401 with alternate_sniffio_library():
2402 nursery.start_soon(check_inside_trio)
2403 nursery.start_soon(check_function_returning_coroutine)
2404
2405 _core.run(check_new_task_resets_sniffio_library)
2406
2407
2408 async def test_Task_custom_sleep_data() -> None:
2409 task = _core.current_task()
2410 assert task.custom_sleep_data is None
2411 task.custom_sleep_data = 1
2412 assert task.custom_sleep_data == 1
2413 await _core.checkpoint()
2414 assert task.custom_sleep_data is None
2415
2416
2417 @types.coroutine
2418 def async_yield(value: T) -> Generator[T, None, None]:
2419 yield value
2420
2421
2422 async def test_permanently_detach_coroutine_object() -> None:
2423 task: _core.Task | None = None
2424 pdco_outcome: outcome.Outcome[str] | None = None
2425
2426 async def detachable_coroutine(
2427 task_outcome: outcome.Outcome[None],
2428 yield_value: object,
2429 ) -> None:
2430 await sleep(0)
2431 nonlocal task, pdco_outcome
2432 task = _core.current_task()
2433 # `No overload variant of "acapture" matches argument types "Callable[[Outcome[object]], Coroutine[Any, Any, object]]", "Outcome[None]"`
2434 pdco_outcome = await outcome.acapture( # type: ignore[call-overload]
2435 _core.permanently_detach_coroutine_object,
2436 task_outcome,
2437 )
2438 await async_yield(yield_value)
2439
2440 async with _core.open_nursery() as nursery:
2441 nursery.start_soon(detachable_coroutine, outcome.Value(None), "I'm free!")
2442
2443 # If we get here then Trio thinks the task has exited... but the coroutine
2444 # is still iterable. At that point anything can be sent into the coroutine, so the .coro type
2445 # is wrong.
2446 assert pdco_outcome is None
2447 # `Argument 1 to "send" of "Coroutine" has incompatible type "str"; expected "Outcome[object]"`
2448 assert not_none(task).coro.send("be free!") == "I'm free!" # type: ignore[arg-type]
2449 assert pdco_outcome == outcome.Value("be free!")
2450 with pytest.raises(StopIteration):
2451 not_none(task).coro.send(None) # type: ignore[arg-type]
2452
2453 # Check the exception paths too
2454 task = None
2455 pdco_outcome = None
2456 with pytest.RaisesGroup(KeyError):
2457 async with _core.open_nursery() as nursery:
2458 nursery.start_soon(detachable_coroutine, outcome.Error(KeyError()), "uh oh")
2459 throw_in = ValueError()
2460 assert isinstance(task, _core.Task) # For type checkers.
2461 assert not_none(task).coro.throw(throw_in) == "uh oh"
2462 assert pdco_outcome == outcome.Error(throw_in)
2463 with pytest.raises(StopIteration):
2464 task.coro.send(None)
2465
2466 async def bad_detach() -> None:
2467 async with _core.open_nursery():
2468 with pytest.raises(RuntimeError) as excinfo:
2469 await _core.permanently_detach_coroutine_object(outcome.Value(None))
2470 assert "open nurser" in str(excinfo.value)
2471
2472 async with _core.open_nursery() as nursery:
2473 nursery.start_soon(bad_detach)
2474
2475
2476 async def test_detach_and_reattach_coroutine_object() -> None:
2477 unrelated_task: _core.Task | None = None
2478 task: _core.Task | None = None
2479
2480 async def unrelated_coroutine() -> None:
2481 nonlocal unrelated_task
2482 unrelated_task = _core.current_task()
2483
2484 async def reattachable_coroutine() -> None:
2485 nonlocal task
2486 await sleep(0)
2487
2488 task = _core.current_task()
2489
2490 def abort_fn(_: _core.RaiseCancelT) -> _core.Abort: # pragma: no cover
2491 return _core.Abort.FAILED
2492
2493 got = await _core.temporarily_detach_coroutine_object(abort_fn)
2494 assert got == "not trio!"
2495
2496 await async_yield(1)
2497 await async_yield(2)
2498
2499 with pytest.raises(RuntimeError) as excinfo:
2500 await _core.reattach_detached_coroutine_object(
2501 not_none(unrelated_task),
2502 None,
2503 )
2504 assert "does not match" in str(excinfo.value)
2505
2506 await _core.reattach_detached_coroutine_object(task, "byebye")
2507
2508 await sleep(0)
2509
2510 async with _core.open_nursery() as nursery:
2511 nursery.start_soon(unrelated_coroutine)
2512 nursery.start_soon(reattachable_coroutine)
2513 await wait_all_tasks_blocked()
2514
2515 # Okay, it's detached. Here's our coroutine runner:
2516 # `Argument 1 to "send" of "Coroutine" has incompatible type "str"; expected "Outcome[object]"`
2517 assert not_none(task).coro.send("not trio!") == 1 # type: ignore[arg-type]
2518 assert not_none(task).coro.send(None) == 2 # type: ignore[arg-type]
2519 assert not_none(task).coro.send(None) == "byebye" # type: ignore[arg-type]
2520
2521 # Now it's been reattached, and we can leave the nursery
2522
2523
2524 async def test_detached_coroutine_cancellation() -> None:
2525 abort_fn_called = False
2526 task: _core.Task | None = None
2527
2528 async def reattachable_coroutine() -> None:
2529 await sleep(0)
2530
2531 nonlocal task
2532 task = _core.current_task()
2533
2534 def abort_fn(_: _core.RaiseCancelT) -> _core.Abort:
2535 nonlocal abort_fn_called
2536 abort_fn_called = True
2537 return _core.Abort.FAILED
2538
2539 await _core.temporarily_detach_coroutine_object(abort_fn)
2540 await _core.reattach_detached_coroutine_object(task, None)
2541 with pytest.raises(_core.Cancelled):
2542 await sleep(0)
2543
2544 async with _core.open_nursery() as nursery:
2545 nursery.start_soon(reattachable_coroutine)
2546 await wait_all_tasks_blocked()
2547 assert task is not None
2548 nursery.cancel_scope.cancel()
2549 # `Argument 1 to "send" of "Coroutine" has incompatible type "None"; expected "Outcome[object]"`
2550 task.coro.send(None) # type: ignore[arg-type]
2551
2552 assert abort_fn_called
2553
2554
2555 @restore_unraisablehook()
2556 def test_async_function_implemented_in_C() -> None:
2557 # These used to crash because we'd try to mutate the coroutine object's
2558 # cr_frame, but C functions don't have Python frames.
2559
2560 async def agen_fn(record: list[str]) -> AsyncIterator[None]:
2561 assert not _core.currently_ki_protected()
2562 record.append("the generator ran")
2563 yield
2564
2565 run_record: list[str] = []
2566 agen = agen_fn(run_record)
2567 _core.run(agen.__anext__)
2568 assert run_record == ["the generator ran"]
2569
2570 async def main() -> None:
2571 start_soon_record: list[str] = []
2572 agen = agen_fn(start_soon_record)
2573 async with _core.open_nursery() as nursery:
2574 nursery.start_soon(agen.__anext__)
2575 assert start_soon_record == ["the generator ran"]
2576
2577 _core.run(main)
2578
2579
2580 async def test_very_deep_cancel_scope_nesting() -> None:
2581 # This used to crash with a RecursionError in CancelStatus.recalculate
2582 with ExitStack() as exit_stack:
2583 outermost_scope = _core.CancelScope()
2584 exit_stack.enter_context(outermost_scope)
2585 for _ in range(5000):
2586 exit_stack.enter_context(_core.CancelScope())
2587 outermost_scope.cancel()
2588
2589
2590 async def test_cancel_scope_deadline_duplicates() -> None:
2591 # This exercises an assert in Deadlines._prune, by intentionally creating
2592 # duplicate entries in the deadline heap.
2593 now = _core.current_time()
2594 with _core.CancelScope() as cscope:
2595 for _ in range(DEADLINE_HEAP_MIN_PRUNE_THRESHOLD * 2):
2596 cscope.deadline = now + 9998
2597 cscope.deadline = now + 9999
2598 await sleep(0.01)
2599
2600
2601 # I don't know if this one can fail anymore, the `del` next to the comment that used to
2602 # refer to this only seems to break test_cancel_scope_exit_doesnt_create_cyclic_garbage
2603 # We're keeping it for now to cover Outcome and potential future refactoring
2604 @pytest.mark.skipif(
2605 sys.implementation.name != "cpython",
2606 reason="Only makes sense with refcounting GC",
2607 )
2608 async def test_simple_cancel_scope_usage_doesnt_create_cyclic_garbage() -> None:
2609 # https://github.com/python-trio/trio/issues/1770
2610 gc.collect()
2611
2612 async def do_a_cancel() -> None:
2613 with _core.CancelScope() as cscope:
2614 cscope.cancel()
2615 await sleep_forever()
2616
2617 async def crasher() -> NoReturn:
2618 raise ValueError("this is a crash")
2619
2620 old_flags = gc.get_debug()
2621 try:
2622 gc.collect()
2623 gc.set_debug(gc.DEBUG_SAVEALL)
2624
2625 # cover outcome.Error.unwrap
2626 # (See https://github.com/python-trio/outcome/pull/29)
2627 await do_a_cancel()
2628 # cover outcome.Error.unwrap if unrolled_run hangs on to exception refs
2629 # (See https://github.com/python-trio/trio/pull/1864)
2630 await do_a_cancel()
2631
2632 with pytest.RaisesGroup(
2633 pytest.RaisesExc(ValueError, match="^this is a crash$")
2634 ):
2635 async with _core.open_nursery() as nursery:
2636 # cover NurseryManager.__aexit__
2637 nursery.start_soon(crasher)
2638
2639 gc.collect()
2640 assert not gc.garbage
2641 finally:
2642 gc.set_debug(old_flags)
2643 gc.garbage.clear()
2644
2645
2646 @pytest.mark.skipif(
2647 sys.implementation.name != "cpython",
2648 reason="Only makes sense with refcounting GC",
2649 )
2650 async def test_cancel_scope_exit_doesnt_create_cyclic_garbage() -> None:
2651 # https://github.com/python-trio/trio/pull/2063
2652 gc.collect()
2653
2654 async def crasher() -> NoReturn:
2655 raise ValueError("this is a crash")
2656
2657 old_flags = gc.get_debug()
2658 try:
2659 with (
2660 pytest.RaisesGroup(
2661 pytest.RaisesExc(ValueError, match="^this is a crash$"),
2662 ),
2663 _core.CancelScope() as outer,
2664 ):
2665 async with _core.open_nursery() as nursery:
2666 gc.collect()
2667 gc.set_debug(gc.DEBUG_SAVEALL)
2668 # One child that gets cancelled by the outer scope
2669 nursery.start_soon(sleep_forever)
2670 outer.cancel()
2671 # And one that raises a different error
2672 nursery.start_soon(crasher)
2673 # so that outer filters a Cancelled from the ExceptionGroup and
2674 # covers CancelScope.__exit__ (and NurseryManager.__aexit__)
2675 # (See https://github.com/python-trio/trio/pull/2063)
2676
2677 gc.collect()
2678 assert not gc.garbage
2679 finally:
2680 gc.set_debug(old_flags)
2681 gc.garbage.clear()
2682
2683
2684 @pytest.mark.skipif(
2685 sys.implementation.name != "cpython",
2686 reason="Only makes sense with refcounting GC",
2687 )
2688 async def test_nursery_cancel_doesnt_create_cyclic_garbage() -> None:
2689 collected = False
2690
2691 # https://github.com/python-trio/trio/issues/1770#issuecomment-730229423
2692 def toggle_collected() -> None:
2693 nonlocal collected
2694 collected = True
2695
2696 gc.collect()
2697 old_flags = gc.get_debug()
2698 try:
2699 gc.set_debug(0)
2700 gc.collect()
2701 gc.set_debug(gc.DEBUG_SAVEALL)
2702
2703 # cover Nursery._nested_child_finished
2704 async with _core.open_nursery() as nursery:
2705 nursery.cancel_scope.cancel()
2706
2707 weakref.finalize(nursery, toggle_collected)
2708 del nursery
2709 # a checkpoint clears the nursery from the internals, apparently
2710 # TODO: stop event loop from hanging on to the nursery at this point
2711 await _core.checkpoint()
2712
2713 assert collected
2714 gc.collect()
2715 assert not gc.garbage
2716 finally:
2717 gc.set_debug(old_flags)
2718 gc.garbage.clear()
2719
2720
2721 @pytest.mark.skipif(
2722 sys.implementation.name != "cpython",
2723 reason="Only makes sense with refcounting GC",
2724 )
2725 async def test_locals_destroyed_promptly_on_cancel() -> None:
2726 destroyed = False
2727
2728 def finalizer() -> None:
2729 nonlocal destroyed
2730 destroyed = True
2731
2732 class A:
2733 pass
2734
2735 async def task() -> None:
2736 a = A()
2737 weakref.finalize(a, finalizer)
2738 await _core.checkpoint()
2739
2740 async with _core.open_nursery() as nursery:
2741 nursery.start_soon(task)
2742 nursery.cancel_scope.cancel()
2743 assert destroyed
2744
2745
2746 def _create_kwargs(strictness: bool | None) -> dict[str, bool]:
2747 """Turn a bool|None into a kwarg dict that can be passed to `run` or `open_nursery`"""
2748
2749 if strictness is None:
2750 return {}
2751 return {"strict_exception_groups": strictness}
2752
2753
2754 @pytest.mark.filterwarnings(
2755 "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning",
2756 )
2757 @pytest.mark.parametrize("run_strict", [True, False, None])
2758 @pytest.mark.parametrize("open_nursery_strict", [True, False, None])
2759 @pytest.mark.parametrize("multiple_exceptions", [True, False])
2760 def test_setting_strict_exception_groups(
2761 run_strict: bool | None,
2762 open_nursery_strict: bool | None,
2763 multiple_exceptions: bool,
2764 ) -> None:
2765 """
2766 Test default values and that nurseries can both inherit and override the global context
2767 setting of strict_exception_groups.
2768 """
2769
2770 async def raise_error() -> NoReturn:
2771 raise RuntimeError("test error")
2772
2773 async def main() -> None:
2774 """Open a nursery, and raise one or two errors inside"""
2775 async with _core.open_nursery(**_create_kwargs(open_nursery_strict)) as nursery:
2776 nursery.start_soon(raise_error)
2777 if multiple_exceptions:
2778 nursery.start_soon(raise_error)
2779
2780 def run_main() -> None:
2781 # mypy doesn't like kwarg magic
2782 _core.run(main, **_create_kwargs(run_strict)) # type: ignore[arg-type]
2783
2784 matcher = pytest.RaisesExc(RuntimeError, match=r"^test error$")
2785
2786 if multiple_exceptions:
2787 with pytest.RaisesGroup(matcher, matcher):
2788 run_main()
2789 elif open_nursery_strict or (
2790 open_nursery_strict is None and run_strict is not False
2791 ):
2792 with pytest.RaisesGroup(matcher):
2793 run_main()
2794 else:
2795 with pytest.raises(RuntimeError, match=r"^test error$"):
2796 run_main()
2797
2798
2799 @pytest.mark.filterwarnings(
2800 "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning",
2801 )
2802 @pytest.mark.parametrize("strict", [True, False, None])
2803 async def test_nursery_collapse(strict: bool | None) -> None:
2804 """
2805 Test that a single exception from a nested nursery gets collapsed correctly
2806 depending on strict_exception_groups value when CancelledErrors are stripped from it.
2807 """
2808
2809 async def raise_error() -> NoReturn:
2810 raise RuntimeError("test error")
2811
2812 # mypy requires explicit type for conditional expression
2813 maybe_wrapped_runtime_error: (
2814 type[RuntimeError] | pytest.RaisesGroup[RuntimeError]
2815 ) = (RuntimeError if strict is False else pytest.RaisesGroup(RuntimeError))
2816
2817 with pytest.RaisesGroup(RuntimeError, maybe_wrapped_runtime_error):
2818 async with _core.open_nursery() as nursery:
2819 nursery.start_soon(sleep_forever)
2820 nursery.start_soon(raise_error)
2821 async with _core.open_nursery(**_create_kwargs(strict)) as nursery2:
2822 nursery2.start_soon(sleep_forever)
2823 nursery2.start_soon(raise_error)
2824 nursery.cancel_scope.cancel()
2825
2826
2827 async def test_cancel_scope_no_cancellederror() -> None:
2828 """
2829 Test that when a cancel scope encounters an exception group that does NOT contain
2830 a Cancelled exception, it will NOT set the ``cancelled_caught`` flag.
2831 """
2832
2833 with pytest.RaisesGroup(RuntimeError, RuntimeError, match="test"):
2834 with _core.CancelScope() as scope:
2835 scope.cancel()
2836 raise ExceptionGroup("test", [RuntimeError(), RuntimeError()])
2837
2838 assert not scope.cancelled_caught
2839
2840
2841 @pytest.mark.filterwarnings(
2842 "ignore:.*strict_exception_groups=False:trio.TrioDeprecationWarning",
2843 )
2844 @pytest.mark.parametrize("run_strict", [False, True])
2845 @pytest.mark.parametrize("start_raiser_strict", [False, True, None])
2846 @pytest.mark.parametrize("raise_after_started", [False, True])
2847 @pytest.mark.parametrize("raise_custom_exc_grp", [False, True])
2848 def test_trio_run_strict_before_started(
2849 run_strict: bool,
2850 start_raiser_strict: bool | None,
2851 raise_after_started: bool,
2852 raise_custom_exc_grp: bool,
2853 ) -> None:
2854 """
2855 Regression tests for #2611, where exceptions raised before
2856 `TaskStatus.started()` caused `Nursery.start()` to wrap them in an
2857 ExceptionGroup when using `run(..., strict_exception_groups=True)`.
2858
2859 Regression tests for #2844, where #2611 was initially fixed in a way that
2860 had unintended side effects.
2861 """
2862
2863 raiser_exc: ValueError | ExceptionGroup[ValueError]
2864 if raise_custom_exc_grp:
2865 raiser_exc = ExceptionGroup("my group", [ValueError()])
2866 else:
2867 raiser_exc = ValueError()
2868
2869 async def raiser(*, task_status: _core.TaskStatus[None]) -> None:
2870 if raise_after_started:
2871 task_status.started()
2872 raise raiser_exc
2873
2874 async def start_raiser() -> None:
2875 try:
2876 async with _core.open_nursery(
2877 strict_exception_groups=start_raiser_strict,
2878 ) as nursery:
2879 await nursery.start(raiser)
2880 except BaseExceptionGroup as exc_group:
2881 if start_raiser_strict:
2882 # Iff the code using the nursery *forced* it to be strict
2883 # (overriding the runner setting) then it may replace the bland
2884 # exception group raised by trio with a more specific one (subtype,
2885 # different message, etc.).
2886 raise BaseExceptionGroup(
2887 "start_raiser nursery custom message",
2888 exc_group.exceptions,
2889 ) from None
2890 raise
2891
2892 with pytest.raises(BaseException) as exc_info: # noqa: PT011 # no `match`
2893 _core.run(start_raiser, strict_exception_groups=run_strict)
2894
2895 if start_raiser_strict or (run_strict and start_raiser_strict is None):
2896 # start_raiser's nursery was strict.
2897 assert isinstance(exc_info.value, BaseExceptionGroup)
2898 if start_raiser_strict:
2899 # start_raiser didn't unknowingly inherit its nursery strictness
2900 # from `run`---it explicitly chose for its nursery to be strict.
2901 assert exc_info.value.message == "start_raiser nursery custom message"
2902 assert len(exc_info.value.exceptions) == 1
2903 should_be_raiser_exc = exc_info.value.exceptions[0]
2904 else:
2905 # start_raiser's nursery was not strict.
2906 should_be_raiser_exc = exc_info.value
2907 if isinstance(raiser_exc, ValueError):
2908 assert should_be_raiser_exc is raiser_exc
2909 else:
2910 # Check attributes, not identity, because should_be_raiser_exc may be a
2911 # copy of raiser_exc rather than raiser_exc by identity.
2912 assert type(should_be_raiser_exc) is type(raiser_exc)
2913 assert should_be_raiser_exc.message == raiser_exc.message
2914 assert should_be_raiser_exc.exceptions == raiser_exc.exceptions
2915
2916
2917 async def test_start_exception_preserves_cause_and_context() -> None:
2918 """Regression test for #3261: exceptions raised before task_status.started()
2919 should preserve __cause__ and __context__."""
2920
2921 async def task(*, task_status: _core.TaskStatus[None]) -> None:
2922 e = ValueError("foo")
2923 e.__cause__ = SyntaxError("bar")
2924 e.__context__ = TypeError("baz")
2925 raise e
2926
2927 with pytest.RaisesGroup(
2928 pytest.RaisesExc(
2929 ValueError,
2930 check=lambda exc: isinstance(exc.__cause__, SyntaxError)
2931 and isinstance(exc.__context__, TypeError),
2932 ),
2933 ):
2934 async with _core.open_nursery() as nursery:
2935 await nursery.start(task)
2936
2937
2938 async def test_internal_error_old_nursery_multiple_tasks() -> None:
2939 async def error_func() -> None:
2940 raise ValueError
2941
2942 async def spawn_tasks_in_old_nursery(task_status: _core.TaskStatus[None]) -> None:
2943 old_nursery = _core.current_task().parent_nursery
2944 assert old_nursery is not None
2945 old_nursery.start_soon(error_func)
2946 old_nursery.start_soon(error_func)
2947
2948 async with _core.open_nursery() as nursery:
2949 with pytest.raises(_core.TrioInternalError) as excinfo:
2950 await nursery.start(spawn_tasks_in_old_nursery)
2951 assert pytest.RaisesGroup(ValueError, ValueError).matches(excinfo.value.__cause__)
2952
2953
2954 if sys.version_info >= (3, 11):
2955
2956 def no_other_refs() -> list[object]:
2957 return []
2958
2959 else:
2960
2961 def no_other_refs() -> list[object]:
2962 return [sys._getframe(1)]
2963
2964
2965 @pytest.mark.skipif(
2966 sys.implementation.name != "cpython",
2967 reason="Only makes sense with refcounting GC",
2968 )
2969 @pytest.mark.xfail(
2970 sys.version_info >= (3, 14),
2971 reason="https://github.com/python/cpython/issues/125603",
2972 )
2973 async def test_ki_protection_doesnt_leave_cyclic_garbage() -> None:
2974 class MyException(Exception):
2975 pass
2976
2977 async def demo() -> None:
2978 async def handle_error() -> None:
2979 try:
2980 raise MyException
2981 except MyException as e:
2982 exceptions.append(e)
2983
2984 exceptions: list[MyException] = []
2985 try:
2986 async with _core.open_nursery() as n:
2987 n.start_soon(handle_error)
2988 raise ExceptionGroup("errors", exceptions)
2989 finally:
2990 exceptions = []
2991
2992 exc: Exception | None = None
2993 try:
2994 await demo()
2995 except ExceptionGroup as excs:
2996 exc = excs.exceptions[0]
2997
2998 assert isinstance(exc, MyException)
2999 assert gc.get_referrers(exc) == no_other_refs()
3000
3001
3002 def test_context_run_tb_frames() -> None:
3003 class Context:
3004 def run(self, fn: Callable[[], object]) -> object:
3005 return fn()
3006
3007 with mock.patch("trio._core._run.copy_context", return_value=Context()):
3008 assert _count_context_run_tb_frames() == 1
3009
3010
3011 @restore_unraisablehook()
3012 def test_trio_context_detection() -> None:
3013 assert not _core.in_trio_run()
3014 assert not _core.in_trio_task()
3015
3016 def inner() -> None:
3017 assert _core.in_trio_run()
3018 assert _core.in_trio_task()
3019
3020 def sync_inner() -> None:
3021 assert not _core.in_trio_run()
3022 assert not _core.in_trio_task()
3023
3024 def inner_abort(_: object) -> _core.Abort:
3025 assert _core.in_trio_run()
3026 assert _core.in_trio_task()
3027 return _core.Abort.SUCCEEDED
3028
3029 async def main() -> None:
3030 assert _core.in_trio_run()
3031 assert _core.in_trio_task()
3032
3033 inner()
3034
3035 await to_thread_run_sync(sync_inner)
3036 with _core.CancelScope(deadline=_core.current_time() - 1):
3037 await _core.wait_task_rescheduled(inner_abort)
3038
3039 _core.run(main)