github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/testing/testing.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // パッケージtestingはGoパッケージの自動テストをサポートします。 6 // これは"go test"コマンドと一緒に使用することを意図しています。"go test"コマンドは以下の形式の関数を自動的に実行します。 7 // 8 // func TestXxx(*testing.T) 9 // 10 // ただし、Xxxは小文字ではじまらないものとします。関数名はテストルーチンを識別するために使用されます。 11 // 12 // これらの関数内では、FailureをシグナルするためにError、Fail、または関連するメソッドを使用します。 13 // 14 // 新しいテストスイートを書くためには、次の要件に従っているファイルを作成し、"_test.go"で終わる名前を付けます。 15 // このファイルは通常のパッケージのビルドから除外されますが、"go test"コマンドの実行時には含まれます。 16 // 17 // テストファイルは、テスト対象のパッケージと同じパッケージにあるか、"_test"という接尾辞の付いた対応するパッケージに含めることができます。 18 // 19 // テストファイルが同じパッケージにある場合、パッケージ内の非公開の識別子を参照することができます。次の例のようになります。 20 // 21 // package abs 22 // 23 // import "testing" 24 // 25 // func TestAbs(t *testing.T) { 26 // got := Abs(-1) 27 // if got != 1 { 28 // t.Errorf("Abs(-1) = %d; want 1", got) 29 // } 30 // } 31 // 32 // ファイルが別の"_test"パッケージにある場合、テスト対象のパッケージを明示的にインポートする必要があり、公開された識別子のみ使用できます。これは「ブラックボックス」テストとして知られています。 33 // 34 // package abs_test 35 // 36 // import ( 37 // "testing" 38 // 39 // "path_to_pkg/abs" 40 // ) 41 // 42 // func TestAbs(t *testing.T) { 43 // got := abs.Abs(-1) 44 // if got != 1 { 45 // t.Errorf("Abs(-1) = %d; want 1", got) 46 // } 47 // } 48 // 49 // 詳細については、「go help test」と「go help testflag」を実行してください。 50 // 51 // # ベンチマーク 52 // 53 // 次の形式の関数 54 // 55 // func BenchmarkXxx(*testing.B) 56 // 57 // are considered benchmarks, and are executed by the "go test" command when 58 // its -bench flag is provided. Benchmarks are run sequentially. 59 // 60 // For a description of the testing flags, see 61 // https://golang.org/cmd/go/#hdr-Testing_flags. 62 // 63 // A sample benchmark function looks like this: 64 // 65 // func BenchmarkRandInt(b *testing.B) { 66 // for i := 0; i < b.N; i++ { 67 // rand.Int() 68 // } 69 // } 70 // 71 // The benchmark function must run the target code b.N times. 72 // During benchmark execution, b.N is adjusted until the benchmark function lasts 73 // long enough to be timed reliably. The output 74 // 75 // BenchmarkRandInt-8 68453040 17.8 ns/op 76 // 77 // means that the loop ran 68453040 times at a speed of 17.8 ns per loop. 78 // 79 // If a benchmark needs some expensive setup before running, the timer 80 // may be reset: 81 // 82 // func BenchmarkBigLen(b *testing.B) { 83 // big := NewBig() 84 // b.ResetTimer() 85 // for i := 0; i < b.N; i++ { 86 // big.Len() 87 // } 88 // } 89 // 90 // If a benchmark needs to test performance in a parallel setting, it may use 91 // the RunParallel helper function; such benchmarks are intended to be used with 92 // the go test -cpu flag: 93 // 94 // func BenchmarkTemplateParallel(b *testing.B) { 95 // templ := template.Must(template.New("test").Parse("Hello, {{.}}!")) 96 // b.RunParallel(func(pb *testing.PB) { 97 // var buf bytes.Buffer 98 // for pb.Next() { 99 // buf.Reset() 100 // templ.Execute(&buf, "World") 101 // } 102 // }) 103 // } 104 // 105 // A detailed specification of the benchmark results format is given 106 // in https://golang.org/design/14313-benchmark-format. 107 // 108 // There are standard tools for working with benchmark results at 109 // https://golang.org/x/perf/cmd. 110 // In particular, https://golang.org/x/perf/cmd/benchstat performs 111 // statistically robust A/B comparisons. 112 // 113 // # Examples 114 // 115 // The package also runs and verifies example code. Example functions may 116 // include a concluding line comment that begins with "Output:" and is compared with 117 // the standard output of the function when the tests are run. (The comparison 118 // ignores leading and trailing space.) These are examples of an example: 119 // 120 // func ExampleHello() { 121 // fmt.Println("hello") 122 // // Output: hello 123 // } 124 // 125 // func ExampleSalutations() { 126 // fmt.Println("hello, and") 127 // fmt.Println("goodbye") 128 // // Output: 129 // // hello, and 130 // // goodbye 131 // } 132 // 133 // The comment prefix "Unordered output:" is like "Output:", but matches any 134 // line order: 135 // 136 // func ExamplePerm() { 137 // for _, value := range Perm(5) { 138 // fmt.Println(value) 139 // } 140 // // Unordered output: 4 141 // // 2 142 // // 1 143 // // 3 144 // // 0 145 // } 146 // 147 // Example functions without output comments are compiled but not executed. 148 // 149 // The naming convention to declare examples for the package, a function F, a type T and 150 // method M on type T are: 151 // 152 // func Example() { ... } 153 // func ExampleF() { ... } 154 // func ExampleT() { ... } 155 // func ExampleT_M() { ... } 156 // 157 // Multiple example functions for a package/type/function/method may be provided by 158 // appending a distinct suffix to the name. The suffix must start with a 159 // lower-case letter. 160 // 161 // func Example_suffix() { ... } 162 // func ExampleF_suffix() { ... } 163 // func ExampleT_suffix() { ... } 164 // func ExampleT_M_suffix() { ... } 165 // 166 // The entire test file is presented as the example when it contains a single 167 // example function, at least one other function, type, variable, or constant 168 // declaration, and no test or benchmark functions. 169 // 170 // # Fuzzing 171 // 172 // 'go test' and the testing package support fuzzing, a testing technique where 173 // a function is called with randomly generated inputs to find bugs not 174 // anticipated by unit tests. 175 // 176 // Functions of the form 177 // 178 // func FuzzXxx(*testing.F) 179 // 180 // are considered fuzz tests. 181 // 182 // For example: 183 // 184 // func FuzzHex(f *testing.F) { 185 // for _, seed := range [][]byte{{}, {0}, {9}, {0xa}, {0xf}, {1, 2, 3, 4}} { 186 // f.Add(seed) 187 // } 188 // f.Fuzz(func(t *testing.T, in []byte) { 189 // enc := hex.EncodeToString(in) 190 // out, err := hex.DecodeString(enc) 191 // if err != nil { 192 // t.Fatalf("%v: decode: %v", in, err) 193 // } 194 // if !bytes.Equal(in, out) { 195 // t.Fatalf("%v: not equal after round trip: %v", in, out) 196 // } 197 // }) 198 // } 199 // 200 // A fuzz test maintains a seed corpus, or a set of inputs which are run by 201 // default, and can seed input generation. Seed inputs may be registered by 202 // calling (*F).Add or by storing files in the directory testdata/fuzz/<Name> 203 // (where <Name> is the name of the fuzz test) within the package containing 204 // the fuzz test. Seed inputs are optional, but the fuzzing engine may find 205 // bugs more efficiently when provided with a set of small seed inputs with good 206 // code coverage. These seed inputs can also serve as regression tests for bugs 207 // identified through fuzzing. 208 // 209 // The function passed to (*F).Fuzz within the fuzz test is considered the fuzz 210 // target. A fuzz target must accept a *T parameter, followed by one or more 211 // parameters for random inputs. The types of arguments passed to (*F).Add must 212 // be identical to the types of these parameters. The fuzz target may signal 213 // that it's found a problem the same way tests do: by calling T.Fail (or any 214 // method that calls it like T.Error or T.Fatal) or by panicking. 215 // 216 // When fuzzing is enabled (by setting the -fuzz flag to a regular expression 217 // that matches a specific fuzz test), the fuzz target is called with arguments 218 // generated by repeatedly making random changes to the seed inputs. On 219 // supported platforms, 'go test' compiles the test executable with fuzzing 220 // coverage instrumentation. The fuzzing engine uses that instrumentation to 221 // find and cache inputs that expand coverage, increasing the likelihood of 222 // finding bugs. If the fuzz target fails for a given input, the fuzzing engine 223 // writes the inputs that caused the failure to a file in the directory 224 // testdata/fuzz/<Name> within the package directory. This file later serves as 225 // a seed input. If the file can't be written at that location (for example, 226 // because the directory is read-only), the fuzzing engine writes the file to 227 // the fuzz cache directory within the build cache instead. 228 // 229 // When fuzzing is disabled, the fuzz target is called with the seed inputs 230 // registered with F.Add and seed inputs from testdata/fuzz/<Name>. In this 231 // mode, the fuzz test acts much like a regular test, with subtests started 232 // with F.Fuzz instead of T.Run. 233 // 234 // See https://go.dev/doc/fuzz for documentation about fuzzing. 235 // 236 // # Skipping 237 // 238 // Tests or benchmarks may be skipped at run time with a call to 239 // the Skip method of *T or *B: 240 // 241 // func TestTimeConsuming(t *testing.T) { 242 // if testing.Short() { 243 // t.Skip("skipping test in short mode.") 244 // } 245 // ... 246 // } 247 // 248 // The Skip method of *T can be used in a fuzz target if the input is invalid, 249 // but should not be considered a failing input. For example: 250 // 251 // func FuzzJSONMarshaling(f *testing.F) { 252 // f.Fuzz(func(t *testing.T, b []byte) { 253 // var v interface{} 254 // if err := json.Unmarshal(b, &v); err != nil { 255 // t.Skip() 256 // } 257 // if _, err := json.Marshal(v); err != nil { 258 // t.Errorf("Marshal: %v", err) 259 // } 260 // }) 261 // } 262 // 263 // # Subtests and Sub-benchmarks 264 // 265 // The Run methods of T and B allow defining subtests and sub-benchmarks, 266 // without having to define separate functions for each. This enables uses 267 // like table-driven benchmarks and creating hierarchical tests. 268 // It also provides a way to share common setup and tear-down code: 269 // 270 // func TestFoo(t *testing.T) { 271 // // <setup code> 272 // t.Run("A=1", func(t *testing.T) { ... }) 273 // t.Run("A=2", func(t *testing.T) { ... }) 274 // t.Run("B=1", func(t *testing.T) { ... }) 275 // // <tear-down code> 276 // } 277 // 278 // Each subtest and sub-benchmark has a unique name: the combination of the name 279 // of the top-level test and the sequence of names passed to Run, separated by 280 // slashes, with an optional trailing sequence number for disambiguation. 281 // 282 // The argument to the -run, -bench, and -fuzz command-line flags is an unanchored regular 283 // expression that matches the test's name. For tests with multiple slash-separated 284 // elements, such as subtests, the argument is itself slash-separated, with 285 // expressions matching each name element in turn. Because it is unanchored, an 286 // empty expression matches any string. 287 // For example, using "matching" to mean "whose name contains": 288 // 289 // go test -run '' # Run all tests. 290 // go test -run Foo # Run top-level tests matching "Foo", such as "TestFooBar". 291 // go test -run Foo/A= # For top-level tests matching "Foo", run subtests matching "A=". 292 // go test -run /A=1 # For all top-level tests, run subtests matching "A=1". 293 // go test -fuzz FuzzFoo # Fuzz the target matching "FuzzFoo" 294 // 295 // The -run argument can also be used to run a specific value in the seed 296 // corpus, for debugging. For example: 297 // 298 // go test -run=FuzzFoo/9ddb952d9814 299 // 300 // The -fuzz and -run flags can both be set, in order to fuzz a target but 301 // skip the execution of all other tests. 302 // 303 // Subtests can also be used to control parallelism. A parent test will only 304 // complete once all of its subtests complete. In this example, all tests are 305 // run in parallel with each other, and only with each other, regardless of 306 // other top-level tests that may be defined: 307 // 308 // func TestGroupedParallel(t *testing.T) { 309 // for _, tc := range tests { 310 // tc := tc // capture range variable 311 // t.Run(tc.Name, func(t *testing.T) { 312 // t.Parallel() 313 // ... 314 // }) 315 // } 316 // } 317 // 318 // Run does not return until parallel subtests have completed, providing a way 319 // to clean up after a group of parallel tests: 320 // 321 // func TestTeardownParallel(t *testing.T) { 322 // // This Run will not return until the parallel tests finish. 323 // t.Run("group", func(t *testing.T) { 324 // t.Run("Test1", parallelTest1) 325 // t.Run("Test2", parallelTest2) 326 // t.Run("Test3", parallelTest3) 327 // }) 328 // // <tear-down code> 329 // } 330 // 331 // # Main 332 // 333 // It is sometimes necessary for a test or benchmark program to do extra setup or teardown 334 // before or after it executes. It is also sometimes necessary to control 335 // which code runs on the main thread. To support these and other cases, 336 // if a test file contains a function: 337 // 338 // func TestMain(m *testing.M) 339 // 340 // then the generated test will call TestMain(m) instead of running the tests or benchmarks 341 // directly. TestMain runs in the main goroutine and can do whatever setup 342 // and teardown is necessary around a call to m.Run. m.Run will return an exit 343 // code that may be passed to os.Exit. If TestMain returns, the test wrapper 344 // will pass the result of m.Run to os.Exit itself. 345 // 346 // When TestMain is called, flag.Parse has not been run. If TestMain depends on 347 // command-line flags, including those of the testing package, it should call 348 // flag.Parse explicitly. Command line flags are always parsed by the time test 349 // or benchmark functions run. 350 // 351 // A simple implementation of TestMain is: 352 // 353 // func TestMain(m *testing.M) { 354 // // call flag.Parse() here if TestMain uses flags 355 // os.Exit(m.Run()) 356 // } 357 // 358 // TestMain is a low-level primitive and should not be necessary for casual 359 // testing needs, where ordinary test functions suffice. 360 package testing 361 362 import ( 363 "github.com/shogo82148/std/sync" 364 "github.com/shogo82148/std/time" 365 ) 366 367 // Initはテストフラグを登録します。これらのフラグは、テスト関数を実行する前に"go test"コマンドによって自動的に登録されるため、Initは、"go test"を使用せずにBenchmarkなどの関数を呼び出す場合にのみ必要です。 368 // 369 // Initは並行して呼び出すことは安全ではありません。 すでに呼び出されている場合は、効果がありません。 370 func Init() 371 372 // Short は -test.short フラグが設定されているかどうかを報告します。 373 func Short() bool 374 375 // Testingは現在のコードがテストで実行されているかどうかを報告します。 376 // "go test"で作られたプログラムではtrueを報告し、 377 // "go build"で作られたプログラムではfalseを報告します。 378 func Testing() bool 379 380 // CoverModeはテストカバレッジモードの設定を報告します。値は「set」、「count」または「atomic」です。テストカバレッジが有効でない場合、戻り値は空になります。 381 func CoverMode() string 382 383 // Verboseは、-test.vフラグが設定されているかどうかを報告します。 384 func Verbose() bool 385 386 // TBはT、B、Fに共通するインターフェースです。 387 type TB interface { 388 Cleanup(func()) 389 Error(args ...any) 390 Errorf(format string, args ...any) 391 Fail() 392 FailNow() 393 Failed() bool 394 Fatal(args ...any) 395 Fatalf(format string, args ...any) 396 Helper() 397 Log(args ...any) 398 Logf(format string, args ...any) 399 Name() string 400 Setenv(key, value string) 401 Skip(args ...any) 402 SkipNow() 403 Skipf(format string, args ...any) 404 Skipped() bool 405 TempDir() string 406 407 private() 408 } 409 410 var _ TB = (*T)(nil) 411 var _ TB = (*B)(nil) 412 413 // Tはテスト状態を管理し、フォーマットされたテストログをサポートするためにTest関数に渡される型です。 414 // 415 // テストは、そのTest関数が返却されるか、またはFailNow、Fatal、Fatalf、SkipNow、Skip、Skipfのいずれかのメソッドが呼び出された時に終了します。これらのメソッド、およびParallelメソッドは、テスト関数を実行しているゴルーチンからのみ呼び出す必要があります。 416 // 417 // LogやErrorのバリエーションなど、他のレポートメソッドは、複数のゴルーチンから同時に呼び出すことができます。 418 type T struct { 419 common 420 isEnvSet bool 421 context *testContext 422 } 423 424 // Parallelは、このテストが並行して(そしてそれ以外では)実行されることを示します。 425 // -test.countや-test.cpuの使用により、テストが複数回実行される場合、単一のテストの複数のインスタンスは互いに並行して実行されません。 426 func (t *T) Parallel() 427 428 // Setenvはos.Setenv(key, value)を呼び出し、Cleanupを使用してテスト後に環境変数を元の値に復元します。 429 // 430 // Setenvはプロセス全体に影響を与えるため、並列テストや並列祖先を持つテストで使用することはできません。 431 func (t *T) Setenv(key, value string) 432 433 // InternalTestは内部の型ですが、異なるパッケージでも使用するためにエクスポートされています。 434 // これは「go test」コマンドの実装の一部です。 435 type InternalTest struct { 436 Name string 437 F func(*T) 438 } 439 440 // Runはfをtのサブテストとして実行します。nameという名前で実行されます。fは別のゴルーチンで実行され、 441 // fが返るか、t.Parallelを呼び出して並列テストになるまでブロックされます。 442 // Runはfが成功したか(またはt.Parallelを呼び出す前に失敗しなかったか)を報告します。 443 // 444 // Runは複数のゴルーチンから同時に呼び出すことができますが、そのようなすべての呼び出しは、 445 // tが外部テスト関数を返す前に返さなければなりません。 446 func (t *T) Run(name string, f func(t *T)) bool 447 448 // Deadlineは、-timeoutフラグで指定されたタイムアウトを超えるテストバイナリの時間を報告します。 449 // 450 // -timeoutフラグが「タイムアウトなし」(0)を示す場合、ok結果はfalseです。 451 func (t *T) Deadline() (deadline time.Time, ok bool) 452 453 // Mainは"go test"コマンドの実装の一部である内部関数です。 454 // これは、クロスパッケージであり、「internal」パッケージより前にエクスポートされました。 455 // "go test"ではもはや使用されていませんが、他のシステムにはできるだけ保持されます。 456 // "go test"をシミュレートする他のシステムが、Mainを使用する一方で、Mainは更新できないことがあります。 457 // "go test"をシミュレートするシステムは、MainStartを使用するように更新する必要があります。 458 func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample) 459 460 // MはTestMain関数に渡される型で、実際のテストを実行するために使用されます。 461 type M struct { 462 deps testDeps 463 tests []InternalTest 464 benchmarks []InternalBenchmark 465 fuzzTargets []InternalFuzzTarget 466 examples []InternalExample 467 468 timer *time.Timer 469 afterOnce sync.Once 470 471 numRun int 472 473 // os.Exitに渡す値、外部のtest func mainに 474 // harnessはこのコードでos.Exitを呼び出します。#34129を参照してください。 475 exitCode int 476 } 477 478 // MainStartは「go test」によって生成されたテストで使用することを意図しています。 479 // 直接呼び出すことは意図されておらず、Go 1の互換性ドキュメントの対象外です。 480 // リリースごとにシグネチャが変更される可能性があります。 481 func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M 482 483 // Runはテストを実行します。os.Exitに渡すための終了コードを返します。 484 func (m *M) Run() (code int) 485 486 // RunTestsは内部関数ですが、クロスパッケージであるためにエクスポートされています。 487 // これは"go test"コマンドの実装の一部です。 488 func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)