python - 使用 FastAPI TestClient 进行测试返回 422 状态码
问题描述
我尝试使用TestClient
来自 FastAPI 的端点(基本上是 Scarlett 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
标头传递给客户端以避免潜在错误。
这是我的测试:
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))
推荐阅读
- c++ - char 数组转无符号字符 *
- python - 如何从 MongoDb Atlas 免费云版中导出存储在数据库中的现有文档?
- python - 在完成 main 方法之前终止所有进程
- ios - AWS SNS - 卸载应用程序时 iOS 终端节点不会被禁用
- python - 删除 x 和 y 标签的空间
- java - Hibernate TypeMismatchException - 为类提供了错误类型的 id
- angular - 检测 Angular 9 应用程序的浏览器关闭
- networking - 捎带如何抑制重复段?
- python - Split String in Text File to Multiple Rows in Python
- html - VBA Web-scraping:单击具有动态生成的名称和 ID 的按钮