【问题标题】:Pytest with FastAPI: Assertion Error (Response 422)带有 FastAPI 的 Pytest:断言错误(响应 422)
【发布时间】:2021-04-13 02:26:03
【问题描述】:

我想用以下代码测试 FastAPI:

import pytest
from fastapi.testclient import TestClient
from main import applications

client = TestClient(app)


@pytest.mark.parametrize(
    "view, status_code",
    [
        ("predict", 200)
    ],
)

def test_predict(view, status_code):
    response = client.post(f"/{view}/", json={"data": {"text": "test"}})

    assert response.status_code == status_code

    response_json = response.json()

    if status_code == 200:
        assert len(response_json[0]) == 2
        assert isinstance(response_json[0][0], float) and isinstance(
            response_json[0][1], float
        )

    elif status_code == 404:
        assert response_json["detail"] == "Not Found"

    elif status_code == 422:
        assert response_json["detail"] != "Error"

但是,我收到以下错误:

>       assert response.status_code == status_code
E       assert 422 == 200
E        +  where 422 = <Response [422]>.status_code

tests.py:24: AssertionError

我知道我只给出 (predict, 200) 作为输入但抛出 422 错误。这是什么意思,我该如何解决?我以为我正在考虑 elif 语句中的 422 错误,但仍然在有/没有它的情况下抛出它。我做错了什么?

编辑:终点是:

@app.post("/predict/")
def predict(request: Input):

    return tokenizer.batch_decode(
        translate_text(request.data), skip_special_tokens=True
    )[0]

【问题讨论】:

  • 请分享端点。
  • request: Input 输入是什么?
  • 这是一个字符串data: str

标签: python unit-testing testing pytest fastapi


【解决方案1】:

您的请求正文和预期的请求正文不匹配。

你正在发送这个

`{"data": {"text": "test"}`

Input 模型中应该是这样的

from typing import Dict

class Input(BaseModel):
    data: Dict[str, str]

您看不到错误,但它会在下面引发此错误

{
  "detail": [
    {
      "loc": [
        "body",
        "data"
      ],
      "msg": "str type expected",
      "type": "type_error.str"
    }
  ]
}

所以你应该改为Dict[str, str]Dict[Any, Any]

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 2021-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多