简体   繁体   中英

FastAPI test client redirects the request when it is a POST or PUT

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM