Go1.14 的這個改進讓 Gopher 生活更美好

Go1.14 的 go test -v 支持流式輸出

testing 包是 Go 標準庫中我最喜歡的程序包之一,不僅是它具有低干擾的單元測試方法,而且在 Go 的整個生命週期中,它可以改善、提高生活質量 ^_^。

在 Go1.14 中,go test -v 將使 t.Log 的輸出變成流式,而不是在測試運行結束之前進行存儲,最後一起輸出。看一個例子:

<code>package main
import (
"fmt"
"testing"
"time"
)
func TestLogStreaming(t *testing.T) {
for i := 0; i < 5; i++ {
time.Sleep(300 * time.Millisecond)
fmt.Println("fmt.Println:", i)
t.Log("t.Log:", i)
}
}
/<code>

注意:在測試內部調用 fmt.Println通 常被認為是不該使用的,因為它繞過測試包的輸出緩衝,而與 -v 標誌無關。但是,在此示例中,有必要演示流式 t.Log 的變更。

<code>% go1.13 test -v tlog_test.go
=== RUN TestLogStreaming
fmt.Println: 0
fmt.Println: 1
fmt.Println: 2
fmt.Println: 3
fmt.Println: 4
--- PASS: TestLogStreaming (1.52s)
tlog_test.go:13: t.Log: 0
tlog_test.go:13: t.Log: 1
tlog_test.go:13: t.Log: 2
tlog_test.go:13: t.Log: 3
tlog_test.go:13: t.Log: 4
PASS
ok command-line-arguments 1.971s
/<code>

在 Go 1.13 和更早版本下,fmt.Println 會立即輸出。t.Log 會被緩衝並在測試完成後打印。

<code>% go1.14 test -v tlog_test.go
=== RUN TestLogStreaming
fmt.Println: 0
TestLogStreaming: tlog_test.go:13: t.Log: 0
fmt.Println: 1
TestLogStreaming: tlog_test.go:13: t.Log: 1
fmt.Println: 2
TestLogStreaming: tlog_test.go:13: t.Log: 2
fmt.Println: 3
TestLogStreaming: tlog_test.go:13: t.Log: 3
fmt.Println: 4
TestLogStreaming: tlog_test.go:13: t.Log: 4
--- PASS: TestLogStreaming (1.51s)
PASS
ok command-line-arguments 1.809s
/<code>

在 Go 1.14 下,fmt.Println 和 t.Log 是交錯的,而不是等待測試完成,這表明使用 go test -v 時測試輸出是流式的。

對於集成類測試,這可以提高生活質量,當測試失敗時,集成類測試通常會長時間重試。流式 t.Log 輸出將幫助 Gophers 調試那些測試失敗,而不必等到整個測試超時才能看到它們的輸出。

原文鏈接:https://dave.cheney.net/2020/03/10/go-test-v-streaming-output

編譯:polaris

Go1.14 的這個改進讓 Gopher 生活更美好

圖片來自:pexels



喜歡本文的朋友,歡迎關注“Go語言中文網”:

Go1.14 的這個改進讓 Gopher 生活更美好

Go語言中文網啟用微信學習交流群,歡迎加微信:274768166,投稿亦歡迎


分享到:


相關文章: