我有一个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"}
找到了解决办法
TestClient
有一个接受base_url
的选项,然后通过路由path
对其进行urljoin
。因此,我将路由前缀附加到这个base_url
然而,只有当
base_url
以/
结尾,并且path
不以/
开头时,才会像预期的那样进行连接This SO answer解释得很好这导致了以下变化:
test.py
相关问题 更多 >
编程相关推荐