示例测试相对于单元测试和性能测试来说.实现机制比较简单.没有复杂的数据结构.也
不需要额外的流程控制.核心工作原理在于收集测试过程中打印日志.然后与期望字符
串做比较.最后的出去是否一致的报告.
1.数据结构:
源码位置:src/testing/example.go
type InternalExample struct {
Name string
F func()
Output string
Unordered bool
}
Name:示例名称.对应的Example函数名称.
F:要执行的函数.
Output:函数执行的预期结果.
Unorderd:输出是否不要求顺序.
2.RunExamples()函数:
源码位置:src/testing/example.go
对外暴露的入口函数.供go test使用.
func RunExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ok bool) {
_, ok = runExamples(matchString, examples)
return ok
}
3.runExamples()函数:
源码位置:src/testing/example.go
func runExamples(matchString func(pat, str string) (bool, error), examples []InternalExample) (ran, ok bool) {
ok = true
m := newMatcher(matchString, *match, "-test.run", *skip)
var eg InternalExample
for _, eg = range examples {
_, matched, _ := m.fullName(nil, eg.Name)
if !matched {
continue
}
ran = true
if !runExample(eg) {
ok = false
}
}
return ran, ok
}
4.runExample()函数:
源码位置:src/testing/run_example.go
func runExample(eg InternalExample) (ok bool) {
if chatty.on {
fmt.Printf("%s=== RUN %s\n", chatty.prefix(), eg.Name)
}
// Capture stdout.
stdout := os.Stdout
r, w, err := os.Pipe()
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Stdout = w
outC := make(chan string)
go func() {
var buf strings.Builder
_, err := io.Copy(&buf, r)
r.Close()
if err != nil {
fmt.Fprintf(os.Stderr, "testing: copying pipe: %v\n", err)
os.Exit(1)
}
outC <- buf.String()
}()
finished := false
start := time.Now()
// Clean up in a deferred call so we can recover if the example panics.
defer func() {
timeSpent := time.Since(start)
// Close pipe, restore stdout, get output.
w.Close()
os.Stdout = stdout
out := <-outC
err := recover()
ok = eg.processRunResult(out, timeSpent, finished, err)
}()
// Run example.
eg.F()
finished = true
return
}
1).打印启动日志:
2).重定向标准输出:
3).初始化执行状态:
4).延迟清理和异常恢复:
5).执行示例函数和标记完成状态:
流程图:
5.processRunResult()函数:
func (eg *InternalExample) processRunResult(stdout string, timeSpent time.Duration, finished bool, recovered any) (passed bool) {
passed = true
dstr := fmtDuration(timeSpent)
var fail string
got := strings.TrimSpace(stdout)
want := strings.TrimSpace(eg.Output)
if runtime.GOOS == "windows" {
got = strings.ReplaceAll(got, "\r\n", "\n")
want = strings.ReplaceAll(want, "\r\n", "\n")
}
if eg.Unordered {
if sortLines(got) != sortLines(want) && recovered == nil {
fail = fmt.Sprintf("got:\n%s\nwant (unordered):\n%s\n", stdout, eg.Output)
}
} else {
if got != want && recovered == nil {
fail = fmt.Sprintf("got:\n%s\nwant:\n%s\n", got, want)
}
}
if fail != "" || !finished || recovered != nil {
fmt.Printf("%s--- FAIL: %s (%s)\n%s", chatty.prefix(), eg.Name, dstr, fail)
passed = false
} else if chatty.on {
fmt.Printf("%s--- PASS: %s (%s)\n", chatty.prefix(), eg.Name, dstr)
}
if chatty.on && chatty.json {
fmt.Printf("%s=== NAME %s\n", chatty.prefix(), "")
}
if recovered != nil {
// Propagate the previously recovered result, by panicking.
panic(recovered)
} else if !finished {
panic(errNilPanicOrGoexit)
}
return
}
流程图:
语雀地址www.yuque.com/itbosunmian…?
《Go.》 密码:xbkk 欢迎大家访问.提意见.
天经地纬六横十二纵.
如果大家喜欢我的分享的话.可以关注我的微信公众号
念何架构之路