Internal Service Error when testing fastapi views

34 views Asked by At

I was asked to modify sql statement so that the objects will be filtered by created_at. Specifically like this. a.created_at <= :created_at in avatar_views.py:

async def get_user_avatars_view(
    user_id: int,
    offset: int,
    limit: int,
    engine: AsyncEngine,
    created_at: datetime, # If I comment this
) -> list[Row]:
    print("get_user_avatars_view entered...")
    async with engine.begin() as connection:
    cursor_avatars = await connection.execute(
        text(f"""
            {statement}
            where a.user_id=:user_id
            and a.is_archived=false and a.deleted_at is null
            and a.created_at<=:created_at # If I comment this
            order by a.created_at desc
            offset :offset rows fetch next :limit rows only
        """), {
            "offset": offset,
            "limit": limit,
            "user_id": user_id,
            "created_at": created_at,# If I comment this
        },
    )
return cursor_avatars.all()

Then I decided to test it using pytest:

    async def test_get_user_avatars(
    self,
    service_test_client,
    create_user,
    user_db_factory,
    create_avatar,
    avatar_db_factory,
):
    user = await create_user()
    await user_db_factory(user=user)
    avatar_1 = await create_avatar(
        user=user,
        image=AvatarImage(
            small_url="https://test1.com",
            large_url="https://test2.com",
        ),
    )
    await avatar_db_factory(avatar=avatar_1)
    avatar_2 = await create_avatar(
        user=user,
        image=AvatarImage(
            small_url="https://test1.com",
            large_url="https://test2.com",
        ),
    )
    await avatar_db_factory(avatar=avatar_2)
    status, data = await service_test_client.get_user_avatars_handler( #error line
        user_id=1,
    )
    print("data in test_get_user_avatars:", data)
    assert data == {
        'data': {
            'items': [
                {'created_at': data['data']['items'][0]['created_at'],
                 'id': 2,
                 'large_url': 'https://test2.com',
                 'small_url': 'https://test1.com',
                 'user_id': 1},
                {'created_at': data['data']['items'][1]['created_at'],
                 'id': 1,
                 'large_url': 'https://test2.com',
                 'small_url': 'https://test1.com',
                 'user_id': 1}
            ],
            'limit': 100,
            'offset': 0,
            'total': None,
        }
    }
    assert status == 200

The line highlighted causes an error:

{'exc_code': 'InternalServiceError', 'exc_data': {}, 'message': 'Internal Service Error'}

Full log: get_user_avatars_handler entered... params before request: {'offset': 0, 'limit': 100, 'created_at': datetime.datetime(2023, 11, 5, 21, 0, 34, 472518, tzinfo=)} request entered... passed args: path: /users/1/avatars method: get json: None headers: None data: None files: None params: {'offset': 0, 'limit': 100, 'created_at': datetime.datetime(2023, 11, 5, 21, 0, 34, 472518, tzinfo=)} cookies: None going to request with given args... response being retrieved...

status: 500 data: {'exc_code': 'InternalServiceError', 'exc_data': {}, 'message': 'Internal Service Error'} data in test_get_user_avatars: {'exc_code': 'InternalServiceError', 'exc_data': {}, 'message': 'Internal Service Error'}

get_user_avatars_handler:

@classmethod
async def get_user_avatars_handler(
    cls,
    user_id: int,
    created_at: datetime | None = None,
    offset: int = 0,
    limit: int = 100,
):
    print("get_user_avatars_handler entered...")
    params = {
        "offset": offset,
        "limit": limit,
        "created_at": created_at.isoformat() if created_at else now(),
    }
    print("params before request:", params)
    return await cls.request(
        path=f"/users/{user_id}/avatars",
        method="get",
        params=params,
    )

request:

@classmethod
async def request(
        cls,
        path: str,
        method: str,
        json=None,
        headers=None,
        data=None,
        files=None,
        params=None,
        cookies=None,
        prefix: str = "v1",
):
    print("request entered...")
    print("passed args:")
    print("path:", path)
    print("method:", method)
    print("json:", json)
    print("headers:", headers)
    print("data:", data)
    print("files:", files)
    print("params:", params)
    print("cookies:", cookies)
    host = "localhost"
    port = int(os.environ.get("GATEWAY_PORT"))
    async with AsyncClient(base_url=f"http://{host}:{port}/{prefix}") as client:
        print("going to request with given args...")
        resp = await client.request(
            method=method,
            params=params,
            url=path,
            json=json,
            files=files,
            data=data,
            headers=headers,
            cookies=cookies,
            timeout=10,
        )
        print("response being retrieved...")
        status = resp.status_code
        data = resp.json() if resp.text else None
        print()
        print("status:", status)
        print("data:", data)
    return status, data

The interesting thing is that, if I comment the lines I specified in avatar_views.py, test passes without issues. I am pretty sure that there is some stupid error, but I gave up on searching possible issues, so I am hoping that someone can help me.

Full log:

FAILED [100%]get_user_avatars_handler entered...
params before request: {'offset': 0, 'limit': 100, 'created_at': datetime.datetime(2023, 11, 5, 21, 36, 15, 360297, tzinfo=<UTC>)}
request entered...
passed args:
path: /users/1/avatars
method: get
json: None
headers: None
data: None
files: None
params: {'offset': 0, 'limit': 100, 'created_at': datetime.datetime(2023, 11, 5, 21, 36, 15, 360297, tzinfo=<UTC>)}
cookies: None
going to request with given args...
response being retrieved...

status: 500
data: {'exc_code': 'InternalServiceError', 'exc_data': {}, 'message': 'Internal Service Error'}
data in test_get_user_avatars: {'exc_code': 'InternalServiceError', 'exc_data': {}, 'message': 'Internal Service Error'}
0

There are 0 answers