成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

Go test基礎用法大全

開發 后端
go 語言的 test 命令有很多參數,怎么利用 test 命令和它提供的參數,又能做到什么?本文做了詳細解讀。

[[442478]]

 go 語言的 test 命令有很多參數,怎么利用 test 命令和它提供的參數,又能做到什么?本文做了詳細解讀。

當直接使用IDE進行單元測試時,有沒有好奇它時如何實現的?比如GoLand寫的測試用例。

所有的代碼都需要寫測試用例。這不僅僅是對自己的代碼負責,也是對別人的負責。

最近工作中使用glog這個庫,因為它對外提供的方法都很簡單,想封裝處理一下。但卻遇到了點麻煩:這個包需要在命令行傳遞log_dir參數,來指定日志文件的路徑。

所以,正常運行的話,首先需要編譯可執行文件,然后命令行指定參數執行。如下示例: 

  1. go build main.go  
  2. ./main -log_dir="/data"    //當前目錄作為日志輸出目錄 

但在go test的時候,如何指定這個參數了?

Test

調查發現,發現go test也可以生成可執行文件。需要使用-c來指定。示例如下: 

  1. go test -c param_test_dir   //最后一個參數是待測試的目錄 

執行后就會發現:這樣的做法,會運行所有的Test用例。如何僅僅執行某一個測試用例了(編譯器到底是如何做到的?)。

這里有另一個屬性-run,用來指定執行的測試用例的匹配模式。舉個例子: 

  1. func TestGetRootLogger(t *testing.T) {  
  2.  writeLog("測試")  
  3.  
  4. func TestGetRootLogger2(t *testing.T) {  
  5.  writeLog("測試 2")  

當我在命令行明確匹配執行Logger2,運行的時候確實僅僅執行該測試用例 

  1. go test -v -run Logger2 ./util/     //-v 表示 verbose,輸出相信信息 

但是,我發現,在指定了c參數之后,run參數無法生效!這樣的話,還真是沒有好的辦法來處理這種情況。

option

  1. -timeout 

默認go test運行超過10m會發生panic。如果需要運行更長的時間,需要明確指定。將timeout指定為 0,用于忽略時間限制。 

  1. nohup go test -v -timeout 0 -run TestGetRange . > log.txt 

使用map的測試

可以結合使用閉包,設置期望值,來寫測試用例。Run函數內部是阻塞的,所以TestSum方法依次執行測試。

同時testSumFunc返回了test方法使用了閉包的特性,對返回函數內部的值是無法確定的。 

  1. func TestSum(t *testing.T) {  
  2.  t.Run("A", testSumFunc([]int{1, 2, 3}, 7))  
  3.  t.Run("B", testSumFunc([]int{2, 3, 4}, 8))  
  4.  
  5. func Sum(numbers []int) int {  
  6.  total :0  
  7.  for _, v :range numbers {  
  8.   total += v  
  9.  }  
  10.  return total  
  11.  
  12. func testSumFunc(numbers []int, expected int) func(t *testing.T) {  
  13.  return func(t *testing.T) {  
  14.   actual :Sum(numbers)  
  15.   if actual != expected {  
  16.    t.Error(fmt.Sprintf("Expected the sum of %v to be %d but instead got %d!", numbers, expected, actual))  
  17.   }  
  18.  } 

Main

非常簡單,看如下示例。這樣在執行任何test case時都首先執行準備,在測試用例執行完畢后,會運行清理工作。需要特別說明的是:flag.Parse()以及os.Exit(m.Run())是不可缺少的兩步。 

  1. func TestMain(m *testing.M) {  
  2.     //準備工作  
  3.  fmt.Println("start prepare")  
  4.  flag.Parse()  
  5.  exitCode :m.Run()  
  6.         //清理工作  
  7.  fmt.Println("prepare to clean")  
  8.   os.Exit(exitCode)  

性能測試pprof

定位服務是否存在資源泄漏或者濫用API的行為,光靠review代碼是不行的,最好能借助工具。

Profile

引用 godoc for pprof 描述:

A Profile is a collection of stack traces showing the call sequences that led to instances of a particular event, such as allocation. Packages can create and maintain their own profiles; the most common use is for tracking resources that must be explicitly closed, such as files or network connections.

性能測試涉及如下方面:

  1.  CPU Profiling:CPU分析,按照一定的頻率采集所監聽的應用程序CPU(含寄存器)的使用情況,可確定應用程序在主動消耗CPU 周期時花費時間的位置
  2.  Memory Profiling:內存分析,在應用程序進行堆分配時記錄堆棧跟蹤,用于監視當前和歷史內存使用情況,以及檢查內存泄漏
  3.  Block Profiling:阻塞分析,記錄 goroutine 阻塞等待同步(包括定時器通道)的位置
  4.  Mutex Profiling:互斥鎖分析,報告互斥鎖的競爭情況

在程序中引入如下包,便可以通過 web 方式查看性能情況,訪問的路徑為:/debug/pprof/,該路徑下會顯示多個查看項。該路徑下還有其他子頁面。 

  1. _ "net/http/pprof" 

關于/debug/pprof/下的子頁面:

  1.  $HOST/debug/pprof/profile
  2.  $HOST/debug/pprof/block
  3.  $HOST/debug/pprof/goroutine
  4.  $HOST/debug/pprof/heap
  5.  $HOST/debug/pprof/mutex
  6.  $HOST/debug/pprof/threadcreate

在終端查看性能

只要服務器在啟動時,引入pprof包,便可在終端獲取profile文件。如下所示: 

  1. pprof -seconds=10 http://192.168.77.77:3900/debug/pprof/profile 

如果獲取到cpu.prof文件,可以通過如下命令可視化查看運行結果,這是另一種格式的火焰圖,也是挺帥的: 

  1. ## 通過在瀏覽器中 localhost:1313 可以在 web 端查看  
  2. ##   
  3. pprof -http=:1313 cpu.prof  
  4. ## 或直接在終端查看  
  5. go tool pprof cpu.prof  
  6. $ web | top 

Benchmark測試

基本用法: 

  1. func BenchmarkBadgeRelationMapper_GetCountByUid(b *testing.B) {  
  2.  count :0  
  3.  for i :0; i < b.N; i++ {  
  4.   count++  
  5.  }  
  6.  fmt.Println("total:", count)  

bench測試輸出結果,函數體被重復執行了 6 次,并對b.N的值做了調整: 

  1. total: 1  
  2. total: 100  
  3. total: 10000  
  4. total: 1000000  
  5. total: 100000000  
  6. total: 1000000000  
  7. 1000000000          0.598 ns/op 

并發用法: 

  1. func BenchmarkBadgeRelationMapper_GetCountByUid(b *testing.B) {  
  2.  count :0  
  3.  b.RunParallel(func(pb *testing.PB) {  
  4.   for pb.Next() {  
  5.    count++  
  6.   }  
  7.  })  
  8.  fmt.Println("total:", count)  

輸出的結果: 

  1. total: 1  
  2. total: 100  
  3. total: 6336  
  4. total: 306207  
  5. total: 34221963  
  6. total: 129821900  
  7. 378966799          2.94 ns/op 

在并行用法中,b.N被RunParallel接管。

簡單分析一下源碼

核心思路在于Next方法,通過atomic.AddUint64并發安全的操作pb.globalN,pb.cache用來存儲該goroutine執行的次數。當某個goroutine計算到pb.bN<=n<=pb.bN+pb.grain時,雖然程序迭代次數已經完全超過b.N,但還是會讓它繼續執行。 

  1. // Next reports whether there are more iterations to execute.  
  2. func (pb *PB) Next() bool {  
  3.  if pb.cache == 0 {  
  4.   n :atomic.AddUint64(pb.globalN, pb.grain)  
  5.   if n <= pb.bN {  
  6.    pbpb.cache = pb.grain  
  7.   } else if n < pb.bN+pb.grain {  
  8.    pbpb.cache = pb.bN + pb.grain - n  
  9.   } else {  
  10.    return false  
  11.   }  
  12.  }  
  13.  pb.cache--  
  14.  return true  

regular expression

先列舉參考的example。在我們要運行特定case時,可以通過指定正則表達式來實現: 

  1. // -bench takes a regular expression that matches the names of the benchmarks you want to run  
  2. go test -bench=. ./examples/fib/  
  3. // -run flag with a regex that matches nothing  
  4. go test -run=^$ 

關于如何運行Benchmark測試,默認執行go test并不會執行Benchmark,需要在命令行明確加上-bench=標記,它接受一個表達式作為參數,匹配基準測試的函數,. 表示運行所有基準測試。 

  1. go test -bench=.  
  2. // 明確指定要運行哪個測試,傳遞一個正則表達式給 run 屬性,XXX=BenchmarkReceiveGift_GetGiftReceiveList  
  3. go test -run=XXX -bench=. 

默認情況下,benchmark最小運行時長為1s。如果benchmark函數執行返回,但1s的時間還沒有結束,b.N會根據某種機制依次遞增。可以通過參數-benchtime=20s來改變這種行為。

還有一個參數:benchmem。可以提供每次操作分配內存的次數,以及每次操作分配的字節數。

  1. go test -bench=Fib40 -benchtime=20s 

Run Example

獲取線上的pprof數據到本地,這里是另一個工具: 

  1. go-torch -u http://192.168.77.77:3900/debug/pprof/profile -t 10 

在Go 代碼調優利器-火焰圖這篇文章中,對例子介紹的挺精彩的。 

  1. ## 對函數 GetGiftReceiveList 進行 Benchmark 測試 因為只想壓測 GetGiftReceiveList 這個函數  
  2. ## 所以指定了 run 參數  
  3. go test -bench . -run=GetGiftReceiveList -benchmem -cpuprofile prof.cpu  
  4. ## 其中 present.test 是壓測的二進制文件,prof.cpu 也是生產的文件  
  5. ## (pprof) top10  
  6. ## (pprof) list Marshal 單獨查看這個函數的耗時,這里應該是正則匹配的  
  7. go tool pprof present.test prof.cpu  
  8. ## 查看內存使用情況  
  9. go test -bench . -benchmem -memprofile prof.mem  
  10. go tool pprof --alloc_objects  present.test prof.mem 

覆蓋率

跟執行go test不同的是,需要多加一個參數-coverprofile, 所以完整的命令: 

  1. go test -v -coverprofile=c.out 

生成報告有 go 為我們提供的工具,使用 

  1. go tool cover -html=c.out -o=tag.html 

即可生成一個名字為 tag.html 的 HTML 格式的測試覆蓋率報告,這里有詳細的信息告訴我們哪一行代碼測試到了,哪一行代碼沒有測試到。

火焰圖

學習了解火焰圖,分析函數調用棧的信息。主要是相關的工具: 

  1. ## tool1  
  2. git clone https://github.com/brendangregg/FlameGraph.git  
  3. cp flamegraph.pl /usr/local/bin  
  4. flamegraph.pl -h  
  5. go get -v github.com/uber/go-torch  
  6. go-torch -h  

 

責任編輯:龐桂玉 來源: 馬哥Linux運維
相關推薦

2010-07-20 12:52:26

Perl特殊變量

2010-07-19 15:01:26

Perl數學函數

2010-07-19 11:00:24

Perl操作符

2013-05-22 16:34:34

iOS開發String用法iOS筆記

2018-12-29 15:50:06

Python基礎知識編程語言

2010-07-16 11:22:31

Perl

2010-07-19 13:06:13

Perl二維數組

2021-10-12 13:35:30

C++Set紅黑樹

2011-01-17 10:57:55

思科認證

2020-12-02 09:10:22

Go結構數據類型

2023-12-30 10:22:57

Go語言函數開發

2023-08-07 14:28:07

SpringBoot工具

2010-07-23 13:16:07

Perl

2020-10-21 12:45:12

Redis數據結構

2010-08-31 10:57:44

clipCSS

2021-09-16 10:05:09

鴻蒙HarmonyOS應用

2021-06-09 09:06:52

Go語言算法

2021-02-06 18:19:54

TimeGo語言

2009-05-26 12:13:24

test

2009-05-26 12:14:34

test
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 午夜精品久久久久久久99黑人 | 五月激情婷婷在线 | 久久久久久久国产精品视频 | 午夜男人天堂 | 中文字幕一区二区视频 | 亚洲日本免费 | 久久久久91 | 91精品国产综合久久久久蜜臀 | 亚洲一区二区成人 | 亚洲一区二区三区免费视频 | 精品国产不卡一区二区三区 | 国产在线精品一区二区三区 | 日韩欧美视频网站 | 日本精品视频一区二区 | 成人九区 | 国产偷录视频叫床高潮对白 | 91久久久久久 | 精品国产视频 | 中文字幕国产视频 | 国产一级一级毛片 | av一二三四 | 超碰精品在线观看 | 丁香六月伊人 | 国产一级免费视频 | 一二区成人影院电影网 | 亚洲精品毛片av | 成人在线视频观看 | 999国产精品视频免费 | 国产一区二区三区四区三区四 | 亚洲在线观看视频 | 99久久婷婷国产综合精品电影 | 久久免费视频1 | 亚洲乱码一区二区三区在线观看 | 精品日韩一区二区 | 九九亚洲 | 国产香蕉视频在线播放 | 干干天天 | 欧美一区二区三区在线观看 | 亚洲成人精品 | 午夜久久av| 日韩a在线 |