python runtime_error ai_generated true

RuntimeError: 当另一个循环正在运行时无法运行事件循环

RuntimeError: Cannot run the event loop while another loop is running

ID: python/starlette-testclient-blocking-async

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 92% 成功率
    Use httpx.AsyncClient(transport=ASGITransport(app=app), base_url='http://test') with pytest.mark.asyncio
  2. 90% 成功率
    await the call directly: response = await client.get('/')

无效尝试

常见但无效的做法:

  1. 55% 失败

    Patches loop globally and can mask other async bugs.

  2. 60% 失败

    TestClient blocks; cannot test concurrent async behavior.