python
runtime_error
ai_generated
true
运行时错误: 没有异步客户端时TestClient不能用于异步函数。
RuntimeError: TestClient cannot be used with async functions without an async client.
ID: python/fastapi-test-client-error
80%修复率
87%置信度
0证据数
2024-08-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
使用FastAPI的TestClient测试异步路由时,未使用异步客户端或事件循环。
English
使用FastAPI的TestClient测试异步路由时,未使用异步客户端或事件循环。
解决方案
-
95% 成功率 使用TestClient的async模式
from fastapi.testclient import TestClient; from main import app; client = TestClient(app); with client: response = client.get('/async-endpoint') -
90% 成功率 使用httpx.AsyncClient直接测试
from httpx import AsyncClient; async with AsyncClient(app=app, base_url='http://test') as ac: response = await ac.get('/async-endpoint')
无效尝试
常见但无效的做法:
-
在同步测试函数中直接调用异步路由
90% 失败
TestClient默认同步。
-
使用pytest-asyncio但不配置
70% 失败
需要正确标记测试函数。