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)變化

        共 2043字,需瀏覽 5分鐘

         ·

        2021-09-12 10:13

        閱讀本文大概需要 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。




        往期推薦


        我是 polarisxu,北大碩士畢業(yè),曾在 360 等知名互聯(lián)網(wǎng)公司工作,10多年技術(shù)研發(fā)與架構(gòu)經(jīng)驗!2012 年接觸 Go 語言并創(chuàng)建了 Go 語言中文網(wǎng)!著有《Go語言編程之旅》、開源圖書《Go語言標(biāo)準(zhǔn)庫》等。


        堅持輸出技術(shù)(包括 Go、Rust 等技術(shù))、職場心得和創(chuàng)業(yè)感悟!歡迎關(guān)注「polarisxu」一起成長!也歡迎加我微信好友交流:gopherstudio


        瀏覽 20
        點贊
        評論
        收藏
        分享

        手機掃一掃分享

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

        手機掃一掃分享

        分享
        舉報
        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>
            美女福利在线观看 | 国产黄a三级三级三 | 成人无码区免费视频网站入口 | 十八禁网站免费观看 | 国产欧美一区二区三区在线看蜜臀 | 啊灬啊灬啊灬快灬高潮了玉子 | 午夜成人一区二区三区影院在线 | 在线观看网址你懂的 | 国产一区二区大鸡巴操女女在线视频91 | 无码破解成人免费一区 |