0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

CIでGoのテストを実行するとき、失敗したテストを探すのが面倒だから改善した

Last updated at Posted at 2025-02-12

GitHub Actionsの黄色いぐるぐるが赤いバツマークになったとき、うんざりする。しかも詳細を見てみると、テストで失敗している。そして画面をスクロールしながら"FAIL"の文字を一生懸命探すことになる。テストが多くなると、探すのがとても面倒。

image.png

(テストのエラー画面。画像はサンプルなので大した量ではないが、仕事で扱うテストの量は膨大でつらい。)

そこで、mfridman/tparseを導入することで失敗したテストをすぐに探せるようにした。

tparse attempts to do just that; return failed tests and panics, if any, followed by a single package-level summary. No more searching for the literal string: "--- FAIL".

上記の説明の通り、まさに自分が感じていた課題にうってつけのライブラリだ。

さっそくスクリプトを書いてみる。元のスクリプトは以下の通り。

before

name: CI
on:
  push:
    branches:
      - master
  pull_request:
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: Check out code
        uses: actions/checkout@v2
      - name: Set up Go
        uses: actions/setup-go@v3
        with:
          go-version: "1.23"
      - name: Install dependencies
        run: go mod tidy

      - name: Run tests
        run: go test ./...
変更箇所
       - name: Install dependencies
         run: go mod tidy

+      - name: Install tparse
+        run: go install github.com/mfridman/tparse@latest

       - name: Run tests
-         run: go test ./... -v
+         run: |
+           set -o pipefail
+           go test ./... -json | tparse -all

ポイントは2つある。1つは、go testを -jsonをつけて実行すること。公式にも

Don't forget to run go test with the -json flag.

と書いてある。ちなみに-vはなくてok。

もう1つはgo test ./... -json | tparse -allとしてそれぞれパイプ演算子でつなぐこと。

     run: |
       set -o pipefail
       go test ./... -json
       tparse -all

上記のようにgo testとtparseをパイプ演算子で繋がないとgo testとtparseが独立して実行される。tparseはgo testの結果を受け取るのではなく空のデータで解析するので、CIにはgo testの実行結果がjson形式で表示される。

ちなみに、突如として現れたset -o pipefailはよくおまじない的に使われるらしい。パイプラインの中で失敗したいずれかのコマンドの終了ステータスがパイプライン全体の終了ステータスになる。これにより、「前のコマンドは失敗したのに、後のコマンドは成功したのでパイプラインとしては正常終了」のようなことが起きず、エラーを追跡しやすくなる

参考: https://hirosaji.hatenablog.com/entry/2022/07/05/210045

以上をふまえ、tparseを使ってテストを失敗させると以下のようになる。

image.png

一番下にパッケージ単位でテストのサマリーが出てくる。また、その上に失敗したテストが表示されるので探す手間が省ける。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?