2025-07-30

Github Actions matrix + Pytest mark 多節點同步執行 case

隨著自動化測試的 case 越來越多,總有一天會遇到該來平行跑測試這件事。

根據使用的框架、CI/CD 工具不同,實作方式也會有所差異。這邊紀錄一下我之前用 pytest mark 搭配 GitHub Actions 做平行執行的做法。

pytest 的 mark 拿來執行一系列 case 很方便,所以放在 Github Actions 時,決定以 matrix 同時開多個同 mark 名稱的節點來執行,類似下面這樣:
strategy:
  matrix:
    mark: ['node_serviceA', 'node_serviceB', 'node_serviceC']
  fail-fast: false
記得把 fail-fast 設成 false,不然只要有一個節點先執行完,matrix 裡所有節點都會一起終止。

在後續執行的部分,就像這樣使用:
run: pytest -m ${{ matrix.mark }}

而在case裡,case function 或 class 就加上想要在哪個 node 執行,如:

@pytest.mark.node_serviceA
def test_api_service_a():
#...

Github Actions 的收費會看執行時間,執行時間在 matrix 就是看所有節點各別都花了多少時間(等於同時多開n台),所以費用和原先不會有差異。

沒有留言:

張貼留言