python runtime_error ai_generated true

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

ID: python/starlette-testclient-blocking-async

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-11-02First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active — — —

Root Cause

Calling asyncio.run() or loop.run_until_complete inside an async test that already has a running loop, often mixing TestClient and AsyncClient.

generic

中文

在已有运行循环的异步测试中调用 asyncio.run() 或 loop.run_until_complete,常见于混用 TestClient 和 AsyncClient。

Workarounds

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

Dead Ends

Common approaches that don't work:

  1. 55% fail

    Patches loop globally and can mask other async bugs.

  2. 60% fail

    TestClient blocks; cannot test concurrent async behavior.