python
network_error
ai_generated
true
starlette.testclient.TestClient: Connection refused
ID: python/starlette-testclient-connection-error
80%Fix Rate
82%Confidence
0Evidence
2024-05-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
TestClient 尝试连接未启动的应用服务器,或应用启动失败。
generic中文
测试客户端尝试连接未启动的应用服务器,或应用启动失败。
Workarounds
-
95% success
使用 with TestClient(app) as client: 确保生命周期管理
-
90% success
检查应用是否在 __main__ 中启动,并确保测试使用相同实例
-
85% success
使用 httpx 的 ASGITransport 替代 TestClient
Dead Ends
Common approaches that don't work:
-
60% fail
根本原因不是超时,而是服务器未运行。
-
50% fail
绕过 TestClient 的 ASGI 支持,可能导致上下文错误。
-
70% fail
可能引起端口占用或资源泄漏。