Documentation
¶
Overview ¶
testingパッケージはGoパッケージの自動テストをサポートします。 これは"go test"コマンドと一緒に使用することを意図しています。"go test"コマンドは以下の形式の関数を自動的に実行します。
func TestXxx(*testing.T)
ただし、Xxxは小文字ではじまらないものとします。関数名はテストルーチンを識別するために使用されます。
これらの関数内では、FailureをシグナルするためにError、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 https://golang.org/cmd/go/#hdr-Testing_flags.
A sample benchmark function looks like this:
func BenchmarkRandInt(b *testing.B) { for range b.N { rand.Int() } }
The benchmark function must run the target code b.N times. It is called multiple times with b.N adjusted until the benchmark function lasts long enough to be timed reliably. The output
BenchmarkRandInt-8 68453040 17.8 ns/op
means that the loop ran 68453040 times at a speed of 17.8 ns per loop.
If a benchmark needs some expensive setup before running, the timer may be reset:
func BenchmarkBigLen(b *testing.B) { big := NewBig() b.ResetTimer() for range b.N { 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://golang.org/design/14313-benchmark-format.
There are standard tools for working with benchmark results at https://golang.org/x/perf/cmd. In particular, https://golang.org/x/perf/cmd/benchstat performs statistically robust A/B comparisons.
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 the Skip method of *T or *B:
func TestTimeConsuming(t *testing.T) { if testing.Short() { t.Skip("skipping test in short mode.") } ... }
The Skip method of *T 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 Run methods of T and B 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 { tc := tc // capture range variable 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 ¶
- func AllocsPerRun(runs int, f func()) (avg float64)
- func CoverMode() string
- func Coverage() float64
- func Init()
- func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, ...)
- func RegisterCover(c Cover)
- func RunBenchmarks(matchString func(pat, str string) (bool, error), ...)
- func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)
- func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)
- func Short() bool
- func Testing() bool
- func Verbose() bool
- type B
- func (b *B) Elapsed() time.Duration
- func (b *B) ReportAllocs()
- func (b *B) ReportMetric(n float64, unit string)
- func (b *B) ResetTimer()
- func (b *B) Run(name string, f func(b *B)) bool
- func (b *B) RunParallel(body func(*PB))
- func (b *B) SetBytes(n int64)
- func (b *B) SetParallelism(p int)
- func (b *B) StartTimer()
- func (b *B) StopTimer()
- type BenchmarkResult
- type Cover
- type CoverBlock
- type F
- type InternalBenchmark
- type InternalExample
- type InternalFuzzTarget
- type InternalTest
- type M
- type PB
- type T
- type TB
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AllocsPerRun ¶ added in v1.1.0
AllocsPerRunは、関数fの呼び出し中に行われる平均的な割り当ての数を返します。 返り値はfloat64型ですが、常に整数値になります。
割り当ての数を計算するために、まず関数はウォームアップとして一度実行されます。 指定された回数の実行における平均的な割り当ての数が測定され、返されます。
AllocsPerRunは、計測中に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は現在のコードカバレッジを[0, 1]の範囲で示します。 カバレッジが有効でない場合、Coverageは0を返します。
大量のシーケンシャルなテストケースを実行する際に、各テストケースの後にCoverageをチェックすることは 新しいコードパスを実行するテストケースを特定するのに役立ちます。 これは 'go test -cover' と '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"をシミュレートする他のシステムが、Mainを使用する一方で、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"コマンドの実装の一部です。
Types ¶
type B ¶
type B struct { N int // contains filtered or unexported fields }
Bはベンチマークのタイミングを管理し、実行する繰り返し回数を指定するために Benchmark 関数に渡される型です。
ベンチマーク関数がリターンするか、またはFailNow、Fatal、Fatalf、SkipNow、Skip、Skipfのいずれかのメソッドを呼び出すことでベンチマークは終了します。これらのメソッドはベンチマーク関数を実行しているゴルーチンからのみ呼び出す必要があります。 ログやエラーのバリエーションといった他の報告用メソッドは、複数のゴルーチンから同時に呼び出すことができます。
テストと同様に、ベンチマークのログは実行中に蓄積され、終了時に標準出力に出力されます。ただし、ベンチマークのログは常に出力されるため、ベンチマーク結果に影響を与える可能性がある出力を隠すことはありません。
func (*B) Elapsed ¶ added in v1.20.0
Elapsedはベンチマークの計測された経過時間を返します。 Elapsedによって報告される期間は、B.StartTimer、B.StopTimer、B.ResetTimer によって計測される期間と一致します。
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
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 i := 0; i < b.N; i++ { 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") }) }
Output:
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") }) }
Output:
func (*B) ResetTimer ¶
func (b *B) ResetTimer()
ResetTimerは経過したベンチマーク時間とメモリ割り当てのカウンターをゼロにし、 ユーザーが報告したメトリクスを削除します。 タイマーが実行中かどうかには影響しません。
func (*B) Run ¶ added in v1.7.0
指定された名前でサブベンチマークとしてベンチマークを実行します。 フェイルが発生したかどうかを報告します。
サブベンチマークは他のどんなベンチマークとも同じです。 Runを少なくとも1回呼び出すベンチマークは自体は計測されず、N=1で1回呼び出されます。
func (*B) RunParallel ¶ added in v1.3.0
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") } }) }) }
Output:
func (*B) SetParallelism ¶ added in v1.3.0
SetParallelismは、B.RunParallel によって使用されるゴルーチンの数をp*GOMAXPROCSに設定します。 CPUに依存するベンチマークでは、通常SetParallelismを呼び出す必要はありません。 pが1未満の場合、この呼び出しは効果がありません。
func (*B) StartTimer ¶
func (b *B) StartTimer()
StartTimerはテストの計測を開始します。この関数はベンチマークが開始する前に自動的に呼び出されますが、B.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はベンチマークの実行結果を含んでいます。
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
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を呼び出さなければなりません。 例についてはテストパッケージのドキュメンテーションを参照し、詳細については F.Fuzz と F.Add メソッドのドキュメンテーションを参照してください。
*Fのメソッドは(*F).Fuzzの前にのみ呼び出すことができます。テストがフラズターゲットを実行している間は、(*T)のメソッドのみを使用することができます。 (*F).Fuzz関数内で許可されている*Fのメソッドは、(*F).Failedと(*F).Nameのみです。
func (*F) Add ¶ added in v1.18.0
Addは、引数をfuzzテストのシードコーパスに追加します。これは、fuzzターゲットの後または中で呼び出された場合は無効になり、argsはfuzzターゲットの引数と一致する必要があります。
func (*F) Fuzz ¶ added in v1.18.0
Fuzzはfuzzテストのために、関数ffを実行します。もしffが一連の引数で失敗した場合、それらの引数はシードコーパスに追加されます。
ffは、戻り値を持たない関数でなければならず、最初の引数は*T型であり、残りの引数はfuzzテストを実施する型です。 例:
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).Log、(*F).Error、(*F).Skipなどの*Fメソッドを呼び出してはなりません。代わりに、対応する*Tメソッドを使用してください。 (*F).Fuzz関数で許可される*Fメソッドは、(*F).Failedと(*F).Nameのみです。
この関数は高速で決定的であるべきであり、その振る舞いは共有状態に依存してはなりません。 可変の入力引数、またはそれらへのポインターは、fuzz関数の実行間で保持されるべきではありません。 なぜなら、それらをバックアップするメモリは、後続の呼び出し中に変更される可能性があるからです。 ffは、fuzzingエンジンによって提供される引数の基礎となるデータを変更してはなりません。
fuzzing中、F.Fuzzは問題が見つかるまで、時間切れ(-fuzztimeで設定)またはテストプロセスがシグナルによって中断されるまで、戻りません。 F.Fuzzは、F.Skipまたは F.Fail が先に呼び出されない限り、正確に1回呼び出す必要があります。
type InternalBenchmark ¶
InternalBenchmarkは内部の型ですが、他のパッケージからも利用できるように公開されています。 これは"go test"コマンドの実装の一部です。
type InternalExample ¶
type InternalFuzzTarget ¶ added in v1.18.0
InternalFuzzTargetは内部型ですが、異なるパッケージで使われるために公開されています。 これは"go test"コマンドの実装の一部です。
type InternalTest ¶
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の互換性ドキュメントの対象外です。 リリースごとにシグネチャが変更される可能性があります。
type PB ¶ added in v1.3.0
type PB struct {
// contains filtered or unexported fields
}
PBはRunParallelによって並列ベンチマークの実行に使用されます。
type T ¶
type T struct {
// contains filtered or unexported fields
}
Tはテスト状態を管理し、フォーマットされたテストログをサポートするためにTest関数に渡される型です。
テストは、そのTest関数が返却されるか、またはFailNow、Fatal、Fatalf、SkipNow、Skip、Skipfのいずれかのメソッドが呼び出された時に終了します。これらのメソッド、およびParallelメソッドは、テスト関数を実行しているゴルーチンからのみ呼び出す必要があります。
LogやErrorのバリエーションなど、他のレポートメソッドは、複数のゴルーチンから同時に呼び出すことができます。
func (*T) Deadline ¶ added in v1.15.0
Deadlineは、-timeoutフラグで指定されたタイムアウトを超えるテストバイナリの時間を報告します。
-timeoutフラグが「タイムアウトなし」(0)を示す場合、ok結果はfalseです。
func (*T) Parallel ¶
func (t *T) Parallel()
Parallelは、このテストが並行して(そしてそれ以外では)実行されることを示します。 -test.countや-test.cpuの使用により、テストが複数回実行される場合、単一のテストの複数のインスタンスは互いに並行して実行されません。
type TB ¶ added in v1.2.0
type TB interface { 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) Skip(args ...any) SkipNow() Skipf(format string, args ...any) Skipped() bool TempDir() string // contains filtered or unexported methods }
TBはT、B、Fに共通するインターフェースです。
Source Files
¶
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の実装をテストするためのサポートを提供します。 |