package testing
import "testing"
Package testing 为 Go 包的自动化测试提供支持。 它旨在与 "go test" 命令配合使用,该命令会自动执行任何形式的函数
func TestXxx(*testing.T)
其中 Xxx 不以小写字母开头。函数名用于标识该测试例程。
在这些函数中,使用 T.Error、T.Fail 或相关方法来表示失败。
要编写新的测试套件,请创建一个文件,其中包含此处所述的 TestXxx 函数, 并将该文件命名为以 "_test.go" 结尾。 该文件将被排除在常规包构建之外,但在运行 "go test" 命令时会被包含进来。
测试文件可以与被测包位于同一包中, 也可以位于带有后缀 "_test" 的对应包中。
如果测试文件位于同一包中,它可以引用包内未导出的标识符,如下例所示:
package abs
import "testing"
func TestAbs(t *testing.T) {
got := abs(-1)
if got != 1 {
t.Errorf("abs(-1) = %d; want 1", got)
}
}
如果文件位于单独的 "_test" 包中,则必须显式导入被测包, 并且只能使用其导出的标识符。这被称为 "黑盒" 测试。
package abs_test
import (
"testing"
"path_to_pkg/abs"
)
func TestAbs(t *testing.T) {
got := abs.Abs(-1)
if got != 1 {
t.Errorf("Abs(-1) = %d; want 1", got)
}
}
更多详情,请运行 go help test 和 go help testflag。
基准测试
形式如下的函数
func BenchmarkXxx(*testing.B)
被视为基准测试,当提供 -bench 标志时由 "go test" 命令执行。基准测试按顺序运行。
关于测试标志的说明,请参阅 go help testflag。
一个基准测试函数示例看起来像这样:
func BenchmarkRandInt(b *testing.B) {
for b.Loop() {
rand.Int()
}
}
输出
BenchmarkRandInt-8 68453040 17.8 ns/op
表示循环体运行了 68453040 次,每次循环的速度为 17.8 ns。
只对循环体计时,因此基准测试可以在调用 b.Loop 之前进行耗时的准备工作, 这些准备不会被计入基准测试的测量结果:
func BenchmarkBigLen(b *testing.B) {
big := NewBig()
for b.Loop() {
big.Len()
}
}
如果基准测试需要在并行环境下测试性能,可以使用 RunParallel 辅助函数;此类基准测试旨在与 go test -cpu 标志一起使用:
func BenchmarkTemplateParallel(b *testing.B) {
templ := template.Must(template.New("test").Parse("Hello, {{.}}!"))
b.RunParallel(func(pb *testing.PB) {
var buf bytes.Buffer
for pb.Next() {
buf.Reset()
templ.Execute(&buf, "World")
}
})
}
基准测试结果格式的详细规范见 https://go.dev/design/14313-benchmark-format。
在 golang.org/x/perf/cmd 中有处理基准测试结果的标准工具。 特别是,golang.org/x/perf/cmd/benchstat 执行 统计上稳健的 A/B 比较。
b.N 风格的基准测试
在引入 B.Loop 之前,基准测试使用 B.N 以不同的风格编写。例如:
func BenchmarkRandInt(b *testing.B) {
for range b.N {
rand.Int()
}
}
在这种风格的基准测试中,基准测试函数必须运行目标代码 b.N 次。 基准测试函数会被多次调用,并调整 b.N,直到基准测试函数持续足够长的时间 以进行可靠计时。这也意味着循环之前执行的任何准备工作可能会运行多次。
如果基准测试在运行前需要一些耗时的准备工作,应显式重置计时器:
func BenchmarkBigLen(b *testing.B) {
big := NewBig()
b.ResetTimer()
for range b.N {
big.Len()
}
}
新的基准测试应优先使用 B.Loop,它更稳健也更高效。
示例
该包还会运行并验证示例代码。示例函数可以包含一个以 "Output:" 开头的 结尾行注释,在运行测试时会将其与该函数的标准输出进行比较。 (比较会忽略前导和尾随空格。)以下是一个示例的示例:
func ExampleHello() {
fmt.Println("hello")
// Output: hello
}
func ExampleSalutations() {
fmt.Println("hello, and")
fmt.Println("goodbye")
// Output:
// hello, and
// goodbye
}
注释前缀 "Unordered output:" 类似于 "Output:",但匹配任意行顺序:
func ExamplePerm() {
for _, value := range Perm(5) {
fmt.Println(value)
}
// Unordered output: 4
// 2
// 1
// 3
// 0
}
没有输出注释的示例函数会被编译但不会被执行。
为包、函数 F、类型 T 以及类型 T 上的方法 M 声明示例的命名约定为:
func Example() { ... }
func ExampleF() { ... }
func ExampleT() { ... }
func ExampleT_M() { ... }
通过为名称附加不同的后缀,可以为包/类型/函数/方法提供多个示例函数。 后缀必须以小写字母开头。
func Example_suffix() { ... }
func ExampleF_suffix() { ... }
func ExampleT_suffix() { ... }
func ExampleT_M_suffix() { ... }
当整个测试文件只包含一个示例函数、至少一个其他函数/类型/变量/常量 声明,且不包含任何测试或基准测试函数时,整个测试文件会作为示例呈现。
模糊测试
'go test' 和 testing 包支持模糊测试(fuzzing),这是一种用随机生成的 输入调用函数以发现单元测试未预料到的缺陷的测试技术。
形式如下的函数
func FuzzXxx(*testing.F)
被视为模糊测试。
例如:
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)
}
})
}
模糊测试会维护一个种子语料库(seed corpus),即一组默认运行的输入, 并可为输入生成提供种子。种子输入可以通过调用 F.Add 注册, 也可以通过将文件存储在包含模糊测试的包内的 testdata/fuzz/<Name> 目录中(其中 <Name> 是模糊测试的名称)。种子输入是可选的, 但当提供一组具有良好代码覆盖率的小型种子输入时,模糊测试引擎可以更高效地 发现缺陷。这些种子输入也可以用作通过模糊测试发现的缺陷的回归测试。
模糊测试中传递给 F.Fuzz 的函数被视为模糊测试目标(fuzz target)。 模糊测试目标必须接受一个 *T 参数,后跟一个或多个用于随机输入的参数。 传递给 F.Add 的参数类型必须与这些参数的类型完全一致。 模糊测试目标可以像测试一样以相同方式表示发现了问题: 通过调用 T.Fail(或任何调用它的方法,如 T.Error 或 T.Fatal)或通过 panic。
当启用模糊测试时(通过将 -fuzz 标志设置为匹配特定模糊测试的正则表达式), 会使用通过对种子输入反复进行随机更改而生成的参数来调用模糊测试目标。 在支持的平台上,'go test' 会使用模糊测试覆盖率插桩来编译测试可执行文件。 模糊测试引擎利用该插桩来查找并缓存能扩大覆盖率的输入,从而提高 发现缺陷的可能性。如果模糊测试目标对某个输入失败,模糊测试引擎 会将导致失败的输入写入包目录内 testdata/fuzz/<Name> 目录中的文件。 该文件随后会作为种子输入。如果无法写入该位置(例如, 因为目录是只读的),模糊测试引擎会改为将该文件写入构建缓存内的 模糊测试缓存目录。
当模糊测试被禁用时,会使用通过 F.Add 注册的种子输入以及来自 testdata/fuzz/<Name> 的种子输入来调用模糊测试目标。在此模式下, 模糊测试的行为很像常规测试,其子测试由 F.Fuzz 而非 T.Run 启动。
关于模糊测试的文档,请参阅 https://go.dev/doc/fuzz。
跳过
测试或基准测试可以在运行时通过调用 T.Skip 或 B.Skip 来跳过:
func TestTimeConsuming(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}
...
}
如果输入无效,可以在模糊测试目标中使用 T.Skip 方法, 但不应将其视为导致失败的输入。例如:
func FuzzJSONMarshaling(f *testing.F) {
f.Fuzz(func(t *testing.T, b []byte) {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
t.Skip()
}
if _, err := json.Marshal(v); err != nil {
t.Errorf("Marshal: %v", err)
}
})
}
子测试与子基准测试
T.Run 和 B.Run 方法允许定义子测试和子基准测试, 而无需为每个分别定义函数。这使得表驱动基准测试和创建 分层测试等用法成为可能。它还提供了一种共享公共 准备和清理代码的方式:
func TestFoo(t *testing.T) {
// <setup code>
t.Run("A=1", func(t *testing.T) { ... })
t.Run("A=2", func(t *testing.T) { ... })
t.Run("B=1", func(t *testing.T) { ... })
// <tear-down code>
}
每个子测试和子基准测试都有一个唯一名称:顶层测试的名称与 传递给 Run 的名称序列的组合,以斜杠分隔,并可选择附带一个 用于消歧的尾随序号。
-run、-bench 和 -fuzz 命令行标志的参数是一个不锚定的正则表达式, 用于匹配测试的名称。对于包含多个以斜杠分隔元素的测试(例如子测试), 该参数本身也以斜杠分隔,其中的表达式依次匹配每个名称元素。 由于它是不锚定的,空表达式会匹配任意字符串。 例如,用 "匹配" 表示 "其名称包含":
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"
-run 参数也可以用于运行种子语料库中的特定值,以便调试。例如:
go test -run=FuzzFoo/9ddb952d9814
可以同时设置 -fuzz 和 -run 标志,以便对某个目标进行模糊测试, 但跳过所有其他测试的执行。
子测试还可以用于控制并行性。父测试只有在所有子测试完成后才会 完成。在此示例中,所有测试都彼此并行运行,且仅彼此并行运行, 无论可能定义了哪些其他顶层测试:
func TestGroupedParallel(t *testing.T) {
for _, tc := range tests {
t.Run(tc.Name, func(t *testing.T) {
t.Parallel()
...
})
}
}
Run 会等到并行的子测试全部完成后才返回,这提供了一种 在一组并行测试之后进行清理的方式:
func TestTeardownParallel(t *testing.T) {
// This Run will not return until the parallel tests finish.
t.Run("group", func(t *testing.T) {
t.Run("Test1", parallelTest1)
t.Run("Test2", parallelTest2)
t.Run("Test3", parallelTest3)
})
// <tear-down code>
}
Main
有时测试或基准测试程序需要在执行前后进行额外的准备或清理。 有时还需要控制哪些代码在主线程上运行。为支持这些 及其他情况,如果测试文件包含如下函数:
func TestMain(m *testing.M)
那么生成的测试将调用 TestMain(m),而不是直接运行测试或基准测试。 TestMain 在主 goroutine 中运行,可以在调用 m.Run 前后进行任何必要的 准备和清理工作。m.Run 会返回一个退出码,可将其传递给 os.Exit。 如果 TestMain 返回,测试包装器会自行将 m.Run 的结果传递给 os.Exit。
调用 TestMain 时,flag.Parse 尚未运行。如果 TestMain 依赖于 命令行标志(包括 testing 包的标志),它应显式调用 flag.Parse。 当测试或基准测试函数运行时,命令行标志始终已被解析。
TestMain 的一个简单实现是:
func TestMain(m *testing.M) {
// call flag.Parse() here if TestMain uses flags
m.Run()
}
TestMain 是一个底层原语,对于普通的测试需求(普通测试函数即可满足) 应该是不必要的。
Index
- func AllocsPerRun(runs int, f func()) (avg float64)
- func CoverMode() string
- func Coverage() float64
- func Init()
- func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, ...)
- func RegisterCover(c Cover)
- func RunBenchmarks(matchString func(pat, str string) (bool, error), ...)
- func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)
- func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)
- func Short() bool
- func Testing() bool
- func Verbose() bool
-
type B
- func (c *B) ArtifactDir() string
- func (c *B) Attr(key, value string)
- func (c *B) Chdir(dir string)
- func (c *B) Cleanup(f func())
- func (c *B) Context() context.Context
- func (b *B) Elapsed() time.Duration
- func (c *B) Error(args ...any)
- func (c *B) Errorf(format string, args ...any)
- func (c *B) Fail()
- func (c *B) FailNow()
- func (c *B) Failed() bool
- func (c *B) Fatal(args ...any)
- func (c *B) Fatalf(format string, args ...any)
- func (c *B) Helper()
- func (c *B) Log(args ...any)
- func (c *B) Logf(format string, args ...any)
- func (b *B) Loop() bool
- func (c *B) Name() string
- func (c *B) Output() io.Writer
- func (b *B) ReportAllocs()
- func (b *B) ReportMetric(n float64, unit string)
- func (b *B) ResetTimer()
- func (b *B) Run(name string, f func(b *B)) bool
- func (b *B) RunParallel(body func(*PB))
- func (b *B) SetBytes(n int64)
- func (b *B) SetParallelism(p int)
- func (c *B) Setenv(key, value string)
- func (c *B) Skip(args ...any)
- func (c *B) SkipNow()
- func (c *B) Skipf(format string, args ...any)
- func (c *B) Skipped() bool
- func (b *B) StartTimer()
- func (b *B) StopTimer()
- func (c *B) TempDir() string
- type BenchmarkResult
- type Cover
- type CoverBlock
-
type F
- func (f *F) Add(args ...any)
- func (c *F) ArtifactDir() string
- func (c *F) Attr(key, value string)
- func (c *F) Chdir(dir string)
- func (c *F) Cleanup(f func())
- func (c *F) Context() context.Context
- func (c *F) Error(args ...any)
- func (c *F) Errorf(format string, args ...any)
- func (f *F) Fail()
- func (c *F) FailNow()
- func (c *F) Failed() bool
- func (c *F) Fatal(args ...any)
- func (c *F) Fatalf(format string, args ...any)
- func (f *F) Fuzz(ff any)
- func (f *F) Helper()
- func (c *F) Log(args ...any)
- func (c *F) Logf(format string, args ...any)
- func (c *F) Name() string
- func (c *F) Output() io.Writer
- func (c *F) Setenv(key, value string)
- func (c *F) Skip(args ...any)
- func (c *F) SkipNow()
- func (c *F) Skipf(format string, args ...any)
- func (f *F) Skipped() bool
- func (c *F) TempDir() string
- type InternalBenchmark
- type InternalExample
- type InternalFuzzTarget
- type InternalTest
- type M
- type PB
-
type T
- func (c *T) ArtifactDir() string
- func (c *T) Attr(key, value string)
- func (t *T) Chdir(dir string)
- func (c *T) Cleanup(f func())
- func (c *T) Context() context.Context
- func (t *T) Deadline() (deadline time.Time, ok bool)
- func (c *T) Error(args ...any)
- func (c *T) Errorf(format string, args ...any)
- func (c *T) Fail()
- func (c *T) FailNow()
- func (c *T) Failed() bool
- func (c *T) Fatal(args ...any)
- func (c *T) Fatalf(format string, args ...any)
- func (c *T) Helper()
- func (c *T) Log(args ...any)
- func (c *T) Logf(format string, args ...any)
- func (c *T) Name() string
- func (c *T) Output() io.Writer
- func (t *T) Parallel()
- func (t *T) Run(name string, f func(t *T)) bool
- func (t *T) Setenv(key, value string)
- func (c *T) Skip(args ...any)
- func (c *T) SkipNow()
- func (c *T) Skipf(format string, args ...any)
- func (c *T) Skipped() bool
- func (c *T) TempDir() string
- type TB
Examples
Functions
func AllocsPerRun
func AllocsPerRun(runs int, f func()) (avg float64)
AllocsPerRun 返回调用 f 期间的平均分配次数。 尽管返回值类型为 float64,但它始终是一个整数值。
为了计算分配次数,该函数会先运行一次作为预热。 随后将测量并返回指定运行次数内的平均分配次数。
AllocsPerRun 在测量期间将 runtime.GOMAXPROCS 设置为 1,并在返回前恢复它。
func CoverMode
func CoverMode() string
CoverMode 报告测试覆盖率模式被设置为什么。 取值为 "set"、"count" 或 "atomic"。如果未启用测试覆盖率, 返回值将为空。
func Coverage
func Coverage() float64
Coverage 以 [0, 1] 范围内的分数形式报告当前代码覆盖率。 如果未启用覆盖率,Coverage 返回 0。
在运行大量顺序测试用例时,每运行完一个就检查一次 Coverage, 有助于识别哪些测试用例覆盖了新的代码路径。 它不能替代 'go test -cover' 和 'go tool cover' 生成的报告。
func Init
func Init()
Init 注册 testing 标志。这些标志由 "go test" 命令在运行测试函数前自动注册, 因此只有在不使用 "go test" 而调用诸如 Benchmark 之类的函数时才需要 Init。
Init 并发调用不安全。如果已经调用过,则不会产生任何效果。
func Main
func Main(matchString func(pat, str string) (bool, error), tests []InternalTest, benchmarks []InternalBenchmark, examples []InternalExample)
Main 是一个内部函数,是 "go test" 命令实现的一部分。 它被导出是因为它跨包使用,并且早于 "internal" 包。 "go test" 不再使用它,但尽可能为其他使用 Main 来模拟 "go test" 的系统保留了它,然而随着 testing 包添加新功能,Main 有时无法更新。 模拟 "go test" 的系统应更新为使用 MainStart。
func RegisterCover
func RegisterCover(c Cover)
RegisterCover 记录测试的覆盖率数据累加器。 注意:该函数属于测试基础设施内部实现,可能会发生变化。 它(尚)不受 Go 1 兼容性准则的保护。
func RunBenchmarks
func RunBenchmarks(matchString func(pat, str string) (bool, error), benchmarks []InternalBenchmark)
RunBenchmarks 是一个内部函数,但因其跨包使用而被导出; 它是 "go test" 命令实现的一部分。
func RunExamples
func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool)
RunExamples 是一个内部函数,但由于它是跨包使用的而被导出; 它是 "go test" 命令实现的一部分。
func RunTests
func RunTests(matchString func(pat, str string) (bool, error), tests []InternalTest) (ok bool)
RunTests 是一个内部函数,但因需要跨包调用而导出; 它是 "go test" 命令实现的一部分。
func Short
func Short() bool
Short 报告是否设置了 -test.short 标志。
func Testing
func Testing() bool
Testing 报告当前代码是否正在测试中运行。 在由 "go test" 创建的程序中它会报告 true, 在由 "go build" 创建的程序中报告 false。
func Verbose
func Verbose() bool
Verbose 报告是否设置了 -test.v 标志。
Types
type B
type B struct { N int // contains filtered or unexported fields }
B 是传递给 Benchmark 函数的类型,用于管理基准测试的 计时并控制迭代次数。
当 Benchmark 函数返回或调用 B.FailNow、B.Fatal、B.Fatalf、 B.SkipNow、B.Skip 或 B.Skipf 中的任一方法时,基准测试结束。 这些方法只能从运行 Benchmark 函数的 goroutine 中调用。 其他报告方法,例如 B.Log 和 B.Error 的各种变体, 可以从多个 goroutine 同时调用。
与测试类似,基准测试日志在执行期间累积, 并在结束时转储到标准输出。与测试不同的是,基准测试日志 总是会打印出来,以免隐藏那些可能正在影响基准测试结果的输出。
func (*B) ArtifactDir
func (c *B) ArtifactDir() string
ArtifactDir 返回一个目录,测试应在其中存储输出文件。 当提供 -artifacts 标志时,该目录位于输出目录之下。 否则,ArtifactDir 返回一个在测试完成后被删除的临时目录。
每个测试包中的每个测试或子测试都有唯一的 artifact 目录。 在同一测试或子测试中重复调用 ArtifactDir 会返回相同的目录。 子测试的输出不位于父测试的输出目录之下。
func (*B) Attr
func (c *B) Attr(key, value string)
Attr 发出一个与该测试关联的测试属性。
键不能包含空白字符。 值不能包含换行符或回车符。
不同属性键的含义由持续集成系统和测试框架 自行决定。
测试属性会立即在测试日志中发出, 但它们应被视为无序的。
func (*B) Chdir
func (c *B) Chdir(dir string)
Chdir 调用 os.Chdir,并使用 Cleanup 在测试后将当前 工作目录恢复为其原始值。在 Unix 上,它还会在测试期间 设置 PWD 环境变量。
由于 Chdir 会影响整个进程,因此不能在并行测试或 具有并行祖先的测试中使用。
func (*B) Cleanup
func (c *B) Cleanup(f func())
Cleanup 注册一个在测试(或子测试)及其所有子测试完成时 调用的函数。Cleanup 函数将按最后添加、最先调用的顺序调用。
func (*B) Context
func (c *B) Context() context.Context
Context 返回一个 context,它会在 Cleanup 注册的函数 被调用之前被取消。
Cleanup 函数可以等待任何在测试或基准测试完成前 通过 context.Context.Done 关闭的资源。
func (*B) Elapsed
func (b *B) Elapsed() time.Duration
Elapsed 返回该基准测试测得的已流逝时间。 Elapsed 报告的时长与 B.StartTimer、B.StopTimer 和 B.ResetTimer 所测量的时长一致。
func (*B) Error
func (c *B) Error(args ...any)
Error 等价于依次调用 Log 和 Fail。
func (*B) Errorf
func (c *B) Errorf(format string, args ...any)
Errorf 等价于依次调用 Logf 和 Fail。
func (*B) Fail
func (c *B) Fail()
Fail 将该函数标记为已失败,但会继续执行。
func (*B) FailNow
func (c *B) FailNow()
FailNow 将该函数标记为已失败,并通过调用 runtime.Goexit (随后会运行当前 goroutine 中的所有延迟调用)来停止其执行。 执行将在下一个测试或基准测试处继续。 FailNow 必须从运行测试或基准测试函数的 goroutine 中调用, 而不是从测试期间创建的其他 goroutine 中调用。 调用 FailNow 不会停止那些其他 goroutine。
func (*B) Failed
func (c *B) Failed() bool
Failed 报告该函数是否已失败。
func (*B) Fatal
func (c *B) Fatal(args ...any)
Fatal 等价于依次调用 Log 和 FailNow。
func (*B) Fatalf
func (c *B) Fatalf(format string, args ...any)
Fatalf 等价于依次调用 Logf 和 FailNow。
func (*B) Helper
func (c *B) Helper()
Helper 将调用函数标记为测试辅助函数。 在打印文件和行信息时,该函数将被跳过。 Helper 可以从多个 goroutine 同时调用。
func (*B) Log
func (c *B) Log(args ...any)
Log 使用默认格式(类似于 fmt.Println)格式化其参数, 并将文本记录到错误日志中。对于测试,只有测试失败或设置了 -test.v 标志时才会打印该文本。对于基准测试,文本始终会打印, 以避免性能依赖于 -test.v 标志的取值。 在测试或基准测试返回后调用 Log 是错误的。
func (*B) Logf
func (c *B) Logf(format string, args ...any)
Logf 按照格式(类似于 fmt.Printf)格式化其参数, 并将文本记录到错误日志中。如果未提供,会添加最后的换行符。 对于测试,只有测试失败或设置了 -test.v 标志时才会打印 该文本。对于基准测试,文本始终会打印,以避免性能 依赖于 -test.v 标志的取值。 在测试或基准测试返回后调用 Logf 是错误的。
func (*B) Loop
func (b *B) Loop() bool
只要基准测试应继续运行,Loop 就返回 true。
一个典型的基准测试结构如下:
func Benchmark(b *testing.B) {
... setup ...
for b.Loop() {
... code to measure ...
}
... cleanup ...
}
Loop 在基准测试中第一次被调用时会重置基准测试计时器, 因此在开始基准测试循环之前执行的任何设置都不会计入 基准测试的测量。同样,当它返回 false 时,它会停止 计时器,因此清理代码不会被测量。
在 "for b.Loop() { ... }" 循环体内,循环内函数调用的参数和 结果以及被赋值的变量会保持存活,从而阻止编译器完全 优化掉循环体。 目前,这是通过一个编译器变换实现的,它用 runtime.KeepAlive 内建调用包装这类变量。这仅适用于 语法上位于循环花括号之间的语句,并且循环 条件必须完全写作 "b.Loop()"。
在 Loop 返回 false 之后,b.N 包含已运行的总迭代次数, 因此基准测试可以使用 b.N 来计算其他平均指标。
在引入 Loop 之前,基准测试被期望包含一个
从 0 到 b.N 的显式循环。基准测试应使用 Loop 或包含一个
到 b.N 的循环,但不能同时使用两者。Loop 提供了对基准测试
计时器更自动化的管理,并且每次测量只运行一次基准测试函数,
而基于 b.N 的基准测试必须多次运行基准测试函数(以及任何
相关的设置和清理)。
Example
package main
import (
"math/rand/v2"
"testing"
)
// ExBenchmark shows how to use b.Loop in a benchmark.
//
// (If this were a real benchmark, not an example, this would be named
// BenchmarkSomething.)
func ExBenchmark(b *testing.B) {
// Generate a large random slice to use as an input.
// Since this is done before the first call to b.Loop(),
// it doesn't count toward the benchmark time.
input := make([]int, 128<<10)
for i := range input {
input[i] = rand.Int()
}
// Perform the benchmark.
for b.Loop() {
// Normally, the compiler would be allowed to optimize away the call
// to sum because it has no side effects and the result isn't used.
// However, inside a b.Loop loop, the compiler ensures function calls
// aren't optimized away.
sum(input)
}
// Outside the loop, the timer is stopped, so we could perform
// cleanup if necessary without affecting the result.
}
func sum(data []int) int {
total := 0
for _, value := range data {
total += value
}
return total
}
func main() {
testing.Benchmark(ExBenchmark)
}
func (*B) Name
func (c *B) Name() string
Name 返回正在运行的(子)测试或基准测试的名称。
该名称将包含测试的名称以及任何嵌套子测试的名称。 如果两个同级的子测试同名,Name 会附加一个后缀 以保证返回的名称唯一。
func (*B) Output
func (c *B) Output() io.Writer
Output 返回一个 Writer,它写入与 TB.Log 相同的测试输出流。 输出会像 TB.Log 行一样缩进,但 Output 不会 添加源位置或换行符。输出在内部按行缓冲, 调用 TB.Log 或测试结束时都会隐式刷新缓冲区, 并随后添加一个换行符。在测试函数及其所有 父级返回之后,不得调用 Output 或 Write 方法。
func (*B) ReportAllocs
func (b *B) ReportAllocs()
ReportAllocs 为该基准测试启用内存分配统计。 它等价于设置 -test.benchmem,但只影响调用 ReportAllocs 的那个基准测试函数。
func (*B) ReportMetric
func (b *B) ReportMetric(n float64, unit string)
ReportMetric 将 "n unit" 添加到报告的基准测试结果中。
如果该指标是按次迭代的,调用方应除以 b.N,
按照惯例,单位应以 "/op" 结尾。
ReportMetric 会覆盖同一单位之前报告的任何值。
如果 unit 为空字符串或包含任何空白字符,
ReportMetric 会 panic。
如果 unit 是基准测试框架本身通常报告的单位
(例如 "allocs/op"),ReportMetric 将覆盖该指标。
将 "ns/op" 设为 0 将抑制该内置指标。
Example
package main
import (
"cmp"
"slices"
"testing"
)
func main() {
// 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 b.Loop() {
s := []int{5, 4, 3, 2, 1}
slices.SortFunc(s, func(a, b int) int {
compares++
return cmp.Compare(a, b)
})
}
// 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")
})
}
Example (Parallel)
package main
import (
"cmp"
"slices"
"sync/atomic"
"testing"
)
func main() {
// 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}
slices.SortFunc(s, func(a, b int) int {
// Because RunParallel runs the function many
// times in parallel, we must increment the
// counter atomically to avoid racing writes.
compares.Add(1)
return cmp.Compare(a, b)
})
}
})
// 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")
})
}
func (*B) ResetTimer
func (b *B) ResetTimer()
ResetTimer 将已流逝的基准测试时间和内存分配计数器清零, 并删除用户报告的指标。 它不影响计时器是否正在运行。
func (*B) Run
func (b *B) Run(name string, f func(b *B)) bool
Run 以给定名称将基准测试 f 作为子基准测试运行。它报告 是否存在任何失败。
子基准测试与任何其他基准测试类似。至少调用过一次 Run 的 基准测试自身不会被测量,并且会以 N=1 调用一次。
func (*B) RunParallel
func (b *B) RunParallel(body func(*PB))
RunParallel 并行运行基准测试。 它创建多个 goroutine,并将 b.N 次迭代分配给它们。 goroutine 的数量默认为 GOMAXPROCS。要增加非 CPU 密集型 基准测试的并行度,可在 RunParallel 之前调用 B.SetParallelism。 RunParallel 通常与 go test -cpu 标志一起使用。
body 函数将在每个 goroutine 中运行。它应设置任何 goroutine 局部的状态,然后迭代直到 pb.Next 返回 false。 它不应使用 B.StartTimer、B.StopTimer 或 B.ResetTimer 函数, 因为它们具有全局效果。它也不应调用 B.Run。
RunParallel 报告的 ns/op 值是整个基准测试的墙钟时间,
而不是各个并行 goroutine 的墙钟时间或 CPU 时间之和。
Example
package main
import (
"bytes"
"testing"
"text/template"
)
func main() {
// 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(&buf, "World")
}
})
})
}
func (*B) SetBytes
func (b *B) SetBytes(n int64)
SetBytes 记录单次操作处理的字节数。 如果调用此方法,基准测试将报告 ns/op 和 MB/s。
func (*B) SetParallelism
func (b *B) SetParallelism(p int)
SetParallelism 将 B.RunParallel 使用的 goroutine 数量设置为 p*GOMAXPROCS。 对于 CPU 密集型基准测试,通常无需调用 SetParallelism。 如果 p 小于 1,此调用将不起作用。
func (*B) Setenv
func (c *B) Setenv(key, value string)
Setenv 调用 os.Setenv,并使用 Cleanup 在测试后将 环境变量恢复为其原始值。
由于 Setenv 会影响整个进程,因此不能在并行测试或 具有并行祖先的测试中使用。
func (*B) Skip
func (c *B) Skip(args ...any)
Skip 等价于依次调用 Log 和 SkipNow。
func (*B) SkipNow
func (c *B) SkipNow()
SkipNow 将该测试标记为已被跳过,并通过调用 runtime.Goexit 停止其执行。 如果测试失败(参见 Error、Errorf、Fail)随后又被跳过, 它仍会被视为已失败。 执行将在下一个测试或基准测试处继续。另请参见 FailNow。 SkipNow 必须从运行该测试的 goroutine 中调用,而不是从测试期间 创建的其他 goroutine 中调用。调用 SkipNow 不会停止 那些其他 goroutine。
func (*B) Skipf
func (c *B) Skipf(format string, args ...any)
Skipf 等价于依次调用 Logf 和 SkipNow。
func (*B) Skipped
func (c *B) Skipped() bool
Skipped 报告该测试是否被跳过。
func (*B) StartTimer
func (b *B) StartTimer()
StartTimer 开始为测试计时。该函数会在基准测试开始前 自动调用,但也可用于在调用 B.StopTimer 后恢复计时。
func (*B) StopTimer
func (b *B) StopTimer()
StopTimer 停止为测试计时。可在执行你不想测量的步骤时 用它来暂停计时器。
func (*B) TempDir
func (c *B) TempDir() string
TempDir 返回一个供测试使用的临时目录。 当测试及其所有子测试完成时,该目录会被自动删除。 后续每次调用 TempDir 都会返回一个唯一的目录; 如果目录创建失败,TempDir 会通过调用 Fatal 终止测试。 如果设置了环境变量 GOTMPDIR,临时目录将在 该目录之下某处创建。
type BenchmarkResult
type BenchmarkResult struct { N int // 迭代次数。 T time.Duration // 总耗时。 Bytes int64 // 单次迭代处理的字节数。 MemAllocs uint64 // 内存分配总次数。 MemBytes uint64 // 分配的总字节数。 // Extra 记录由 ReportMetric 报告的额外指标。 Extra map[string]float64 }
BenchmarkResult 包含一次基准测试运行的结果。
func Benchmark
func Benchmark(f func(b *B)) BenchmarkResult
Benchmark 对单个函数进行基准测试。它对于创建不使用 "go test" 命令的自定义基准测试很有用。
如果 f 依赖于 testing 标志,则必须在调用 Benchmark 之前 以及在调用 flag.Parse 之前使用 Init 注册这些标志。
如果 f 调用 Run,结果将是对在单个基准测试中按顺序运行 其所有不调用 Run 的子基准测试的估计。
func (BenchmarkResult) AllocedBytesPerOp
func (r BenchmarkResult) AllocedBytesPerOp() int64
AllocedBytesPerOp 返回 "B/op" 指标, 其计算方式为 r.MemBytes / r.N。
func (BenchmarkResult) AllocsPerOp
func (r BenchmarkResult) AllocsPerOp() int64
AllocsPerOp 返回 "allocs/op" 指标, 其计算方式为 r.MemAllocs / r.N。
func (BenchmarkResult) MemString
func (r BenchmarkResult) MemString() string
MemString 以与 'go test' 相同的格式返回 r.AllocedBytesPerOp 和 r.AllocsPerOp。
func (BenchmarkResult) NsPerOp
func (r BenchmarkResult) NsPerOp() int64
NsPerOp 返回 "ns/op" 指标。
func (BenchmarkResult) String
func (r BenchmarkResult) String() string
String 返回基准测试结果的摘要。 它遵循 https://golang.org/design/14313-benchmark-format 中的 基准测试结果行格式,不包括 基准测试名称。 额外指标会覆盖同名的内置指标。 String 不包含 allocs/op 或 B/op,因为它们由 BenchmarkResult.MemString 报告。
type Cover
type Cover struct { Mode string Counters map[string][]uint32 Blocks map[string][]CoverBlock CoveredPackages string }
Cover 记录有关测试覆盖率检查的信息。 注意:该结构体属于测试基础设施内部实现,可能会发生变化。 它(尚)不受 Go 1 兼容性准则的保护。
type CoverBlock
type CoverBlock struct { Line0 uint32 // 块起始的行号。 Col0 uint16 // 块起始的列号。 Line1 uint32 // 块结束的行号。 Col1 uint16 // 块结束的列号。 Stmts uint16 // 此块中包含的语句数量。 }
CoverBlock 记录单个基本块的覆盖率数据。 各字段采用 1 起始索引,如同编辑器中的行号:例如, 文件的开头一行编号为 1。列以字节为单位度量。 注意:该结构体属于测试基础设施内部实现,可能会发生变化。 它(尚)不受 Go 1 兼容性准则的保护。
type F
type F struct { // contains filtered or unexported fields }
F 是传递给模糊测试的类型。
模糊测试会针对提供的模糊测试目标运行生成的输入,从而发现并报告 被测代码中潜在的 bug。
模糊测试默认会运行种子语料库,其中包含由 F.Add 提供的条目以及 testdata/fuzz/<FuzzTestName> 目录中的条目。在完成必要的设置并调用 F.Add 之后,模糊测试必须调用 F.Fuzz 来提供模糊测试目标。 示例参见 testing 包文档,详情参见 F.Fuzz 和 F.Add 方法的文档。
*F 的方法只能在 F.Fuzz 之前调用。一旦测试开始 执行模糊测试目标,就只能使用 *T 的方法。在 F.Fuzz 函数中 唯一允许使用的 *F 方法是 F.Failed 和 F.Name。
func (*F) Add
func (f *F) Add(args ...any)
Add 会将参数添加到模糊测试的种子语料库中。如果在模糊测试目标之后 或在其内部调用,则该调用不执行任何操作,并且 args 必须与模糊测试目标的 参数匹配。
func (*F) ArtifactDir
func (c *F) ArtifactDir() string
ArtifactDir 返回一个目录,测试应在其中存储输出文件。 当提供 -artifacts 标志时,该目录位于输出目录之下。 否则,ArtifactDir 返回一个在测试完成后被删除的临时目录。
每个测试包中的每个测试或子测试都有唯一的 artifact 目录。 在同一测试或子测试中重复调用 ArtifactDir 会返回相同的目录。 子测试的输出不位于父测试的输出目录之下。
func (*F) Attr
func (c *F) Attr(key, value string)
Attr 发出一个与该测试关联的测试属性。
键不能包含空白字符。 值不能包含换行符或回车符。
不同属性键的含义由持续集成系统和测试框架 自行决定。
测试属性会立即在测试日志中发出, 但它们应被视为无序的。
func (*F) Chdir
func (c *F) Chdir(dir string)
Chdir 调用 os.Chdir,并使用 Cleanup 在测试后将当前 工作目录恢复为其原始值。在 Unix 上,它还会在测试期间 设置 PWD 环境变量。
由于 Chdir 会影响整个进程,因此不能在并行测试或 具有并行祖先的测试中使用。
func (*F) Cleanup
func (c *F) Cleanup(f func())
Cleanup 注册一个在测试(或子测试)及其所有子测试完成时 调用的函数。Cleanup 函数将按最后添加、最先调用的顺序调用。
func (*F) Context
func (c *F) Context() context.Context
Context 返回一个 context,它会在 Cleanup 注册的函数 被调用之前被取消。
Cleanup 函数可以等待任何在测试或基准测试完成前 通过 context.Context.Done 关闭的资源。
func (*F) Error
func (c *F) Error(args ...any)
Error 等价于依次调用 Log 和 Fail。
func (*F) Errorf
func (c *F) Errorf(format string, args ...any)
Errorf 等价于依次调用 Logf 和 Fail。
func (*F) Fail
func (f *F) Fail()
Fail 将函数标记为已失败,但会继续执行。
func (*F) FailNow
func (c *F) FailNow()
FailNow 将该函数标记为已失败,并通过调用 runtime.Goexit (随后会运行当前 goroutine 中的所有延迟调用)来停止其执行。 执行将在下一个测试或基准测试处继续。 FailNow 必须从运行测试或基准测试函数的 goroutine 中调用, 而不是从测试期间创建的其他 goroutine 中调用。 调用 FailNow 不会停止那些其他 goroutine。
func (*F) Failed
func (c *F) Failed() bool
Failed 报告该函数是否已失败。
func (*F) Fatal
func (c *F) Fatal(args ...any)
Fatal 等价于依次调用 Log 和 FailNow。
func (*F) Fatalf
func (c *F) Fatalf(format string, args ...any)
Fatalf 等价于依次调用 Logf 和 FailNow。
func (*F) Fuzz
func (f *F) Fuzz(ff any)
Fuzz 运行模糊测试函数 ff,用于模糊测试。如果 ff 针对某组参数 失败,则这些参数将被添加到种子语料库中。
ff 必须是一个没有返回值的函数,其第一个参数为 *T, 其余参数为要模糊测试的类型。 例如:
f.Fuzz(func(t *testing.T, b []byte, i int) { ... })
允许使用以下类型:[]byte、string、bool、byte、rune、float32、 float64、int、int8、int16、int32、int64、uint、uint8、uint16、uint32、uint64。 未来可能会支持更多类型。
ff 不得调用任何 *F 方法,例如 F.Log、F.Error、F.Skip。 而应使用对应的 *T 方法。在 F.Fuzz 函数中唯一允许使用的 *F 方法是 F.Failed 和 F.Name。
该函数应当快速且确定,其行为不应依赖共享状态。在模糊测试函数的 多次执行之间,不应保留可变的输入参数或指向它们的指针, 因为支撑它们的内存可能在后续调用中被修改。ff 不得 修改模糊测试引擎所提供参数的底层数据。
进行模糊测试时,F.Fuzz 会一直运行,直到发现问题、时间耗尽 (通过 -fuzztime 设置),或测试进程被信号中断。F.Fuzz 应当只调用一次,除非事先调用了 F.Skip 或 F.Fail。
func (*F) Helper
func (f *F) Helper()
Helper 将调用它的函数标记为测试辅助函数。 在打印文件和行信息时,该函数将被跳过。 Helper 可以从多个 goroutine 同时调用。
func (*F) Log
func (c *F) Log(args ...any)
Log 使用默认格式(类似于 fmt.Println)格式化其参数, 并将文本记录到错误日志中。对于测试,只有测试失败或设置了 -test.v 标志时才会打印该文本。对于基准测试,文本始终会打印, 以避免性能依赖于 -test.v 标志的取值。 在测试或基准测试返回后调用 Log 是错误的。
func (*F) Logf
func (c *F) Logf(format string, args ...any)
Logf 按照格式(类似于 fmt.Printf)格式化其参数, 并将文本记录到错误日志中。如果未提供,会添加最后的换行符。 对于测试,只有测试失败或设置了 -test.v 标志时才会打印 该文本。对于基准测试,文本始终会打印,以避免性能 依赖于 -test.v 标志的取值。 在测试或基准测试返回后调用 Logf 是错误的。
func (*F) Name
func (c *F) Name() string
Name 返回正在运行的(子)测试或基准测试的名称。
该名称将包含测试的名称以及任何嵌套子测试的名称。 如果两个同级的子测试同名,Name 会附加一个后缀 以保证返回的名称唯一。
func (*F) Output
func (c *F) Output() io.Writer
Output 返回一个 Writer,它写入与 TB.Log 相同的测试输出流。 输出会像 TB.Log 行一样缩进,但 Output 不会 添加源位置或换行符。输出在内部按行缓冲, 调用 TB.Log 或测试结束时都会隐式刷新缓冲区, 并随后添加一个换行符。在测试函数及其所有 父级返回之后,不得调用 Output 或 Write 方法。
func (*F) Setenv
func (c *F) Setenv(key, value string)
Setenv 调用 os.Setenv,并使用 Cleanup 在测试后将 环境变量恢复为其原始值。
由于 Setenv 会影响整个进程,因此不能在并行测试或 具有并行祖先的测试中使用。
func (*F) Skip
func (c *F) Skip(args ...any)
Skip 等价于依次调用 Log 和 SkipNow。
func (*F) SkipNow
func (c *F) SkipNow()
SkipNow 将该测试标记为已被跳过,并通过调用 runtime.Goexit 停止其执行。 如果测试失败(参见 Error、Errorf、Fail)随后又被跳过, 它仍会被视为已失败。 执行将在下一个测试或基准测试处继续。另请参见 FailNow。 SkipNow 必须从运行该测试的 goroutine 中调用,而不是从测试期间 创建的其他 goroutine 中调用。调用 SkipNow 不会停止 那些其他 goroutine。
func (*F) Skipf
func (c *F) Skipf(format string, args ...any)
Skipf 等价于依次调用 Logf 和 SkipNow。
func (*F) Skipped
func (f *F) Skipped() bool
Skipped 报告测试是否被跳过。
func (*F) TempDir
func (c *F) TempDir() string
TempDir 返回一个供测试使用的临时目录。 当测试及其所有子测试完成时,该目录会被自动删除。 后续每次调用 TempDir 都会返回一个唯一的目录; 如果目录创建失败,TempDir 会通过调用 Fatal 终止测试。 如果设置了环境变量 GOTMPDIR,临时目录将在 该目录之下某处创建。
type InternalBenchmark
type InternalBenchmark struct { Name string F func(b *B) }
InternalBenchmark 是一个内部类型,但因其跨包使用而被导出; 它是 "go test" 命令实现的一部分。
type InternalExample
type InternalExample struct { Name string F func() Output string Unordered bool }
type InternalFuzzTarget
type InternalFuzzTarget struct { Name string Fn func(f *F) }
InternalFuzzTarget 是一个内部类型,但由于需要跨包使用而导出; 它是 "go test" 命令实现的一部分。
type InternalTest
type InternalTest struct { Name string F func(*T) }
InternalTest 是一个内部类型,但因跨包使用而导出; 它是 "go test" 命令实现的一部分。
type M
type M struct { // contains filtered or unexported fields }
M 是传递给 TestMain 函数以运行实际测试的类型。
func MainStart
func MainStart(deps testDeps, tests []InternalTest, benchmarks []InternalBenchmark, fuzzTargets []InternalFuzzTarget, examples []InternalExample) *M
MainStart 供 'go test' 生成的测试使用。 它不应被直接调用,也不受 Go 1 兼容性文档的约束。 它的签名可能随版本发布而变化。
func (*M) Run
func (m *M) Run() (code int)
Run 运行测试。它返回一个要传递给 os.Exit 的退出码。 当所有测试通过时退出码为零,任何类型的失败时 退出码非零。要获得机器可读的测试结果,请解析 'go test -json' 的输出。
type PB
type PB struct { // contains filtered or unexported fields }
PB 由 RunParallel 用于运行并行基准测试。
func (*PB) Next
func (pb *PB) Next() bool
Next 报告是否还有更多迭代要执行。
type T
type T struct { // contains filtered or unexported fields }
T 是传递给 Test 函数的类型,用于管理测试状态并支持格式化测试日志。
当测试函数返回或调用 T.FailNow、T.Fatal、T.Fatalf、T.SkipNow、T.Skip 或 T.Skipf 中的任一方法时,测试结束。这些方法以及 T.Parallel 方法 只能从运行该测试函数的 goroutine 中调用。
其他的报告方法,例如 T.Log 和 T.Error 的各种变体, 可以从多个 goroutine 同时调用。
func (*T) ArtifactDir
func (c *T) ArtifactDir() string
ArtifactDir 返回一个目录,测试应在其中存储输出文件。 当提供 -artifacts 标志时,该目录位于输出目录之下。 否则,ArtifactDir 返回一个在测试完成后被删除的临时目录。
每个测试包中的每个测试或子测试都有唯一的 artifact 目录。 在同一测试或子测试中重复调用 ArtifactDir 会返回相同的目录。 子测试的输出不位于父测试的输出目录之下。
func (*T) Attr
func (c *T) Attr(key, value string)
Attr 发出一个与该测试关联的测试属性。
键不能包含空白字符。 值不能包含换行符或回车符。
不同属性键的含义由持续集成系统和测试框架 自行决定。
测试属性会立即在测试日志中发出, 但它们应被视为无序的。
func (*T) Chdir
func (t *T) Chdir(dir string)
Chdir 调用 os.Chdir,并使用 Cleanup 在测试后将当前 工作目录恢复为其原始值。在 Unix 上,它还会在测试期间 设置 PWD 环境变量。
由于 Chdir 会影响整个进程,因此不能在并行测试或 具有并行祖先的测试中使用。
func (*T) Cleanup
func (c *T) Cleanup(f func())
Cleanup 注册一个在测试(或子测试)及其所有子测试完成时 调用的函数。Cleanup 函数将按最后添加、最先调用的顺序调用。
func (*T) Context
func (c *T) Context() context.Context
Context 返回一个 context,它会在 Cleanup 注册的函数 被调用之前被取消。
Cleanup 函数可以等待任何在测试或基准测试完成前 通过 context.Context.Done 关闭的资源。
func (*T) Deadline
func (t *T) Deadline() (deadline time.Time, ok bool)
Deadline 报告测试二进制文件将超过 -timeout 标志所指定 超时的时间。
如果 -timeout 标志表示“无超时”(0),则 ok 结果为 false。
func (*T) Error
func (c *T) Error(args ...any)
Error 等价于依次调用 Log 和 Fail。
func (*T) Errorf
func (c *T) Errorf(format string, args ...any)
Errorf 等价于依次调用 Logf 和 Fail。
func (*T) Fail
func (c *T) Fail()
Fail 将该函数标记为已失败,但会继续执行。
func (*T) FailNow
func (c *T) FailNow()
FailNow 将该函数标记为已失败,并通过调用 runtime.Goexit (随后会运行当前 goroutine 中的所有延迟调用)来停止其执行。 执行将在下一个测试或基准测试处继续。 FailNow 必须从运行测试或基准测试函数的 goroutine 中调用, 而不是从测试期间创建的其他 goroutine 中调用。 调用 FailNow 不会停止那些其他 goroutine。
func (*T) Failed
func (c *T) Failed() bool
Failed 报告该函数是否已失败。
func (*T) Fatal
func (c *T) Fatal(args ...any)
Fatal 等价于依次调用 Log 和 FailNow。
func (*T) Fatalf
func (c *T) Fatalf(format string, args ...any)
Fatalf 等价于依次调用 Logf 和 FailNow。
func (*T) Helper
func (c *T) Helper()
Helper 将调用函数标记为测试辅助函数。 在打印文件和行信息时,该函数将被跳过。 Helper 可以从多个 goroutine 同时调用。
func (*T) Log
func (c *T) Log(args ...any)
Log 使用默认格式(类似于 fmt.Println)格式化其参数, 并将文本记录到错误日志中。对于测试,只有测试失败或设置了 -test.v 标志时才会打印该文本。对于基准测试,文本始终会打印, 以避免性能依赖于 -test.v 标志的取值。 在测试或基准测试返回后调用 Log 是错误的。
func (*T) Logf
func (c *T) Logf(format string, args ...any)
Logf 按照格式(类似于 fmt.Printf)格式化其参数, 并将文本记录到错误日志中。如果未提供,会添加最后的换行符。 对于测试,只有测试失败或设置了 -test.v 标志时才会打印 该文本。对于基准测试,文本始终会打印,以避免性能 依赖于 -test.v 标志的取值。 在测试或基准测试返回后调用 Logf 是错误的。
func (*T) Name
func (c *T) Name() string
Name 返回正在运行的(子)测试或基准测试的名称。
该名称将包含测试的名称以及任何嵌套子测试的名称。 如果两个同级的子测试同名,Name 会附加一个后缀 以保证返回的名称唯一。
func (*T) Output
func (c *T) Output() io.Writer
Output 返回一个 Writer,它写入与 TB.Log 相同的测试输出流。 输出会像 TB.Log 行一样缩进,但 Output 不会 添加源位置或换行符。输出在内部按行缓冲, 调用 TB.Log 或测试结束时都会隐式刷新缓冲区, 并随后添加一个换行符。在测试函数及其所有 父级返回之后,不得调用 Output 或 Write 方法。
func (*T) Parallel
func (t *T) Parallel()
Parallel 表示此测试要与其他并行测试并行(且仅与其他并行测试) 运行。当一个测试因使用 -test.count 或 -test.cpu 而被运行多次时, 单个测试的多个实例从不会彼此并行运行。
func (*T) Run
func (t *T) Run(name string, f func(t *T)) bool
Run 将 f 作为 t 的一个名为 name 的子测试运行。它在一个单独的 goroutine 中运行 f,并阻塞直到 f 返回或调用 t.Parallel 成为并行测试。 Run 报告 f 是否成功(或至少在调用 t.Parallel 之前没有失败)。
Run 可以从多个 goroutine 同时调用,但所有此类调用都必须在 t 的外层测试函数返回之前返回。
func (*T) Setenv
func (t *T) Setenv(key, value string)
Setenv 调用 os.Setenv(key, value),并使用 Cleanup 在测试后 将环境变量恢复为其原始值。
由于 Setenv 会影响整个进程,因此不能在并行测试或 具有并行祖先的测试中使用。
func (*T) Skip
func (c *T) Skip(args ...any)
Skip 等价于依次调用 Log 和 SkipNow。
func (*T) SkipNow
func (c *T) SkipNow()
SkipNow 将该测试标记为已被跳过,并通过调用 runtime.Goexit 停止其执行。 如果测试失败(参见 Error、Errorf、Fail)随后又被跳过, 它仍会被视为已失败。 执行将在下一个测试或基准测试处继续。另请参见 FailNow。 SkipNow 必须从运行该测试的 goroutine 中调用,而不是从测试期间 创建的其他 goroutine 中调用。调用 SkipNow 不会停止 那些其他 goroutine。
func (*T) Skipf
func (c *T) Skipf(format string, args ...any)
Skipf 等价于依次调用 Logf 和 SkipNow。
func (*T) Skipped
func (c *T) Skipped() bool
Skipped 报告该测试是否被跳过。
func (*T) TempDir
func (c *T) TempDir() string
TempDir 返回一个供测试使用的临时目录。 当测试及其所有子测试完成时,该目录会被自动删除。 后续每次调用 TempDir 都会返回一个唯一的目录; 如果目录创建失败,TempDir 会通过调用 Fatal 终止测试。 如果设置了环境变量 GOTMPDIR,临时目录将在 该目录之下某处创建。
type TB
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) Fatalf(format string, args ...any) Helper() Log(args ...any) Logf(format string, args ...any) Name() string Setenv(key, value string) Chdir(dir string) Skip(args ...any) SkipNow() Skipf(format string, args ...any) Skipped() bool TempDir() string Context() context.Context Output() io.Writer // contains filtered or unexported methods }
Directories
| cryptotest | Package cryptotest 提供确定性随机源测试。 |
| fstest | fstest 包实现对文件系统实现和用户的测试支持。 |
| iotest | Package iotest 实现了主要用于测试的 Readers 和 Writers。 |
| quick | Package quick 实现了帮助进行黑盒测试的实用函数。 |
| slogtest | Package slogtest 支持测试 log/slog.Handler 的实现。 |
| synctest | synctest 包为测试并发代码提供支持。 |