Kiểm thử tự động với FastAPI

Nhập môn FastAPI

Matt Eckerle

Software and Data Engineering Leader

Kiểm thử tự động là gì?

Unit test

  • Trọng tâm: Mã tách biệt
  • Mục đích: Xác thực chức năng mã
  • Phạm vi: Hàm hoặc phương thức
  • Môi trường: Môi trường Python tách biệt
def test_main():
    response = main()
    assert response == {"msg": "Hello"}

System test

  • Trọng tâm: Hoạt động hệ thống tách biệt
  • Mục đích: Xác thực chức năng hệ thống
  • Phạm vi: Endpoint
  • Môi trường: Python với ứng dụng đang chạy
def test_read_main():
    response = client.get("/")
    assert response.status_code == 200
    assert response.json() == {"msg": 
                               "Hello"}
Nhập môn FastAPI

Dùng TestClient

TestClient: HTTP client cho pytest

# Import TestClient và app
from fastapi.testclient import TestClient
from .main import app

# Tạo client kiểm thử với ngữ cảnh ứng dụng
client = TestClient(app)

def test_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello"}
Nhập môn FastAPI

Kiểm thử phản hồi lỗi/thất bại

Ứng dụng

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

Kiểm thử

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."}
Nhập môn FastAPI

Let's practice!

Nhập môn FastAPI

Preparing Video For Download...