summaryrefslogtreecommitdiff
path: root/devdocs/go/testing%2Findex.html
blob: 15c0b37c9eeb72cc1d23784a3c472f5348492c58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
<h1> Package testing  </h1>     <ul id="short-nav">
<li><code>import "testing"</code></li>
<li><a href="#pkg-overview" class="overviewLink">Overview</a></li>
<li><a href="#pkg-index" class="indexLink">Index</a></li>
<li><a href="#pkg-examples" class="examplesLink">Examples</a></li>
<li><a href="#pkg-subdirectories">Subdirectories</a></li>
</ul>     <h2 id="pkg-overview">Overview </h2> <p>Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the "go test" command, which automates execution of any function of the form </p>
<pre data-language="go">func TestXxx(*testing.T)
</pre> <p>where Xxx does not start with a lowercase letter. The function name serves to identify the test routine. </p>
<p>Within these functions, use the Error, Fail or related methods to signal failure. </p>
<p>To write a new test suite, create a file that contains the TestXxx functions as described here, and give that file a name ending in "_test.go". The file will be excluded from regular package builds but will be included when the "go test" command is run. </p>
<p>The test file can be in the same package as the one being tested, or in a corresponding package with the suffix "_test". </p>
<p>If the test file is in the same package, it may refer to unexported identifiers within the package, as in this example: </p>
<pre data-language="go">package abs

import "testing"

func TestAbs(t *testing.T) {
    got := Abs(-1)
    if got != 1 {
        t.Errorf("Abs(-1) = %d; want 1", got)
    }
}
</pre> <p>If the file is in a separate "_test" package, the package being tested must be imported explicitly and only its exported identifiers may be used. This is known as "black box" testing. </p>
<pre data-language="go">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)
    }
}
</pre> <p>For more detail, run "go help test" and "go help testflag". </p>
<h3 id="hdr-Benchmarks">Benchmarks</h3> <p>Functions of the form </p>
<pre data-language="go">func BenchmarkXxx(*testing.B)
</pre> <p>are considered benchmarks, and are executed by the "go test" command when its -bench flag is provided. Benchmarks are run sequentially. </p>
<p>For a description of the testing flags, see <a href="https://golang.org/cmd/go/#hdr-Testing_flags">https://golang.org/cmd/go/#hdr-Testing_flags</a>. </p>
<p>A sample benchmark function looks like this: </p>
<pre data-language="go">func BenchmarkRandInt(b *testing.B) {
    for i := 0; i &lt; b.N; i++ {
        rand.Int()
    }
}
</pre> <p>The benchmark function must run the target code b.N times. During benchmark execution, b.N is adjusted until the benchmark function lasts long enough to be timed reliably. The output </p>
<pre data-language="go">BenchmarkRandInt-8   	68453040	        17.8 ns/op
</pre> <p>means that the loop ran 68453040 times at a speed of 17.8 ns per loop. </p>
<p>If a benchmark needs some expensive setup before running, the timer may be reset: </p>
<pre data-language="go">func BenchmarkBigLen(b *testing.B) {
    big := NewBig()
    b.ResetTimer()
    for i := 0; i &lt; b.N; i++ {
        big.Len()
    }
}
</pre> <p>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: </p>
<pre data-language="go">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(&amp;buf, "World")
        }
    })
}
</pre> <p>A detailed specification of the benchmark results format is given in <a href="https://golang.org/design/14313-benchmark-format">https://golang.org/design/14313-benchmark-format</a>. </p>
<p>There are standard tools for working with benchmark results at <a href="https://golang.org/x/perf/cmd">https://golang.org/x/perf/cmd</a>. In particular, <a href="https://golang.org/x/perf/cmd/benchstat">https://golang.org/x/perf/cmd/benchstat</a> performs statistically robust A/B comparisons. </p>
<h3 id="hdr-Examples">Examples</h3> <p>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: </p>
<pre data-language="go">func ExampleHello() {
    fmt.Println("hello")
    // Output: hello
}

func ExampleSalutations() {
    fmt.Println("hello, and")
    fmt.Println("goodbye")
    // Output:
    // hello, and
    // goodbye
}
</pre> <p>The comment prefix "Unordered output:" is like "Output:", but matches any line order: </p>
<pre data-language="go">func ExamplePerm() {
    for _, value := range Perm(5) {
        fmt.Println(value)
    }
    // Unordered output: 4
    // 2
    // 1
    // 3
    // 0
}
</pre> <p>Example functions without output comments are compiled but not executed. </p>
<p>The naming convention to declare examples for the package, a function F, a type T and method M on type T are: </p>
<pre data-language="go">func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }
</pre> <p>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. </p>
<pre data-language="go">func Example_suffix() { ... }
func ExampleF_suffix() { ... }
func ExampleT_suffix() { ... }
func ExampleT_M_suffix() { ... }
</pre> <p>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. </p>
<h3 id="hdr-Fuzzing">Fuzzing</h3> <p>'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. </p>
<p>Functions of the form </p>
<pre data-language="go">func FuzzXxx(*testing.F)
</pre> <p>are considered fuzz tests. </p>
<p>For example: </p>
<pre data-language="go">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)
    }
  })
}
</pre> <p>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/&lt;Name&gt; (where &lt;Name&gt; 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. </p>
<p>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. </p>
<p>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/&lt;Name&gt; 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. </p>
<p>When fuzzing is disabled, the fuzz target is called with the seed inputs registered with F.Add and seed inputs from testdata/fuzz/&lt;Name&gt;. In this mode, the fuzz test acts much like a regular test, with subtests started with F.Fuzz instead of T.Run. </p>
<p>See <a href="https://go.dev/doc/fuzz">https://go.dev/doc/fuzz</a> for documentation about fuzzing. </p>
<h3 id="hdr-Skipping">Skipping</h3> <p>Tests or benchmarks may be skipped at run time with a call to the Skip method of *T or *B: </p>
<pre data-language="go">func TestTimeConsuming(t *testing.T) {
    if testing.Short() {
        t.Skip("skipping test in short mode.")
    }
    ...
}
</pre> <p>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: </p>
<pre data-language="go">func FuzzJSONMarshaling(f *testing.F) {
    f.Fuzz(func(t *testing.T, b []byte) {
        var v interface{}
        if err := json.Unmarshal(b, &amp;v); err != nil {
            t.Skip()
        }
        if _, err := json.Marshal(v); err != nil {
            t.Errorf("Marshal: %v", err)
        }
    })
}
</pre> <h3 id="hdr-Subtests_and_Sub_benchmarks">Subtests and Sub-benchmarks</h3> <p>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: </p>
<pre data-language="go">func TestFoo(t *testing.T) {
    // &lt;setup code&gt;
    t.Run("A=1", func(t *testing.T) { ... })
    t.Run("A=2", func(t *testing.T) { ... })
    t.Run("B=1", func(t *testing.T) { ... })
    // &lt;tear-down code&gt;
}
</pre> <p>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. </p>
<p>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": </p>
<pre data-language="go">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"
</pre> <p>The -run argument can also be used to run a specific value in the seed corpus, for debugging. For example: </p>
<pre data-language="go">go test -run=FuzzFoo/9ddb952d9814
</pre> <p>The -fuzz and -run flags can both be set, in order to fuzz a target but skip the execution of all other tests. </p>
<p>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: </p>
<pre data-language="go">func TestGroupedParallel(t *testing.T) {
    for _, tc := range tests {
        tc := tc // capture range variable
        t.Run(tc.Name, func(t *testing.T) {
            t.Parallel()
            ...
        })
    }
}
</pre> <p>Run does not return until parallel subtests have completed, providing a way to clean up after a group of parallel tests: </p>
<pre data-language="go">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)
    })
    // &lt;tear-down code&gt;
}
</pre> <h3 id="hdr-Main">Main</h3> <p>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: </p>
<pre data-language="go">func TestMain(m *testing.M)
</pre> <p>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. </p>
<p>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. </p>
<p>A simple implementation of TestMain is: </p>
<pre data-language="go">func TestMain(m *testing.M) {
	// call flag.Parse() here if TestMain uses flags
	os.Exit(m.Run())
}
</pre> <p>TestMain is a low-level primitive and should not be necessary for casual testing needs, where ordinary test functions suffice. </p>     <h2 id="pkg-index">Index </h2>  <ul id="manual-nav">
<li><a href="#AllocsPerRun">func AllocsPerRun(runs int, f func()) (avg float64)</a></li>
<li><a href="#CoverMode">func CoverMode() string</a></li>
<li><a href="#Coverage">func Coverage() float64</a></li>
<li><a href="#Init">func Init()</a></li>
<li><a href="#Main">func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)</a></li>
<li><a href="#RegisterCover">func RegisterCover(c Cover)</a></li>
<li><a href="#RunBenchmarks">func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)</a></li>
<li><a href="#RunExamples">func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)</a></li>
<li><a href="#RunTests">func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)</a></li>
<li><a href="#Short">func Short() bool</a></li>
<li><a href="#Testing">func Testing() bool</a></li>
<li><a href="#Verbose">func Verbose() bool</a></li>
<li><a href="#B">type B</a></li>
<li> <a href="#B.Cleanup">func (c *B) Cleanup(f func())</a>
</li>
<li> <a href="#B.Elapsed">func (b *B) Elapsed() time.Duration</a>
</li>
<li> <a href="#B.Error">func (c *B) Error(args ...any)</a>
</li>
<li> <a href="#B.Errorf">func (c *B) Errorf(format string, args ...any)</a>
</li>
<li> <a href="#B.Fail">func (c *B) Fail()</a>
</li>
<li> <a href="#B.FailNow">func (c *B) FailNow()</a>
</li>
<li> <a href="#B.Failed">func (c *B) Failed() bool</a>
</li>
<li> <a href="#B.Fatal">func (c *B) Fatal(args ...any)</a>
</li>
<li> <a href="#B.Fatalf">func (c *B) Fatalf(format string, args ...any)</a>
</li>
<li> <a href="#B.Helper">func (c *B) Helper()</a>
</li>
<li> <a href="#B.Log">func (c *B) Log(args ...any)</a>
</li>
<li> <a href="#B.Logf">func (c *B) Logf(format string, args ...any)</a>
</li>
<li> <a href="#B.Name">func (c *B) Name() string</a>
</li>
<li> <a href="#B.ReportAllocs">func (b *B) ReportAllocs()</a>
</li>
<li> <a href="#B.ReportMetric">func (b *B) ReportMetric(n float64, unit string)</a>
</li>
<li> <a href="#B.ResetTimer">func (b *B) ResetTimer()</a>
</li>
<li> <a href="#B.Run">func (b *B) Run(name string, f func(b *B)) bool</a>
</li>
<li> <a href="#B.RunParallel">func (b *B) RunParallel(body func(*PB))</a>
</li>
<li> <a href="#B.SetBytes">func (b *B) SetBytes(n int64)</a>
</li>
<li> <a href="#B.SetParallelism">func (b *B) SetParallelism(p int)</a>
</li>
<li> <a href="#B.Setenv">func (c *B) Setenv(key, value string)</a>
</li>
<li> <a href="#B.Skip">func (c *B) Skip(args ...any)</a>
</li>
<li> <a href="#B.SkipNow">func (c *B) SkipNow()</a>
</li>
<li> <a href="#B.Skipf">func (c *B) Skipf(format string, args ...any)</a>
</li>
<li> <a href="#B.Skipped">func (c *B) Skipped() bool</a>
</li>
<li> <a href="#B.StartTimer">func (b *B) StartTimer()</a>
</li>
<li> <a href="#B.StopTimer">func (b *B) StopTimer()</a>
</li>
<li> <a href="#B.TempDir">func (c *B) TempDir() string</a>
</li>
<li><a href="#BenchmarkResult">type BenchmarkResult</a></li>
<li> <a href="#Benchmark">func Benchmark(f func(b *B)) BenchmarkResult</a>
</li>
<li> <a href="#BenchmarkResult.AllocedBytesPerOp">func (r BenchmarkResult) AllocedBytesPerOp() int64</a>
</li>
<li> <a href="#BenchmarkResult.AllocsPerOp">func (r BenchmarkResult) AllocsPerOp() int64</a>
</li>
<li> <a href="#BenchmarkResult.MemString">func (r BenchmarkResult) MemString() string</a>
</li>
<li> <a href="#BenchmarkResult.NsPerOp">func (r BenchmarkResult) NsPerOp() int64</a>
</li>
<li> <a href="#BenchmarkResult.String">func (r BenchmarkResult) String() string</a>
</li>
<li><a href="#Cover">type Cover</a></li>
<li><a href="#CoverBlock">type CoverBlock</a></li>
<li><a href="#F">type F</a></li>
<li> <a href="#F.Add">func (f *F) Add(args ...any)</a>
</li>
<li> <a href="#F.Cleanup">func (c *F) Cleanup(f func())</a>
</li>
<li> <a href="#F.Error">func (c *F) Error(args ...any)</a>
</li>
<li> <a href="#F.Errorf">func (c *F) Errorf(format string, args ...any)</a>
</li>
<li> <a href="#F.Fail">func (f *F) Fail()</a>
</li>
<li> <a href="#F.FailNow">func (c *F) FailNow()</a>
</li>
<li> <a href="#F.Failed">func (c *F) Failed() bool</a>
</li>
<li> <a href="#F.Fatal">func (c *F) Fatal(args ...any)</a>
</li>
<li> <a href="#F.Fatalf">func (c *F) Fatalf(format string, args ...any)</a>
</li>
<li> <a href="#F.Fuzz">func (f *F) Fuzz(ff any)</a>
</li>
<li> <a href="#F.Helper">func (f *F) Helper()</a>
</li>
<li> <a href="#F.Log">func (c *F) Log(args ...any)</a>
</li>
<li> <a href="#F.Logf">func (c *F) Logf(format string, args ...any)</a>
</li>
<li> <a href="#F.Name">func (c *F) Name() string</a>
</li>
<li> <a href="#F.Setenv">func (c *F) Setenv(key, value string)</a>
</li>
<li> <a href="#F.Skip">func (c *F) Skip(args ...any)</a>
</li>
<li> <a href="#F.SkipNow">func (c *F) SkipNow()</a>
</li>
<li> <a href="#F.Skipf">func (c *F) Skipf(format string, args ...any)</a>
</li>
<li> <a href="#F.Skipped">func (f *F) Skipped() bool</a>
</li>
<li> <a href="#F.TempDir">func (c *F) TempDir() string</a>
</li>
<li><a href="#InternalBenchmark">type InternalBenchmark</a></li>
<li><a href="#InternalExample">type InternalExample</a></li>
<li><a href="#InternalFuzzTarget">type InternalFuzzTarget</a></li>
<li><a href="#InternalTest">type InternalTest</a></li>
<li><a href="#M">type M</a></li>
<li> <a href="#MainStart">func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M</a>
</li>
<li> <a href="#M.Run">func (m *M) Run() (code int)</a>
</li>
<li><a href="#PB">type PB</a></li>
<li> <a href="#PB.Next">func (pb *PB) Next() bool</a>
</li>
<li><a href="#T">type T</a></li>
<li> <a href="#T.Cleanup">func (c *T) Cleanup(f func())</a>
</li>
<li> <a href="#T.Deadline">func (t *T) Deadline() (deadline time.Time, ok bool)</a>
</li>
<li> <a href="#T.Error">func (c *T) Error(args ...any)</a>
</li>
<li> <a href="#T.Errorf">func (c *T) Errorf(format string, args ...any)</a>
</li>
<li> <a href="#T.Fail">func (c *T) Fail()</a>
</li>
<li> <a href="#T.FailNow">func (c *T) FailNow()</a>
</li>
<li> <a href="#T.Failed">func (c *T) Failed() bool</a>
</li>
<li> <a href="#T.Fatal">func (c *T) Fatal(args ...any)</a>
</li>
<li> <a href="#T.Fatalf">func (c *T) Fatalf(format string, args ...any)</a>
</li>
<li> <a href="#T.Helper">func (c *T) Helper()</a>
</li>
<li> <a href="#T.Log">func (c *T) Log(args ...any)</a>
</li>
<li> <a href="#T.Logf">func (c *T) Logf(format string, args ...any)</a>
</li>
<li> <a href="#T.Name">func (c *T) Name() string</a>
</li>
<li> <a href="#T.Parallel">func (t *T) Parallel()</a>
</li>
<li> <a href="#T.Run">func (t *T) Run(name string, f func(t *T)) bool</a>
</li>
<li> <a href="#T.Setenv">func (t *T) Setenv(key, value string)</a>
</li>
<li> <a href="#T.Skip">func (c *T) Skip(args ...any)</a>
</li>
<li> <a href="#T.SkipNow">func (c *T) SkipNow()</a>
</li>
<li> <a href="#T.Skipf">func (c *T) Skipf(format string, args ...any)</a>
</li>
<li> <a href="#T.Skipped">func (c *T) Skipped() bool</a>
</li>
<li> <a href="#T.TempDir">func (c *T) TempDir() string</a>
</li>
<li><a href="#TB">type TB</a></li>
</ul> <div id="pkg-examples"> <h3>Examples</h3>  <dl> <dd><a class="exampleLink" href="#example_B_ReportMetric">B.ReportMetric</a></dd> <dd><a class="exampleLink" href="#example_B_ReportMetric_parallel">B.ReportMetric (Parallel)</a></dd> <dd><a class="exampleLink" href="#example_B_RunParallel">B.RunParallel</a></dd> </dl> </div> <h3>Package files</h3> <p>  <span>allocs.go</span> <span>benchmark.go</span> <span>cover.go</span> <span>example.go</span> <span>fuzz.go</span> <span>match.go</span> <span>newcover.go</span> <span>run_example.go</span> <span>testing.go</span> <span>testing_other.go</span>  </p>   <h2 id="AllocsPerRun">func <span>AllocsPerRun</span>  <span title="Added in Go 1.1">1.1</span> </h2> <pre data-language="go">func AllocsPerRun(runs int, f func()) (avg float64)</pre> <p>AllocsPerRun returns the average number of allocations during calls to f. Although the return value has type float64, it will always be an integral value. </p>
<p>To compute the number of allocations, the function will first be run once as a warm-up. The average number of allocations over the specified number of runs will then be measured and returned. </p>
<p>AllocsPerRun sets GOMAXPROCS to 1 during its measurement and will restore it before returning. </p>
<h2 id="CoverMode">func <span>CoverMode</span>  <span title="Added in Go 1.8">1.8</span> </h2> <pre data-language="go">func CoverMode() string</pre> <p>CoverMode reports what the test coverage mode is set to. The values are "set", "count", or "atomic". The return value will be empty if test coverage is not enabled. </p>
<h2 id="Coverage">func <span>Coverage</span>  <span title="Added in Go 1.4">1.4</span> </h2> <pre data-language="go">func Coverage() float64</pre> <p>Coverage reports the current code coverage as a fraction in the range [0, 1]. If coverage is not enabled, Coverage returns 0. </p>
<p>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'. </p>
<h2 id="Init">func <span>Init</span>  <span title="Added in Go 1.13">1.13</span> </h2> <pre data-language="go">func Init()</pre> <p>Init registers testing flags. These flags are automatically registered by the "go test" command before running test functions, so Init is only needed when calling functions such as Benchmark without using "go test". </p>
<p>Init is not safe to call concurrently. It has no effect if it was already called. </p>
<h2 id="Main">func <span>Main</span>  </h2> <pre data-language="go">func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)</pre> <p>Main is an internal function, part of the implementation of the "go test" command. It was exported because it is cross-package and predates "internal" packages. It is no longer used by "go test" but preserved, as much as possible, for other systems that simulate "go test" using Main, but Main sometimes cannot be updated as new functionality is added to the testing package. Systems simulating "go test" should be updated to use MainStart. </p>
<h2 id="RegisterCover">func <span>RegisterCover</span>  <span title="Added in Go 1.2">1.2</span> </h2> <pre data-language="go">func RegisterCover(c Cover)</pre> <p>RegisterCover records the coverage data accumulators for the tests. NOTE: This function is internal to the testing infrastructure and may change. It is not covered (yet) by the Go 1 compatibility guidelines. </p>
<h2 id="RunBenchmarks">func <span>RunBenchmarks</span>  </h2> <pre data-language="go">func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)</pre> <p>RunBenchmarks is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command. </p>
<h2 id="RunExamples">func <span>RunExamples</span>  </h2> <pre data-language="go">func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)</pre> <p>RunExamples is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command. </p>
<h2 id="RunTests">func <span>RunTests</span>  </h2> <pre data-language="go">func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)</pre> <p>RunTests is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command. </p>
<h2 id="Short">func <span>Short</span>  </h2> <pre data-language="go">func Short() bool</pre> <p>Short reports whether the -test.short flag is set. </p>
<h2 id="Testing">func <span>Testing</span>  <span title="Added in Go 1.21">1.21</span> </h2> <pre data-language="go">func Testing() bool</pre> <p>Testing reports whether the current code is being run in a test. This will report true in programs created by "go test", false in programs created by "go build". </p>
<h2 id="Verbose">func <span>Verbose</span>  <span title="Added in Go 1.1">1.1</span> </h2> <pre data-language="go">func Verbose() bool</pre> <p>Verbose reports whether the -test.v flag is set. </p>
<h2 id="B">type <span>B</span>  </h2> <p>B is a type passed to <a href="#Benchmark">Benchmark</a> functions to manage benchmark timing and to specify the number of iterations to run. </p>
<p>A benchmark ends when its Benchmark function returns or calls any of the methods FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods must be called only from the goroutine running the Benchmark function. The other reporting methods, such as the variations of Log and Error, may be called simultaneously from multiple goroutines. </p>
<p>Like in tests, benchmark logs are accumulated during execution and dumped to standard output when done. Unlike in tests, benchmark logs are always printed, so as not to hide output whose existence may be affecting benchmark results. </p>
<pre data-language="go">type B struct {
    N int
    // contains filtered or unexported fields
}
</pre> <h3 id="B.Cleanup">func (*B) <span>Cleanup</span>  <span title="Added in Go 1.14">1.14</span> </h3> <pre data-language="go">func (c *B) Cleanup(f func())</pre> <p>Cleanup registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order. </p>
<h3 id="B.Elapsed">func (*B) <span>Elapsed</span>  <span title="Added in Go 1.20">1.20</span> </h3> <pre data-language="go">func (b *B) Elapsed() time.Duration</pre> <p>Elapsed returns the measured elapsed time of the benchmark. The duration reported by Elapsed matches the one measured by <a href="#B.StartTimer">B.StartTimer</a>, <a href="#B.StopTimer">B.StopTimer</a>, and <a href="#B.ResetTimer">B.ResetTimer</a>. </p>
<h3 id="B.Error">func (*B) <span>Error</span>  </h3> <pre data-language="go">func (c *B) Error(args ...any)</pre> <p>Error is equivalent to Log followed by Fail. </p>
<h3 id="B.Errorf">func (*B) <span>Errorf</span>  </h3> <pre data-language="go">func (c *B) Errorf(format string, args ...any)</pre> <p>Errorf is equivalent to Logf followed by Fail. </p>
<h3 id="B.Fail">func (*B) <span>Fail</span>  </h3> <pre data-language="go">func (c *B) Fail()</pre> <p>Fail marks the function as having failed but continues execution. </p>
<h3 id="B.FailNow">func (*B) <span>FailNow</span>  </h3> <pre data-language="go">func (c *B) FailNow()</pre> <p>FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines. </p>
<h3 id="B.Failed">func (*B) <span>Failed</span>  </h3> <pre data-language="go">func (c *B) Failed() bool</pre> <p>Failed reports whether the function has failed. </p>
<h3 id="B.Fatal">func (*B) <span>Fatal</span>  </h3> <pre data-language="go">func (c *B) Fatal(args ...any)</pre> <p>Fatal is equivalent to Log followed by FailNow. </p>
<h3 id="B.Fatalf">func (*B) <span>Fatalf</span>  </h3> <pre data-language="go">func (c *B) Fatalf(format string, args ...any)</pre> <p>Fatalf is equivalent to Logf followed by FailNow. </p>
<h3 id="B.Helper">func (*B) <span>Helper</span>  <span title="Added in Go 1.9">1.9</span> </h3> <pre data-language="go">func (c *B) Helper()</pre> <p>Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines. </p>
<h3 id="B.Log">func (*B) <span>Log</span>  </h3> <pre data-language="go">func (c *B) Log(args ...any)</pre> <p>Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag. </p>
<h3 id="B.Logf">func (*B) <span>Logf</span>  </h3> <pre data-language="go">func (c *B) Logf(format string, args ...any)</pre> <p>Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. A final newline is added if not provided. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag. </p>
<h3 id="B.Name">func (*B) <span>Name</span>  <span title="Added in Go 1.8">1.8</span> </h3> <pre data-language="go">func (c *B) Name() string</pre> <p>Name returns the name of the running (sub-) test or benchmark. </p>
<p>The name will include the name of the test along with the names of any nested sub-tests. If two sibling sub-tests have the same name, Name will append a suffix to guarantee the returned name is unique. </p>
<h3 id="B.ReportAllocs">func (*B) <span>ReportAllocs</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (b *B) ReportAllocs()</pre> <p>ReportAllocs enables malloc statistics for this benchmark. It is equivalent to setting -test.benchmem, but it only affects the benchmark function that calls ReportAllocs. </p>
<h3 id="B.ReportMetric">func (*B) <span>ReportMetric</span>  <span title="Added in Go 1.13">1.13</span> </h3> <pre data-language="go">func (b *B) ReportMetric(n float64, unit string)</pre> <p>ReportMetric adds "n unit" to the reported benchmark results. If the metric is per-iteration, the caller should divide by b.N, and by convention units should end in "/op". ReportMetric overrides any previously reported value for the same unit. ReportMetric panics if unit is the empty string or if unit contains any whitespace. If unit is a unit normally reported by the benchmark framework itself (such as "allocs/op"), ReportMetric will override that metric. Setting "ns/op" to 0 will suppress that built-in metric. </p>   <h4 id="example_B_ReportMetric"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// This reports a custom benchmark metric relevant to a
// specific algorithm (in this case, sorting).
testing.Benchmark(func(b *testing.B) {
    var compares int64
    for i := 0; i &lt; b.N; i++ {
        s := []int{5, 4, 3, 2, 1}
        sort.Slice(s, func(i, j int) bool {
            compares++
            return s[i] &lt; s[j]
        })
    }
    // This metric is per-operation, so divide by b.N and
    // report it as a "/op" unit.
    b.ReportMetric(float64(compares)/float64(b.N), "compares/op")
    // This metric is per-time, so divide by b.Elapsed and
    // report it as a "/ns" unit.
    b.ReportMetric(float64(compares)/float64(b.Elapsed().Nanoseconds()), "compares/ns")
})
</pre>      <h4 id="example_B_ReportMetric_parallel"> <span class="text">Example (Parallel)</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// This reports a custom benchmark metric relevant to a
// specific algorithm (in this case, sorting) in parallel.
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}
            sort.Slice(s, func(i, j int) bool {
                // Because RunParallel runs the function many
                // times in parallel, we must increment the
                // counter atomically to avoid racing writes.
                compares.Add(1)
                return s[i] &lt; s[j]
            })
        }
    })

    // NOTE: Report each metric once, after all of the parallel
    // calls have completed.

    // This metric is per-operation, so divide by b.N and
    // report it as a "/op" unit.
    b.ReportMetric(float64(compares.Load())/float64(b.N), "compares/op")
    // This metric is per-time, so divide by b.Elapsed and
    // report it as a "/ns" unit.
    b.ReportMetric(float64(compares.Load())/float64(b.Elapsed().Nanoseconds()), "compares/ns")
})
</pre>   <h3 id="B.ResetTimer">func (*B) <span>ResetTimer</span>  </h3> <pre data-language="go">func (b *B) ResetTimer()</pre> <p>ResetTimer zeroes the elapsed benchmark time and memory allocation counters and deletes user-reported metrics. It does not affect whether the timer is running. </p>
<h3 id="B.Run">func (*B) <span>Run</span>  <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (b *B) Run(name string, f func(b *B)) bool</pre> <p>Run benchmarks f as a subbenchmark with the given name. It reports whether there were any failures. </p>
<p>A subbenchmark is like any other benchmark. A benchmark that calls Run at least once will not be measured itself and will be called once with N=1. </p>
<h3 id="B.RunParallel">func (*B) <span>RunParallel</span>  <span title="Added in Go 1.3">1.3</span> </h3> <pre data-language="go">func (b *B) RunParallel(body func(*PB))</pre> <p>RunParallel runs a benchmark in parallel. It creates multiple goroutines and distributes b.N iterations among them. The number of goroutines defaults to GOMAXPROCS. To increase parallelism for non-CPU-bound benchmarks, call <a href="#B.SetParallelism">B.SetParallelism</a> before RunParallel. RunParallel is usually used with the go test -cpu flag. </p>
<p>The body function will be run in each goroutine. It should set up any goroutine-local state and then iterate until pb.Next returns false. It should not use the <a href="#B.StartTimer">B.StartTimer</a>, <a href="#B.StopTimer">B.StopTimer</a>, or <a href="#B.ResetTimer">B.ResetTimer</a> functions, because they have global effect. It should also not call <a href="#B.Run">B.Run</a>. </p>
<p>RunParallel reports ns/op values as wall time for the benchmark as a whole, not the sum of wall time or CPU time over each parallel goroutine. </p>   <h4 id="example_B_RunParallel"> <span class="text">Example</span>
</h4> <p>Code:</p> <pre class="code" data-language="go">
// Parallel benchmark for text/template.Template.Execute on a single object.
testing.Benchmark(func(b *testing.B) {
    templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
    // RunParallel will create GOMAXPROCS goroutines
    // and distribute work among them.
    b.RunParallel(func(pb *testing.PB) {
        // Each goroutine has its own bytes.Buffer.
        var buf bytes.Buffer
        for pb.Next() {
            // The loop body is executed b.N times total across all goroutines.
            buf.Reset()
            templ.Execute(&amp;buf, "World")
        }
    })
})
</pre>   <h3 id="B.SetBytes">func (*B) <span>SetBytes</span>  </h3> <pre data-language="go">func (b *B) SetBytes(n int64)</pre> <p>SetBytes records the number of bytes processed in a single operation. If this is called, the benchmark will report ns/op and MB/s. </p>
<h3 id="B.SetParallelism">func (*B) <span>SetParallelism</span>  <span title="Added in Go 1.3">1.3</span> </h3> <pre data-language="go">func (b *B) SetParallelism(p int)</pre> <p>SetParallelism sets the number of goroutines used by <a href="#B.RunParallel">B.RunParallel</a> to p*GOMAXPROCS. There is usually no need to call SetParallelism for CPU-bound benchmarks. If p is less than 1, this call will have no effect. </p>
<h3 id="B.Setenv">func (*B) <span>Setenv</span>  <span title="Added in Go 1.17">1.17</span> </h3> <pre data-language="go">func (c *B) Setenv(key, value string)</pre> <p>Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test. </p>
<p>Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors. </p>
<h3 id="B.Skip">func (*B) <span>Skip</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *B) Skip(args ...any)</pre> <p>Skip is equivalent to Log followed by SkipNow. </p>
<h3 id="B.SkipNow">func (*B) <span>SkipNow</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *B) SkipNow()</pre> <p>SkipNow marks the test as having been skipped and stops its execution by calling <span>runtime.Goexit</span>. If a test fails (see Error, Errorf, Fail) and is then skipped, it is still considered to have failed. Execution will continue at the next test or benchmark. See also FailNow. SkipNow must be called from the goroutine running the test, not from other goroutines created during the test. Calling SkipNow does not stop those other goroutines. </p>
<h3 id="B.Skipf">func (*B) <span>Skipf</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *B) Skipf(format string, args ...any)</pre> <p>Skipf is equivalent to Logf followed by SkipNow. </p>
<h3 id="B.Skipped">func (*B) <span>Skipped</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *B) Skipped() bool</pre> <p>Skipped reports whether the test was skipped. </p>
<h3 id="B.StartTimer">func (*B) <span>StartTimer</span>  </h3> <pre data-language="go">func (b *B) StartTimer()</pre> <p>StartTimer starts timing a test. This function is called automatically before a benchmark starts, but it can also be used to resume timing after a call to <a href="#B.StopTimer">B.StopTimer</a>. </p>
<h3 id="B.StopTimer">func (*B) <span>StopTimer</span>  </h3> <pre data-language="go">func (b *B) StopTimer()</pre> <p>StopTimer stops timing a test. This can be used to pause the timer while performing complex initialization that you don't want to measure. </p>
<h3 id="B.TempDir">func (*B) <span>TempDir</span>  <span title="Added in Go 1.15">1.15</span> </h3> <pre data-language="go">func (c *B) TempDir() string</pre> <p>TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal. </p>
<h2 id="BenchmarkResult">type <span>BenchmarkResult</span>  </h2> <p>BenchmarkResult contains the results of a benchmark run. </p>
<pre data-language="go">type BenchmarkResult struct {
    N         int           // The number of iterations.
    T         time.Duration // The total time taken.
    Bytes     int64         // Bytes processed in one iteration.
    MemAllocs uint64        // The total number of memory allocations; added in Go 1.1
    MemBytes  uint64        // The total number of bytes allocated; added in Go 1.1

    // Extra records additional metrics reported by ReportMetric.
    Extra map[string]float64 // Go 1.13
}
</pre> <h3 id="Benchmark">func <span>Benchmark</span>  </h3> <pre data-language="go">func Benchmark(f func(b *B)) BenchmarkResult</pre> <p>Benchmark benchmarks a single function. It is useful for creating custom benchmarks that do not use the "go test" command. </p>
<p>If f depends on testing flags, then <a href="#Init">Init</a> must be used to register those flags before calling Benchmark and before calling <span>flag.Parse</span>. </p>
<p>If f calls Run, the result will be an estimate of running all its subbenchmarks that don't call Run in sequence in a single benchmark. </p>
<h3 id="BenchmarkResult.AllocedBytesPerOp">func (BenchmarkResult) <span>AllocedBytesPerOp</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (r BenchmarkResult) AllocedBytesPerOp() int64</pre> <p>AllocedBytesPerOp returns the "B/op" metric, which is calculated as r.MemBytes / r.N. </p>
<h3 id="BenchmarkResult.AllocsPerOp">func (BenchmarkResult) <span>AllocsPerOp</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (r BenchmarkResult) AllocsPerOp() int64</pre> <p>AllocsPerOp returns the "allocs/op" metric, which is calculated as r.MemAllocs / r.N. </p>
<h3 id="BenchmarkResult.MemString">func (BenchmarkResult) <span>MemString</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (r BenchmarkResult) MemString() string</pre> <p>MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'. </p>
<h3 id="BenchmarkResult.NsPerOp">func (BenchmarkResult) <span>NsPerOp</span>  </h3> <pre data-language="go">func (r BenchmarkResult) NsPerOp() int64</pre> <p>NsPerOp returns the "ns/op" metric. </p>
<h3 id="BenchmarkResult.String">func (BenchmarkResult) <span>String</span>  </h3> <pre data-language="go">func (r BenchmarkResult) String() string</pre> <p>String returns a summary of the benchmark results. It follows the benchmark result line format from <a href="https://golang.org/design/14313-benchmark-format">https://golang.org/design/14313-benchmark-format</a>, not including the benchmark name. Extra metrics override built-in metrics of the same name. String does not include allocs/op or B/op, since those are reported by <a href="#BenchmarkResult.MemString">BenchmarkResult.MemString</a>. </p>
<h2 id="Cover">type <span>Cover</span>  <span title="Added in Go 1.2">1.2</span> </h2> <p>Cover records information about test coverage checking. NOTE: This struct is internal to the testing infrastructure and may change. It is not covered (yet) by the Go 1 compatibility guidelines. </p>
<pre data-language="go">type Cover struct {
    Mode            string
    Counters        map[string][]uint32
    Blocks          map[string][]CoverBlock
    CoveredPackages string
}
</pre> <h2 id="CoverBlock">type <span>CoverBlock</span>  <span title="Added in Go 1.2">1.2</span> </h2> <p>CoverBlock records the coverage data for a single basic block. The fields are 1-indexed, as in an editor: The opening line of the file is number 1, for example. Columns are measured in bytes. NOTE: This struct is internal to the testing infrastructure and may change. It is not covered (yet) by the Go 1 compatibility guidelines. </p>
<pre data-language="go">type CoverBlock struct {
    Line0 uint32 // Line number for block start.
    Col0  uint16 // Column number for block start.
    Line1 uint32 // Line number for block end.
    Col1  uint16 // Column number for block end.
    Stmts uint16 // Number of statements included in this block.
}
</pre> <h2 id="F">type <span>F</span>  <span title="Added in Go 1.18">1.18</span> </h2> <p>F is a type passed to fuzz tests. </p>
<p>Fuzz tests run generated inputs against a provided fuzz target, which can find and report potential bugs in the code being tested. </p>
<p>A fuzz test runs the seed corpus by default, which includes entries provided by (*F).Add and entries in the testdata/fuzz/&lt;FuzzTestName&gt; directory. After any necessary setup and calls to (*F).Add, the fuzz test must then call (*F).Fuzz to provide the fuzz target. See the testing package documentation for an example, and see the <a href="#F.Fuzz">F.Fuzz</a> and <a href="#F.Add">F.Add</a> method documentation for details. </p>
<p>*F methods can only be called before (*F).Fuzz. Once the test is executing the fuzz target, only (*T) methods can be used. The only *F methods that are allowed in the (*F).Fuzz function are (*F).Failed and (*F).Name. </p>
<pre data-language="go">type F struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="F.Add">func (*F) <span>Add</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (f *F) Add(args ...any)</pre> <p>Add will add the arguments to the seed corpus for the fuzz test. This will be a no-op if called after or within the fuzz target, and args must match the arguments for the fuzz target. </p>
<h3 id="F.Cleanup">func (*F) <span>Cleanup</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Cleanup(f func())</pre> <p>Cleanup registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order. </p>
<h3 id="F.Error">func (*F) <span>Error</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Error(args ...any)</pre> <p>Error is equivalent to Log followed by Fail. </p>
<h3 id="F.Errorf">func (*F) <span>Errorf</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Errorf(format string, args ...any)</pre> <p>Errorf is equivalent to Logf followed by Fail. </p>
<h3 id="F.Fail">func (*F) <span>Fail</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (f *F) Fail()</pre> <p>Fail marks the function as having failed but continues execution. </p>
<h3 id="F.FailNow">func (*F) <span>FailNow</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) FailNow()</pre> <p>FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines. </p>
<h3 id="F.Failed">func (*F) <span>Failed</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Failed() bool</pre> <p>Failed reports whether the function has failed. </p>
<h3 id="F.Fatal">func (*F) <span>Fatal</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Fatal(args ...any)</pre> <p>Fatal is equivalent to Log followed by FailNow. </p>
<h3 id="F.Fatalf">func (*F) <span>Fatalf</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Fatalf(format string, args ...any)</pre> <p>Fatalf is equivalent to Logf followed by FailNow. </p>
<h3 id="F.Fuzz">func (*F) <span>Fuzz</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (f *F) Fuzz(ff any)</pre> <p>Fuzz runs the fuzz function, ff, for fuzz testing. If ff fails for a set of arguments, those arguments will be added to the seed corpus. </p>
<p>ff must be a function with no return value whose first argument is *T and whose remaining arguments are the types to be fuzzed. For example: </p>
<pre data-language="go">f.Fuzz(func(t *testing.T, b []byte, i int) { ... })
</pre> <p>The following types are allowed: []byte, string, bool, byte, rune, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64. More types may be supported in the future. </p>
<p>ff must not call any *F methods, e.g. (*F).Log, (*F).Error, (*F).Skip. Use the corresponding *T method instead. The only *F methods that are allowed in the (*F).Fuzz function are (*F).Failed and (*F).Name. </p>
<p>This function should be fast and deterministic, and its behavior should not depend on shared state. No mutatable input arguments, or pointers to them, should be retained between executions of the fuzz function, as the memory backing them may be mutated during a subsequent invocation. ff must not modify the underlying data of the arguments provided by the fuzzing engine. </p>
<p>When fuzzing, F.Fuzz does not return until a problem is found, time runs out (set with -fuzztime), or the test process is interrupted by a signal. F.Fuzz should be called exactly once, unless F.Skip or <a href="#F.Fail">F.Fail</a> is called beforehand. </p>
<h3 id="F.Helper">func (*F) <span>Helper</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (f *F) Helper()</pre> <p>Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines. </p>
<h3 id="F.Log">func (*F) <span>Log</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Log(args ...any)</pre> <p>Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag. </p>
<h3 id="F.Logf">func (*F) <span>Logf</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Logf(format string, args ...any)</pre> <p>Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. A final newline is added if not provided. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag. </p>
<h3 id="F.Name">func (*F) <span>Name</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Name() string</pre> <p>Name returns the name of the running (sub-) test or benchmark. </p>
<p>The name will include the name of the test along with the names of any nested sub-tests. If two sibling sub-tests have the same name, Name will append a suffix to guarantee the returned name is unique. </p>
<h3 id="F.Setenv">func (*F) <span>Setenv</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Setenv(key, value string)</pre> <p>Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test. </p>
<p>Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors. </p>
<h3 id="F.Skip">func (*F) <span>Skip</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Skip(args ...any)</pre> <p>Skip is equivalent to Log followed by SkipNow. </p>
<h3 id="F.SkipNow">func (*F) <span>SkipNow</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) SkipNow()</pre> <p>SkipNow marks the test as having been skipped and stops its execution by calling <span>runtime.Goexit</span>. If a test fails (see Error, Errorf, Fail) and is then skipped, it is still considered to have failed. Execution will continue at the next test or benchmark. See also FailNow. SkipNow must be called from the goroutine running the test, not from other goroutines created during the test. Calling SkipNow does not stop those other goroutines. </p>
<h3 id="F.Skipf">func (*F) <span>Skipf</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) Skipf(format string, args ...any)</pre> <p>Skipf is equivalent to Logf followed by SkipNow. </p>
<h3 id="F.Skipped">func (*F) <span>Skipped</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (f *F) Skipped() bool</pre> <p>Skipped reports whether the test was skipped. </p>
<h3 id="F.TempDir">func (*F) <span>TempDir</span>  <span title="Added in Go 1.18">1.18</span> </h3> <pre data-language="go">func (c *F) TempDir() string</pre> <p>TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal. </p>
<h2 id="InternalBenchmark">type <span>InternalBenchmark</span>  </h2> <p>InternalBenchmark is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command. </p>
<pre data-language="go">type InternalBenchmark struct {
    Name string
    F    func(b *B)
}
</pre> <h2 id="InternalExample">type <span>InternalExample</span>  </h2> <pre data-language="go">type InternalExample struct {
    Name      string
    F         func()
    Output    string
    Unordered bool // Go 1.7
}
</pre> <h2 id="InternalFuzzTarget">type <span>InternalFuzzTarget</span>  <span title="Added in Go 1.18">1.18</span> </h2> <p>InternalFuzzTarget is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command. </p>
<pre data-language="go">type InternalFuzzTarget struct {
    Name string
    Fn   func(f *F)
}
</pre> <h2 id="InternalTest">type <span>InternalTest</span>  </h2> <p>InternalTest is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command. </p>
<pre data-language="go">type InternalTest struct {
    Name string
    F    func(*T)
}
</pre> <h2 id="M">type <span>M</span>  <span title="Added in Go 1.4">1.4</span> </h2> <p>M is a type passed to a TestMain function to run the actual tests. </p>
<pre data-language="go">type M struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="MainStart">func <span>MainStart</span>  <span title="Added in Go 1.4">1.4</span> </h3> <pre data-language="go">func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M</pre> <p>MainStart is meant for use by tests generated by 'go test'. It is not meant to be called directly and is not subject to the Go 1 compatibility document. It may change signature from release to release. </p>
<h3 id="M.Run">func (*M) <span>Run</span>  <span title="Added in Go 1.4">1.4</span> </h3> <pre data-language="go">func (m *M) Run() (code int)</pre> <p>Run runs the tests. It returns an exit code to pass to os.Exit. </p>
<h2 id="PB">type <span>PB</span>  <span title="Added in Go 1.3">1.3</span> </h2> <p>A PB is used by RunParallel for running parallel benchmarks. </p>
<pre data-language="go">type PB struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="PB.Next">func (*PB) <span>Next</span>  <span title="Added in Go 1.3">1.3</span> </h3> <pre data-language="go">func (pb *PB) Next() bool</pre> <p>Next reports whether there are more iterations to execute. </p>
<h2 id="T">type <span>T</span>  </h2> <p>T is a type passed to Test functions to manage test state and support formatted test logs. </p>
<p>A test ends when its Test function returns or calls any of the methods FailNow, Fatal, Fatalf, SkipNow, Skip, or Skipf. Those methods, as well as the Parallel method, must be called only from the goroutine running the Test function. </p>
<p>The other reporting methods, such as the variations of Log and Error, may be called simultaneously from multiple goroutines. </p>
<pre data-language="go">type T struct {
    // contains filtered or unexported fields
}
</pre> <h3 id="T.Cleanup">func (*T) <span>Cleanup</span>  <span title="Added in Go 1.14">1.14</span> </h3> <pre data-language="go">func (c *T) Cleanup(f func())</pre> <p>Cleanup registers a function to be called when the test (or subtest) and all its subtests complete. Cleanup functions will be called in last added, first called order. </p>
<h3 id="T.Deadline">func (*T) <span>Deadline</span>  <span title="Added in Go 1.15">1.15</span> </h3> <pre data-language="go">func (t *T) Deadline() (deadline time.Time, ok bool)</pre> <p>Deadline reports the time at which the test binary will have exceeded the timeout specified by the -timeout flag. </p>
<p>The ok result is false if the -timeout flag indicates “no timeout” (0). </p>
<h3 id="T.Error">func (*T) <span>Error</span>  </h3> <pre data-language="go">func (c *T) Error(args ...any)</pre> <p>Error is equivalent to Log followed by Fail. </p>
<h3 id="T.Errorf">func (*T) <span>Errorf</span>  </h3> <pre data-language="go">func (c *T) Errorf(format string, args ...any)</pre> <p>Errorf is equivalent to Logf followed by Fail. </p>
<h3 id="T.Fail">func (*T) <span>Fail</span>  </h3> <pre data-language="go">func (c *T) Fail()</pre> <p>Fail marks the function as having failed but continues execution. </p>
<h3 id="T.FailNow">func (*T) <span>FailNow</span>  </h3> <pre data-language="go">func (c *T) FailNow()</pre> <p>FailNow marks the function as having failed and stops its execution by calling runtime.Goexit (which then runs all deferred calls in the current goroutine). Execution will continue at the next test or benchmark. FailNow must be called from the goroutine running the test or benchmark function, not from other goroutines created during the test. Calling FailNow does not stop those other goroutines. </p>
<h3 id="T.Failed">func (*T) <span>Failed</span>  </h3> <pre data-language="go">func (c *T) Failed() bool</pre> <p>Failed reports whether the function has failed. </p>
<h3 id="T.Fatal">func (*T) <span>Fatal</span>  </h3> <pre data-language="go">func (c *T) Fatal(args ...any)</pre> <p>Fatal is equivalent to Log followed by FailNow. </p>
<h3 id="T.Fatalf">func (*T) <span>Fatalf</span>  </h3> <pre data-language="go">func (c *T) Fatalf(format string, args ...any)</pre> <p>Fatalf is equivalent to Logf followed by FailNow. </p>
<h3 id="T.Helper">func (*T) <span>Helper</span>  <span title="Added in Go 1.9">1.9</span> </h3> <pre data-language="go">func (c *T) Helper()</pre> <p>Helper marks the calling function as a test helper function. When printing file and line information, that function will be skipped. Helper may be called simultaneously from multiple goroutines. </p>
<h3 id="T.Log">func (*T) <span>Log</span>  </h3> <pre data-language="go">func (c *T) Log(args ...any)</pre> <p>Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag. </p>
<h3 id="T.Logf">func (*T) <span>Logf</span>  </h3> <pre data-language="go">func (c *T) Logf(format string, args ...any)</pre> <p>Logf formats its arguments according to the format, analogous to Printf, and records the text in the error log. A final newline is added if not provided. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag. </p>
<h3 id="T.Name">func (*T) <span>Name</span>  <span title="Added in Go 1.8">1.8</span> </h3> <pre data-language="go">func (c *T) Name() string</pre> <p>Name returns the name of the running (sub-) test or benchmark. </p>
<p>The name will include the name of the test along with the names of any nested sub-tests. If two sibling sub-tests have the same name, Name will append a suffix to guarantee the returned name is unique. </p>
<h3 id="T.Parallel">func (*T) <span>Parallel</span>  </h3> <pre data-language="go">func (t *T) Parallel()</pre> <p>Parallel signals that this test is to be run in parallel with (and only with) other parallel tests. When a test is run multiple times due to use of -test.count or -test.cpu, multiple instances of a single test never run in parallel with each other. </p>
<h3 id="T.Run">func (*T) <span>Run</span>  <span title="Added in Go 1.7">1.7</span> </h3> <pre data-language="go">func (t *T) Run(name string, f func(t *T)) bool</pre> <p>Run runs f as a subtest of t called name. It runs f in a separate goroutine and blocks until f returns or calls t.Parallel to become a parallel test. Run reports whether f succeeded (or at least did not fail before calling t.Parallel). </p>
<p>Run may be called simultaneously from multiple goroutines, but all such calls must return before the outer test function for t returns. </p>
<h3 id="T.Setenv">func (*T) <span>Setenv</span>  <span title="Added in Go 1.17">1.17</span> </h3> <pre data-language="go">func (t *T) Setenv(key, value string)</pre> <p>Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test. </p>
<p>Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors. </p>
<h3 id="T.Skip">func (*T) <span>Skip</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *T) Skip(args ...any)</pre> <p>Skip is equivalent to Log followed by SkipNow. </p>
<h3 id="T.SkipNow">func (*T) <span>SkipNow</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *T) SkipNow()</pre> <p>SkipNow marks the test as having been skipped and stops its execution by calling <span>runtime.Goexit</span>. If a test fails (see Error, Errorf, Fail) and is then skipped, it is still considered to have failed. Execution will continue at the next test or benchmark. See also FailNow. SkipNow must be called from the goroutine running the test, not from other goroutines created during the test. Calling SkipNow does not stop those other goroutines. </p>
<h3 id="T.Skipf">func (*T) <span>Skipf</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *T) Skipf(format string, args ...any)</pre> <p>Skipf is equivalent to Logf followed by SkipNow. </p>
<h3 id="T.Skipped">func (*T) <span>Skipped</span>  <span title="Added in Go 1.1">1.1</span> </h3> <pre data-language="go">func (c *T) Skipped() bool</pre> <p>Skipped reports whether the test was skipped. </p>
<h3 id="T.TempDir">func (*T) <span>TempDir</span>  <span title="Added in Go 1.15">1.15</span> </h3> <pre data-language="go">func (c *T) TempDir() string</pre> <p>TempDir returns a temporary directory for the test to use. The directory is automatically removed when the test and all its subtests complete. Each subsequent call to t.TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal. </p>
<h2 id="TB">type <span>TB</span>  <span title="Added in Go 1.2">1.2</span> </h2> <p>TB is the interface common to T, B, and F. </p>
<pre data-language="go">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
}</pre> <h2 id="pkg-subdirectories">Subdirectories</h2> <div class="pkg-dir"> <table> <tr> <th class="pkg-name">Name</th> <th class="pkg-synopsis">Synopsis</th> </tr> <tr> <td colspan="2"><a href="../index">..</a></td> </tr> <tr> <td class="pkg-name"> <a href="fstest/index">fstest</a> </td> <td class="pkg-synopsis"> Package fstest implements support for testing implementations and users of file systems. </td> </tr> <tr> <td class="pkg-name"> <a href="iotest/index">iotest</a> </td> <td class="pkg-synopsis"> Package iotest implements Readers and Writers useful mainly for testing. </td> </tr> <tr> <td class="pkg-name"> <a href="quick/index">quick</a> </td> <td class="pkg-synopsis"> Package quick implements utility functions to help with black box testing. </td> </tr> <tr> <td class="pkg-name"> <a href="slogtest/index">slogtest</a> </td> <td class="pkg-synopsis"> Package slogtest implements support for testing implementations of log/slog.Handler. </td> </tr> </table> </div><div class="_attribution">
  <p class="_attribution-p">
    &copy; Google, Inc.<br>Licensed under the Creative Commons Attribution License 3.0.<br>
    <a href="http://golang.org/pkg/testing/" class="_attribution-link">http://golang.org/pkg/testing/</a>
  </p>
</div>