# RuntimeError: 事件循环已关闭

- **ID:** `python/pytest-asyncio-event-loop-closed`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

pytest-asyncio 默认每个测试创建一个新的事件循环。如果异步资源（如 aiohttp 会话、异步数据库连接）在一个测试中创建并在另一个测试中使用，或者在清理前循环已关闭，就会发生此错误。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 0.21 | active | — | — |
| 0.23 | active | — | — |

## 解决方案

1. **** (95% 成功率)
   ```
   In conftest.py:
import pytest
import asyncio

@pytest.fixture(scope='session')
def event_loop():
    loop = asyncio.new_event_loop()
    yield loop
    loop.close()

Or use pytest-asyncio's built-in: set asyncio_mode = auto and use @pytest.mark.asyncio(scope='session').
   ```
2. **** (90% 成功率)
   ```
   @pytest_asyncio.fixture(scope='module')
async def client():
    session = aiohttp.ClientSession()
    yield session
    await session.close()
   ```

## 无效尝试

- **** — Sleeping does not prevent the loop from being closed between tests. (90% 失败率)
- **** — This only affects Windows and does not address the per-test loop creation. (85% 失败率)
