testing

package
v1.25.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 5, 2025 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

testingパッケージはGoパッケージの自動テストをサポートします。 これは"go test"コマンドと一緒に使用することを意図しています。"go test"コマンドは以下の形式の関数を自動的に実行します。

func TestXxx(*testing.T)

ただし、Xxxは小文字ではじまらないものとします。関数名はテストルーチンを識別するために使用されます。

これらの関数内では、失敗を通知するために [T.Error]、[T.Fail] などの関連メソッドを使用してください。

新しいテストスイートを書くためには、次の要件に従っているファイルを作成し、"_test.go"で終わる名前を付けます。 このファイルは通常のパッケージのビルドから除外されますが、"go test"コマンドの実行時には含まれます。

テストファイルは、テスト対象のパッケージと同じパッケージにあるか、"_test"という接尾辞の付いた対応するパッケージに含めることができます。

テストファイルが同じパッケージにある場合、パッケージ内の非公開の識別子を参照することができます。次の例のようになります。

package abs

import "testing"

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

ファイルが別の"_test"パッケージにある場合、テスト対象のパッケージを明示的にインポートする必要があり、公開された識別子のみ使用できます。これは「ブラックボックス」テストとして知られています。

package abs_test

import (
	"testing"

	"path_to_pkg/abs"
)

func TestAbs(t *testing.T) {
    got := abs.Abs(-1)
    if got != 1 {
        t.Errorf("Abs(-1) = %d; want 1", got)
    }
}

詳細については go help test および go help testflag を実行してください。

# ベンチマーク

次の形式の関数

func BenchmarkXxx(*testing.B)

are considered benchmarks, and are executed by the "go test" command when its -bench flag is provided. Benchmarks are run sequentially.

For a description of the testing flags, see go help testflag.

A sample benchmark function looks like this:

func BenchmarkRandInt(b *testing.B) {
    for b.Loop() {
        rand.Int()
    }
}

The output

BenchmarkRandInt-8   	68453040	        17.8 ns/op

means that the body of the loop ran 68453040 times at a speed of 17.8 ns per loop.

Only the body of the loop is timed, so benchmarks may do expensive setup before calling b.Loop, which will not be counted toward the benchmark measurement:

func BenchmarkBigLen(b *testing.B) {
    big := NewBig()
    for b.Loop() {
        big.Len()
    }
}

If a benchmark needs to test performance in a parallel setting, it may use the RunParallel helper function; such benchmarks are intended to be used with the go test -cpu flag:

func BenchmarkTemplateParallel(b *testing.B) {
    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
    b.RunParallel(func(pb *testing.PB) {
        var buf bytes.Buffer
        for pb.Next() {
            buf.Reset()
            templ.Execute(&buf, "World")
        }
    })
}

A detailed specification of the benchmark results format is given in https://go.dev/design/14313-benchmark-format.

There are standard tools for working with benchmark results at golang.org/x/perf/cmd. In particular, golang.org/x/perf/cmd/benchstat performs statistically robust A/B comparisons.

b.N-style benchmarks

Prior to the introduction of B.Loop, benchmarks were written in a different style using B.N. For example:

func BenchmarkRandInt(b *testing.B) {
    for range b.N {
        rand.Int()
    }
}

In this style of benchmark, the benchmark function must run the target code b.N times. The benchmark function is called multiple times with b.N adjusted until the benchmark function lasts long enough to be timed reliably. This also means any setup done before the loop may be run several times.

If a benchmark needs some expensive setup before running, the timer should be explicitly reset:

func BenchmarkBigLen(b *testing.B) {
    big := NewBig()
    b.ResetTimer()
    for range b.N {
        big.Len()
    }
}

New benchmarks should prefer using B.Loop, which is more robust and more efficient.

Examples

The package also runs and verifies example code. Example functions may include a concluding line comment that begins with "Output:" and is compared with the standard output of the function when the tests are run. (The comparison ignores leading and trailing space.) These are examples of an example:

func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}

func ExampleSalutations() {
    fmt.Println("hello, and")
    fmt.Println("goodbye")
    // Output:
    // hello, and
    // goodbye
}

The comment prefix "Unordered output:" is like "Output:", but matches any line order:

func ExamplePerm() {
    for _, value := range Perm(5) {
        fmt.Println(value)
    }
    // Unordered output: 4
    // 2
    // 1
    // 3
    // 0
}

Example functions without output comments are compiled but not executed.

The naming convention to declare examples for the package, a function F, a type T and method M on type T are:

func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }

Multiple example functions for a package/type/function/method may be provided by appending a distinct suffix to the name. The suffix must start with a lower-case letter.

func Example_suffix() { ... }
func ExampleF_suffix() { ... }
func ExampleT_suffix() { ... }
func ExampleT_M_suffix() { ... }

The entire test file is presented as the example when it contains a single example function, at least one other function, type, variable, or constant declaration, and no test or benchmark functions.

Fuzzing

'go test' and the testing package support fuzzing, a testing technique where a function is called with randomly generated inputs to find bugs not anticipated by unit tests.

Functions of the form

func FuzzXxx(*testing.F)

are considered fuzz tests.

For example:

func FuzzHex(f *testing.F) {
  for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} {
    f.Add(seed)
  }
  f.Fuzz(func(t *testing.T, in []byte) {
    enc := hex.EncodeToString(in)
    out, err := hex.DecodeString(enc)
    if err != nil {
      t.Fatalf("%v: decode: %v", in, err)
    }
    if !bytes.Equal(in, out) {
      t.Fatalf("%v: not equal after round trip: %v", in, out)
    }
  })
}

A fuzz test maintains a seed corpus, or a set of inputs which are run by default, and can seed input generation. Seed inputs may be registered by calling F.Add or by storing files in the directory testdata/fuzz/<Name> (where <Name> is the name of the fuzz test) within the package containing the fuzz test. Seed inputs are optional, but the fuzzing engine may find bugs more efficiently when provided with a set of small seed inputs with good code coverage. These seed inputs can also serve as regression tests for bugs identified through fuzzing.

The function passed to F.Fuzz within the fuzz test is considered the fuzz target. A fuzz target must accept a *T parameter, followed by one or more parameters for random inputs. The types of arguments passed to F.Add must be identical to the types of these parameters. The fuzz target may signal that it's found a problem the same way tests do: by calling [T.Fail] (or any method that calls it like [T.Error] or [T.Fatal]) or by panicking.

When fuzzing is enabled (by setting the -fuzz flag to a regular expression that matches a specific fuzz test), the fuzz target is called with arguments generated by repeatedly making random changes to the seed inputs. On supported platforms, 'go test' compiles the test executable with fuzzing coverage instrumentation. The fuzzing engine uses that instrumentation to find and cache inputs that expand coverage, increasing the likelihood of finding bugs. If the fuzz target fails for a given input, the fuzzing engine writes the inputs that caused the failure to a file in the directory testdata/fuzz/<Name> within the package directory. This file later serves as a seed input. If the file can't be written at that location (for example, because the directory is read-only), the fuzzing engine writes the file to the fuzz cache directory within the build cache instead.

When fuzzing is disabled, the fuzz target is called with the seed inputs registered with F.Add and seed inputs from testdata/fuzz/<Name>. In this mode, the fuzz test acts much like a regular test, with subtests started with F.Fuzz instead of T.Run.

See https://go.dev/doc/fuzz for documentation about fuzzing.

Skipping

Tests or benchmarks may be skipped at run time with a call to [T.Skip] or [B.Skip]:

func TestTimeConsuming(t *testing.T) {
    if testing.Short() {
        t.Skip("skipping test in short mode.")
    }
    ...
}

The [T.Skip] method can be used in a fuzz target if the input is invalid, but should not be considered a failing input. For example:

func FuzzJSONMarshaling(f *testing.F) {
    f.Fuzz(func(t *testing.T, b []byte) {
        var v interface{}
        if err := json.Unmarshal(b, &v); err != nil {
            t.Skip()
        }
        if _, err := json.Marshal(v); err != nil {
            t.Errorf("Marshal: %v", err)
        }
    })
}

Subtests and Sub-benchmarks

The T.Run and B.Run methods allow defining subtests and sub-benchmarks, without having to define separate functions for each. This enables uses like table-driven benchmarks and creating hierarchical tests. It also provides a way to share common setup and tear-down code:

func TestFoo(t *testing.T) {
    // <setup code>
    t.Run("A=1", func(t *testing.T) { ... })
    t.Run("A=2", func(t *testing.T) { ... })
    t.Run("B=1", func(t *testing.T) { ... })
    // <tear-down code>
}

Each subtest and sub-benchmark has a unique name: the combination of the name of the top-level test and the sequence of names passed to Run, separated by slashes, with an optional trailing sequence number for disambiguation.

The argument to the -run, -bench, and -fuzz command-line flags is an unanchored regular expression that matches the test's name. For tests with multiple slash-separated elements, such as subtests, the argument is itself slash-separated, with expressions matching each name element in turn. Because it is unanchored, an empty expression matches any string. For example, using "matching" to mean "whose name contains":

go test -run ''        # Run all tests.
go test -run Foo       # Run top-level tests matching "Foo", such as "TestFooBar".
go test -run Foo/A=    # For top-level tests matching "Foo", run subtests matching "A=".
go test -run /A=1      # For all top-level tests, run subtests matching "A=1".
go test -fuzz FuzzFoo  # Fuzz the target matching "FuzzFoo"

The -run argument can also be used to run a specific value in the seed corpus, for debugging. For example:

go test -run=FuzzFoo/9ddb952d9814

The -fuzz and -run flags can both be set, in order to fuzz a target but skip the execution of all other tests.

Subtests can also be used to control parallelism. A parent test will only complete once all of its subtests complete. In this example, all tests are run in parallel with each other, and only with each other, regardless of other top-level tests that may be defined:

func TestGroupedParallel(t *testing.T) {
    for _, tc := range tests {
        t.Run(tc.Name, func(t *testing.T) {
            t.Parallel()
            ...
        })
    }
}

Run does not return until parallel subtests have completed, providing a way to clean up after a group of parallel tests:

func TestTeardownParallel(t *testing.T) {
    // This Run will not return until the parallel tests finish.
    t.Run("group", func(t *testing.T) {
        t.Run("Test1", parallelTest1)
        t.Run("Test2", parallelTest2)
        t.Run("Test3", parallelTest3)
    })
    // <tear-down code>
}

Main

It is sometimes necessary for a test or benchmark program to do extra setup or teardown before or after it executes. It is also sometimes necessary to control which code runs on the main thread. To support these and other cases, if a test file contains a function:

func TestMain(m *testing.M)

then the generated test will call TestMain(m) instead of running the tests or benchmarks directly. TestMain runs in the main goroutine and can do whatever setup and teardown is necessary around a call to m.Run. m.Run will return an exit code that may be passed to os.Exit. If TestMain returns, the test wrapper will pass the result of m.Run to os.Exit itself.

When TestMain is called, flag.Parse has not been run. If TestMain depends on command-line flags, including those of the testing package, it should call flag.Parse explicitly. Command line flags are always parsed by the time test or benchmark functions run.

A simple implementation of TestMain is:

func TestMain(m *testing.M) {
	// call flag.Parse() here if TestMain uses flags
	m.Run()
}

TestMain is a low-level primitive and should not be necessary for casual testing needs, where ordinary test functions suffice.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllocsPerRun added in v1.1.0

func AllocsPerRun(runs int, f func()) (avg float64)

AllocsPerRunは、関数fの呼び出し中に行われる平均的な割り当ての数を返します。 返り値はfloat64型ですが、常に整数値になります。

割り当ての数を計算するために、まず関数はウォームアップとして一度実行されます。 指定された回数の実行における平均的な割り当ての数が測定され、返されます。

AllocsPerRunは、計測中に runtime.GOMAXPROCS を1に設定し、終了時に元に戻します。

func CoverMode added in v1.8.0

func CoverMode() string

CoverModeはテストカバレッジモードの設定を報告します。値は「set」、「count」または「atomic」です。テストカバレッジが有効でない場合、戻り値は空になります。

func Coverage added in v1.4.0

func Coverage() float64

Coverage reports the current code coverage as a fraction in the range [0, 1]. If coverage is not enabled, Coverage returns 0.

When running a large set of sequential test cases, checking Coverage after each one can be useful for identifying which test cases exercise new code paths. It is not a replacement for the reports generated by 'go test -cover' and 'go tool cover'.

func Init added in v1.13.0

func Init()

Initはテストフラグを登録します。これらのフラグは、テスト関数を実行する前に"go test"コマンドによって自動的に登録されるため、Initは、"go test"を使用せずにBenchmarkなどの関数を呼び出す場合にのみ必要です。

Initは並行して呼び出すことは安全ではありません。 すでに呼び出されている場合は、効果がありません。

func Main

func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)

Mainは"go test"コマンドの実装の一部である内部関数です。 クロスパッケージであり "internal" パッケージ以前から存在するためエクスポートされています。 現在は"go test"では使用されていませんが、可能な限り他の"go test"を模倣するシステムのために保持されています。 ただし、testingパッケージに新機能が追加されるとMainを更新できない場合があります。 "go test"を模倣するシステムは MainStart の使用に切り替えるべきです。

func RegisterCover added in v1.2.0

func RegisterCover(c Cover)

RegisterCoverはテストのためのカバレッジデータアキュムレータを記録します。 注意: この関数はテストインフラストラクチャ内部のものであり、変更される可能性があります。 まだGo 1互換性ガイドラインには含まれていません。

func RunBenchmarks

func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)

RunBenchmarksは内部関数ですが、クロスパッケージであるためにエクスポートされています。 これは"go test"コマンドの実装の一部です。

func RunExamples

func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)

RunExamples は内部関数ですが、クロスパッケージとなっているため公開されています。 これは「go test」コマンドの実装の一部です。

func RunTests

func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)

RunTestsは内部関数ですが、クロスパッケージであるためにエクスポートされています。 これは"go test"コマンドの実装の一部です。

func Short

func Short() bool

Short は -test.short フラグが設定されているかどうかを報告します。

func Testing added in v1.21.0

func Testing() bool

Testingは現在のコードがテストで実行されているかどうかを報告します。 "go test"で作られたプログラムではtrueを報告し、 "go build"で作られたプログラムではfalseを報告します。

func Verbose added in v1.1.0

func Verbose() bool

Verboseは、-test.vフラグが設定されているかどうかを報告します。

Types

type B

type B struct {
	N int
	// contains filtered or unexported fields
}

Bはベンチマーク関数に渡され、ベンチマークのタイミングや反復回数の管理を行う型です。

ベンチマークは、そのBenchmark関数がreturnするか、[B.FailNow]、[B.Fatal]、[B.Fatalf]、[B.SkipNow]、[B.Skip]、[B.Skipf] のいずれかのメソッドを呼び出すことで終了します。 これらのメソッドは、Benchmark関数を実行しているゴルーチンからのみ呼び出す必要があります。 その他の報告用メソッド([B.Log] や [B.Error] のバリエーションなど)は、複数のゴルーチンから同時に呼び出すことができます。

テストと同様に、ベンチマークのログは実行中に蓄積され、終了時に標準出力に出力されます。ただし、ベンチマークのログは常に出力されるため、ベンチマーク結果に影響を与える可能性がある出力を隠すことはありません。

func (*B) Elapsed added in v1.20.0

func (b *B) Elapsed() time.Duration

Elapsedはベンチマークの計測された経過時間を返します。 Elapsedによって報告される期間は、B.StartTimerB.StopTimerB.ResetTimer によって計測される期間と一致します。

func (*B) Loop added in v1.25.0

func (b *B) Loop() bool

Loopはベンチマークを継続して実行すべき間、trueを返します。

一般的なベンチマークの構造例:

func Benchmark(b *testing.B) {
	... セットアップ ...
	for b.Loop() {
		... 計測対象のコード ...
	}
	... クリーンアップ ...
}

Loopはベンチマーク内で最初に呼び出されたときにベンチマークタイマーをリセットします。 そのため、ベンチマークループ開始前のセットアップ処理は計測に含まれません。 同様に、falseを返すときにタイマーを停止するため、クリーンアップ処理も計測されません。

"for b.Loop() { ... }" ループの本体内では、ループ内で呼び出される関数の引数や戻り値が生存し続け、 コンパイラによるループ本体の完全な最適化が防がれます。現在は、b.Loopループ内で呼び出される関数のインライン化を無効化することで実現されています。 これはループの波括弧内で構文的に呼び出される関数にのみ適用され、ループ条件は必ず "b.Loop()" と記述する必要があります。 ループ内から呼び出される関数では通常通り最適化が行われます。

Loopがfalseを返した後、b.Nには実行された総イテレーション数が格納されるため、ベンチマークはb.Nを使って他の平均値を計算できます。

Loop導入以前は、ベンチマークは0からb.Nまでの明示的なループを含む必要がありました。 ベンチマークはLoopを使うかb.Nまでのループを含むか、どちらか一方にすべきです。 Loopはベンチマークタイマーの管理をより自動化し、各ベンチマーク関数を計測ごとに一度だけ実行します。 一方、b.Nベースのベンチマークはベンチマーク関数(および関連するセットアップ・クリーンアップ)を複数回実行する必要があります。

Example
testing.Benchmark(ExBenchmark)

func (*B) ReportAllocs added in v1.1.0

func (b *B) ReportAllocs()

ReportAllocsはこのベンチマークのためにmallocの統計情報を有効にします。 これは-test.benchmemを設定するのと同じ効果ですが、ReportAllocsを呼び出すベンチマーク関数にのみ影響します。

func (*B) ReportMetric added in v1.13.0

func (b *B) ReportMetric(n float64, unit string)

ReportMetricは報告されたベンチマーク結果に「n unit」を追加します。 もしメトリックが反復ごとのものであれば、呼び出し元はb.Nで割る必要があります。 また、単位は通常"/op"で終わるべきです。 同じ単位の以前の報告値は、ReportMetricによって上書きされます。 unitが空の文字列または空白を含む場合、ReportMetricはパニックを起こします。 unitが通常ベンチマークフレームワーク自体によって報告される単位である場合 (例:"allocs/op")、ReportMetricはそのメトリックを上書きします。 "ns/op"を0に設定すると、組み込まれたメトリックは抑制されます。

Example
package main

import (
	"github.com/shogo82148/std/cmp"
	"github.com/shogo82148/std/slices"
	"github.com/shogo82148/std/testing"
)

func main() {
	// これは特定のアルゴリズム(この場合はソート)に関連するカスタムベンチマークメトリックを報告します。
	testing.Benchmark(func(b *testing.B) {
		var compares int64
		for b.Loop() {
			s := []int{5, 4, 3, 2, 1}
			slices.SortFunc(s, func(a, b int) int {
				compares++
				return cmp.Compare(a, b)
			})
		}
		// このメトリックは操作ごとのものなので、b.Nで割り、"/op"単位で報告してください。
		b.ReportMetric(float64(compares)/float64(b.N), "compares/op")

		// このメトリックは時間当たりの値ですので、b.Elapsed で割り、
		// "/ns" 単位として報告してください。
		b.ReportMetric(float64(compares)/float64(b.Elapsed().Nanoseconds()), "compares/ns")
	})
}
Example (Parallel)
package main

import (
	"github.com/shogo82148/std/cmp"
	"github.com/shogo82148/std/slices"
	"github.com/shogo82148/std/sync/atomic"
	"github.com/shogo82148/std/testing"
)

func main() {
	// これは特定のアルゴリズム(この場合はソート)に関連するカスタムベンチマークメトリックを並列で報告します。
	testing.Benchmark(func(b *testing.B) {
		var compares atomic.Int64
		b.RunParallel(func(pb *testing.PB) {
			for pb.Next() {
				s := []int{5, 4, 3, 2, 1}
				slices.SortFunc(s, func(a, b int) int {
					// RunParallelは関数を並列で多くの回数実行するため、競合する書き込みを避けるためにカウンターを原子的にインクリメントする必要があります。
					compares.Add(1)
					return cmp.Compare(a, b)
				})
			}
		})

		// 注意:すべての並列呼び出しが完了した後に、各メトリックを1回だけ報告してください。

		// このメトリックは操作ごとに計測されるため、b.Nで割り、"/op"単位で報告してください。
		b.ReportMetric(float64(compares.Load())/float64(b.N), "compares/op")

		// このメトリックは時間に対してのものなので、b.Elapsedで割り算して、"/ns"の単位で報告します。
		b.ReportMetric(float64(compares.Load())/float64(b.Elapsed().Nanoseconds()), "compares/ns")
	})
}

func (*B) ResetTimer

func (b *B) ResetTimer()

ResetTimerは経過したベンチマーク時間とメモリ割り当てのカウンターをゼロにし、 ユーザーが報告したメトリクスを削除します。 タイマーが実行中かどうかには影響しません。

func (*B) Run added in v1.7.0

func (b *B) Run(name string, f func(b *B)) bool

指定された名前でサブベンチマークとしてベンチマークを実行します。 フェイルが発生したかどうかを報告します。

サブベンチマークは他のどんなベンチマークとも同じです。 Runを少なくとも1回呼び出すベンチマークは自体は計測されず、N=1で1回呼び出されます。

func (*B) RunParallel added in v1.3.0

func (b *B) RunParallel(body func(*PB))

RunParallelは、ベンチマークを並行して実行します。 複数のゴルーチンを作成し、b.Nの反復をそれらの間で分散します。 ゴルーチンの数はデフォルトでGOMAXPROCSです。CPUに依存しないベンチマークの並列性を 増加させるためには、RunParallelの前に[B.SetParallelism]を呼び出します。 RunParallelは通常、go test -cpuフラグと一緒に使用されます。

body関数は各ゴルーチンで実行されます。それは任意の ゴルーチンローカルの状態を設定し、その後pb.Nextがfalseを返すまで反復します。 それは[B.StartTimer]、B.StopTimer、または[B.ResetTimer]関数を 使用すべきではありません、なぜならそれらはグローバルな影響を持つからです。また、[B.Run]を呼び出すべきでもありません。

RunParallelは、ベンチマーク全体の壁時計時間(ns/op値)を報告します。これは並列ゴルーチンごとの壁時計時間またはCPU時間の合計ではありません。

Example
package main

import (
	"github.com/shogo82148/std/bytes"
	"github.com/shogo82148/std/testing"
	"github.com/shogo82148/std/text/template"
)

func main() {
	// 1つのオブジェクトに対してtext/template.Template.Executeの並列ベンチマーク。
	testing.Benchmark(func(b *testing.B) {
		templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))

		// RunParallelはGOMAXPROCSのゴルーチンを作成し、
		// それらに作業を分散させます。
		b.RunParallel(func(pb *testing.PB) {
			// 各goroutineは独自のbytes.Bufferを持っています。
			var buf bytes.Buffer
			for pb.Next() {
				// ループ本体はすべてのゴルーチンを通じて合計で b.N 回実行されます。
				buf.Reset()
				templ.Execute(&buf, "World")
			}
		})
	})
}

func (*B) SetBytes

func (b *B) SetBytes(n int64)

SetBytesは単一の操作で処理されたバイト数を記録します。 これが呼び出された場合、ベンチマークはns/opとMB/sを報告します。

func (*B) SetParallelism added in v1.3.0

func (b *B) SetParallelism(p int)

SetParallelismは、B.RunParallel によって使用されるゴルーチンの数をp*GOMAXPROCSに設定します。 CPUに依存するベンチマークでは、通常SetParallelismを呼び出す必要はありません。 pが1未満の場合、この呼び出しは効果がありません。

func (*B) StartTimer

func (b *B) StartTimer()

StartTimerはテストの計測を開始します。この関数はベンチマークが開始する前に自動的に呼び出されますが、B.StopTimer を呼び出した後に計測を再開するためにも使用することができます。

func (*B) StopTimer

func (b *B) StopTimer()

StopTimerはテストのタイミングを停止します。これは、計測したくない複雑な初期化を実行する間にタイマーを一時停止するために使用することができます。

type BenchmarkResult

type BenchmarkResult struct {
	N         int
	T         time.Duration
	Bytes     int64
	MemAllocs uint64
	MemBytes  uint64

	// Extra records additional metrics reported by ReportMetric.
	// ExtraはReportMetricによって報告された追加のメトリクスを記録します。
	Extra map[string]float64
}

BenchmarkResult contains the results of a benchmark run.

func Benchmark

func Benchmark(f func(b *B)) BenchmarkResult

Benchmarkは単一の関数をベンチマークします。これは、"go test"コマンドを使用しない カスタムベンチマークを作成するのに便利です。

もしfがテストフラグに依存しているなら、Benchmarkを呼び出す前と flag.Parse を呼び出す前に、それらのフラグを登録するために Init を使用する必要があります。

もしfがRunを呼び出すなら、結果は単一のベンチマーク内で連続して Runを呼び出さないすべてのサブベンチマークを実行するための推定値になります。

func (BenchmarkResult) AllocedBytesPerOp added in v1.1.0

func (r BenchmarkResult) AllocedBytesPerOp() int64

AllocedBytesPerOpは「B/op」メトリックを返します。 これはr.MemBytes / r.Nで計算されます。

func (BenchmarkResult) AllocsPerOp added in v1.1.0

func (r BenchmarkResult) AllocsPerOp() int64

AllocsPerOpは「allocs/op」メトリックスを返します。 このメトリックスはr.MemAllocs / r.Nで計算されます。

func (BenchmarkResult) MemString added in v1.1.0

func (r BenchmarkResult) MemString() string

MemStringは、'go test'と同じ形式でr.AllocedBytesPerOpとr.AllocsPerOpを返します。

func (BenchmarkResult) NsPerOp

func (r BenchmarkResult) NsPerOp() int64

NsPerOpは"ns/op"メトリックを返します。

func (BenchmarkResult) String

func (r BenchmarkResult) String() string

Stringは、ベンチマーク結果の概要を返します。 これは、https://golang.org/design/14313-benchmark-format からの ベンチマーク結果行の形式に従いますが、ベンチマーク名は含まれません。 追加のメトリクスは、同じ名前の組み込みメトリクスを上書きします。 Stringは、allocs/opやB/opを含みません。これらは BenchmarkResult.MemString によって報告されます。

type Cover added in v1.2.0

type Cover struct {
	Mode            string
	Counters        map[string][]uint32
	Blocks          map[string][]CoverBlock
	CoveredPackages string
}

Coverはテストカバレッジのチェックに関する情報を記録します。 注意: この構造体はテストインフラストラクチャに内部的に使用され、変更される可能性があります。 Go 1の互換性ガイドラインではまだ対象外です。

type CoverBlock added in v1.2.0

type CoverBlock struct {
	Line0 uint32
	Col0  uint16
	Line1 uint32
	Col1  uint16
	Stmts uint16
}

CoverBlock は単一の基本ブロックのカバレッジデータを記録します。 フィールドは1からインデックス付けされています。エディタのように、 ファイルの開始行は1です。例えば、列はバイト単位で測定されます。 注: この struct はテストインフラストラクチャ内部で使用されるものであり、変更される可能性があります。 まだ Go 1 互換性ガイドラインにカバーされていません。

type F added in v1.18.0

type F struct {
	// contains filtered or unexported fields
}

Fはフラズテストに渡される型です。

フラズテストは生成された入力値を提供されたフラズターゲットに対して実行し、 テストされるコードに潜在的なバグを見つけて報告することができます。

ファズテストはデフォルトでシードコーパスを実行します。これには F.Add で追加されたエントリや testdata/fuzz/<FuzzTestName> ディレクトリ内のエントリが含まれます。 必要なセットアップと F.Add の呼び出しの後、ファズテストは F.Fuzz を呼び出してファズターゲットを指定する必要があります。 詳細は testing パッケージのドキュメントや F.Fuzz および F.Add メソッドのドキュメントを参照してください。

*F メソッドは F.Fuzz の前にのみ呼び出すことができます。テストがファズターゲットを実行している間は *T メソッドのみ使用できます。 F.Fuzz 関数内で許可される *F メソッドは [F.Failed] と [F.Name] のみです。

func (*F) Add added in v1.18.0

func (f *F) Add(args ...any)

Addは、引数をfuzzテストのシードコーパスに追加します。これは、fuzzターゲットの後または中で呼び出された場合は無効になり、argsはfuzzターゲットの引数と一致する必要があります。

func (*F) Fail added in v1.18.0

func (f *F) Fail()

Failは関数が失敗したことを示しますが、実行を続けます。

func (*F) Fuzz added in v1.18.0

func (f *F) Fuzz(ff any)

Fuzzはfuzzテストのために、関数ffを実行します。もしffが一連の引数で失敗した場合、それらの引数はシードコーパスに追加されます。

ffは戻り値がなく、最初の引数が[*T]であり、残りの引数がファズ対象の型である関数でなければなりません。 例:

f.Fuzz(func(t *testing.T, b []byte, i int) { ... })

以下の型が許可されます:[]byte, string, bool, byte, rune, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64。将来的にはより多くの型がサポートされるかもしれません。

ffは[*F]のメソッド(例: [F.Log], [F.Error], [F.Skip])を呼び出してはいけません。代わりに対応する[*T]メソッドを使用してください。 F.Fuzz関数内で許可される *F メソッドは [F.Failed] と [F.Name] のみです。

この関数は高速で決定的であるべきであり、その振る舞いは共有状態に依存してはなりません。 可変の入力引数、またはそれらへのポインターは、fuzz関数の実行間で保持されるべきではありません。 なぜなら、それらをバックアップするメモリは、後続の呼び出し中に変更される可能性があるからです。 ffは、fuzzingエンジンによって提供される引数の基礎となるデータを変更してはなりません。

ファズ実行中は、F.Fuzzは問題が見つかるか、タイムアウト(-fuzztimeで設定)、またはテストプロセスがシグナルで中断されるまで戻りません。 F.Fuzzは [F.Skip] または F.Fail が事前に呼ばれない限り、必ず一度だけ呼び出す必要があります。

func (*F) Helper added in v1.18.0

func (f *F) Helper()

Helperは呼び出し元の関数をテストのヘルパー関数としてマークします。 ファイルと行情報を表示するとき、その関数はスキップされます。 Helperは複数のゴルーチンから同時に呼び出すことができます。

func (*F) Skipped added in v1.18.0

func (f *F) Skipped() bool

Skippedはテストがスキップされたかどうかを報告します。

type InternalBenchmark

type InternalBenchmark struct {
	Name string
	F    func(b *B)
}

InternalBenchmarkは内部の型ですが、他のパッケージからも利用できるように公開されています。 これは"go test"コマンドの実装の一部です。

type InternalExample

type InternalExample struct {
	Name      string
	F         func()
	Output    string
	Unordered bool
}

type InternalFuzzTarget added in v1.18.0

type InternalFuzzTarget struct {
	Name string
	Fn   func(f *F)
}

InternalFuzzTargetは内部型ですが、異なるパッケージで使われるために公開されています。 これは"go test"コマンドの実装の一部です。

type InternalTest

type InternalTest struct {
	Name string
	F    func(*T)
}

InternalTestは内部型ですが、クロスパッケージであるためにエクスポートされています。 これは"go test"コマンドの実装の一部です。

type M added in v1.4.0

type M struct {
	// contains filtered or unexported fields
}

MはTestMain関数に渡される型で、実際のテストを実行するために使用されます。

func MainStart added in v1.4.0

func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M

MainStartは「go test」によって生成されたテストで使用することを意図しています。 直接呼び出すことは意図されておらず、Go 1の互換性ドキュメントの対象外です。 リリースごとにシグネチャが変更される可能性があります。

func (*M) Run added in v1.4.0

func (m *M) Run() (code int)

Runはテストを実行します。os.Exitに渡す終了コードを返します。 終了コードはすべてのテストが成功した場合はゼロ、何らかの失敗があった場合は非ゼロです。 機械可読なテスト結果が必要な場合は、'go test -json'の出力を解析してください。

type PB added in v1.3.0

type PB struct {
	// contains filtered or unexported fields
}

PBはRunParallelによって並列ベンチマークの実行に使用されます。

func (*PB) Next added in v1.3.0

func (pb *PB) Next() bool

Nextは、さらに実行するイテレーションがあるかどうかを返します。

type T

type T struct {
	// contains filtered or unexported fields
}

Tはテスト状態を管理し、フォーマットされたテストログをサポートするためにTest関数に渡される型です。

テストは、そのTest関数がreturnするか、[T.FailNow]、[T.Fatal]、[T.Fatalf]、[T.SkipNow]、[T.Skip]、[T.Skipf] のいずれかのメソッドを呼び出すことで終了します。 これらのメソッドおよび T.Parallel メソッドは、Test関数を実行しているゴルーチンからのみ呼び出す必要があります。

その他の報告用メソッド([T.Log] や [T.Error] のバリエーションなど)は、複数のゴルーチンから同時に呼び出すことができます。

func (*T) Chdir added in v1.25.0

func (t *T) Chdir(dir string)

Chdirは os.Chdir を呼び出し、テスト後に作業ディレクトリを元の値に復元するためにCleanupを使用します。Unixでは、テストの実行中のみPWD環境変数も設定されます。

Chdirはプロセス全体に影響を与えるため、並列テストや並列祖先を持つテストでは使用できません。

func (*T) Deadline added in v1.15.0

func (t *T) Deadline() (deadline time.Time, ok bool)

Deadlineは、-timeoutフラグで指定されたタイムアウトを超えるテストバイナリの時間を報告します。

-timeoutフラグが「タイムアウトなし」(0)を示す場合、ok結果はfalseです。

func (*T) Parallel

func (t *T) Parallel()

Parallelは、このテストが並行して(そしてそれ以外では)実行されることを示します。 -test.countや-test.cpuの使用により、テストが複数回実行される場合、単一のテストの複数のインスタンスは互いに並行して実行されません。

func (*T) Run added in v1.7.0

func (t *T) Run(name string, f func(t *T)) bool

Runはfをtのサブテストとして実行します。nameという名前で実行されます。fは別のゴルーチンで実行され、 fが返るか、t.Parallelを呼び出して並列テストになるまでブロックされます。 Runはfが成功したか(またはt.Parallelを呼び出す前に失敗しなかったか)を報告します。

Runは複数のゴルーチンから同時に呼び出すことができますが、そのようなすべての呼び出しは、 tが外部テスト関数を返す前に返さなければなりません。

func (*T) Setenv added in v1.17.0

func (t *T) Setenv(key, value string)

Setenvはos.Setenv(key, value)を呼び出し、Cleanupを使用してテスト後に環境変数を元の値に復元します。

Setenvはプロセス全体に影響を与えるため、並列テストや並列祖先を持つテストで使用することはできません。

type TB added in v1.2.0

type TB interface {
	Attr(key, value string)
	Cleanup(func())
	Error(args ...any)
	Errorf(format string, args ...any)
	Fail()
	FailNow()
	Failed() bool
	Fatal(args ...any)
	Fatalf(format string, args ...any)
	Helper()
	Log(args ...any)
	Logf(format string, args ...any)
	Name() string
	Setenv(key, value string)
	Chdir(dir string)
	Skip(args ...any)
	SkipNow()
	Skipf(format string, args ...any)
	Skipped() bool
	TempDir() string
	Context() context.Context
	Output() io.Writer
	// contains filtered or unexported methods
}

TBは T, B, F に共通するインターフェースです。

Directories

Path Synopsis
fstestパッケージは、ファイルシステムの実装およびユーザーのテストをサポートする機能を実装します。
fstestパッケージは、ファイルシステムの実装およびユーザーのテストをサポートする機能を実装します。
internal
testdeps
Package testdeps provides access to dependencies needed by test execution.
Package testdeps provides access to dependencies needed by test execution.
iotestパッケージは、主にテストに役立つReaderとWriterを実装します。
iotestパッケージは、主にテストに役立つReaderとWriterを実装します。
quickパッケージは、ブラックボックステストを支援するためのユーティリティ関数を実装します。
quickパッケージは、ブラックボックステストを支援するためのユーティリティ関数を実装します。
slogtestパッケージは、log/slog.Handlerの実装をテストするためのサポートを提供します。
slogtestパッケージは、log/slog.Handlerの実装をテストするためのサポートを提供します。
Package synctest provides support for testing concurrent code.
Package synctest provides support for testing concurrent code.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL