kakakakakku blog

Weekly Tech Blog: Keep on Learning!

go test -short で長時間実行されるテストをスキップする

go test でテストを実行するときに -short オプションを付けると実行対象のテストを減らせる.

例えば,長時間実行されるテストがあった場合に毎回全体の実行を待つのではなく,一部のテストをスキップすることで時間短縮できる.開発中に素早くフィードバックを得たいような場合に使えそう❗️最近使う機会があって簡単にまとめておく📝

go help testflag でヘルプを確認すると以下のように表示された.

$ go help testflag
The 'go test' command takes both flags that apply to 'go test' itself
and flags that apply to the resulting test binary.

(中略)

    -short
        Tell long-running tests to shorten their run time.
        It is off by default but set during all.bash so that installing
        the Go tree can run a sanity check but not spend time running
        exhaustive tests.

testing.Short() と組み合わせる

go test -short と実行すると testing.Short() の値が true になる.よって,長時間実行されるテストが自動的に判別されるのではなく,テストコードに以下のような実装を追加することでスキップできるようになる.スキップする場合は SkipNow() 以外に Skip()Skipf() もある.

  • func (c *T) Skip(args ...any)
  • func (c *T) SkipNow()
  • func (c *T) Skipf(format string, args ...any)
if testing.Short() {
    t.SkipNow()
}

pkg.go.dev

サンプルコード

以下のように main_test.go を書いてみた.

  • TestCase1 は毎回実行される
  • TestCase2 はスキップできる
package main

import (
    "testing"
)

func TestCase1(t *testing.T) {
    got := 1
    want := 1
    if got != want {
        t.Errorf("got %d, want %d", want, got)
    }
}

func TestCase2(t *testing.T) {
    if testing.Short() {
        t.SkipNow()
        // t.Skip("it skipped")
        // t.Skipf("it skipped because `testing.Short()` is %t", testing.Short())
    }
    got := 1
    want := 1
    if got != want {
        t.Errorf("got %d, want %d", want, got)
    }
}

実行例 1

TestCase1TestCase2 も実行された.

$ go test -v
=== RUN   TestCase1
--- PASS: TestCase1 (0.00s)
=== RUN   TestCase2
--- PASS: TestCase2 (0.00s)
PASS
ok

実行例 2: t.SkipNow()

TestCase2 はスキップされた.

$ go test -v -short
=== RUN   TestCase1
--- PASS: TestCase1 (0.00s)
=== RUN   TestCase2
--- SKIP: TestCase2 (0.00s)
PASS
ok

実行例 3: t.Skip()

TestCase2 はスキップされた.t.Skip() で指定したログも出力された.

$ go test -v -short
=== RUN   TestCase1
--- PASS: TestCase1 (0.00s)
=== RUN   TestCase2
    main_test.go:18: it skipped
--- SKIP: TestCase2 (0.00s)
PASS
ok

実行例 4: t.Skipf()

TestCase2 はスキップされた.t.Skipf() で指定したログも出力された.

$ go test -v -short
=== RUN   TestCase1
--- PASS: TestCase1 (0.00s)
=== RUN   TestCase2
    main_test.go:19: it skipped because `testing.Short()` is true
--- SKIP: TestCase2 (0.00s)
PASS
ok