# httpx.ConnectError: 所有连接尝试均失败（lifespan 启动从未执行）

- **ID:** `python/starlette-testclient-lifespan-not-run`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 0.100+ | active | — | — |
| 0.110+ | active | — | — |

## 解决方案

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

## 无效尝试

- **** — Misses teardown; leaks resources and diverges from prod. (65% 失败率)
- **** — Still no lifespan; same None state. (85% 失败率)
