python runtime_error ai_generated true

RuntimeError: TestClient cannot be used with async functions without an async client.

ID: python/fastapi-test-client-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2024-08-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

使用FastAPI的TestClient测试异步路由时,未使用异步客户端或事件循环。

generic

中文

使用FastAPI的TestClient测试异步路由时,未使用异步客户端或事件循环。

Workarounds

  1. 95% success 使用TestClient的async模式
    from fastapi.testclient import TestClient; from main import app; client = TestClient(app); with client: response = client.get('/async-endpoint')
  2. 90% success 使用httpx.AsyncClient直接测试
    from httpx import AsyncClient; async with AsyncClient(app=app, base_url='http://test') as ac: response = await ac.get('/async-endpoint')

Dead Ends

Common approaches that don't work:

  1. 在同步测试函数中直接调用异步路由 90% fail

    TestClient默认同步。

  2. 使用pytest-asyncio但不配置 70% fail

    需要正确标记测试函数。