python
runtime_error
ai_generated
true
RuntimeError: 当另一个循环正在运行时无法运行事件循环
RuntimeError: Cannot run the event loop while another loop is running
ID: python/starlette-testclient-blocking-async
80%修复率
86%置信度
0证据数
2024-11-02首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在已有运行循环的异步测试中调用 asyncio.run() 或 loop.run_until_complete,常见于混用 TestClient 和 AsyncClient。
English
Calling asyncio.run() or loop.run_until_complete inside an async test that already has a running loop, often mixing TestClient and AsyncClient.
解决方案
-
92% 成功率
Use httpx.AsyncClient(transport=ASGITransport(app=app), base_url='http://test') with pytest.mark.asyncio
-
90% 成功率
await the call directly: response = await client.get('/')
无效尝试
常见但无效的做法:
-
55% 失败
Patches loop globally and can mask other async bugs.
-
60% 失败
TestClient blocks; cannot test concurrent async behavior.