【问题标题】:Testing FastAPI TestClient returns 422 on requests测试 FastAPI TestClient 对请求返回 422
【发布时间】:2021-05-17 19:25:29
【问题描述】:

我正在尝试测试我的代码,但不知道我做错了什么。 我将 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 ==============================

【问题讨论】:

    标签: python pytest fastapi


    【解决方案1】:

    问题在于您的函数定义。您正在指定一个 cat 类型的参数 cat 并复制参数来创建 cat。你应该只有cat 参数。试试这个:

    # Cat creation 
    @app.post("/cats", status_code=status.HTTP_201_CREATED)
    async def add_cat(cat: Cat):
        return cat
    

    【讨论】:

    • 它可以工作,但它破坏了我在函数内部的验证代码。示例:如果品种(new_cat['breed'] = breed) 已经存在,则引发错误。也许我做错了这部分?
    • 如果您想添加检查,只需使用 cat 对象属性:if cat.breed == "something": raise
    猜你喜欢
    • 2020-12-30
    • 2020-08-06
    • 2020-08-04
    • 2023-01-08
    • 2020-05-12
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    • 2015-11-18
    相关资源
    最近更新 更多