FastAPI 비동기 API를 pytest로 테스트 하기

poetry로 Python 프로젝트를 세팅하고 FastAPI의 비동기 API를 pytest로 테스트 해보겠습니다. 보통 Database transaction이 있는 동작의 경우 DB 연결을 비동기 형태로 해서 API를 구현하는 경우가 있을텐데 이런 경우 sync 형태로 pytest를 하면 에러가 발생합니다. 비동기 방식 API는 비동기 방식에 맞게 테스트를 구성해주어야 합니다.

간단한 예제로 FastAPI의 공식 문서도 있으니 참고하시면 좋을 것 같습니다.

참고 : https://fastapi.tiangolo.com/advanced/async-tests/

FastAPI 프로젝트 생성

mkdir test_project
cd test_project
poetry init

의존 패키치 설치

기본적으로 필요한 의존 패키지들을 설치하겠습니다. 비동기 테스트를 위해 필요한 패키지가 anyio, httpx, trio 등입니다.

poetry add fastapi uvicorn pytest anyio httpx trio

프로젝트 구조

.
├── __init__.py
├── main.py
├── poetry.lock
├── pyproject.toml
└── tests
    ├── __init__.py
    └── test_main.py

테스트용 main.py 생성

from fastapi import FastAPI
import time

app = FastAPI()

@app.get("/")
async def read_root():
    return {"Hello": "World"}

test_main.py 생성

import pytest
from httpx import AsyncClient
from test.main import app

@pytest.mark.anyio
async def test_root():
    async with AsyncClient(app=app, base_url="http://test") as ac:
        response = await ac.get("/")
    assert response.status_code == 200

테스트

poetry run pytest

Leave a Reply