V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
guonaihong

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

  •  
  •   guonaihong ·
    guonaihong · Oct 3, 2019 · 3255 views
    This topic created in 2410 days ago, the information mentioned may be changed or developed.

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

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2710 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 39ms · UTC 15:43 · PVG 23:43 · LAX 08:43 · JFK 11:43
    ♥ Do have faith in what you're doing.