gpt4 book ai didi

python - 用 FastAPI TestClient 测试返回 422 状态码

转载 作者:行者123 更新时间:2023-12-04 03:56:17 24 4
gpt4 key购买 nike

我尝试使用来自 FastAPI(基本上是 Scarlett TestClient)的 TestClient 测试端点。
响应代码始终为 422 Unprocessable Entity。
这是我目前的代码:

from typing import Dict, Optional

from fastapi import APIRouter
from pydantic import BaseModel

router = APIRouter()


class CreateRequest(BaseModel):
number: int
ttl: Optional[float] = None


@router.post("/create")
async def create_users(body: CreateRequest) -> Dict:
return {
"msg": f"{body.number} Users are created"
}
如您所见,我还将 application/json header 传递给客户端以避免潜在错误。
这是我的测试:
from fastapi.testclient import TestClient
from metusa import app


def test_create_50_users():
client = TestClient(app)
client.headers["Content-Type"] = "application/json"

body = {
"number": 50,
"ttl": 2.0
}
response = client.post('/v1/users/create', data=body)

assert response.status_code == 200
assert response.json() == {"msg": "50 Users created"}

我也在响应对象中发现了这个错误信息
b'{"detail":[{"loc":["body",0],"msg":"Expecting value: line 1 column 1 (char 0)","type":"value_error.jsondecode","ctx":{"msg":"Expecting value","doc":"number=50&ttl=2.0","pos":0,"lineno":1,"colno":1}}]}'
感谢您的支持和时间!

最佳答案

您不需要手动设置标题。您可以在 client.post 方法中使用 json 参数代替 data

def test_create_50_users():
client = TestClient(router)

body = {
"number": 50,
"ttl": 2.0
}
response = client.post('/create', json=body)
如果还想使用 data 属性,则需要使用 json.dumps
def test_create_50_users():
client = TestClient(router)
client.headers["Content-Type"] = "application/json"

body = {
"number": 50,
"ttl": 2.0
}
response = client.post('/create', data=json.dumps(body))

关于python - 用 FastAPI TestClient 测试返回 422 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63854588/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com