Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用FastAPI TestClient进行的测试返回422状态代码_Python_Fastapi - Fatal编程技术网

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

Python 使用FastAPI TestClient进行的测试返回422状态代码,python,fastapi,Python,Fastapi,我尝试使用FastAPI中的TestClient测试端点(基本上就是TestClient) 响应代码始终为422不可处理实体 这是我当前的代码: 从输入import Dict开始,可选 从fastapi导入APIRouter 从pydantic导入BaseModel 路由器=APIRouter() 类CreateRequest(BaseModel): 编号:int ttl:可选[浮动]=无 @router.post(“/create”) 异步定义创建用户(正文:CreateRequest)->D

我尝试使用FastAPI中的
TestClient
测试端点(基本上就是TestClient)

响应代码始终为422不可处理实体

这是我当前的代码:

从输入import Dict开始,可选
从fastapi导入APIRouter
从pydantic导入BaseModel
路由器=APIRouter()
类CreateRequest(BaseModel):
编号:int
ttl:可选[浮动]=无
@router.post(“/create”)
异步定义创建用户(正文:CreateRequest)->Dict:
返回{
“msg”:f“{body.number}用户已创建”
}
如您所见,我还将
application/json
头传递给客户端,以避免潜在的错误

这是我的测试:

从fastapi.testclient导入testclient
来自metusa导入应用程序
def测试_创建_50_用户():
client=TestClient(应用程序)
client.headers[“Content Type”]=“application/json”
正文={
“数字”:50,
“ttl”:2.0
}
response=client.post('/v1/users/create',data=body)
assert response.status_code==200
assert response.json()=={“msg”:“创建了50个用户”}
我还在响应对象中发现了此错误消息

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(路由器)
正文={
“数字”:50,
“ttl”:2.0
}
response=client.post('/create',json=body)
如果仍要使用
数据
属性,则需要使用
json.dumps

def test_create_50_users():
client=TestClient(路由器)
client.headers[“Content Type”]=“application/json”
正文={
“数字”:50,
“ttl”:2.0
}
response=client.post('/create',data=json.dumps(body))