測試左移:使用 K6 和 Github Action 進行小範圍的 Load Testing

測試左移:使用 K6 和 Github Action 進行小範圍的 Load Testing
Photo by Towfiqu barbhuiya / Unsplash

隨著產品快速迭代,團隊開始重視「測試左移(Shift Left Testing)」,也就是把測試往開發流程的前端推進。而性能測試(Performance Testing)過去往往是在部署或上線前才進行,是否可以相其他測試項目,提早發現系統瓶頸的機會。

本篇文章想要分享如何在開發階段就導入簡單的負載測試,透過使用 K6 和 Github Action 的整合,讓每次 push 程式碼就可以執行小範圍的負載測試,讓開發人員能夠提早發現潛在問題。

本篇文章裡會說明:

  • 在 Github 專案裡整合 K6 到 CI 的工作流程
  • 在開發人員 push 時觸發負載測試
  • 撰寫簡單的 K6 測試腳本
  • 透過 Github comment 手動觸發負載測試
  • 在 Grafana Cloud 上面看到測試結果

安裝 K6 環境

Load testing for engineering teams | Grafana k6
k6 is an open-source tool and cloud service that makes load testing easy for developers and QA engineers.

在開始之前,我們需要先安裝 K6。根據你的作業系統,可以參考官網的 https://grafana.com/docs/k6/latest/set-up/install-k6/

專案架構建議

k6-perf-project/
├── .github/
│ └── workflows/
│ └── perf-test.yml
├── tests/
│ └── basic-test.js
├ ...

撰寫測試腳本 (Test Script)

import http from 'k6/http';
import { check, sleep } from 'k6';

export let options = {
  vus: 5, // 虛擬使用者數量
  duration: '10s', // 測試時間
};

export default function () {
  const res = http.get('https://reqres.in/');
  check(res, {
    'status is 200': (r) => r.status === 200,
  });
  sleep(1);
}

設定 GitHub Actions Workflow

name: K6 Performance Test

on:
  push:
    branches:
      - main
  issue_comment:
    types: [created]

jobs:
  run-perf:
    if: github.event_name == 'push' || (github.event.comment.body == '/run-perf')

    runs-on: ubuntu-latest
    env:
      K6_CLOUD_TOKEN: ${{ secrets.K6_CLOUD_TOKEN }}
      K6_CLOUD_PROJECT_ID: ${{ secrets.K6_CLOUD_PROJECT_ID }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Setup K6
        uses: grafana/setup-k6-action@v1
        with:
          browser: true

      - name: Run K6 Performance Test
        uses: grafana/run-k6-action@v1
        with:
          path: |
            tests/*.js
          parallel: true
          cloud-run-locally: true
          cloud-comment-on-pr: true

透過 comment 執行 perf test

透過 github action 判斷 comment 內容,可以讓開發人員送出 PR (Pull Request),可以透過留言的方式 /run-perf 來觸發測試。

測試左移的好處

這樣的流程雖然測試規模不大(例如每次只跑 5~10 個虛擬使用者),但目的不是要做壓力測試,而是讓開發者能「提早發現異常」,例如:

  • 某個 API response time 突然飆高
  • 資料庫查詢被 N+1 打爆
  • Health check 出現不穩定

這些問題能在開發流程中就發現就可以大幅減少後期需要修復的風險。

結語

K6 是一個輕量但強大的工具,結合 GitHub Actions 可以實現更早期、更頻繁的效能驗證。雖然只是小規模測試,但對穩定度、可預測性與 DevOps 文化來說,是非常實用的一步。

如果你對於效能測試有興趣,請訂閱我的部落格,可以獲得最新的文章。

Subscribe to RyotaVL 測試工程師

Sign up now to get access to the library of members-only issues.
Jamie Larson
Subscribe