github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/cmd/go/internal/test/test.go (about) 1 // Copyright 2011 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 package test 6 7 import ( 8 "github.com/shogo82148/std/cmd/go/internal/base" 9 ) 10 11 var CmdTest = &base.Command{ 12 CustomFlags: true, 13 UsageLine: testUsage, 14 Short: "test packages", 15 Long: ` 16 'Go test' automates testing the packages named by the import paths. 17 It prints a summary of the test results in the format: 18 19 ok archive/tar 0.011s 20 FAIL archive/zip 0.022s 21 ok compress/gzip 0.033s 22 ... 23 24 followed by detailed output for each failed package. 25 26 'Go test' recompiles each package along with any files with names matching 27 the file pattern "*_test.go". 28 These additional files can contain test functions, benchmark functions, fuzz 29 tests and example functions. See 'go help testfunc' for more. 30 Each listed package causes the execution of a separate test binary. 31 Files whose names begin with "_" (including "_test.go") or "." are ignored. 32 33 Test files that declare a package with the suffix "_test" will be compiled as a 34 separate package, and then linked and run with the main test binary. 35 36 The go tool will ignore a directory named "testdata", making it available 37 to hold ancillary data needed by the tests. 38 39 As part of building a test binary, go test runs go vet on the package 40 and its test source files to identify significant problems. If go vet 41 finds any problems, go test reports those and does not run the test 42 binary. Only a high-confidence subset of the default go vet checks are 43 used. That subset is: atomic, bool, buildtags, directive, errorsas, 44 ifaceassert, nilfunc, printf, and stringintconv. You can see 45 the documentation for these and other vet tests via "go doc cmd/vet". 46 To disable the running of go vet, use the -vet=off flag. To run all 47 checks, use the -vet=all flag. 48 49 All test output and summary lines are printed to the go command's 50 standard output, even if the test printed them to its own standard 51 error. (The go command's standard error is reserved for printing 52 errors building the tests.) 53 54 The go command places $GOROOT/bin at the beginning of $PATH 55 in the test's environment, so that tests that execute 56 'go' commands use the same 'go' as the parent 'go test' command. 57 58 Go test runs in two different modes: 59 60 The first, called local directory mode, occurs when go test is 61 invoked with no package arguments (for example, 'go test' or 'go 62 test -v'). In this mode, go test compiles the package sources and 63 tests found in the current directory and then runs the resulting 64 test binary. In this mode, caching (discussed below) is disabled. 65 After the package test finishes, go test prints a summary line 66 showing the test status ('ok' or 'FAIL'), package name, and elapsed 67 time. 68 69 The second, called package list mode, occurs when go test is invoked 70 with explicit package arguments (for example 'go test math', 'go 71 test ./...', and even 'go test .'). In this mode, go test compiles 72 and tests each of the packages listed on the command line. If a 73 package test passes, go test prints only the final 'ok' summary 74 line. If a package test fails, go test prints the full test output. 75 If invoked with the -bench or -v flag, go test prints the full 76 output even for passing package tests, in order to display the 77 requested benchmark results or verbose logging. After the package 78 tests for all of the listed packages finish, and their output is 79 printed, go test prints a final 'FAIL' status if any package test 80 has failed. 81 82 In package list mode only, go test caches successful package test 83 results to avoid unnecessary repeated running of tests. When the 84 result of a test can be recovered from the cache, go test will 85 redisplay the previous output instead of running the test binary 86 again. When this happens, go test prints '(cached)' in place of the 87 elapsed time in the summary line. 88 89 The rule for a match in the cache is that the run involves the same 90 test binary and the flags on the command line come entirely from a 91 restricted set of 'cacheable' test flags, defined as -benchtime, -cpu, 92 -list, -parallel, -run, -short, -timeout, -failfast, -fullpath and -v. 93 If a run of go test has any test or non-test flags outside this set, 94 the result is not cached. To disable test caching, use any test flag 95 or argument other than the cacheable flags. The idiomatic way to disable 96 test caching explicitly is to use -count=1. Tests that open files within 97 the package's source root (usually $GOPATH) or that consult environment 98 variables only match future runs in which the files and environment 99 variables are unchanged. A cached test result is treated as executing 100 in no time at all, so a successful package test result will be cached and 101 reused regardless of -timeout setting. 102 103 In addition to the build flags, the flags handled by 'go test' itself are: 104 105 -args 106 Pass the remainder of the command line (everything after -args) 107 to the test binary, uninterpreted and unchanged. 108 Because this flag consumes the remainder of the command line, 109 the package list (if present) must appear before this flag. 110 111 -c 112 Compile the test binary to pkg.test in the current directory but do not run it 113 (where pkg is the last element of the package's import path). 114 The file name or target directory can be changed with the -o flag. 115 116 -exec xprog 117 Run the test binary using xprog. The behavior is the same as 118 in 'go run'. See 'go help run' for details. 119 120 -json 121 Convert test output to JSON suitable for automated processing. 122 See 'go doc test2json' for the encoding details. 123 124 -o file 125 Compile the test binary to the named file. 126 The test still runs (unless -c or -i is specified). 127 If file ends in a slash or names an existing directory, 128 the test is written to pkg.test in that directory. 129 130 The test binary also accepts flags that control execution of the test; these 131 flags are also accessible by 'go test'. See 'go help testflag' for details. 132 133 For more about build flags, see 'go help build'. 134 For more about specifying packages, see 'go help packages'. 135 136 See also: go build, go vet. 137 `, 138 } 139 140 var HelpTestflag = &base.Command{ 141 UsageLine: "testflag", 142 Short: "testing flags", 143 Long: ` 144 The 'go test' command takes both flags that apply to 'go test' itself 145 and flags that apply to the resulting test binary. 146 147 Several of the flags control profiling and write an execution profile 148 suitable for "go tool pprof"; run "go tool pprof -h" for more 149 information. The --alloc_space, --alloc_objects, and --show_bytes 150 options of pprof control how the information is presented. 151 152 The following flags are recognized by the 'go test' command and 153 control the execution of any test: 154 155 -bench regexp 156 Run only those benchmarks matching a regular expression. 157 By default, no benchmarks are run. 158 To run all benchmarks, use '-bench .' or '-bench=.'. 159 The regular expression is split by unbracketed slash (/) 160 characters into a sequence of regular expressions, and each 161 part of a benchmark's identifier must match the corresponding 162 element in the sequence, if any. Possible parents of matches 163 are run with b.N=1 to identify sub-benchmarks. For example, 164 given -bench=X/Y, top-level benchmarks matching X are run 165 with b.N=1 to find any sub-benchmarks matching Y, which are 166 then run in full. 167 168 -benchtime t 169 Run enough iterations of each benchmark to take t, specified 170 as a time.Duration (for example, -benchtime 1h30s). 171 The default is 1 second (1s). 172 The special syntax Nx means to run the benchmark N times 173 (for example, -benchtime 100x). 174 175 -count n 176 Run each test, benchmark, and fuzz seed n times (default 1). 177 If -cpu is set, run n times for each GOMAXPROCS value. 178 Examples are always run once. -count does not apply to 179 fuzz tests matched by -fuzz. 180 181 -cover 182 Enable coverage analysis. 183 Note that because coverage works by annotating the source 184 code before compilation, compilation and test failures with 185 coverage enabled may report line numbers that don't correspond 186 to the original sources. 187 188 -covermode set,count,atomic 189 Set the mode for coverage analysis for the package[s] 190 being tested. The default is "set" unless -race is enabled, 191 in which case it is "atomic". 192 The values: 193 set: bool: does this statement run? 194 count: int: how many times does this statement run? 195 atomic: int: count, but correct in multithreaded tests; 196 significantly more expensive. 197 Sets -cover. 198 199 -coverpkg pattern1,pattern2,pattern3 200 Apply coverage analysis in each test to packages matching the patterns. 201 The default is for each test to analyze only the package being tested. 202 See 'go help packages' for a description of package patterns. 203 Sets -cover. 204 205 -cpu 1,2,4 206 Specify a list of GOMAXPROCS values for which the tests, benchmarks or 207 fuzz tests should be executed. The default is the current value 208 of GOMAXPROCS. -cpu does not apply to fuzz tests matched by -fuzz. 209 210 -failfast 211 Do not start new tests after the first test failure. 212 213 -fullpath 214 Show full file names in the error messages. 215 216 -fuzz regexp 217 Run the fuzz test matching the regular expression. When specified, 218 the command line argument must match exactly one package within the 219 main module, and regexp must match exactly one fuzz test within 220 that package. Fuzzing will occur after tests, benchmarks, seed corpora 221 of other fuzz tests, and examples have completed. See the Fuzzing 222 section of the testing package documentation for details. 223 224 -fuzztime t 225 Run enough iterations of the fuzz target during fuzzing to take t, 226 specified as a time.Duration (for example, -fuzztime 1h30s). 227 The default is to run forever. 228 The special syntax Nx means to run the fuzz target N times 229 (for example, -fuzztime 1000x). 230 231 -fuzzminimizetime t 232 Run enough iterations of the fuzz target during each minimization 233 attempt to take t, as specified as a time.Duration (for example, 234 -fuzzminimizetime 30s). 235 The default is 60s. 236 The special syntax Nx means to run the fuzz target N times 237 (for example, -fuzzminimizetime 100x). 238 239 -json 240 Log verbose output and test results in JSON. This presents the 241 same information as the -v flag in a machine-readable format. 242 243 -list regexp 244 List tests, benchmarks, fuzz tests, or examples matching the regular 245 expression. No tests, benchmarks, fuzz tests, or examples will be run. 246 This will only list top-level tests. No subtest or subbenchmarks will be 247 shown. 248 249 -parallel n 250 Allow parallel execution of test functions that call t.Parallel, and 251 fuzz targets that call t.Parallel when running the seed corpus. 252 The value of this flag is the maximum number of tests to run 253 simultaneously. 254 While fuzzing, the value of this flag is the maximum number of 255 subprocesses that may call the fuzz function simultaneously, regardless of 256 whether T.Parallel is called. 257 By default, -parallel is set to the value of GOMAXPROCS. 258 Setting -parallel to values higher than GOMAXPROCS may cause degraded 259 performance due to CPU contention, especially when fuzzing. 260 Note that -parallel only applies within a single test binary. 261 The 'go test' command may run tests for different packages 262 in parallel as well, according to the setting of the -p flag 263 (see 'go help build'). 264 265 -run regexp 266 Run only those tests, examples, and fuzz tests matching the regular 267 expression. For tests, the regular expression is split by unbracketed 268 slash (/) characters into a sequence of regular expressions, and each 269 part of a test's identifier must match the corresponding element in 270 the sequence, if any. Note that possible parents of matches are 271 run too, so that -run=X/Y matches and runs and reports the result 272 of all tests matching X, even those without sub-tests matching Y, 273 because it must run them to look for those sub-tests. 274 See also -skip. 275 276 -short 277 Tell long-running tests to shorten their run time. 278 It is off by default but set during all.bash so that installing 279 the Go tree can run a sanity check but not spend time running 280 exhaustive tests. 281 282 -shuffle off,on,N 283 Randomize the execution order of tests and benchmarks. 284 It is off by default. If -shuffle is set to on, then it will seed 285 the randomizer using the system clock. If -shuffle is set to an 286 integer N, then N will be used as the seed value. In both cases, 287 the seed will be reported for reproducibility. 288 289 -skip regexp 290 Run only those tests, examples, fuzz tests, and benchmarks that 291 do not match the regular expression. Like for -run and -bench, 292 for tests and benchmarks, the regular expression is split by unbracketed 293 slash (/) characters into a sequence of regular expressions, and each 294 part of a test's identifier must match the corresponding element in 295 the sequence, if any. 296 297 -timeout d 298 If a test binary runs longer than duration d, panic. 299 If d is 0, the timeout is disabled. 300 The default is 10 minutes (10m). 301 302 -v 303 Verbose output: log all tests as they are run. Also print all 304 text from Log and Logf calls even if the test succeeds. 305 306 -vet list 307 Configure the invocation of "go vet" during "go test" 308 to use the comma-separated list of vet checks. 309 If list is empty, "go test" runs "go vet" with a curated list of 310 checks believed to be always worth addressing. 311 If list is "off", "go test" does not run "go vet" at all. 312 313 The following flags are also recognized by 'go test' and can be used to 314 profile the tests during execution: 315 316 -benchmem 317 Print memory allocation statistics for benchmarks. 318 Allocations made in C or using C.malloc are not counted. 319 320 -blockprofile block.out 321 Write a goroutine blocking profile to the specified file 322 when all tests are complete. 323 Writes test binary as -c would. 324 325 -blockprofilerate n 326 Control the detail provided in goroutine blocking profiles by 327 calling runtime.SetBlockProfileRate with n. 328 See 'go doc runtime.SetBlockProfileRate'. 329 The profiler aims to sample, on average, one blocking event every 330 n nanoseconds the program spends blocked. By default, 331 if -test.blockprofile is set without this flag, all blocking events 332 are recorded, equivalent to -test.blockprofilerate=1. 333 334 -coverprofile cover.out 335 Write a coverage profile to the file after all tests have passed. 336 Sets -cover. 337 338 -cpuprofile cpu.out 339 Write a CPU profile to the specified file before exiting. 340 Writes test binary as -c would. 341 342 -memprofile mem.out 343 Write an allocation profile to the file after all tests have passed. 344 Writes test binary as -c would. 345 346 -memprofilerate n 347 Enable more precise (and expensive) memory allocation profiles by 348 setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'. 349 To profile all memory allocations, use -test.memprofilerate=1. 350 351 -mutexprofile mutex.out 352 Write a mutex contention profile to the specified file 353 when all tests are complete. 354 Writes test binary as -c would. 355 356 -mutexprofilefraction n 357 Sample 1 in n stack traces of goroutines holding a 358 contended mutex. 359 360 -outputdir directory 361 Place output files from profiling in the specified directory, 362 by default the directory in which "go test" is running. 363 364 -trace trace.out 365 Write an execution trace to the specified file before exiting. 366 367 Each of these flags is also recognized with an optional 'test.' prefix, 368 as in -test.v. When invoking the generated test binary (the result of 369 'go test -c') directly, however, the prefix is mandatory. 370 371 The 'go test' command rewrites or removes recognized flags, 372 as appropriate, both before and after the optional package list, 373 before invoking the test binary. 374 375 For instance, the command 376 377 go test -v -myflag testdata -cpuprofile=prof.out -x 378 379 will compile the test binary and then run it as 380 381 pkg.test -test.v -myflag testdata -test.cpuprofile=prof.out 382 383 (The -x flag is removed because it applies only to the go command's 384 execution, not to the test itself.) 385 386 The test flags that generate profiles (other than for coverage) also 387 leave the test binary in pkg.test for use when analyzing the profiles. 388 389 When 'go test' runs a test binary, it does so from within the 390 corresponding package's source code directory. Depending on the test, 391 it may be necessary to do the same when invoking a generated test 392 binary directly. Because that directory may be located within the 393 module cache, which may be read-only and is verified by checksums, the 394 test must not write to it or any other directory within the module 395 unless explicitly requested by the user (such as with the -fuzz flag, 396 which writes failures to testdata/fuzz). 397 398 The command-line package list, if present, must appear before any 399 flag not known to the go test command. Continuing the example above, 400 the package list would have to appear before -myflag, but could appear 401 on either side of -v. 402 403 When 'go test' runs in package list mode, 'go test' caches successful 404 package test results to avoid unnecessary repeated running of tests. To 405 disable test caching, use any test flag or argument other than the 406 cacheable flags. The idiomatic way to disable test caching explicitly 407 is to use -count=1. 408 409 To keep an argument for a test binary from being interpreted as a 410 known flag or a package name, use -args (see 'go help test') which 411 passes the remainder of the command line through to the test binary 412 uninterpreted and unaltered. 413 414 For instance, the command 415 416 go test -v -args -x -v 417 418 will compile the test binary and then run it as 419 420 pkg.test -test.v -x -v 421 422 Similarly, 423 424 go test -args math 425 426 will compile the test binary and then run it as 427 428 pkg.test math 429 430 In the first example, the -x and the second -v are passed through to the 431 test binary unchanged and with no effect on the go command itself. 432 In the second example, the argument math is passed through to the test 433 binary, instead of being interpreted as the package list. 434 `, 435 } 436 437 var HelpTestfunc = &base.Command{ 438 UsageLine: "testfunc", 439 Short: "testing functions", 440 Long: ` 441 The 'go test' command expects to find test, benchmark, and example functions 442 in the "*_test.go" files corresponding to the package under test. 443 444 A test function is one named TestXxx (where Xxx does not start with a 445 lower case letter) and should have the signature, 446 447 func TestXxx(t *testing.T) { ... } 448 449 A benchmark function is one named BenchmarkXxx and should have the signature, 450 451 func BenchmarkXxx(b *testing.B) { ... } 452 453 A fuzz test is one named FuzzXxx and should have the signature, 454 455 func FuzzXxx(f *testing.F) { ... } 456 457 An example function is similar to a test function but, instead of using 458 *testing.T to report success or failure, prints output to os.Stdout. 459 If the last comment in the function starts with "Output:" then the output 460 is compared exactly against the comment (see examples below). If the last 461 comment begins with "Unordered output:" then the output is compared to the 462 comment, however the order of the lines is ignored. An example with no such 463 comment is compiled but not executed. An example with no text after 464 "Output:" is compiled, executed, and expected to produce no output. 465 466 Godoc displays the body of ExampleXxx to demonstrate the use 467 of the function, constant, or variable Xxx. An example of a method M with 468 receiver type T or *T is named ExampleT_M. There may be multiple examples 469 for a given function, constant, or variable, distinguished by a trailing _xxx, 470 where xxx is a suffix not beginning with an upper case letter. 471 472 Here is an example of an example: 473 474 func ExamplePrintln() { 475 Println("The output of\nthis example.") 476 // Output: The output of 477 // this example. 478 } 479 480 Here is another example where the ordering of the output is ignored: 481 482 func ExamplePerm() { 483 for _, value := range Perm(4) { 484 fmt.Println(value) 485 } 486 487 // Unordered output: 4 488 // 2 489 // 1 490 // 3 491 // 0 492 } 493 494 The entire test file is presented as the example when it contains a single 495 example function, at least one other function, type, variable, or constant 496 declaration, and no tests, benchmarks, or fuzz tests. 497 498 See the documentation of the testing package for more information. 499 `, 500 }