|
11 | 11 | import time
|
12 | 12 | import traceback
|
13 | 13 | import warnings
|
| 14 | +import weakref |
14 | 15 | from functools import partial
|
15 | 16 | from math import inf
|
16 | 17 | from typing import (
|
@@ -664,3 +665,51 @@ async def trio_main() -> None:
|
664 | 665 | context.run(aiotrio_run, trio_main, host_uses_signal_set_wakeup_fd=True)
|
665 | 666 |
|
666 | 667 | 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