【问题标题】:FastAPI - adding route prefix to TestClientFastAPI - 向 TestClient 添加路由前缀
【发布时间】: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"}

ma​​in.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"}

【问题讨论】:

    标签: python fastapi starlette


    【解决方案1】:

    想出了一个解决方法。

    TestClient 可以选择接受base_url,然后urljoined 与路由path。所以我将路由前缀附加到这个base_url

    source:

    url = urljoin(self.base_url, url)

    但是,有一个问题 - 只有当 base_url/ 结尾并且 path 不以 / 开头时,urljoin 才会按预期连接. 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"}
    

    【讨论】:

      猜你喜欢
      • 2018-04-30
      • 1970-01-01
      • 2020-11-30
      • 1970-01-01
      • 1970-01-01
      • 2014-09-29
      • 2021-01-08
      • 1970-01-01
      • 2021-08-18
      相关资源
      最近更新 更多