いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

Goメモ-236 (指定回数分テストを実行)(go test, count)

概要

よく忘れるので、ここにメモメモ。。。

goでテストを行う際、たまに所定の回数分テストを実行してほしいときがあります。

その場合、以下のように指定します。

$ go test -count N ./...

サンプル

Taskfile.yml

version: "3"

# -------------------------------------------------------------------------------
# $ go help testflag
#
#        -count n
#            Run each test, benchmark, and fuzz seed n times (default 1).
#            If -cpu is set, run n times for each GOMAXPROCS value.
#            Examples are always run once. -count does not apply to
#            fuzz tests matched by -fuzz.
# -------------------------------------------------------------------------------
tasks:
  default:
    cmds:
      - task: once
      - task: count
  once:
    cmds:
      - go test -count 1 .
  count:
    cmds:
      - go test -count 100 .

lib.go

以下のクソコードはわざとデータ競合が起こるように記載しています。

package lib

import "time"

func Fn(count int) int64 {
    var (
        v int64
    )

    for i := 0; i < count; i++ {
        go func() {
            v += 1
        }()
    }

    time.Sleep(10 * time.Millisecond)

    return v
}

lib_test.go

package lib

import "testing"

func TestFn(t *testing.T) {
    const (
        count = 10
    )

    if v := Fn(count); v != count {
        t.Errorf("[want] %v\t[got] %v", count, v)
    }
}

実行結果

上記の lib.go は、データ競合が発生する可能性がある実装です。

ですが、単純に一回だけテストを実行した場合だとテストが通ってしまうことが多いです。

なので、同じテストを何回も走らせてみると fail してくれます。

gitpod /workspace/try-golang (master) $ task -d examples/testing/testing_count/

task: [once] go test -count 1 .
ok      github.com/devlights/try-golang/examples/testing/testing_count  0.012s

task: [count] go test -count 100 .
--- FAIL: TestFn (0.01s)
    lib._test.go:11: [want] 10  [got] 9
FAIL
FAIL    github.com/devlights/try-golang/examples/testing/testing_count  1.022s
FAIL

まあ、このような場合は -race オプションを付与して実行するのが一番ですね。

あと、 -count 1 を付与してテスト実行すると、常にキャッシュを無視して実行してくれるという効能もあります。

参考情報

https://pkg.go.dev/cmd/go#hdr-Testing_flags

Go言語による並行処理

Go言語による並行処理

Amazon


過去の記事については、以下のページからご参照下さい。

サンプルコードは、以下の場所で公開しています。