python network_error ai_generated true

starlette.testclient.TestClient: Connection refused

ID: python/starlette-testclient-connection-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
82%Confidence
0Evidence
2024-05-10First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

TestClient 尝试连接未启动的应用服务器,或应用启动失败。

generic

中文

测试客户端尝试连接未启动的应用服务器,或应用启动失败。

Workarounds

  1. 95% success
    使用 with TestClient(app) as client: 确保生命周期管理
  2. 90% success
    检查应用是否在 __main__ 中启动,并确保测试使用相同实例
  3. 85% success
    使用 httpx 的 ASGITransport 替代 TestClient

Dead Ends

Common approaches that don't work:

  1. 60% fail

    根本原因不是超时,而是服务器未运行。

  2. 50% fail

    绕过 TestClient 的 ASGI 支持,可能导致上下文错误。

  3. 70% fail

    可能引起端口占用或资源泄漏。