Skip to content

Commit be11787

Browse files
committed
add test for gc in foreign async generators
1 parent 8850705 commit be11787

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

src/trio/_core/_tests/test_guest_mode.py

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
import time
1212
import traceback
1313
import warnings
14+
import weakref
1415
from functools import partial
1516
from math import inf
1617
from typing import (
@@ -664,3 +665,51 @@ async def trio_main() -> None:
664665
context.run(aiotrio_run, trio_main, host_uses_signal_set_wakeup_fd=True)
665666

666667
assert record == {("asyncio", "asyncio"), ("trio", "trio")}
668+
669+
670+
@restore_unraisablehook()
671+
def test_guest_mode_asyncgens_garbage_collection() -> None:
672+
import sniffio
673+
674+
record: set[tuple[str, str, bool]] = set()
675+
676+
async def agen(label: str) -> AsyncGenerator[int, None]:
677+
class A:
678+
pass
679+
680+
a = A()
681+
a_wr = weakref.ref(a)
682+
assert sniffio.current_async_library() == label
683+
try:
684+
yield 1
685+
finally:
686+
library = sniffio.current_async_library()
687+
with contextlib.suppress(trio.Cancelled):
688+
await sys.modules[library].sleep(0)
689+
690+
del a
691+
if sys.implementation.name == "pypy":
692+
gc_collect_harder()
693+
694+
record.add((label, library, a_wr() is None))
695+
696+
async def iterate_in_aio() -> None:
697+
await agen("asyncio").asend(None)
698+
699+
async def trio_main() -> None:
700+
task = asyncio.ensure_future(iterate_in_aio())
701+
done_evt = trio.Event()
702+
task.add_done_callback(lambda _: done_evt.set())
703+
with trio.fail_after(1):
704+
await done_evt.wait()
705+
706+
await agen("trio").asend(None)
707+
708+
gc_collect_harder()
709+
710+
# Ensure we don't pollute the thread-level context if run under
711+
# an asyncio without contextvars support (3.6)
712+
context = contextvars.copy_context()
713+
context.run(aiotrio_run, trio_main, host_uses_signal_set_wakeup_fd=True)
714+
715+
assert record == {("asyncio", "asyncio", True), ("trio", "trio", True)}

0 commit comments

Comments
 (0)