上会聊了 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 里面。