在 Day 24 完成 雲端 VPS 一鍵自動化部署 與 Let's Encrypt SSL/TLS 數位憑證 設定後,PrescriptionVLM 系統已運行於正式公網環境。
然而,系統在實際上線後,可能會遇到多位長輩或照護者在用藥時間同時上傳藥袋照片的情境。為了驗證系統在高併發請求下的穩定性,以及確定 Day 19 實作的 Redis 快取與 API 限流機制 是否有效,我們需要進行完整的 端到端測試(E2E Testing) 與 Locust 壓力測試(Load Testing)。
今天我們將為 PrescriptionVLM 系統建立 自動化 E2E 測試與 Locust 負載壓測。完成項目包含:
在正式發布產品前,進行端到端與壓力測試有以下好處:
requirements.txt)請開啟專案根目錄的 requirements.txt,加入 Locust 壓力測試套件:
locust==2.23.1
tests/test_e2e.py)請在專案中建立 tests/test_e2e.py 檔案,寫入模擬完整分析流程的 E2E 測試:
import pytest
import os
import io
def test_full_prescription_analysis_pipeline(client):
"""測試從圖片上傳、VLM 解析、Redis 快取到 LINE 推播的完整流程"""
# 建立測試用模擬圖片二進位資料
test_image_bytes = b"fake_prescription_image_data_for_e2e_testing"
data = {
'image': (io.BytesIO(test_image_bytes), 'test_rx.jpg')
}
# 1. 第一次發送請求(預期:Cache Miss)
response1 = client.post(
'/analyze-prescription',
data=data,
content_type='multipart/form-data'
)
assert response1.status_code in [200, 429, 503]
if response1.status_code == 200:
json_data1 = response1.get_json()
assert json_data1['status'] == 'success'
assert json_data1['cached'] is False
assert 'request_id' in json_data1
# 2. 第二次發送相同圖片請求(預期:Cache Hit 快取命中)
data_cached = {
'image': (io.BytesIO(test_image_bytes), 'test_rx.jpg')
}
response2 = client.post(
'/analyze-prescription',
data=data_cached,
content_type='multipart/form-data'
)
assert response2.status_code == 200
json_data2 = response2.get_json()
assert json_data2['status'] == 'success'
assert json_data2['cached'] is True
locustfile.py)在專案根目錄建立 locustfile.py,設定模擬使用者的行為模式:
from locust import HttpUser, task, between
import io
class PrescriptionVLMUser(HttpUser):
# 模擬使用者在每次操作之間的等待時間(1 到 3 秒)
wait_time = between(1, 3)
def on_start(self):
"""初始化測試圖片數據"""
self.test_image = b"locust_load_test_prescription_image_bytes"
@task(3)
def test_dashboard(self):
"""模擬使用者瀏覽儀表板頁面 (權重: 3)"""
self.client.get("/dashboard", name="GET /dashboard")
@task(1)
def test_analyze_prescription(self):
"""模擬使用者上傳藥單照片進行分析 (權重: 1)"""
files = {
'image': ('test_rx.jpg', io.BytesIO(self.test_image), 'image/jpeg')
}
headers = {
'X-Request-ID': 'locust-test-trace-id'
}
self.client.post(
"/analyze-prescription",
files=files,
headers=headers,
name="POST /analyze-prescription"
)
1. 啟動 Locust 壓測 Web 介面
在 Terminal 執行命令啟動 Locust:
locust -f locustfile.py --host=http://127.0.0.1
http://localhost:8089。2. 驗證壓測與快取效能數據
點擊 Start Swarming 執行測試,觀察 Locust 統計儀表板:
測試通過後,將 Day 25 的修改提交至 GitHub:
git add requirements.txt tests/test_e2e.py locustfile.py
git commit -m "保留雙引號 改填寫自己要記錄的標記 ex.鐵人賽第二十五天"
git push
今天我們透過 自動化 E2E 端到端測試 與 Locust 負載壓力測試,驗證了 PrescriptionVLM 系統在尖峰流量下的承載能力與快取防禦機制。
明天(Day 26),我們將進入專案維護與營運階段,實作 Grafana / Prometheus 系統數據監控面板與異常警報通知,讓營運者隨時掌握系統健康狀況!