【发布时间】:2021-11-08 22:59:04
【问题描述】:
我有一个路由前缀为 /api/v1 的 FastAPI 应用程序。
当我运行测试时,它会抛出 404。我看到这是因为TestClient 无法在/ping 找到路由,并且当测试用例中的路由更改为/api/v1/ping 时完美运行。
有没有一种方法可以避免根据前缀更改所有测试函数中的所有路由?这似乎很麻烦,因为有很多测试用例,也因为我不想在我的测试用例中对路由前缀有硬编码的依赖。有没有一种方法可以像在app 中一样配置TestClient 中的前缀,并像routes.py 中提到的那样简单地提及路由?
routes.py
from fastapi import APIRouter
router = APIRouter()
@router.get("/ping")
async def ping_check():
return {"msg": "pong"}
main.py
from fastapi import FastAPI
from routes import router
app = FastAPI()
app.include_router(prefix="/api/v1")
在我的测试文件中:
test.py
from main import app
from fastapi.testclient import TestClient
client = TestClient(app)
def test_ping():
response = client.get("/ping")
assert response.status_code == 200
assert response.json() == {"msg": "pong"}
【问题讨论】: