# RuntimeError: 线程 'MainThread' 中没有当前事件循环。

- **ID:** `python/unittest-isolated-asyncio-testcase`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

在 unittest.IsolatedAsyncioTestCase 中使用在非异步上下文调用 asyncio.get_event_loop() 的代码，或错误混合同步/异步测试方法。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.10 | active | — | — |
| 3.11 | active | — | — |
| 3.12 | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   class TestX(unittest.IsolatedAsyncioTestCase):
    async def test_y(self):
        loop = asyncio.get_running_loop()
        await loop.create_task(coro())
   ```
2. **** (90% 成功率)
   ```
   class TestX(unittest.IsolatedAsyncioTestCase):
    async def test_y(self):
        loop = asyncio.get_running_loop()
        result = await my_func(loop=loop)
        self.assertEqual(result, 1)
   ```

## 无效尝试

- **** — IsolatedAsyncioTestCase manages its own loop; overriding it causes 'loop already running' or leaks loops between tests. (85% 失败率)
- **** — Works for simple cases but breaks async fixtures and shares no loop with the test's async methods. (60% 失败率)
- **** — IsolatedAsyncioTestCase exists from 3.8; downgrading does not change the event-loop lookup behavior. (95% 失败率)
