1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        Go1.17 新特性:testing 包的相關(guān)變化

        共 1585字,需瀏覽 4分鐘

         ·

        2021-10-08 21:23

        閱讀本文大概需要 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 這個 flag,1.17 還未發(fā)布時,我就寫過文章介紹:Go1.17這個新特性竟然是6年前提出來的。關(guān)于它的作用,記住關(guān)鍵一點:我們寫測試時,測試之間別相互依賴,應(yīng)該是獨立的。

        本文著重介紹另外一個特性:T.Setenv 和 B.Setenv。

        從名字可以看出,這是設(shè)置環(huán)境變量用的。T 是單元測試,而 B 是基準(zhǔn)測試。

        你可能會說,os 包不是有 Setenv 嗎?

        os.Setenv 會影響當(dāng)前進程的環(huán)境變量,而 T.Setenv 和 B.Setenv 只會影響當(dāng)前測試函數(shù)的環(huán)境變量,不會對其他測試函數(shù)造成影響。通過它們,可以做到每個測試有自己的獨立的環(huán)境變量。

        Go 源碼中,有不少測試文件使用了這個新功能,比如:

        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。

        如果你項目中的測試依賴環(huán)境變量,可以考慮使用這個新的函數(shù)。

        注意:在 Parallel 測試中不能使用 Setenv。




        往期推薦


        福利

        我為大家整理了一份從入門到進階的Go學(xué)習(xí)資料禮包,包含學(xué)習(xí)建議:入門看什么,進階看什么。關(guān)注公眾號 「polarisxu」,回復(fù)?ebook?獲?。贿€可以回復(fù)「進群」,和數(shù)萬 Gopher 交流學(xué)習(xí)。

        瀏覽 41
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        評論
        圖片
        表情
        推薦
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

        分享
        舉報
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            天天操人人妻 | 嗯~用力啊~嗯~c我~鑫 | 美女让男人插 | 美女无遮挡撒尿 | 亚洲色的 | 久久人人添人人爽添人人88v | 国产搞黄色 | 中国女人丰满毛片 | 国产探花 在线观看 | 免费在线看黄色 |