Go1.14 的 go test -v 支持流式输出
testing 包是 Go 标准库中我最喜欢的程序包之一,不仅是它具有低干扰的单元测试方法,而且在 Go 的整个生命周期中,它可以改善、提高生活质量 ^_^。
在 Go1.14 中,go test -v 将使 t.Log 的输出变成流式,而不是在测试运行结束之前进行存储,最后一起输出。看一个例子:
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)
}
}
注意:在测试内部调用 fmt.Println通 常被认为是不该使用的,因为它绕过测试包的输出缓冲,而与 -v 标志无关。但是,在此示例中,有必要演示流式 t.Log 的变更。
% 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
在 Go 1.13 和更早版本下,fmt.Println 会立即输出。t.Log 会被缓冲并在测试完成后打印。
% 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
在 Go 1.14 下,fmt.Println 和 t.Log 是交错的,而不是等待测试完成,这表明使用 go test -v 时测试输出是流式的。
对于集成类测试,这可以提高生活质量,当测试失败时,集成类测试通常会长时间重试。流式 t.Log 输出将帮助 Gophers 调试那些测试失败,而不必等到整个测试超时才能看到它们的输出。
原文作者:Dave Cheney
原文链接:https://dave.cheney.net/2020/03/10/go-test-v-streaming-output
编译:polaris
图片来自:pexels
喜欢本文的朋友,欢迎关注“Go语言中文网”:
Go语言中文网启用微信学习交流群,欢迎加微信:274768166,投稿亦欢迎