Go1.17 新特性:testing 包的相關(guān)變化
閱讀本文大概需要 4 分鐘。
大家好,我是 polarisxu。
今天介紹下 Go1.17 中的特性:testing 包的一些變化。先看 Release Notes 關(guān)于 testing 變化的描述:
Added a new testing flag -shuffle which controls the execution order of tests and benchmarks.
The new T.Setenv and B.Setenv methods support setting an environment variable for the duration of the test or benchmark.
關(guān)于 shuffle 這個(gè) flag,1.17 還未發(fā)布時(shí),我就寫過文章介紹:Go1.17這個(gè)新特性竟然是6年前提出來的。關(guān)于它的作用,記住關(guān)鍵一點(diǎn):我們寫測試時(shí),測試之間別相互依賴,應(yīng)該是獨(dú)立的。
本文著重介紹另外一個(gè)特性:T.Setenv 和 B.Setenv。
從名字可以看出,這是設(shè)置環(huán)境變量用的。T 是單元測試,而 B 是基準(zhǔn)測試。
你可能會(huì)說,os 包不是有 Setenv 嗎?
os.Setenv 會(huì)影響當(dāng)前進(jìn)程的環(huán)境變量,而 T.Setenv 和 B.Setenv 只會(huì)影響當(dāng)前測試函數(shù)的環(huán)境變量,不會(huì)對其他測試函數(shù)造成影響。通過它們,可以做到每個(gè)測試有自己的獨(dú)立的環(huán)境變量。
Go 源碼中,有不少測試文件使用了這個(gè)新功能,比如:
func?TestImportVendor(t?*testing.T)?{
?testenv.MustHaveGoBuild(t)?//?really?must?just?have?source
?t.Setenv("GO111MODULE",?"off")
?ctxt?:=?Default
?wd,?err?:=?os.Getwd()
?if?err?!=?nil?{
??t.Fatal(err)
?}
?ctxt.GOPATH?=?filepath.Join(wd,?"testing/demo")
?p,?err?:=?ctxt.Import("c/d",?filepath.Join(ctxt.GOPATH,?"src/a/b"),?0)
?if?err?!=?nil?{
??t.Fatalf("cannot?find?vendored?c/d?from?testdata?src/a/b?directory:?%v",?err)
?}
?want?:=?"a/vendor/c/d"
?if?p.ImportPath?!=?want?{
??t.Fatalf("Import?succeeded?but?found?%q,?want?%q",?p.ImportPath,?want)
?}
}
具體源碼:https://github.com/golang/go/blob/891547e2d4bc2a23973e2c9f972ce69b2b48478e/src/go/build/build_test.go#L556。
如果你項(xiàng)目中的測試依賴環(huán)境變量,可以考慮使用這個(gè)新的函數(shù)。
注意:在 Parallel 測試中不能使用 Setenv。
