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



天经地纬六横十二纵.



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

念何架构之路

相关推荐
钟智强2 小时前
深度剖析CVE-2023-41064与CVE-2023-4863:libwebp堆溢出漏洞的技术解剖与PoC构建实录
前端·后端
玄〤2 小时前
个人博客网站搭建day3--Spring Boot JWT Token 认证配置的完整实现详解(漫画解析)
java·spring boot·后端·jwt
钟智强2 小时前
MySQL客户端惊现高危漏洞CVE-2023-21980,可导致远程代码执行
前端·后端
用户3521802454752 小时前
RAG 做不好?可能是你的 PDF 在"捣乱" 😅
后端·python·ai编程
Cache技术分享2 小时前
332. Java Stream API - Java Stream 实战进阶:按年份找出合作最多的作者对
前端·后端
果冻虾仁2 小时前
vllm使用plugin集成外部模型结构
人工智能·后端
Penge6662 小时前
Go—临时对象池 sync.Pool
后端
hash__2 小时前
AI Agent 技术解析:从原理到实战
后端
JavaLearnerZGQ2 小时前
Spring SseEmitter 全面解析与使用示例
java·后端·spring