V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
guonaihong
V2EX  ›  Go 编程语言

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

  •  
  •   guonaihong ·
    guonaihong · 2019-10-03 19:45:39 +08:00 · 2903 次点击
    这是一个创建于 1638 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3016 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:56 · PVG 22:56 · LAX 07:56 · JFK 10:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.