python - FastAPI 测试客户端在 POST 或 PUT 时重定向请求

标签 python unit-testing pytest fastapi python-unittest

我正在为 FastAPI 应用程序编写测试。当我使用 GET 方法为端点编写测试时,一切都会按预期工作,但是当我使用 POST 方法调用端点时,我的请求会以某种方式重定向到http://testserver是我的端点的示例:

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)

这是我的测试示例:

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

同样,这种情况仅发生在 POST 和 PUT 请求中,而 GET 请求则工作正常。知道为什么会发生这种情况吗?

最佳答案

当您调用 /api/test/ 时,您的端点注册为 /api/test - 请注意尾部斜杠的差异。

默认情况下,FastAPI 将发出重定向以使您的浏览器与正确的端点通信。您看到的 http://testserver URL 是 TestClient 中使用的内部主机名。

关于python - FastAPI 测试客户端在 POST 或 PUT 时重定向请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72829494/

相关文章:

unit-testing - xsl-fo 的单元测试框架

python - Pytest 适用于旧模拟,但不适用于 unittest.mock

python - 使用 PycURL 下载图片让我崩溃

python - Django:allow_tags和short_description如何工作?

python - Keras 中的预处理功能不起作用

python - pytest-xdist IOError : cannot send to <Channel id=1 closed>

python - pytest:如何在命令行中显式启用插件

python - 对同等大小的图像进行逐像素比较,找到每个像素最常见的颜色

unit-testing - 模拟对象与测试数据库

python - 如何在模拟类的对象上定义任意属性?