带有 FastAPI 的 Pytest:断言错误(响应 422)

时间:2021-01-07 10:56:32

标签: python unit-testing testing pytest fastapi

我想用以下代码测试 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

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

编辑:终点是:

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

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

1 个答案:

答案 0 :(得分:0)

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

你正在发送这个

`{"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]