Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.2k views
in Technique[技术] by (71.8m points)

python - Pytest with FastAPI: Assertion Error (Response 422)

I would like to test FastAPI with the following code:

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"

However, I am getting the following error:

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

tests.py:24: AssertionError

I understand that I am only giving (predict, 200) as an input but throwing 422 errors. What does this mean and how can I fix it? I thought I am taking account of the 422 error in the elif statement but still throwing it with/without that. What am I doing wrong?

EDIT: the end point is:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your request body and expected request body does not matchs.

You are sending this

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

Which should be like this in your Input model

from typing import Dict

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

You can't see the error but, it raises this error underneath

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

So you should change it to Dict[str, str] or Dict[Any, Any] instead


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...