FastAPI 통합 테스트를 개발하는데 참고자료를 정리하고자 간단하게 정리하고자 작성했다.
pip install pytest
# app/routers/post.py
from typing import Dict, Union
from fastapi import APIRouter
from pydantic import BaseModel
post_router = APIRouter()
@post_router.get("")
def get_items():
return [{"name": "item1"}, {"name": "item2"}]
@post_router.get("/{item_id}")
def get_item(item_id: int):
return {"name": "item1", "id": item_id}
class RequestModel(BaseModel):
item_id: Union[str, None]
item_name: Union[str, None]
@post_router.post("")
def get_item(request: RequestModel):
data = {'item_id': request.item_id, 'item_name': request.item_name}
return {'data': data}
from fastapi import Response
from fastapi.testclient import TestClient
from app.main import create_app
from app.routers.post import RequestModel
app = create_app()
client = TestClient(app)
def test_get_items():
response = client.get("/posts")
assert response.status_code == 200
assert response.json() == [{"name": "item1"}, {"name": "item2"}]
def test_get_item_valid_id():
response = client.get("/posts/1")
assert response.status_code == 200
assert response.json() == {"name": "item1", "id": 1}
def test_get_item_invalid_id():
response = client.get("/posts/abc")
assert response.status_code == 422 # 유효하지 않은 요청 데이터
def test_post_item_valid_id():
# dummy_request = RequestModel(item_id='zxczxc', item_name='zxczxcxzczx').model_dump() # 데이터를 json 그대로 넣어도 된다.
dummy_request = {"item_id": 'zxczxc', 'item_name': 'zxczxczxc'}
response = client.post("/posts", json=dummy_request)
assert response.status_code == 200
assert response.json() == '비교할 객체'
pytest를 통해 실행한다. (그냥 pytest만 하면 test파일이 붙은 모든 파일들 테스트 실행)
pytest [파일 경로]
DB 연결 통합 테스트를 검색하다 들어오게 됐습니다~
통합 테스트보다는 Unit테스트에 더 가까운 글인 것 같아요!