什麼是測試 (Testing)?
測試 (Testing) 是透過編寫額外程式碼來自動驗證應用程式邏輯是否正確的過程,就像出廠前的品管檢測,確保產品無瑕疵。
測試 (Testing) 基礎應用
- 使用 Python 標準 pytest 框架搭配 FastAPI 內建的 TestClient 進行 API 整合測試
- 透過
client = TestClient(app)建立模擬客戶端,不需啟動真實伺服器即可發送請求 - 測試檔案與函式名稱皆須以 test_ 開頭 (例如 test_main.py),pytest 才能自動偵測
- 使用 assert 關鍵字檢查
response.status_code與response.json()是否符合預期 - 利用
app.dependency_overrides替換資料庫連線或驗證邏輯,將測試環境與生產環境完全隔離
# test_main.py:撰寫測試程式碼
import pytest
from fastapi.testclient import TestClient
from main import app, get_db
@pytest.fixture
def client():
# 這裡可以做 client 的初始化設定
return TestClient(app)
@pytest.fixture
def override_db():
# 設定假資料庫
app.dependency_overrides[get_db] = lambda: "Test DB"
yield # 讓測試函數執行
# 清除覆寫 (無論測試成功或失敗,這裡都會執行)
app.dependency_overrides.clear()
def test_create_item_success(client, override_db):
payload = {"name": "Laptop", "price": 30000}
response = client.post("/items/", json=payload)
assert response.status_code == 200
assert response.json() == {"name": "Laptop", "db": "Test DB"}
def test_create_item_invalid_price(client):
payload = {"name": "Bad Item", "price": -100}
response = client.post("/items/", json=payload)
assert response.status_code == 400
assert response.json() == {"detail": "Price invalid"}

















