การทดสอบอัตโนมัติใน FastAPI

FastAPI เบื้องต้น

Matt Eckerle

Software and Data Engineering Leader

การทดสอบอัตโนมัติคืออะไร?

Unit Tests

  • จุดเน้น: โค้ดที่แยกอิสระ
  • วัตถุประสงค์: ตรวจสอบการทำงานของโค้ด
  • ขอบเขต: ฟังก์ชันหรือเมธอด
  • สภาพแวดล้อม: Python env แบบแยกอิสระ
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

System Tests

  • จุดเน้น: การทำงานของระบบแบบแยกอิสระ
  • วัตถุประสงค์: ตรวจสอบการทำงานของระบบ
  • ขอบเขต: Endpoint
  • สภาพแวดล้อม: Python env พร้อมแอปที่รันอยู่
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
FastAPI เบื้องต้น

การใช้งาน TestClient

TestClient: HTTP client สำหรับ pytest

# Import TestClient and app
from fastapi.testclient import TestClient
from .main import app

# Create test client with application context
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
FastAPI เบื้องต้น

การทดสอบการตอบสนองแบบข้อผิดพลาดหรือความล้มเหลว

App

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 {}

Test

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...