I have a FastAPI app with a route prefix as /api/v1
.
When I run the test it throws 404
. I see this is because the TestClient
is not able to find the route at /ping
, and works perfectly when the route in the test case is changed to /api/v1/ping
.
Is there a way in which I can avoid changing all the routes in all the test functions as per the prefix? This seems to be cumbersome as there are many test cases, and also because I dont want to have a hard-coded dependency of the route prefix in my test cases. Is there a way in which I can configure the prefix in the TestClient
just as we did in app
, and simply mention the route just as mentioned in the 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")
In the test file I have:
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"}