Debian Codegraph @

src/trio/_tests/test_channel.py

raw
1 from __future__ import annotations
2
3 import sys
4 from typing import TYPE_CHECKING
5
6 import pytest
7
8 import trio
9 from trio import EndOfChannel, as_safe_channel, open_memory_channel
10
11 from ..testing import assert_checkpoints, wait_all_tasks_blocked
12
13 if sys.version_info < (3, 11):
14 from exceptiongroup import ExceptionGroup
15
16 if TYPE_CHECKING:
17 from collections.abc import AsyncGenerator
18
19
20 async def test_channel() -> None:
21 with pytest.raises(TypeError):
22 open_memory_channel(1.0)
23 with pytest.raises(ValueError, match=r"^max_buffer_size must be >= 0$"):
24 open_memory_channel(-1)
25
26 s, r = open_memory_channel[int | str | None](2)
27 repr(s) # smoke test
28 repr(r) # smoke test
29
30 s.send_nowait(1)
31 with assert_checkpoints():
32 await s.send(2)
33 with pytest.raises(trio.WouldBlock):
34 s.send_nowait(None)
35
36 with assert_checkpoints():
37 assert await r.receive() == 1
38 assert r.receive_nowait() == 2
39 with pytest.raises(trio.WouldBlock):
40 r.receive_nowait()
41
42 s.send_nowait("last")
43 await s.aclose()
44 with pytest.raises(trio.ClosedResourceError):
45 await s.send("too late")
46 with pytest.raises(trio.ClosedResourceError):
47 s.send_nowait("too late")
48 with pytest.raises(trio.ClosedResourceError):
49 s.clone()
50 await s.aclose()
51
52 assert r.receive_nowait() == "last"
53 with pytest.raises(EndOfChannel):
54 await r.receive()
55 await r.aclose()
56 with pytest.raises(trio.ClosedResourceError):
57 await r.receive()
58 with pytest.raises(trio.ClosedResourceError):
59 r.receive_nowait()
60 await r.aclose()
61
62
63 async def test_553(autojump_clock: trio.abc.Clock) -> None:
64 s, r = open_memory_channel[str](1)
65 with trio.move_on_after(10) as timeout_scope:
66 await r.receive()
67 assert timeout_scope.cancelled_caught
68 await s.send("Test for PR #553")
69
70
71 async def test_channel_multiple_producers() -> None:
72 async def producer(send_channel: trio.MemorySendChannel[int], i: int) -> None:
73 # We close our handle when we're done with it
74 async with send_channel:
75 for j in range(3 * i, 3 * (i + 1)):
76 await send_channel.send(j)
77
78 send_channel, receive_channel = open_memory_channel[int](0)
79 async with trio.open_nursery() as nursery:
80 # We hand out clones to all the new producers, and then close the
81 # original.
82 async with send_channel:
83 for i in range(10):
84 nursery.start_soon(producer, send_channel.clone(), i)
85
86 got = [value async for value in receive_channel]
87
88 got.sort()
89 assert got == list(range(30))
90
91
92 async def test_channel_multiple_consumers() -> None:
93 successful_receivers = set()
94 received = []
95
96 async def consumer(receive_channel: trio.MemoryReceiveChannel[int], i: int) -> None:
97 async for value in receive_channel:
98 successful_receivers.add(i)
99 received.append(value)
100
101 async with trio.open_nursery() as nursery:
102 send_channel, receive_channel = trio.open_memory_channel[int](1)
103 async with send_channel:
104 for i in range(5):
105 nursery.start_soon(consumer, receive_channel, i)
106 await wait_all_tasks_blocked()
107 for i in range(10):
108 await send_channel.send(i)
109
110 assert successful_receivers == set(range(5))
111 assert len(received) == 10
112 assert set(received) == set(range(10))
113
114
115 async def test_close_basics() -> None:
116 async def send_block(
117 s: trio.MemorySendChannel[None],
118 expect: type[BaseException],
119 ) -> None:
120 with pytest.raises(expect):
121 await s.send(None)
122
123 # closing send -> other send gets ClosedResourceError
124 s, r = open_memory_channel[None](0)
125 async with trio.open_nursery() as nursery:
126 nursery.start_soon(send_block, s, trio.ClosedResourceError)
127 await wait_all_tasks_blocked()
128 await s.aclose()
129
130 # and it's persistent
131 with pytest.raises(trio.ClosedResourceError):
132 s.send_nowait(None)
133 with pytest.raises(trio.ClosedResourceError):
134 await s.send(None)
135
136 # and receive gets EndOfChannel
137 with pytest.raises(EndOfChannel):
138 r.receive_nowait()
139 with pytest.raises(EndOfChannel):
140 await r.receive()
141
142 # closing receive -> send gets BrokenResourceError
143 s, r = open_memory_channel[None](0)
144 async with trio.open_nursery() as nursery:
145 nursery.start_soon(send_block, s, trio.BrokenResourceError)
146 await wait_all_tasks_blocked()
147 await r.aclose()
148
149 # and it's persistent
150 with pytest.raises(trio.BrokenResourceError):
151 s.send_nowait(None)
152 with pytest.raises(trio.BrokenResourceError):
153 await s.send(None)
154
155 # closing receive -> other receive gets ClosedResourceError
156 async def receive_block(r: trio.MemoryReceiveChannel[int]) -> None:
157 with pytest.raises(trio.ClosedResourceError):
158 await r.receive()
159
160 _s2, r2 = open_memory_channel[int](0)
161 async with trio.open_nursery() as nursery:
162 nursery.start_soon(receive_block, r2)
163 await wait_all_tasks_blocked()
164 await r2.aclose()
165
166 # and it's persistent
167 with pytest.raises(trio.ClosedResourceError):
168 r2.receive_nowait()
169 with pytest.raises(trio.ClosedResourceError):
170 await r2.receive()
171
172
173 async def test_close_sync() -> None:
174 async def send_block(
175 s: trio.MemorySendChannel[None],
176 expect: type[BaseException],
177 ) -> None:
178 with pytest.raises(expect):
179 await s.send(None)
180
181 # closing send -> other send gets ClosedResourceError
182 s, r = open_memory_channel[None](0)
183 async with trio.open_nursery() as nursery:
184 nursery.start_soon(send_block, s, trio.ClosedResourceError)
185 await wait_all_tasks_blocked()
186 s.close()
187
188 # and it's persistent
189 with pytest.raises(trio.ClosedResourceError):
190 s.send_nowait(None)
191 with pytest.raises(trio.ClosedResourceError):
192 await s.send(None)
193
194 # and receive gets EndOfChannel
195 with pytest.raises(EndOfChannel):
196 r.receive_nowait()
197 with pytest.raises(EndOfChannel):
198 await r.receive()
199
200 # closing receive -> send gets BrokenResourceError
201 s, r = open_memory_channel[None](0)
202 async with trio.open_nursery() as nursery:
203 nursery.start_soon(send_block, s, trio.BrokenResourceError)
204 await wait_all_tasks_blocked()
205 r.close()
206
207 # and it's persistent
208 with pytest.raises(trio.BrokenResourceError):
209 s.send_nowait(None)
210 with pytest.raises(trio.BrokenResourceError):
211 await s.send(None)
212
213 # closing receive -> other receive gets ClosedResourceError
214 async def receive_block(r: trio.MemoryReceiveChannel[None]) -> None:
215 with pytest.raises(trio.ClosedResourceError):
216 await r.receive()
217
218 s, r = open_memory_channel[None](0)
219 async with trio.open_nursery() as nursery:
220 nursery.start_soon(receive_block, r)
221 await wait_all_tasks_blocked()
222 r.close()
223
224 # and it's persistent
225 with pytest.raises(trio.ClosedResourceError):
226 r.receive_nowait()
227 with pytest.raises(trio.ClosedResourceError):
228 await r.receive()
229
230
231 async def test_receive_channel_clone_and_close() -> None:
232 s, r = open_memory_channel[None](10)
233
234 r2 = r.clone()
235 r3 = r.clone()
236
237 s.send_nowait(None)
238 await r.aclose()
239 with r2:
240 pass
241
242 with pytest.raises(trio.ClosedResourceError):
243 r.clone()
244
245 with pytest.raises(trio.ClosedResourceError):
246 r2.clone()
247
248 # Can still send, r3 is still open
249 s.send_nowait(None)
250
251 await r3.aclose()
252
253 # But now the receiver is really closed
254 with pytest.raises(trio.BrokenResourceError):
255 s.send_nowait(None)
256
257
258 async def test_close_multiple_send_handles() -> None:
259 # With multiple send handles, closing one handle only wakes senders on
260 # that handle, but others can continue just fine
261 s1, r = open_memory_channel[str](0)
262 s2 = s1.clone()
263
264 async def send_will_close() -> None:
265 with pytest.raises(trio.ClosedResourceError):
266 await s1.send("nope")
267
268 async def send_will_succeed() -> None:
269 await s2.send("ok")
270
271 async with trio.open_nursery() as nursery:
272 nursery.start_soon(send_will_close)
273 nursery.start_soon(send_will_succeed)
274 await wait_all_tasks_blocked()
275 await s1.aclose()
276 assert await r.receive() == "ok"
277
278
279 async def test_close_multiple_receive_handles() -> None:
280 # With multiple receive handles, closing one handle only wakes receivers on
281 # that handle, but others can continue just fine
282 s, r1 = open_memory_channel[str](0)
283 r2 = r1.clone()
284
285 async def receive_will_close() -> None:
286 with pytest.raises(trio.ClosedResourceError):
287 await r1.receive()
288
289 async def receive_will_succeed() -> None:
290 assert await r2.receive() == "ok"
291
292 async with trio.open_nursery() as nursery:
293 nursery.start_soon(receive_will_close)
294 nursery.start_soon(receive_will_succeed)
295 await wait_all_tasks_blocked()
296 await r1.aclose()
297 await s.send("ok")
298
299
300 async def test_inf_capacity() -> None:
301 send, receive = open_memory_channel[int](float("inf"))
302
303 # It's accepted, and we can send all day without blocking
304 with send:
305 for i in range(10):
306 send.send_nowait(i)
307
308 got = [i async for i in receive]
309 assert got == list(range(10))
310
311
312 async def test_statistics() -> None:
313 s, r = open_memory_channel[None](2)
314
315 assert s.statistics() == r.statistics()
316 stats = s.statistics()
317 assert stats.current_buffer_used == 0
318 assert stats.max_buffer_size == 2
319 assert stats.open_send_channels == 1
320 assert stats.open_receive_channels == 1
321 assert stats.tasks_waiting_send == 0
322 assert stats.tasks_waiting_receive == 0
323 assert stats.peak_buffer_used == 0
324
325 s.send_nowait(None)
326 assert s.statistics().current_buffer_used == 1
327 assert s.statistics().peak_buffer_used == 1
328
329 s2 = s.clone()
330 assert s.statistics().open_send_channels == 2
331 await s.aclose()
332 assert s2.statistics().open_send_channels == 1
333
334 r2 = r.clone()
335 assert s2.statistics().open_receive_channels == 2
336 await r2.aclose()
337 assert s2.statistics().open_receive_channels == 1
338
339 async with trio.open_nursery() as nursery:
340 s2.send_nowait(None) # fill up the buffer
341 assert s.statistics().current_buffer_used == 2
342 assert s.statistics().peak_buffer_used == 2
343 nursery.start_soon(s2.send, None)
344 nursery.start_soon(s2.send, None)
345 await wait_all_tasks_blocked()
346 assert s.statistics().tasks_waiting_send == 2
347 nursery.cancel_scope.cancel()
348 assert s.statistics().tasks_waiting_send == 0
349
350 # empty out the buffer again
351 try:
352 while True:
353 r.receive_nowait()
354 except trio.WouldBlock:
355 pass
356
357 # draining the buffer doesn't reset the high-water mark
358 assert s.statistics().current_buffer_used == 0
359 assert s.statistics().peak_buffer_used == 2
360
361 async with trio.open_nursery() as nursery:
362 nursery.start_soon(r.receive)
363 await wait_all_tasks_blocked()
364 assert s.statistics().tasks_waiting_receive == 1
365 nursery.cancel_scope.cancel()
366 assert s.statistics().tasks_waiting_receive == 0
367
368
369 async def test_channel_fairness() -> None:
370 # We can remove an item we just sent, and send an item back in after, if
371 # no-one else is waiting.
372 s, r = open_memory_channel[int | None](1)
373 s.send_nowait(1)
374 assert r.receive_nowait() == 1
375 s.send_nowait(2)
376 assert r.receive_nowait() == 2
377
378 # But if someone else is waiting to receive, then they "own" the item we
379 # send, so we can't receive it (even though we run first):
380
381 result: int | None = None
382
383 async def do_receive(r: trio.MemoryReceiveChannel[int | None]) -> None:
384 nonlocal result
385 result = await r.receive()
386
387 async with trio.open_nursery() as nursery:
388 nursery.start_soon(do_receive, r)
389 await wait_all_tasks_blocked()
390 s.send_nowait(2)
391 with pytest.raises(trio.WouldBlock):
392 r.receive_nowait()
393 assert result == 2
394
395 # And the analogous situation for send: if we free up a space, we can't
396 # immediately send something in it if someone is already waiting to do
397 # that
398 s, r = open_memory_channel[int | None](1)
399 s.send_nowait(1)
400 with pytest.raises(trio.WouldBlock):
401 s.send_nowait(None)
402 async with trio.open_nursery() as nursery:
403 nursery.start_soon(s.send, 2)
404 await wait_all_tasks_blocked()
405 assert r.receive_nowait() == 1
406 with pytest.raises(trio.WouldBlock):
407 s.send_nowait(3)
408 assert (await r.receive()) == 2
409
410
411 async def test_unbuffered() -> None:
412 s, r = open_memory_channel[int](0)
413 with pytest.raises(trio.WouldBlock):
414 r.receive_nowait()
415 with pytest.raises(trio.WouldBlock):
416 s.send_nowait(1)
417
418 async def do_send(s: trio.MemorySendChannel[int], v: int) -> None:
419 with assert_checkpoints():
420 await s.send(v)
421
422 async with trio.open_nursery() as nursery:
423 nursery.start_soon(do_send, s, 1)
424 with assert_checkpoints():
425 assert await r.receive() == 1
426 with pytest.raises(trio.WouldBlock):
427 r.receive_nowait()
428
429
430 async def test_as_safe_channel_exhaust() -> None:
431 @as_safe_channel
432 async def agen() -> AsyncGenerator[int]:
433 yield 1
434
435 async with agen() as recv_chan:
436 async for x in recv_chan:
437 assert x == 1
438
439
440 async def test_as_safe_channel_broken_resource() -> None:
441 @as_safe_channel
442 async def agen() -> AsyncGenerator[int]:
443 yield 1
444 yield 2 # pragma: no cover
445
446 async with agen() as recv_chan:
447 assert await recv_chan.__anext__() == 1
448
449 # close the receiving channel
450 await recv_chan.aclose()
451
452 # trying to get the next element errors
453 with pytest.raises(trio.ClosedResourceError):
454 await recv_chan.__anext__()
455
456 # but we don't get an error on exit of the cm
457
458
459 async def test_as_safe_channel_cancelled() -> None:
460 with trio.CancelScope() as cs:
461
462 @as_safe_channel
463 async def agen() -> AsyncGenerator[None]: # pragma: no cover
464 raise AssertionError(
465 "cancel before consumption means generator should not be iterated"
466 )
467 yield # indicate that we're an iterator
468
469 async with agen():
470 cs.cancel()
471
472
473 async def test_as_safe_channel_no_race() -> None:
474 # this previously led to a race condition due to
475 # https://github.com/python-trio/trio/issues/1559
476 @as_safe_channel
477 async def agen() -> AsyncGenerator[int]:
478 yield 1
479 raise ValueError("oae")
480
481 with pytest.raises(ValueError, match=r"^oae$"):
482 async with agen() as recv_chan:
483 async for x in recv_chan:
484 assert x == 1
485
486
487 async def test_as_safe_channel_buffer_size_too_small(
488 autojump_clock: trio.testing.MockClock,
489 ) -> None:
490 @as_safe_channel
491 async def agen() -> AsyncGenerator[int]:
492 yield 1
493 raise AssertionError(
494 "buffer size 0 means we shouldn't be asked for another value"
495 ) # pragma: no cover
496
497 with trio.move_on_after(5):
498 async with agen() as recv_chan:
499 async for x in recv_chan: # pragma: no branch
500 assert x == 1
501 await trio.sleep_forever()
502
503
504 async def test_as_safe_channel_no_interleave() -> None:
505 @as_safe_channel
506 async def agen() -> AsyncGenerator[int]:
507 yield 1
508 raise AssertionError # pragma: no cover
509
510 async with agen() as recv_chan:
511 assert await recv_chan.__anext__() == 1
512 await trio.lowlevel.checkpoint()
513
514
515 async def test_as_safe_channel_genexit_finally() -> None:
516 @as_safe_channel
517 async def agen(events: list[str]) -> AsyncGenerator[int]:
518 try:
519 yield 1
520 except BaseException as e:
521 events.append(repr(e))
522 raise
523 finally:
524 events.append("finally")
525 raise ValueError("agen")
526
527 events: list[str] = []
528 with pytest.RaisesGroup(
529 pytest.RaisesExc(ValueError, match="^agen$"),
530 pytest.RaisesExc(TypeError, match="^iterator$"),
531 ) as g:
532 async with agen(events) as recv_chan:
533 async for i in recv_chan: # pragma: no branch
534 assert i == 1
535 raise TypeError("iterator")
536
537 if sys.version_info >= (3, 11):
538 assert g.value.__notes__ == [
539 "Encountered exception during cleanup of generator object, as "
540 "well as exception in the contextmanager body - unable to unwrap."
541 ]
542
543 assert events == ["GeneratorExit()", "finally"]
544
545
546 async def test_as_safe_channel_nested_loop() -> None:
547 @as_safe_channel
548 async def agen() -> AsyncGenerator[int]:
549 for i in range(2):
550 yield i
551
552 ii = 0
553 async with agen() as recv_chan1:
554 async for i in recv_chan1:
555 async with agen() as recv_chan:
556 jj = 0
557 async for j in recv_chan:
558 assert (i, j) == (ii, jj)
559 jj += 1
560 ii += 1
561
562
563 async def test_as_safe_channel_doesnt_leak_cancellation() -> None:
564 @as_safe_channel
565 async def agen() -> AsyncGenerator[None]:
566 yield
567 with trio.CancelScope() as cscope:
568 cscope.cancel()
569 yield
570
571 with pytest.raises(AssertionError):
572 async with agen() as recv_chan:
573 async for _ in recv_chan:
574 pass
575 raise AssertionError("should be reachable")
576
577
578 async def test_as_safe_channel_dont_unwrap_user_exceptiongroup() -> None:
579 @as_safe_channel
580 async def agen() -> AsyncGenerator[None]:
581 raise NotImplementedError("not entered")
582 yield # pragma: no cover
583
584 with pytest.RaisesGroup(pytest.RaisesExc(ValueError, match="bar"), match="foo"):
585 async with agen() as _:
586 raise ExceptionGroup("foo", [ValueError("bar")])
587
588
589 async def test_as_safe_channel_multiple_receiver() -> None:
590 event = trio.Event()
591
592 @as_safe_channel
593 async def agen() -> AsyncGenerator[int]:
594 await event.wait()
595 yield 0
596 yield 1
597
598 async def handle_value(
599 recv_chan: trio.abc.ReceiveChannel[int],
600 value: int,
601 task_status: trio.TaskStatus,
602 ) -> None:
603 task_status.started()
604 assert await recv_chan.receive() == value
605
606 async with agen() as recv_chan:
607 async with trio.open_nursery() as nursery:
608 await nursery.start(handle_value, recv_chan, 0)
609 await nursery.start(handle_value, recv_chan, 1)
610 event.set()
611
612
613 async def test_as_safe_channel_multi_cancel() -> None:
614 @as_safe_channel
615 async def agen(events: list[str]) -> AsyncGenerator[None]:
616 try:
617 yield
618 finally:
619 # this will give a warning of ASYNC120, although it's not technically a
620 # problem of swallowing existing exceptions
621 try:
622 await trio.lowlevel.checkpoint()
623 except trio.Cancelled:
624 events.append("agen cancel")
625 raise
626
627 events: list[str] = []
628 with trio.CancelScope() as cs:
629 with pytest.raises(trio.Cancelled):
630 async with agen(events) as recv_chan:
631 async for _ in recv_chan: # pragma: no branch
632 cs.cancel()
633 try:
634 await trio.lowlevel.checkpoint()
635 except trio.Cancelled:
636 events.append("body cancel")
637 raise
638 assert events == ["body cancel", "agen cancel"]
639
640
641 async def test_as_safe_channel_genexit_exception_group() -> None:
642 @as_safe_channel
643 async def agen() -> AsyncGenerator[None]:
644 try:
645 async with trio.open_nursery():
646 yield
647 except BaseException as e:
648 assert pytest.RaisesGroup(GeneratorExit).matches(e) # noqa: PT017
649 raise
650
651 async with agen() as g:
652 async for _ in g:
653 break
654
655
656 async def test_as_safe_channel_does_not_suppress_nested_genexit() -> None:
657 @as_safe_channel
658 async def agen() -> AsyncGenerator[None]:
659 yield
660
661 with pytest.RaisesGroup(GeneratorExit):
662 async with agen() as g, trio.open_nursery():
663 await g.receive() # this is for coverage reasons
664 raise GeneratorExit
665
666
667 async def test_as_safe_channel_genexit_filter() -> None:
668 async def wait_then_raise() -> None:
669 try:
670 await trio.sleep_forever()
671 except trio.Cancelled:
672 raise ValueError from None
673
674 @as_safe_channel
675 async def agen() -> AsyncGenerator[None]:
676 async with trio.open_nursery() as nursery:
677 nursery.start_soon(wait_then_raise)
678 yield
679
680 with pytest.RaisesGroup(ValueError):
681 async with agen() as g:
682 async for _ in g:
683 break
684
685
686 async def test_as_safe_channel_swallowing_extra_exceptions() -> None:
687 async def wait_then_raise(ex: type[BaseException]) -> None:
688 try:
689 await trio.sleep_forever()
690 except trio.Cancelled:
691 raise ex from None
692
693 @as_safe_channel
694 async def agen(ex: type[BaseException]) -> AsyncGenerator[None]:
695 async with trio.open_nursery() as nursery:
696 nursery.start_soon(wait_then_raise, ex)
697 nursery.start_soon(wait_then_raise, GeneratorExit)
698 yield
699
700 with pytest.RaisesGroup(AssertionError):
701 async with agen(GeneratorExit) as g:
702 async for _ in g:
703 break
704
705 with pytest.RaisesGroup(ValueError, AssertionError):
706 async with agen(ValueError) as g:
707 async for _ in g:
708 break
709
710
711 async def test_as_safe_channel_close_between_iteration() -> None:
712 @as_safe_channel
713 async def agen() -> AsyncGenerator[None]:
714 while True:
715 yield
716
717 async with agen() as chan, trio.open_nursery() as nursery:
718
719 async def close_channel() -> None:
720 await trio.lowlevel.checkpoint()
721 await chan.aclose()
722
723 nursery.start_soon(close_channel)
724 with pytest.raises(trio.ClosedResourceError):
725 async for _ in chan:
726 pass
727
728
729 async def test_as_safe_channel_close_before_iteration() -> None:
730 @as_safe_channel
731 async def agen() -> AsyncGenerator[None]:
732 raise AssertionError("should be unreachable") # pragma: no cover
733 yield # pragma: no cover
734
735 async with agen() as chan:
736 await chan.aclose()
737 with pytest.raises(trio.ClosedResourceError):
738 await chan.receive()
739
740
741 async def test_as_safe_channel_close_during_iteration() -> None:
742 @as_safe_channel
743 async def agen() -> AsyncGenerator[None]:
744 yield
745 await chan.aclose()
746 while True:
747 yield
748
749 async with agen() as chan:
750 with pytest.raises(trio.ClosedResourceError):
751 async for _ in chan:
752 pass
753
754 # This is necessary to ensure that `chan` has been sent
755 # to. Otherwise, this test sometimes passes on a broken
756 # version of trio.
757 await trio.testing.wait_all_tasks_blocked()