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 欢迎大家访问.提意见.



天经地纬六横十二纵.



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

念何架构之路

相关推荐
nbwenren18 小时前
Springboot中SLF4J详解
java·spring boot·后端
helx8219 小时前
SpringBoot中自定义Starter
java·spring boot·后端
rleS IONS19 小时前
SpringBoot获取bean的几种方式
java·spring boot·后端
lifewange20 小时前
Go语言-开源编程语言
开发语言·后端·golang
白毛大侠20 小时前
深入理解 Go:用户态和内核态
开发语言·后端·golang
王码码203521 小时前
Go语言中的数据库操作:从sqlx到ORM
后端·golang·go·接口
星辰_mya21 小时前
雪花算法和时区的关系
数据库·后端·面试·架构师
计算机学姐1 天前
基于SpringBoot的兴趣家教平台系统
java·spring boot·后端·spring·信息可视化·tomcat·intellij-idea
總鑽風1 天前
单点登录springcloud+mysql
后端·spring·spring cloud
0xDevNull1 天前
Java 11 新特性概览与实战教程
java·开发语言·后端