# RuntimeError: 没有正在运行的事件循环

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

## 根因

异步测试或 fixture 在没有活动 asyncio 事件循环的情况下执行。通常是 pytest-asyncio 模式未配置、测试缺少 @pytest.mark.asyncio 标记，或 fixture 是同步的却在 await。

## 版本兼容性

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

## 解决方案

1. **** (93% 成功率)
   ```
   # pyproject.toml
[tool.pytest.ini_options]
asyncio_mode = "auto"

# or pytest.ini
# [pytest]
# asyncio_mode = auto
   ```
2. **** (90% 成功率)
   ```
   import pytest, pytest_asyncio

@pytest_asyncio.fixture
async def client():
    async with AsyncClient() as c:
        yield c

@pytest.mark.asyncio
async def test_ping(client):
    r = await client.get('/ping')
    assert r.status_code == 200
   ```

## 无效尝试

- **** — pytest-asyncio already manages the loop; nested asyncio.run raises 'asyncio.run() cannot be called from a running event loop' or double-closes the loop. (70% 失败率)
- **** — Sync fixtures cannot yield awaited values; the coroutine object is returned instead of the resolved value, causing the exact error downstream. (65% 失败率)
