FastAPI otomatik testleri

FastAPI'ye Giriş

Matt Eckerle

Software and Data Engineering Leader

Otomatik Testler Nedir?

Birim Testleri

  • Odak: İzole kod
  • Amaç: Kod işlevini doğrulama
  • Kapsam: Fonksiyon veya metot
  • Ortam: İzole Python ortamı
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

Sistem Testleri

  • Odak: İzole sistem işlemleri
  • Amaç: Sistem işlevini doğrulama
  • Kapsam: Uç nokta
  • Ortam: Uygulama çalışan Python ortamı
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
FastAPI'ye Giriş

TestClient kullanımı

TestClient: pytest için HTTP istemcisi

# TestClient ve app'i içe aktarın
from fastapi.testclient import TestClient
from .main import app

# Uygulama bağlamıyla test istemcisi oluşturun
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
FastAPI'ye Giriş

Hata veya başarısızlık yanıtlarını test etme

Uygulama

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'ye Giriş

Hadi pratik yapalım!

FastAPI'ye Giriş

Preparing Video For Download...