在 Day 21 完成 Docker 多階段建構與映像檔瘦身後,PrescriptionVLM 系統已具備輕量化容器。
然而,在團隊協作或持續迭代功能時,人工執行 pytest 單元測試與 Docker 打包容易遺漏,甚至將有問題的程式碼推送到 GitHub。
今天我們將為 PrescriptionVLM 專案建立 GitHub Actions CI/CD 自動化流水線。完成項目包含:
在軟體開發實踐中,導入 CI/CD 流水線有以下好處:
為了讓 CI 流水線有具體的測試目標,我們在專案中建立基礎測試腳本。
請在專案根目錄建立 tests/test_app.py:
import pytest
import json
from app import app, compute_image_hash
@pytest.fixture
def client():
app.config['TESTING'] = True
with app.test_client() as client:
yield client
def test_dashboard_route(client):
"""測試 Web 儀表板頁面是否能正常渲染"""
response = client.get('/dashboard')
assert response.status_code == 200
def test_image_hash_computation():
"""測試圖片 SHA-256 雜湊值計算是否一致"""
dummy_data = b"fake_prescription_image_bytes"
hash1 = compute_image_hash(dummy_data)
hash2 = compute_image_hash(dummy_data)
assert hash1 == hash2
assert len(hash1) == 64
def test_analyze_prescription_no_file(client):
"""測試未傳送圖片時 API 的錯誤防禦"""
response = client.post('/analyze-prescription')
assert response.status_code == 400
data = json.loads(response.data)
assert "error" in data
請在專案目錄下建立 .github/workflows/ci.yml 檔案:
name: PrescriptionVLM CI Pipeline
on:
push:
branches: [ "main", "master" ]
pull_request:
branches: [ "main", "master" ]
jobs:
test-and-build:
runs-on: ubuntu-latest
services:
redis:
image: redis:7.2-alpine
ports:
- 6379:6379
steps:
- name: 1. 檢出專案程式碼
uses: actions/checkout@v4
- name: 2. 設定 Python 3.11 環境
uses: actions/setup-python@v5
with:
python-version: "3.11"
cache: "pip"
- name: 3. 安裝專案套件依賴
run: |
python -m pip install --upgrade pip
pip install flake8 pytest pytest-cov mypy
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
- name: 4. 執行 Flake8 與 Mypy 靜態程式碼檢查
run: |
# 檢查語法錯誤與未定義變數
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# Mypy 型別校驗
mypy schemas.py --ignore-missing-imports
- name: 5. 執行 Pytest 自動化單元測試
env:
REDIS_HOST: localhost
REDIS_PORT: 6379
GEMINI_API_KEY: ${{ secrets.GEMINI_API_KEY }}
run: |
pytest --verbose
- name: 6. 驗證 Docker 多階段建構
run: |
docker build -t prescription-vlm:ci-test .
1. 本地執行測試預演
在推送到 GitHub 前,先在 Terminal 執行 pytest 確保測試全數通過:
pytest --verbose
2. 提交程式碼並觸發 GitHub Actions
將 CI 相關設定與測試程式碼推送到 GitHub 倉庫:
git add .github/workflows/ci.yml tests/test_app.py
git commit -m "Day 22: Setup GitHub Actions CI pipeline with automated testing and Docker build checks"
git push
3. 檢查 GitHub Actions 執行結果
開啟你的 GitHub 專案倉庫頁面:
確保所有檔案皆已版控提交:
git add .
git commit -m "保留雙引號 改填寫自己要記錄的標記 ex.鐵人賽第二十二天"
git push
今天我們透過 GitHub Actions 建構了 CI 自動化測試與建構流水線,讓每一次程式碼的改動都會自動通過靜態檢查、單元測試與 Docker 打包驗證,確保系統品質穩定。
明天(Day 23),我們將進入生產環境部署階段,實作 Gunicorn 高效能 WSGI 伺服器配置與 Nginx 反向代理設定,讓 PrescriptionVLM 擺脫 Flask 內建開發伺服器,邁向高併發正式營運!