golang 常见“坑”(2)-go test

2019-10-03 19:45:39 +08:00
 guonaihong

上会聊了 select 和无缓冲 chan 的作用,这会说下 go test 的输出。

猜下代码输出

如果你觉得会输出
fmt log test1
log test1
fmt error test1
error test1

那就可以继续往下看

package main

import (
        "fmt"
        "testing"
        "time"
)

func TestHelloWorld(t *testing.T) {
        //t.Fatalf("fatal test 1\n")
        fmt.Printf("fmt log test1\n")

        t.Logf("log test1\n")

        fmt.Printf("fmt error test1\n")
        t.Errorf("error test1\n")

        time.Sleep(time.Second * 60)
}

输出分析

go test -v
=== RUN   TestHelloWorld
fmt log test1
fmt error test1

什么?这和预期的不符合的。。。看来 t.Logf 此类函数,只有等 TestHelloWorld 函数结束之后才会把真的数据刷新到 os.Stdout。 这点可以从源码得到佐证,Logf 的调用流程:Logf--->log--->logDepth(s,3)--->只是把数据缓存到 c.output 变量里面。

结论

go test 里面的 t.Logf, t.Errorf 之类函数,只有在 Testxxx 函数测试函数结束之后才会打印到终端,如果你的测试依赖日志的输出状态,可以使用 fmt.Printf 之类函数。
对 go test 调用流程感兴趣的童鞋可以看下 testing.go 。runTests-->tRunner-->Run-->report-->flushToParent。这个链条下面会把 c.output 的的数据写到 os.Stdout 里面。

我的 github

https://github.com/guonaihong/gout

2910 次点击
所在节点    Go 编程语言
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/606184

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX