咱们知道单元测试函数须要传递一个testing.T
类型的参数,而性能测试函数须要传递一个testing.B
类型的参数,该参数可用于控制测试的流程,好比标记测试失败等。git
testing.T
和testing.B
属于testing
包中的两个数据类型,该类型提供一系列的方法用于控制函数执行流程,考虑到两者有必定的类似性,因此Go实现时抽象出一个testing.common
做为一个基础类型,而testing.T
和testing.B
则属于testing.common
的扩展。github
本节,咱们重点看testing.common
,经过其成员及方法,来了解其实现原理。数据结构
// common holds the elements common between T and B and // captures common methods such as Errorf. type common struct { mu sync.RWMutex // guards this group of fields output []byte // Output generated by test or benchmark. w io.Writer // For flushToParent. ran bool // Test or benchmark (or one of its subtests) was executed. failed bool // Test or benchmark has failed. skipped bool // Test of benchmark has been skipped. done bool // Test is finished and all subtests have completed. helpers map[string]struct{} // functions to be skipped when writing file/line info chatty bool // A copy of the chatty flag. finished bool // Test function has completed. hasSub int32 // written atomically raceErrors int // number of races detected during test runner string // function name of tRunner running the test parent *common level int // Nesting depth of test or benchmark. creator []uintptr // If level > 0, the stack trace at the point where the parent called t.Run. name string // Name of test or benchmark. start time.Time // Time test or benchmark started duration time.Duration barrier chan bool // To signal parallel subtests they may start. signal chan bool // To signal a test is done. sub []*T // Queue of subtests to be run in parallel. }
读写锁,仅用于控制本数据内的成员访问。app
存储当前测试产生的日志,每产生一条日志则追加到该切片中,待测试结束后再一并输出。函数
子测试执行结束须要把产生的日志输送到父测试中的output切片中,传递时须要考虑缩进等格式调整,经过w把日志传递到父测试。性能
仅表示是否已执行过。好比,跟据某个规范筛选测试,若是没有测试被匹配到的话,则common.ran为false,表示没有测试运行过。单元测试
若是当前测试执行失败,则置为true。测试
标记当前测试是否已跳过。ui
表示当前测试及其子测试已结束,此状态下再执行Fail()之类的方法标记测试状态会产生panic。this
标记当前为函数为help函数,其中打印的日志,在记录日志时不会显示其文件名及行号。
对应命令行中的-v参数,默认为false,true则打印更多详细日志。
若是当前测试结束,则置为true。
标记当前测试是否包含子测试,当测试使用t.Run()方法启动子测试时,t.hasSub则置为1。
竞态检测错误数。
执行当前测试的函数名。
若是当前测试为子测试,则置为父测试的指针。
测试嵌套层数,好比建立子测试时,子测试嵌套层数就会加1。
测试函数调用栈。
记录每一个测试函数名,好比测试函数TestAdd(t *testing.T)
, 其中t.name即“TestAdd”。 测试结束,打印测试结果会用到该成员。
记录测试开始的时间。
记录测试所花费的时间。
用于控制父测试和子测试执行的channel,若是测试为Parallel,则会阻塞等待父测试结束后再继续。
通知当前测试结束。
子测试列表。
// Name returns the name of the running test or benchmark. func (c *common) Name() string { return c.name }
该方法直接返回common结构体中存储的名称。
// Fail marks the function as having failed but continues execution. func (c *common) Fail() { if c.parent != nil { c.parent.Fail() } c.mu.Lock() defer c.mu.Unlock() // c.done needs to be locked to synchronize checks to c.done in parent tests. if c.done { panic("Fail in goroutine after " + c.name + " has completed") } c.failed = true }
Fail()方法会标记当前测试为失败,而后继续运行,并不会当即退出当前测试。若是是子测试,则除了标记当前测试结果外还经过c.parent.Fail()
来标记父测试失败。
func (c *common) FailNow() { c.Fail() c.finished = true runtime.Goexit() }
FailNow()内部会调用Fail()标记测试失败,还会标记测试结束并退出当前测试协程。 能够简单的把一个测试理解为一个协程,FailNow()只会退出当前协程,并不会影响其余测试协程,但要保证在当前测试协程中调用FailNow()才有效,不能够在当前测试建立的协程中调用该方法。
func (c *common) log(s string) { c.mu.Lock() defer c.mu.Unlock() c.output = append(c.output, c.decorate(s)...) }
common.log()为内部记录日志入口,日志会统一记录到common.output切片中,测试结束时再统一打印出来。 日志记录时会调用common.decorate()进行装饰,即加上文件名和行号,还会作一些其余格式化处理。 调用common.log()的方法,有Log()、Logf()、Error()、Errorf()、Fatal()、Fatalf()、Skip()、Skipf()等。
注意:单元测试中记录的日志只有在执行失败或指定了-v
参数才会打印,不然不会打印。而在性能测试中则老是被打印出来,由于是否打印日志有可能影响性能测试结果。
func (c *common) Log(args ...interface{}) { c.log(fmt.Sprintln(args...)) }
common.Log()方法用于记录简单日志,经过fmt.Sprintln()方法生成日志字符串后记录。
func (c *common) Logf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) }
common.Logf()方法用于格式化记录日志,经过fmt.Sprintf()生成字符串后记录。
// Error is equivalent to Log followed by Fail. func (c *common) Error(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.Fail() }
common.Error()方法等同于common.Log()+common.Fail(),即记录日志并标记失败,但测试继续进行。
// Errorf is equivalent to Logf followed by Fail. func (c *common) Errorf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.Fail() }
common.Errorf()方法等同于common.Logf()+common.Fail(),即记录日志并标记失败,但测试继续进行。
// Fatal is equivalent to Log followed by FailNow. func (c *common) Fatal(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.FailNow() }
common.Fatal()方法等同于common.Log()+common.FailNow(),即记录日志、标记失败并退出当前测试。
// Fatalf is equivalent to Logf followed by FailNow. func (c *common) Fatalf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.FailNow() }
common.Fatalf()方法等同于common.Logf()+common.FailNow(),即记录日志、标记失败并退出当前测试。
func (c *common) skip() { c.mu.Lock() defer c.mu.Unlock() c.skipped = true }
common.skip()方法标记当前测试为已跳过状态,好比测试中检测到某种条件,再也不继续测试。该函数仅标记测试跳过,与测试结果无关。测试结果仍然取决于common.failed。
func (c *common) SkipNow() { c.skip() c.finished = true runtime.Goexit() }
common.SkipNow()方法标记测试跳过,并标记测试结束,最后退出当前测试。
// Skip is equivalent to Log followed by SkipNow. func (c *common) Skip(args ...interface{}) { c.log(fmt.Sprintln(args...)) c.SkipNow() }
common.Skip()方法等同于common.Log()+common.SkipNow()。
// Skipf is equivalent to Logf followed by SkipNow. func (c *common) Skipf(format string, args ...interface{}) { c.log(fmt.Sprintf(format, args...)) c.SkipNow() }
common.Skipf()方法等同于common.Logf() + common.SkipNow()。
// 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. func (c *common) Helper() { c.mu.Lock() defer c.mu.Unlock() if c.helpers == nil { c.helpers = make(map[string]struct{}) } c.helpers[callerName(1)] = struct{}{} }
common.Helper()方法标记当前函数为help
函数,所谓help
函数,即其中打印的日志,不记录help
函数的函数名及行号,而是记录上一层函数的函数名和行号。
赠人玫瑰手留余香,若是以为不错请给个赞~
本篇文章已归档到GitHub项目,求星~ 点我即达