根据请求测试 FastAPI TestClient returns 422

Testing FastAPI TestClient returns 422 on requests

我正在尝试测试我的代码,但无法弄清楚我做错了什么。 我正在使用 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