11import asyncio
2+ import warnings
23
3- from async_lru import alru_cache
4+ import pytest
45
6+ from async_lru import AlruCacheLoopResetWarning , alru_cache
57
8+
9+ @pytest .mark .filterwarnings ("ignore::async_lru.AlruCacheLoopResetWarning" )
610def test_cross_loop_auto_resets_cache () -> None :
711 @alru_cache (maxsize = 100 )
812 async def cached_func (key : str ) -> str :
@@ -25,6 +29,7 @@ async def cached_func(key: str) -> str:
2529 assert cached_func .cache_info ().misses == 1
2630
2731
32+ @pytest .mark .filterwarnings ("ignore::async_lru.AlruCacheLoopResetWarning" )
2833def test_cross_loop_preserves_stats_reset () -> None :
2934 @alru_cache (maxsize = 100 )
3035 async def cached_func (key : str ) -> str :
@@ -47,6 +52,7 @@ async def cached_func(key: str) -> str:
4752 assert cached_func .cache_info ().misses == 1
4853
4954
55+ @pytest .mark .filterwarnings ("ignore::async_lru.AlruCacheLoopResetWarning" )
5056def test_invalid_key_does_not_bind_loop () -> None :
5157 @alru_cache (maxsize = 100 )
5258 async def cached_func (key : object ) -> str :
@@ -140,6 +146,7 @@ async def run_concurrent() -> list[str]:
140146 assert cached_func .cache_info ().hits == 2
141147
142148
149+ @pytest .mark .filterwarnings ("ignore::async_lru.AlruCacheLoopResetWarning" )
143150def test_multiple_loop_transitions () -> None :
144151 @alru_cache (maxsize = 100 )
145152 async def cached_func (key : str ) -> str :
@@ -150,3 +157,43 @@ async def cached_func(key: str) -> str:
150157 result = loop .run_until_complete (cached_func ("test" ))
151158 loop .close ()
152159 assert result == "data_test"
160+
161+
162+ def test_loop_change_emits_warning () -> None :
163+ @alru_cache (maxsize = 100 )
164+ async def cached_func (key : str ) -> str :
165+ return f"data_{ key } "
166+
167+ loop1 = asyncio .new_event_loop ()
168+ loop1 .run_until_complete (cached_func ("test" ))
169+ loop1 .close ()
170+
171+ loop2 = asyncio .new_event_loop ()
172+ with warnings .catch_warnings (record = True ) as w :
173+ warnings .simplefilter ("always" )
174+ loop2 .run_until_complete (cached_func ("test" ))
175+ loop2 .close ()
176+
177+ assert len (w ) == 1
178+ assert issubclass (w [0 ].category , AlruCacheLoopResetWarning )
179+ assert "event loop change" in str (w [0 ].message )
180+
181+
182+ def test_loop_change_warns_only_once () -> None :
183+ @alru_cache (maxsize = 100 )
184+ async def cached_func (key : str ) -> str :
185+ return f"data_{ key } "
186+
187+ all_warnings : list [warnings .WarningMessage ] = []
188+ for _ in range (4 ):
189+ loop = asyncio .new_event_loop ()
190+ with warnings .catch_warnings (record = True ) as w :
191+ warnings .simplefilter ("always" )
192+ loop .run_until_complete (cached_func ("test" ))
193+ loop .close ()
194+ all_warnings .extend (w )
195+
196+ reset_warnings = [
197+ w for w in all_warnings if issubclass (w .category , AlruCacheLoopResetWarning )
198+ ]
199+ assert len (reset_warnings ) == 1
0 commit comments