使用FastAPI TestClient进行测试将返回422状态代码

时间:2020-09-11 21:35:29

标签: python fastapi

我尝试使用来自FastAPI(基本上是Scarlett TestClient)的TestClient测试端点。

响应代码始终为422无法处理的实体。

这是我当前的代码:

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标头传递给客户端,以避免潜在的错误。

这是我的测试:

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}}]}'

感谢您的支持和时间!

1 个答案:

答案 0 :(得分:0)

您不需要手动设置标题。您可以在client.post方法中使用json的{​​{1}}参数。

data

如果您仍然想使用def test_create_50_users(): client = TestClient(router) body = { "number": 50, "ttl": 2.0 } response = client.post('/create', json=body) 属性,则需要使用data

json.dumps