Golang 單元測試和效能測試

來源:互聯網
上載者:User

開發程式其中很重要的一點是測試,我們如何保證代碼的品質,如何保證每個函數是可運行,運行結果是正確的,又如何保證寫出來的代碼效能是好的,我們知道單元測試的重點在於發現程式設計或實現的邏輯錯誤,使問題及早暴露,便於問題的定位解決,而效能測試的重點在於發現程式設計上的一些問題,讓線上的程式能夠在高並發的情況下還能保持穩定。本小節將帶著這一連串的問題來講解Go語言中如何來實現單元測試和效能測試。

Go語言中內建有一個輕量級的測試架構testing和內建的go test命令來實現單元測試和效能測試,testing架構和其他語言中的測試架構類似,你可以基於這個架構寫針對相應函數的測試案例,也可以基於該架構寫相應的壓力測試用例,那麼接下來讓我們一一來看一下怎麼寫。 如何編寫測試案例

由於go test命令只能在一個相應的目錄下執行所有檔案,所以我們接下來建立一個項目目錄gotest,這樣我們所有的代碼和測試代碼都在這個目錄下。

接下來我們在該目錄下面建立兩個檔案:gotest.go和gotest_test.go

gotest.go:這個檔案裡面我們是建立了一個包,裡面有一個函數實現了除法運算:

package gotestimport (    "errors")func Division(a, b float64) (float64, error) {    if b == 0 {        return 0, errors.New("除數不能為0")    }    return a / b, nil}

gotest_test.go:這是我們的單元測試檔案,但是記住下面的這些原則: 檔案名稱必須是_test.go結尾的,這樣在執行go test的時候才會執行到相應的代碼 你必須import testing這個包 所有的測試案例函數必須是Test開頭 測試案例會按照原始碼中寫的順序依次執行 測試函數TestXxx()的參數是testing.T,我們可以使用該類型來記錄錯誤或者是測試狀態 測試格式:func TestXxx (t *testing.T),Xxx部分可以為任意的字母數位組合,但是首字母不能是小寫字母[a-z],例如Testintdiv是錯誤的函數名。 函數中通過調用testing.T的Error, Errorf, FailNow, Fatal, FatalIf方法,說明測試不通過,調用Log方法用來記錄測試的資訊。

下面是我們的測試案例的代碼:

package gotestimport (    "testing")func Test_Division_1(t *testing.T) {    if i, e := Division(6, 2); i != 3 || e != nil { //try a unit test on function        t.Error("除法函數測試沒通過") // 如果不是如預期的那麼就報錯    } else {        t.Log("第一個測試通過了") //記錄一些你期望記錄的資訊    }}func Test_Division_2(t *testing.T) {    t.Error("就是不通過")}

我們在項目目錄下面執行go test,就會顯示如下資訊:

--- FAIL: Test_Division_2 (0.00 seconds)    gotest_test.go:16: 就是不通過FAILexit status 1FAIL    gotest  0.013s

從這個結果顯示測試沒有通過,因為在第二個測試函數中我們寫死了測試不通過的代碼t.Error,那麼我們的第一個函數執行的情況怎麼樣呢。預設情況下執行go test是不會顯示測試通過的資訊的,我們需要帶上參數go test -v,這樣就會顯示如下資訊:

=== RUN Test_Division_1--- PASS: Test_Division_1 (0.00 seconds)    gotest_test.go:11: 第一個測試通過了=== RUN Test_Division_2--- FAIL: Test_Division_2 (0.00 seconds)    gotest_test.go:16: 就是不通過FAILexit status 1FAIL    gotest  0.012s

上面的輸出詳細的展示了這個測試的過程,我們看到測試函數1Test_Division_1測試通過,而測試函數2Test_Division_2測試失敗了,最後得出結論測試不通過。接下來我們把測試函數2修改成如下代碼:

func Test_Division_2(t *testing.T) {    if _, e := Division(6, 0); e == nil { //try a unit test on function        t.Error("Division did not work as expected.") // 如果不是如預期的那麼就報錯    } else {        t.Log("one test passed.", e) //記錄一些你期望記錄的資訊    }}   

然後我們執行go test -v,就顯示如下資訊,測試通過了:

=== RUN Test_Division_1--- PASS: Test_Division_1 (0.00 seconds)    gotest_test.go:11: 第一個測試通過了=== RUN Test_Division_2--- PASS: Test_Division_2 (0.00 seconds)    gotest_test.go:20: one test passed. 除數不能為0PASSok      gotest  0.013s
如何編寫壓力測試

壓力測試用來檢測函數(方法)的效能,和編寫單元功能測試的方法類似,此處不再贅述,但需要注意以下幾點:

壓力測試用例必須遵循如下格式,其中XXX可以是任意字母數位組合,但是首字母不能是小寫字母

func BenchmarkXXX(b *testing.B) { ... }

go test不會預設執行壓力測試的函數,如果要執行壓力測試需要帶上參數-test.bench,文法:-test.bench="test_name_regex",例如go test -test.bench=".*"表示測試全部的壓力測試函數 在壓力測試用例中,請記得在迴圈體內使用testing.B.N,以使測試可以正常的運行 檔案名稱也必須以_test.go結尾

下面我們建立一個壓力測試檔案webbench_test.go,代碼如下所示:

package gotestimport (    "testing")func Benchmark_Division(b *testing.B) {    for i := 0; i < b.N; i++ { //use b.N for looping         Division(4, 5)    }}func Benchmark_TimeConsumingFunction(b *testing.B) {    b.StopTimer() //調用該函數停止壓力測試的時間計數    //做一些初始化的工作,例如讀取檔案資料,資料庫連接之類的,    //這樣這些時間不影響我們測試函數本身的效能    b.StartTimer() //重新開始時間    for i := 0; i < b.N; i++ {        Division(4, 5)    }}

我們執行命令go test -test.bench=".*",可以看到如下結果:

 

PASSBenchmark_Division  500000000            7.76 ns/opBenchmark_TimeConsumingFunction 500000000            7.80 ns/opok      gotest  9.364s  

上面的結果顯示我們沒有執行任何TestXXX的單元測試函數,顯示的結果只執行了壓力測試函數,第一條顯示了Benchmark_Division執行了500000000次,每次的執行平均時間是7.76納秒,第二條顯示了Benchmark_TimeConsumingFunction執行了500000000,每次的平均執行時間是7.80納秒。最後一條顯示總共的執行時間。

我們執行命令go test -test.bench=".*" -count=5,可以看到如下結果: (使用-count可以指定執行多少次)

 

PASSBenchmark_Division-2                 300000000             4.60 ns/opBenchmark_Division-2                 300000000             4.57 ns/opBenchmark_Division-2                 300000000             4.63 ns/opBenchmark_Division-2                 300000000             4.60 ns/opBenchmark_Division-2                 300000000             4.63 ns/opBenchmark_TimeConsumingFunction-2    300000000             4.64 ns/opBenchmark_TimeConsumingFunction-2    300000000             4.61 ns/opBenchmark_TimeConsumingFunction-2    300000000             4.60 ns/opBenchmark_TimeConsumingFunction-2    300000000             4.59 ns/opBenchmark_TimeConsumingFunction-2    300000000             4.60 ns/opok      _/home/diego/GoWork/src/app/testing    18.546s

 

go test -run=檔案名稱字 -bench=bench名字 -cpuprofile=生產的cprofile檔案名稱 檔案夾

 

例子:

testBenchMark下有個popcnt檔案夾,popcnt中有檔案popcunt_test.go

➜  testBenchMark lspopcnt

popcunt_test.go的問價內容:

ackage popcntimport (    "testing")const m1 = 0x5555555555555555const m2 = 0x3333333333333333const m4 = 0x0f0f0f0f0f0f0f0fconst h01 = 0x0101010101010101func popcnt(x uint64) uint64 {    x -= (x >> 1) & m1    x = (x & m2) + ((x >> 2) & m2)    x = (x + (x >> 4)) & m4    return (x * h01) >> 56}func BenchmarkPopcnt(b *testing.B) {    for i := 0; i < b.N; i++ {        x := i        x -= (x >> 1) & m1        x = (x & m2) + ((x >> 2) & m2)        x = (x + (x >> 4)) & m4        _ = (x * h01) >> 56    }}

然後運行go test -bench=".*" -cpuprofile=cpu.profile ./popcnt

 

➜  testBenchMark go test -bench=".*" -cpuprofile=cpu.profile ./popcnttesting: warning: no tests to runPASSBenchmarkPopcnt-8    1000000000             2.01 ns/opok      app/testBenchMark/popcnt    2.219s➜  testBenchMark lltotal 6704drwxr-xr-x  5 diego  staff      170  5  6 13:57 .drwxr-xr-x  3 diego  staff      102  5  6 11:12 ..-rw-r--r--  1 diego  staff     5200  5  6 13:57 cpu.profiledrwxr-xr-x  4 diego  staff      136  5  6 11:47 popcnt-rwxr-xr-x  1 diego  staff  3424176  5  6 13:57 popcnt.test➜  testBenchMark

生產 cpu.profile問價和popcnt.test 檔案

➜  testBenchMark lltotal 6704drwxr-xr-x  5 diego  staff      170  5  6 13:57 .drwxr-xr-x  3 diego  staff      102  5  6 11:12 ..-rw-r--r--  1 diego  staff     5200  5  6 13:57 cpu.profiledrwxr-xr-x  3 diego  staff      102  5  6 14:01 popcnt-rwxr-xr-x  1 diego  staff  3424176  5  6 13:57 popcnt.test➜  testBenchMark
go tool pprof popcnt.test cpu.profile 進入互動模式
➜  testBenchMark go tool pprof popcnt.test cpu.profileEntering interactive mode (type "help" for commands)(pprof) top1880ms of 1880ms total (  100%)      flat  flat%   sum%        cum   cum%    1790ms 95.21% 95.21%     1790ms 95.21%  app/testBenchMark/popcnt.BenchmarkPopcnt      90ms  4.79%   100%       90ms  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.