Go进阶之示例测试原理

示例测试相对于单元测试和性能测试来说.实现机制比较简单.没有复杂的数据结构.也

不需要额外的流程控制.核心工作原理在于收集测试过程中打印日志.然后与期望字符

串做比较.最后的出去是否一致的报告.

1.数据结构:

源码位置:src/testing/example.go

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

go 复制代码
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

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

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()函数:

swift 复制代码
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 欢迎大家访问.提意见.



天经地纬六横十二纵.



如果大家喜欢我的分享的话.可以关注我的微信公众号

念何架构之路

相关推荐
IT_陈寒12 小时前
Vue组件复用率提升300%?这5个高阶技巧让你的代码焕然一新!
前端·人工智能·后端
beata13 小时前
Spring Boot基础-2:Spring Boot 3.x 起步依赖(Starter)深度拆解:为什么引入一个依赖就够了?
spring boot·后端
享棣13 小时前
Win11 安装 Nacos 2.0.4 完整版文档 文档说明
后端
90后的晨仔13 小时前
windows安装 openclaw 报错
后端
AMoon丶13 小时前
Golang--多种数据结构详解
linux·c语言·开发语言·数据结构·c++·后端·golang
深蓝轨迹13 小时前
SpringBoot YAML配置文件全解析:语法+读取+高级用法
java·spring boot·后端·学习
颜酱13 小时前
最小生成树(MST)核心原理 + Kruskal & Prim 算法
javascript·后端·算法
深蓝轨迹13 小时前
乐观锁 vs 悲观锁 含面试模板
java·spring boot·笔记·后端·学习·mysql·面试
用户73440281934216 小时前
SpringBoot —— 实现邮件、短信的发送功能
后端