I'm writing test for a FastAPI application. When I write test for an endpoint with GET method everything works as expected, but when I call an endpoint with POST method somehow my request gets redirected to http://testserver this is an example of my endpoints:
from json import JSONDecodeError
from fastapi import APIRouter
from starlette.requests import Request
from starlette.responses import JSONResponse
from starlette.status import HTTP_400_BAD_REQUEST
router = APIRouter()
@router.post("/test")
async def test(
request: Request,
):
try:
body = await request.json()
except JSONDecodeError:
return JSONResponse(content={}, status_code=HTTP_400_BAD_REQUEST)
return JSONResponse(content=body)
and this is an example of my test:
from starlette.testclient import TestClient
from app import app
client = TestClient(app)
def test_cookies():
res = client.post(
"api/test/",
json={
"name": "test"
},
)
assert 200 == res.status_code
again this happens just with POST and PUT requests the GET request works just fine. any idea why is this happening?
CodePudding user response:
Your endpoint is registered as /api/test
, while you're calling /api/test/
- notice the difference in the trailing slash.
By default FastAPI will issue a redirect to make your browser talk to the correct endpoint. The http://testserver
URL you're seeing is the internal hostname used in the TestClient.