FastAPI向TestClient添加路由前缀

2024-04-25 23:52:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个FastAPI应用程序,路由前缀为/api/v1

当我运行测试时,它抛出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"}

Tags: frompyimportapiapp路由response测试用例
1条回答
网友
1楼 · 发布于 2024-04-25 23:52:59

找到了解决办法

TestClient有一个接受base_url的选项,然后通过路由path对其进行urljoin。因此,我将路由前缀附加到这个base_url

source:

url = urljoin(self.base_url, url)

然而,只有当base_url/结尾,并且path不以/开头时,才会像预期的那样进行连接This SO answer解释得很好

这导致了以下变化:

test.py

from main import app, ROUTE_PREFIX
from fastapi.testclient import TestClient

client = TestClient(app)
client.base_url += ROUTE_PREFIX  # adding prefix
client.base_url = client.base_url.rstrip("/") + "/"  # making sure we have 1 and only 1 `/`

def test_ping():
    response = client.get("ping")  # notice the path no more begins with a `/`
    assert response.status_code == 200
    assert response.json() == {"msg": "pong"}

相关问题 更多 >