Reputation: 75
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]
Upvotes: 2
Views: 6410
Reputation: 20598
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
Upvotes: 2