|
1 | 1 | import asyncio |
| 2 | +import gc |
| 3 | +import logging |
2 | 4 | from functools import partial |
3 | 5 | from unittest import mock |
4 | 6 |
|
5 | 7 | import pytest |
6 | 8 |
|
7 | | -from async_lru import _LRUCacheWrapper |
| 9 | +from async_lru import _CacheItem, _LRUCacheWrapper |
8 | 10 |
|
9 | 11 |
|
10 | 12 | async def test_done_callback_cancelled() -> None: |
@@ -41,6 +43,42 @@ async def test_done_callback_exception() -> None: |
41 | 43 | assert task not in wrapped._LRUCacheWrapper__tasks # type: ignore[attr-defined] |
42 | 44 |
|
43 | 45 |
|
| 46 | +async def test_done_callback_exception_logs(caplog: pytest.LogCaptureFixture) -> None: |
| 47 | + caplog.set_level(logging.ERROR, logger="asyncio") |
| 48 | + |
| 49 | + wrapped = _LRUCacheWrapper(mock.ANY, None, False, None) |
| 50 | + loop = asyncio.get_running_loop() |
| 51 | + |
| 52 | + async def boom() -> None: |
| 53 | + await asyncio.sleep(0) |
| 54 | + raise RuntimeError("boom") |
| 55 | + |
| 56 | + key = object() |
| 57 | + task = loop.create_task(boom()) |
| 58 | + wrapped._LRUCacheWrapper__cache[key] = _CacheItem(task, None, 1) # type: ignore[attr-defined] |
| 59 | + task.add_done_callback(partial(wrapped._task_done_callback, key)) |
| 60 | + |
| 61 | + while not task.done(): |
| 62 | + await asyncio.sleep(0) |
| 63 | + await asyncio.sleep(0) |
| 64 | + |
| 65 | + assert key not in wrapped._LRUCacheWrapper__cache # type: ignore[attr-defined] |
| 66 | + # asyncio disables logging when exception() is called; keep logging enabled. |
| 67 | + assert task._log_traceback |
| 68 | + |
| 69 | + caplog.clear() |
| 70 | + |
| 71 | + del task # Remove reference so task get garbage collected. |
| 72 | + for _ in range(5): # pragma: no branch |
| 73 | + gc.collect() |
| 74 | + await asyncio.sleep(0) |
| 75 | + if "Task exception was never retrieved" in caplog.text: # pragma: no branch |
| 76 | + break |
| 77 | + |
| 78 | + assert "Task exception was never retrieved" in caplog.text |
| 79 | + assert "RuntimeError: boom" in caplog.text |
| 80 | + |
| 81 | + |
44 | 82 | async def test_cache_invalidate_typed() -> None: |
45 | 83 | wrapped = _LRUCacheWrapper(mock.AsyncMock(return_value=1), None, True, None) |
46 | 84 |
|
|
0 commit comments