python runtime_error ai_generated true

httpx.ConnectError: All connection attempts failed (lifespan startup never executed)

ID: python/starlette-testclient-lifespan-not-run

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
0.100+ active — — —
0.110+ active — — —

Root Cause

Using httpx.Client against app without running lifespan, so app.state resources (DB pool, clients) are None.

generic

中文

在未运行 lifespan 的情况下使用 httpx.Client 访问应用,导致 app.state 资源(数据库池、客户端)为 None。

Workarounds

  1. 95% success
    from starlette.testclient import TestClient
    with TestClient(app) as client:  # 'with' runs lifespan
        r = client.get('/health')
  2. 88% success
    Use httpx.ASGITransport with lifespan='on' via asgi-lifespan LifespanManager.

Dead Ends

Common approaches that don't work:

  1. 65% fail

    Misses teardown; leaks resources and diverges from prod.

  2. 85% fail

    Still no lifespan; same None state.