R
R
reqww2022-03-16 16:18:49
Python
reqww, 2022-03-16 16:18:49

422 response code from FastAPI application to request from pytest test using httpx.AsyncClient POST method?

I am trying to send a request to an API using pytest via httpx.AsynClient

@pytest.mark.anyio
async def test_device_create_with_data(self, client, random_uuid):
    device_create = DeviceCreateFactory.build(subId=random_uuid)

    json = device_create.json(by_alias=True)

    response = await client.post("/device", json=json)

    assert response.status_code == 200


Fixture client:

from httpx import AsyncClient


@pytest.fixture(scope="session")
async def client():
    async with AsyncClient(
            app=app,
            base_url="http://test/api/pc",
            headers={"Content-Type": "application/json"}
    ) as client:
        yield client


API endpoint:
@device_router.post("/device", response_model=CommonResponse)
async def create_device(device: DeviceCreate):
    _, err = await crud_device.create_device(device)

    if err:
        return get_common_response(400, err)

    return get_common_response(200, "ok")


schemas:
class DeviceBase(BaseModel):
    device_id: StrictStr = Field(..., alias='deviceId')
    device_name: StrictStr = Field(..., alias='deviceName')
    device_type: StrictStr = Field(..., alias='deviceType')
    age_mode: AgeModeType = Field(..., alias='ageMode')

    class Config:
        allow_population_by_field_name = True
        validate_all = True
        validate_assignment = True


class DeviceCreate(DeviceBase):
    sub_id: StrictStr = Field(..., alias='subId')

    class Config:
        orm_mode = True


factory:
from pydantic_factories import ModelFactory

from app.core.schemas.device import DeviceCreate


class DeviceCreateFactory(ModelFactory):
    __model__ = DeviceCreate

And I get a **422** error with the following response content:
"message":"bad request","details":{"deviceId":"field required","deviceName":"field required","deviceType":"field required","ageMode":"field required","subId":"field required"}


Then I examined the data of the request being sent and got:
b'"{\\"deviceId\\": \\"de\\", \\"deviceName\\": \\"\\", \\"deviceType\\": \\"\\", \\"ageMode\\": \\"child\\", \\"subId\\": \\"11aded61-9966-4be1-a781-387f75346811\\"}"'


Everything seems to be fine, but what's the problem then?

I tried to check the request data in the 422 exception handler
. I did:
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):

    print(await request.json())

    response = validation_error_response(exc)
    return JSONResponse(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        content=jsonable_encoder(response.dict())
    )


But the code after is unreachable, because for some reason this expression takes forever. Is there a way to deal with this issue? I would be grateful for any advice! PS python version: 3.8.9 fastapi version: 0.68.1 httpx version: 0.21.1 print(await request.json())






Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question