python
runtime_error
ai_generated
true
RuntimeError: There is no current event loop in thread 'MainThread'.
ID: python/unittest-isolated-asyncio-testcase
80%Fix Rate
85%Confidence
0Evidence
2025-03-07First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
Using unittest.IsolatedAsyncioTestCase with code that calls asyncio.get_event_loop() from a non-async context, or mixing sync and async test methods incorrectly.
generic中文
在 unittest.IsolatedAsyncioTestCase 中使用在非异步上下文调用 asyncio.get_event_loop() 的代码,或错误混合同步/异步测试方法。
Workarounds
-
95% success
class TestX(unittest.IsolatedAsyncioTestCase): async def test_y(self): loop = asyncio.get_running_loop() await loop.create_task(coro()) -
90% success
class TestX(unittest.IsolatedAsyncioTestCase): async def test_y(self): loop = asyncio.get_running_loop() result = await my_func(loop=loop) self.assertEqual(result, 1)
Dead Ends
Common approaches that don't work:
-
85% fail
IsolatedAsyncioTestCase manages its own loop; overriding it causes 'loop already running' or leaks loops between tests.
-
60% fail
Works for simple cases but breaks async fixtures and shares no loop with the test's async methods.
-
95% fail
IsolatedAsyncioTestCase exists from 3.8; downgrading does not change the event-loop lookup behavior.