1717from __future__ import annotations
1818
1919import asyncio
20+ import gc
2021import sys
2122import threading
2223import time
23- import weakref
2424
2525sys .path [0 :0 ] = ["" ]
2626
@@ -255,24 +255,18 @@ def test_register_adds_weakref(self):
255255 before = len (pe_module ._EXECUTORS )
256256 _register_executor (ex )
257257 self .assertEqual (len (pe_module ._EXECUTORS ), before + 1 )
258- # When executor is GC'd the ref is cleaned up .
259- ref_count_before = len ( pe_module ._EXECUTORS )
258+ # Find the specific weakref we just registered .
259+ ref = next ( r for r in pe_module ._EXECUTORS if r () is ex )
260260 del ex
261- self .assertLessEqual (len (pe_module ._EXECUTORS ), ref_count_before )
261+ gc .collect ()
262+ # The weakref callback must have removed our specific ref.
263+ self .assertNotIn (ref , pe_module ._EXECUTORS )
262264
263265 def test_shutdown_executors_stops_running_executors (self ):
264- stopped = threading .Event ()
265-
266- def target ():
267- stopped .wait (timeout = 5 )
268- return True
269-
270- ex = _make_sync (target = target )
266+ ex = _make_sync (interval = 30.0 )
271267 ex .open ()
272268 time .sleep (0.05 )
273- _register_executor (ex )
274269 _shutdown_executors ()
275- stopped .set ()
276270 ex .join (timeout = 2 )
277271 self .assertTrue (ex ._stopped )
278272
@@ -382,6 +376,9 @@ async def target():
382376 await asyncio .wait_for (ran .wait (), timeout = 2 )
383377 await ex .join (timeout = 2 )
384378 self .assertTrue (ex ._stopped )
379+ # Retrieve the task exception to avoid "Task exception was never retrieved".
380+ if ex ._task is not None and ex ._task .done ():
381+ ex ._task .exception ()
385382
386383 _run (_test ())
387384
@@ -390,7 +387,7 @@ async def _test():
390387 call_times = []
391388
392389 async def target ():
393- call_times .append (asyncio .get_event_loop ().time ())
390+ call_times .append (asyncio .get_running_loop ().time ())
394391 if len (call_times ) >= 2 :
395392 return False
396393 return True
0 commit comments