go test 和benchamark如何只對指定方法進行測試?

go test

demo_test.gonginx

func TestDemo1(t *testing.T) {
	t.Log("test1")
}

func TestDemo2(t *testing.T) {
	t.Log("test2")
}

func BenchmarkDemo3(b *testing.B) {
	b.Log("benchmark1")
}

func BenchmarkDemo4(b *testing.B) {
	b.Log("benchmark2")
}
複製代碼
  • 如何只對TestDemo1測試?
go test -v  demo_test.go -test.run Demo1
複製代碼
  • 輸出
$ go test -v  demo_test.go -test.run Demo1
=== RUN   TestDemo1
--- PASS: TestDemo1 (0.00s)
    demo_test.go:13: test1
PASS
ok      command-line-arguments  (cached)

複製代碼

go benchmark

  • 那如何只對benchMarkDemo3作性能測試呢?
go test -v  demo_test.go -test.bench Demo3 -test.run Demo3
複製代碼
  • 輸出
$ go test -v  demo_test.go -test.bench Demo3 -test.run Demo3
goos: windows
goarch: amd64
BenchmarkDemo3-12       2000000000               0.00 ns/op
--- BENCH: BenchmarkDemo3-12
    demo_test.go:21: benchmark1
    demo_test.go:21: benchmark1
    demo_test.go:21: benchmark1
    demo_test.go:21: benchmark1
    demo_test.go:21: benchmark1
    demo_test.go:21: benchmark1
PASS

複製代碼

go test 參數解讀

go test [-c] [-i] [build/test flags] [packages] [build/test flags & test binary flags]
複製代碼

參數解讀:

-c : 編譯go test成爲可執行的二進制文件,可是不運行測試。

-i : 安裝測試包依賴的package,可是不運行測試。

關於build flags,調用go help build,這些是編譯運行過程當中須要使用到的參數,通常設置爲空

關於packages,調用go help packages,這些是關於包的管理,通常設置爲空

關於flags for test binary,調用go help testflag,這些是go test過程當中常常使用到的參數

-test.v : 是否輸出所有的單元測試用例(無論成功或者失敗),默認沒有加上,因此只輸出失敗的單元測試用例。

-test.run pattern: 只跑哪些單元測試用例

-test.bench patten: 只跑那些性能測試用例

-test.benchmem : 是否在性能測試的時候輸出內存狀況

-test.benchtime t : 性能測試運行的時間,默認是1s

-test.cpuprofile cpu.out : 是否輸出cpu性能分析文件

-test.memprofile mem.out : 是否輸出內存性能分析文件

-test.blockprofile block.out : 是否輸出內部goroutine阻塞的性能分析文件

-test.memprofilerate n : 內存性能分析的時候有一個分配了多少的時候纔打點記錄的問題。這個參數就是設置打點的內存分配間隔,也就是profile中一個sample表明的內存大小。默認是設置爲512 * 1024的。若是你將它設置爲1,則每分配一個內存塊就會在profile中有個打點,那麼生成的profile的sample就會很是多。若是你設置爲0,那就是不作打點了。

你能夠經過設置memprofilerate=1和GOGC=off來關閉內存回收,而且對每一個內存塊的分配進行觀察。

-test.blockprofilerate n: 基本同上,控制的是goroutine阻塞時候打點的納秒數。默認不設置就至關於-test.blockprofilerate=1,每一納秒都打點記錄一下

-test.parallel n : 性能測試的程序並行cpu數,默認等於GOMAXPROCS。

-test.timeout t : 若是測試用例運行時間超過t,則拋出panic

-test.cpu 1,2,4 : 程序運行在哪些CPU上面,使用二進制的1所在位表明,和nginx的nginx_worker_cpu_affinity是一個道理

-test.short : 將那些運行時間較長的測試用例運行時間縮短
複製代碼
相關文章
相關標籤/搜索