python
network_error
ai_generated
true
Starlette 测试客户端:连接被拒绝
starlette.testclient.TestClient: Connection refused
ID: python/starlette-testclient-connection-error
80%修复率
82%置信度
0证据数
2024-05-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
测试客户端尝试连接未启动的应用服务器,或应用启动失败。
English
TestClient 尝试连接未启动的应用服务器,或应用启动失败。
解决方案
-
95% 成功率
使用 with TestClient(app) as client: 确保生命周期管理
-
90% 成功率
检查应用是否在 __main__ 中启动,并确保测试使用相同实例
-
85% 成功率
使用 httpx 的 ASGITransport 替代 TestClient
无效尝试
常见但无效的做法:
-
60% 失败
根本原因不是超时,而是服务器未运行。
-
50% 失败
绕过 TestClient 的 ASGI 支持,可能导致上下文错误。
-
70% 失败
可能引起端口占用或资源泄漏。