I try to test an endpoint with the TestClient from FastAPI (which is the Scarlett TestClient basically).
The response code is always 422 Unprocessable Entity.
This is my current Code:
from typing import Dict, Optional
from fastapi import APIRouter
from pydantic import BaseModel
router = APIRouter()
class CreateRequest(BaseModel):
number: int
ttl: Optional[float] = None
@router.post("/create")
async def create_users(body: CreateRequest) -> Dict:
return {
"msg": f"{body.number} Users are created"
}
As you can see I'm also passing the application/json header to the client to avoid a potential error.
And this is my Test:
from fastapi.testclient import TestClient
from metusa import app
def test_create_50_users():
client = TestClient(app)
client.headers["Content-Type"] = "application/json"
body = {
"number": 50,
"ttl": 2.0
}
response = client.post('/v1/users/create', data=body)
assert response.status_code == 200
assert response.json() == {"msg": "50 Users created"}
I also found this error message in the Response Object
b'{"detail":[{"loc":["body",0],"msg":"Expecting value: line 1 column 1 (char 0)","type":"value_error.jsondecode","ctx":{"msg":"Expecting value","doc":"number=50&ttl=2.0","pos":0,"lineno":1,"colno":1}}]}'
Thank you for your support and time!