python - 测试 FastAPI TestClient 对请求返回 422
问题描述
我正在尝试测试我的代码,但无法弄清楚我做错了什么。我将 FastAPI 与 pydantic 的基本模型一起使用。
# Model
class Cat(BaseModel):
breed: str
location_of_origin: str
coat_length: int
body_type: str
pattern: str
# Cat creation
@app.post("/cats", status_code=status.HTTP_201_CREATED)
async def add_cat(cat: Cat,
breed: str,
location_of_origin: str,
coat_length: int,
body_type: str,
pattern: str):
new_cat = cat.dict()
new_cat['breed'] = breed
...
cats.append(new_cat)
return new_cat
使用 API 创建的猫没有错误。
# Tests
from starlette.testclient import TestClient
from app.main import app
data = {
'breed': 'Ragdoll',
'location_of_origin': 'United States',
'coat_length': 4,
'body_type': 'Medium',
'pattern': 'Chocolate Point'
}
def test_add_cat():
response = client.post("/cats", json=data)
assert response.status_code == 201
assert data in response.json() == data
当我运行测试时,它给了我这些错误:
def test_add_cat():
response = client.post("/cats", json=data)
> assert response.status_code == 201
E assert 422 == 201
E + where 422 = <Response [422]>.status_code
tests\test_app.py:23: AssertionError
=========================== short test summary info ===========================
FAILED tests/test_app.py::test_add_cat - assert 422 == 201
============================== 1 failed in 0.62s ==============================
解决方案
问题在于您的函数定义。您正在指定cat
cat 类型的参数,并且还要复制参数来创建 cat。你应该只有cat
参数。试试这个:
# Cat creation
@app.post("/cats", status_code=status.HTTP_201_CREATED)
async def add_cat(cat: Cat):
return cat
推荐阅读
- robotframework - 尝试使用 Robot Framework 中的 SapGuiLibrary 与 SAP 元素交互时出错
- php - 发送大量信息后如何整理我的网址?
- amazon-web-services - 基于标签保护 AWS 资源
- javascript - 根据 if 条件重新排列一行内容
- c# - 如何在 C# 中可靠地启动进程?
- symfony - 如何为子资源启用分页?
- r - 在 for 循环中访问结构元素
- reactjs - 一次使用多个 get 请求 useEffect (react)
- java - 无法解析配置“:classpath”的所有工件。> 无法解析 com.android.tools.build:gradle:4.1.0
- tqdm - 如何将不同迭代的 TQDM 进度条保持在同一行?