python
runtime_error
ai_generated
true
RuntimeError: Cannot run the event loop while another loop is running
ID: python/starlette-testclient-blocking-async
80%Fix Rate
86%Confidence
0Evidence
2024-11-02First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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
-
92% success
Use httpx.AsyncClient(transport=ASGITransport(app=app), base_url='http://test') with pytest.mark.asyncio
-
90% success
await the call directly: response = await client.get('/')
Dead Ends
Common approaches that don't work:
-
55% fail
Patches loop globally and can mask other async bugs.
-
60% fail
TestClient blocks; cannot test concurrent async behavior.