All packages

testing

import "testing"

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 func TestXxx(*testing.T) where Xxx does not start with a lowercase letter. The function name serves to identify the test routine. Within these functions, use [T.Error], [T.Fail] or related methods to signal failure. To write a new test suite, create a file that contains the TestXxx functions as descri...

Go 1.26.1

Functions

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

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. 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. AllocsPerRun sets [runtime.GOMAXPROCS] to 1 during its measurement and will restore it before returning.

testing/allocs.go:20

func Benchmark(f func(...)) BenchmarkResult

Benchmark benchmarks a single function. It is useful for creating custom benchmarks that do not use the "go test" command. If f depends on testing flags, then [Init] must be used to register those flags before calling Benchmark and before calling [flag.Parse]. 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.

testing/benchmark.go:1008

func Coverage() float64

Coverage reports the current code coverage as a fraction in the range [0, 1]. If coverage is not enabled, Coverage returns 0. When running a large set of sequential test cases, checking Coverage after each one can be useful for identifying which test cases exercise new code paths. It is not a replacement for the reports generated by 'go test -cover' and 'go tool cover'.

testing/newcover.go:54

func CoverMode() string

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.

testing/testing.go:718

func Init()

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". Init is not safe to call concurrently. It has no effect if it was already called.

testing/testing.go:438

func Main(matchString func(...), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)

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].

testing/testing.go:2271

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

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.

testing/testing.go:2319

func RegisterCover(c Cover)

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.

testing/cover.go:36

func RunBenchmarks(matchString func(...), benchmarks []InternalBenchmark)

RunBenchmarks is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.

testing/benchmark.go:687

func RunExamples(matchString func(...), examples []InternalExample) bool

RunExamples is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.

testing/example.go:24

func RunTests(matchString func(...), tests []InternalTest) bool

RunTests is an internal function but exported because it is cross-package; it is part of the implementation of the "go test" command.

testing/testing.go:2539

func Short() bool

Short reports whether the -test.short flag is set.

testing/testing.go:687

func Testing() bool

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".

testing/testing.go:711

func Verbose() bool

Verbose reports whether the -test.v flag is set.

testing/testing.go:723

Types

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

B is a type passed to [Benchmark] functions to manage benchmark timing and control the number of iterations. A benchmark ends when its Benchmark function returns or calls any of the methods [B.FailNow], [B.Fatal], [B.Fatalf], [B.SkipNow], [B.Skip], or [B.Skipf]. Those methods must be called only from the goroutine running the Benchmark function. The other reporting methods, such as the variations of [B.Log] and [B.Error], may be called simultaneously from multiple goroutines. Like in tests,...

testing/benchmark.go:94

func (c *B) ArtifactDir() string

ArtifactDir returns a directory in which the test should store output files. When the -artifacts flag is provided, this directory is located under the output directory. Otherwise, ArtifactDir returns a temporary directory that is removed after the test completes. Each test or subtest within each test package has a unique artifact directory. Repeated calls to ArtifactDir in the same test or subtest return the same directory. Subtest outputs are not located under the parent test's output direc...

testing/testing.go:1333

func (c *B) Attr(key string, value string)

Attr emits a test attribute associated with this test. The key must not contain whitespace. The value must not contain newlines or carriage returns. The meaning of different attribute keys is left up to continuous integration systems and test frameworks. Test attributes are emitted immediately in the test log, but they are intended to be treated as unordered.

testing/testing.go:1604

func (c *B) Chdir(dir string)

Chdir calls [os.Chdir] and uses Cleanup to restore the current working directory to its original value after the test. On Unix, it also sets PWD environment variable for the duration of the test. Because Chdir affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

testing/testing.go:1548

func (c *B) Cleanup(f func(...))

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.

testing/testing.go:1296

func (c *B) Context() context.Context

Context returns a context that is canceled just before Cleanup-registered functions are called. Cleanup functions can wait for any resources that shut down on [context.Context.Done] before the test or benchmark completes.

testing/testing.go:1589

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

Elapsed returns the measured elapsed time of the benchmark. The duration reported by Elapsed matches the one measured by [B.StartTimer], [B.StopTimer], and [B.ResetTimer].

testing/benchmark.go:367

func (c *B) Error(args ...any)

Error is equivalent to Log followed by Fail.

testing/testing.go:1204

func (c *B) Errorf(format string, args ...any)

Errorf is equivalent to Logf followed by Fail.

testing/testing.go:1211

func (c *B) Fail()

Fail marks the function as having failed but continues execution.

testing/testing.go:961

func (c *B) Failed() bool

Failed reports whether the function has failed.

testing/testing.go:975

func (c *B) FailNow()

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.

testing/testing.go:996

func (c *B) Fatal(args ...any)

Fatal is equivalent to Log followed by FailNow.

testing/testing.go:1218

func (c *B) Fatalf(format string, args ...any)

Fatalf is equivalent to Logf followed by FailNow.

testing/testing.go:1225

func (c *B) Helper()

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.

testing/testing.go:1272

func (c *B) Log(args ...any)

Log formats its arguments using default formatting, analogous to [fmt.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. It is an error to call Log after a test or benchmark returns.

testing/testing.go:1187

func (c *B) Logf(format string, args ...any)

Logf formats its arguments according to the format, analogous to [fmt.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. It is an error to call Logf after a test or benchmark returns.

testing/testing.go:1198

func (b *B) Loop() bool

Loop returns true as long as the benchmark should continue running. A typical benchmark is structured like: func Benchmark(b *testing.B) { ... setup ... for b.Loop() { ... code to measure ... } ... cleanup ... } Loop resets the benchmark timer the first time it is called in a benchmark, so any setup performed prior to starting the benchmark loop does not count toward the benchmark measurement. Likewise, when it returns false, it stops the timer so cleanup code is not measured....

testing/benchmark.go:502

func (c *B) Name() string

Name returns the name of the running (sub-) test or benchmark. 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.

testing/testing.go:947

func (c *B) Output() io.Writer

Output returns a Writer that writes to the same test output stream as TB.Log. The output is indented like TB.Log lines, but Output does not add source locations or newlines. The output is internally line buffered, and a call to TB.Log or the end of the test will implicitly flush the buffer, followed by a newline. After a test function and all its parents return, neither Output nor the Write method may be called.

testing/testing.go:1114

func (b *B) ReportAllocs()

ReportAllocs enables malloc statistics for this benchmark. It is equivalent to setting -test.benchmem, but it only affects the benchmark function that calls ReportAllocs.

testing/benchmark.go:192

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

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 t...

testing/benchmark.go:384

func (b *B) ResetTimer()

ResetTimer zeroes the elapsed benchmark time and memory allocation counters and deletes user-reported metrics. It does not affect whether the timer is running.

testing/benchmark.go:166

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

Run benchmarks f as a subbenchmark with the given name. It reports whether there were any failures. 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.

testing/benchmark.go:808

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

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 [B.SetParallelism] before RunParallel. RunParallel is usually used with the go test -cpu flag. 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 [B.StartTimer], [...

testing/benchmark.go:950

func (b *B) SetBytes(n int64)

SetBytes records the number of bytes processed in a single operation. If this is called, the benchmark will report ns/op and MB/s.

testing/benchmark.go:187

func (c *B) Setenv(key string, value string)

Setenv calls [os.Setenv] and uses Cleanup to restore the environment variable to its original value after the test. Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

testing/testing.go:1523

func (b *B) SetParallelism(p int)

SetParallelism sets the number of goroutines used by [B.RunParallel] 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.

testing/benchmark.go:994

func (c *B) Skipf(format string, args ...any)

Skipf is equivalent to Logf followed by SkipNow.

testing/testing.go:1239

func (c *B) SkipNow()

SkipNow marks the test as having been skipped and stops its execution by calling [runtime.Goexit]. 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.

testing/testing.go:1253

func (c *B) Skipped() bool

Skipped reports whether the test was skipped.

testing/testing.go:1263

func (b *B) StartTimer()

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 [B.StopTimer].

testing/benchmark.go:138

func (b *B) StopTimer()

StopTimer stops timing a test. This can be used to pause the timer while performing steps that you don't want to measure.

testing/benchmark.go:151

func (c *B) TempDir() string

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 TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal. If the environment variable GOTMPDIR is set, the temporary directory will be created somewhere beneath it.

testing/testing.go:1422

type BenchmarkResult struct {
	N         int           // The number of iterations.
	T         time.Duration // The total time taken.
	Bytes     int64         // Bytes processed in one iteration.
	...

BenchmarkResult contains the results of a benchmark run.

testing/benchmark.go:536

func (r BenchmarkResult) AllocedBytesPerOp() int64

AllocedBytesPerOp returns the "B/op" metric, which is calculated as r.MemBytes / r.N.

testing/benchmark.go:583

func (r BenchmarkResult) AllocsPerOp() int64

AllocsPerOp returns the "allocs/op" metric, which is calculated as r.MemAllocs / r.N.

testing/benchmark.go:571

func (r BenchmarkResult) MemString() string

MemString returns r.AllocedBytesPerOp and r.AllocsPerOp in the same format as 'go test'.

testing/benchmark.go:665

func (r BenchmarkResult) NsPerOp() int64

NsPerOp returns the "ns/op" metric.

testing/benchmark.go:548

func (r BenchmarkResult) String() string

String returns a summary of the benchmark results. It follows the benchmark result line format from https://golang.org/design/14313-benchmark-format, 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 [BenchmarkResult.MemString].

testing/benchmark.go:600

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

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.

testing/cover.go:26

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...

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.

testing/cover.go:15

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

F is a type passed to fuzz tests. Fuzz tests run generated inputs against a provided fuzz target, which can find and report potential bugs in the code being tested. A fuzz test runs the seed corpus by default, which includes entries provided by [F.Add] and entries in the testdata/fuzz/<FuzzTestName> 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 [F....

testing/fuzz.go:69

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

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.

testing/fuzz.go:153

func (c *F) ArtifactDir() string

ArtifactDir returns a directory in which the test should store output files. When the -artifacts flag is provided, this directory is located under the output directory. Otherwise, ArtifactDir returns a temporary directory that is removed after the test completes. Each test or subtest within each test package has a unique artifact directory. Repeated calls to ArtifactDir in the same test or subtest return the same directory. Subtest outputs are not located under the parent test's output direc...

testing/testing.go:1333

func (c *F) Attr(key string, value string)

Attr emits a test attribute associated with this test. The key must not contain whitespace. The value must not contain newlines or carriage returns. The meaning of different attribute keys is left up to continuous integration systems and test frameworks. Test attributes are emitted immediately in the test log, but they are intended to be treated as unordered.

testing/testing.go:1604

func (c *F) Chdir(dir string)

Chdir calls [os.Chdir] and uses Cleanup to restore the current working directory to its original value after the test. On Unix, it also sets PWD environment variable for the duration of the test. Because Chdir affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

testing/testing.go:1548

func (c *F) Cleanup(f func(...))

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.

testing/testing.go:1296

func (c *F) Context() context.Context

Context returns a context that is canceled just before Cleanup-registered functions are called. Cleanup functions can wait for any resources that shut down on [context.Context.Done] before the test or benchmark completes.

testing/testing.go:1589

func (c *F) Error(args ...any)

Error is equivalent to Log followed by Fail.

testing/testing.go:1204

func (c *F) Errorf(format string, args ...any)

Errorf is equivalent to Logf followed by Fail.

testing/testing.go:1211

func (f *F) Fail()

Fail marks the function as having failed but continues execution.

testing/fuzz.go:129

func (c *F) Failed() bool

Failed reports whether the function has failed.

testing/testing.go:975

func (c *F) FailNow()

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.

testing/testing.go:996

func (c *F) Fatal(args ...any)

Fatal is equivalent to Log followed by FailNow.

testing/testing.go:1218

func (c *F) Fatalf(format string, args ...any)

Fatalf is equivalent to Logf followed by FailNow.

testing/testing.go:1225

func (f *F) Fuzz(ff any)

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. 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: f.Fuzz(func(t *testing.T, b []byte, i int) { ... }) The following types are allowed: []byte, string, bool, byte, rune, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64. More ty...

testing/fuzz.go:211

func (f *F) Helper()

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.

testing/fuzz.go:103

func (c *F) Log(args ...any)

Log formats its arguments using default formatting, analogous to [fmt.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. It is an error to call Log after a test or benchmark returns.

testing/testing.go:1187

func (c *F) Logf(format string, args ...any)

Logf formats its arguments according to the format, analogous to [fmt.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. It is an error to call Logf after a test or benchmark returns.

testing/testing.go:1198

func (c *F) Name() string

Name returns the name of the running (sub-) test or benchmark. 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.

testing/testing.go:947

func (c *F) Output() io.Writer

Output returns a Writer that writes to the same test output stream as TB.Log. The output is indented like TB.Log lines, but Output does not add source locations or newlines. The output is internally line buffered, and a call to TB.Log or the end of the test will implicitly flush the buffer, followed by a newline. After a test function and all its parents return, neither Output nor the Write method may be called.

testing/testing.go:1114

func (c *F) Setenv(key string, value string)

Setenv calls [os.Setenv] and uses Cleanup to restore the environment variable to its original value after the test. Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

testing/testing.go:1523

func (c *F) Skipf(format string, args ...any)

Skipf is equivalent to Logf followed by SkipNow.

testing/testing.go:1239

func (c *F) SkipNow()

SkipNow marks the test as having been skipped and stops its execution by calling [runtime.Goexit]. 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.

testing/testing.go:1253

func (f *F) Skipped() bool

Skipped reports whether the test was skipped.

testing/fuzz.go:140

func (c *F) TempDir() string

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 TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal. If the environment variable GOTMPDIR is set, the temporary directory will be created somewhere beneath it.

testing/testing.go:1422

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

InternalBenchmark is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command.

testing/benchmark.go:76

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

testing/example.go:15

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

InternalFuzzTarget is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command.

testing/fuzz.go:49

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

InternalTest is an internal type but exported because it is cross-package; it is part of the implementation of the "go test" command.

testing/testing.go:1869

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

M is a type passed to a TestMain function to run the actual tests.

testing/testing.go:2276

func (m *M) Run() int

Run runs the tests. It returns an exit code to pass to os.Exit. The exit code is zero when all tests pass, and non-zero for any kind of failure. For machine readable test results, parse the output of 'go test -json'.

testing/testing.go:2340

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

A PB is used by RunParallel for running parallel benchmarks.

testing/benchmark.go:914

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

T is a type passed to Test functions to manage test state and support formatted test logs. A test ends when its Test function returns or calls any of the methods [T.FailNow], [T.Fatal], [T.Fatalf], [T.SkipNow], [T.Skip], or [T.Skipf]. Those methods, as well as the [T.Parallel] method, must be called only from the goroutine running the Test function. The other reporting methods, such as the variations of [T.Log] and [T.Error], may be called simultaneously from multiple goroutines.

testing/testing.go:934

func (c *T) ArtifactDir() string

ArtifactDir returns a directory in which the test should store output files. When the -artifacts flag is provided, this directory is located under the output directory. Otherwise, ArtifactDir returns a temporary directory that is removed after the test completes. Each test or subtest within each test package has a unique artifact directory. Repeated calls to ArtifactDir in the same test or subtest return the same directory. Subtest outputs are not located under the parent test's output direc...

testing/testing.go:1333

func (c *T) Attr(key string, value string)

Attr emits a test attribute associated with this test. The key must not contain whitespace. The value must not contain newlines or carriage returns. The meaning of different attribute keys is left up to continuous integration systems and test frameworks. Test attributes are emitted immediately in the test log, but they are intended to be treated as unordered.

testing/testing.go:1604

func (t *T) Chdir(dir string)

Chdir calls [os.Chdir] and uses Cleanup to restore the current working directory to its original value after the test. On Unix, it also sets PWD environment variable for the duration of the test. Because Chdir affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

testing/testing.go:1862

func (c *T) Cleanup(f func(...))

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.

testing/testing.go:1296

func (c *T) Context() context.Context

Context returns a context that is canceled just before Cleanup-registered functions are called. Cleanup functions can wait for any resources that shut down on [context.Context.Done] before the test or benchmark completes.

testing/testing.go:1589

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

Deadline reports the time at which the test binary will have exceeded the timeout specified by the -timeout flag. The ok result is false if the -timeout flag indicates “no timeout” (0).

testing/testing.go:2163

func (c *T) Error(args ...any)

Error is equivalent to Log followed by Fail.

testing/testing.go:1204

func (c *T) Errorf(format string, args ...any)

Errorf is equivalent to Logf followed by Fail.

testing/testing.go:1211

func (c *T) Fail()

Fail marks the function as having failed but continues execution.

testing/testing.go:961

func (c *T) Failed() bool

Failed reports whether the function has failed.

testing/testing.go:975

func (c *T) FailNow()

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.

testing/testing.go:996

func (c *T) Fatal(args ...any)

Fatal is equivalent to Log followed by FailNow.

testing/testing.go:1218

func (c *T) Fatalf(format string, args ...any)

Fatalf is equivalent to Logf followed by FailNow.

testing/testing.go:1225

func (c *T) Helper()

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.

testing/testing.go:1272

func (c *T) Log(args ...any)

Log formats its arguments using default formatting, analogous to [fmt.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. It is an error to call Log after a test or benchmark returns.

testing/testing.go:1187

func (c *T) Logf(format string, args ...any)

Logf formats its arguments according to the format, analogous to [fmt.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. It is an error to call Logf after a test or benchmark returns.

testing/testing.go:1198

func (c *T) Name() string

Name returns the name of the running (sub-) test or benchmark. 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.

testing/testing.go:947

func (c *T) Output() io.Writer

Output returns a Writer that writes to the same test output stream as TB.Log. The output is indented like TB.Log lines, but Output does not add source locations or newlines. The output is internally line buffered, and a call to TB.Log or the end of the test will implicitly flush the buffer, followed by a newline. After a test function and all its parents return, neither Output nor the Write method may be called.

testing/testing.go:1114

func (t *T) Parallel()

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.

testing/testing.go:1758

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

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). Run may be called simultaneously from multiple goroutines, but all such calls must return before the outer test function for t returns.

testing/testing.go:2050

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

Setenv calls os.Setenv(key, value) and uses Cleanup to restore the environment variable to its original value after the test. Because Setenv affects the whole process, it cannot be used in parallel tests or tests with parallel ancestors.

testing/testing.go:1851

func (c *T) Skipf(format string, args ...any)

Skipf is equivalent to Logf followed by SkipNow.

testing/testing.go:1239

func (c *T) SkipNow()

SkipNow marks the test as having been skipped and stops its execution by calling [runtime.Goexit]. 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.

testing/testing.go:1253

func (c *T) Skipped() bool

Skipped reports whether the test was skipped.

testing/testing.go:1263

func (c *T) TempDir() string

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 TempDir returns a unique directory; if the directory creation fails, TempDir terminates the test by calling Fatal. If the environment variable GOTMPDIR is set, the temporary directory will be created somewhere beneath it.

testing/testing.go:1422

type TB interface {
	ArtifactDir() string
	Attr(key, value string)
	Cleanup(func())
	Error(args ...any)
	Errorf(format string, args ...any)
	Fail()
	FailNow()
	Failed() bool
	Fatal(args ...any)
	Fa...

TB is the interface common to [T], [B], and [F].

testing/testing.go:889