FastAPI 자동화 테스트

FastAPI 입문

Matt Eckerle

Software and Data Engineering Leader

자동화 테스트란?

단위 테스트

  • 초점: 고립된 코드
  • 목적: 코드 기능 검증
  • 범위: 함수 또는 메서드
  • 환경: 분리된 Python 환경
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

시스템 테스트

  • 초점: 분리된 시스템 동작
  • 목적: 시스템 기능 검증
  • 범위: 엔드포인트
  • 환경: 앱이 실행 중인 Python 환경
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
FastAPI 입문

TestClient 사용

TestClient: pytest용 HTTP 클라이언트

# TestClient와 app 임포트
from fastapi.testclient import TestClient
from .main import app

# 애플리케이션 컨텍스트로 테스트 클라이언트 생성
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
FastAPI 입문

오류/실패 응답 테스트

app = FastAPI()

@app.delete("/items")
def delete_item(item: Item):
    if item.id not in item_ids:
        raise HTTPException(
            status_code=404, 
            detail="Item not found.")
    else:
        delete_item_in_database(item)
        return {}

테스트

def test_delete_nonexistent_item():
    response = client.delete(
        "/items",
        json={"id": -999})
    assert response.status_code == 404
    json = response.json()
    assert json == {"detail":
                    "Item not found."}
FastAPI 입문

연습해 봅시다!

FastAPI 입문

Preparing Video For Download...