go?test?命令示例詳解
1.簡介
go test 是 Go 用來執(zhí)行測試函數(shù)(test function)、基準(zhǔn)函數(shù)(benchmark function)和示例函數(shù)(example function)的命令。
執(zhí)行 go test 命令,它會在*_test.go
文件中尋找 test、benchmark 和 example 函數(shù)來執(zhí)行。測試函數(shù)名必須以 TestXXX 開頭,基準(zhǔn)函數(shù)名必須以 BenchmarkXXX 開頭,示例函數(shù)必須以 ExampleXXX 開頭。
// test 測試函數(shù) func TestXXX(t *testing.T) { ... } // benchmark 基準(zhǔn)函數(shù) func BenchmarkXXX(b *testing.B) { ... } // examples 示例函數(shù),其相關(guān)命名方式可以查看第一篇文章 func ExamplePrintln() { Println("The output of\nthis example.") // Output: The output of // this example. }
關(guān)于更多測試函數(shù)的信息請查看go help testfunc
。
命令格式如下:
go test [build/test flags] [packages] [build/test flags & test binary flags]
go test 自動測試指定的包。它以以下格式打印測試結(jié)果摘要:
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
然后是每個失敗包的詳細輸出。
go test 重新編譯每個包中后綴為_test.go
的文件。這些文件可以包含測試函數(shù)、基準(zhǔn)函數(shù)和示例函數(shù)。有關(guān)更多信息,請參閱“go help testfunc”。每個列出的包都會導(dǎo)致執(zhí)行一個單獨的測試二進制文件。注意名稱以_
或.
開頭的文件即使后綴是_test.go
將被忽略。
測試文件中如果聲明的包后綴為_test
將被作為單獨的包來編譯,然后與主測試二進制文件鏈接并運行。
go test 命令還會忽略 testdata 目錄,該目錄用來保存測試需要用到的輔助數(shù)據(jù)。
go test 有兩種運行模式:
(1)本地目錄模式,在沒有包參數(shù)(如 go test 或 go test -v)調(diào)用時發(fā)生。在此模式下,go test 編譯當(dāng)前目錄中找到的包和測試,然后運行測試二進制文件。在這種模式下,caching 是禁用的。在包測試完成后,go test 打印一個概要行,顯示測試狀態(tài)、包名和運行時間。
(2)包列表模式,在使用顯示包參數(shù)調(diào)用 go test 時發(fā)生(例如 go test math,go test ./… 甚至是 go test .)。在此模式下,go 測試編譯并測試在命令上列出的每個包。如果一個包測試通過,go test 只打印最終的 ok 總結(jié)行。如果一個包測試失敗,go test 將輸出完整的測試輸出。如果使用 -bench 或 -v 選項,則 go test 會輸出完整的輸出,甚至是通過包測試,以顯示所請求的基準(zhǔn)測試結(jié)果或詳細日志記錄。
注意: 描述軟件包列表時,命令使用三個點作為通配符。如測試當(dāng)前目錄及其子目錄中的所有軟件包。
go test ./...
僅在包列表模式下,go test 會緩存成功的包測試結(jié)果,以避免不必要的重復(fù)運行測試。當(dāng)測試結(jié)果可以從緩存中恢復(fù)時,go tes t將重新顯示以前的輸出,而不是再次運行測試二進制文件。發(fā)生這種情況時,go test 打印 “(cached)” 以代替摘要行中的已用時間。
緩存中匹配的規(guī)則是,運行涉及相同的測試二進制文件,命令行上的選項完全來自一組受限的“可緩存”測試選項,定義為 -benchtime、-cpu、-list、-parallel、-run、-short 和 -v。如果運行 go test 時任何測試選項或非測試選項在此集合之外,則不會緩存結(jié)果。要禁用緩存,請使用除可緩存選項之外的任何測試選項或參數(shù)。明確禁用測試緩存的慣用方法是使用 -count=1。測試在包的根目錄(通常為 $GOPATH)打開的文件和依賴的環(huán)境變量,只有不發(fā)生變化時才能匹配緩存。
被緩存的測試結(jié)果將被視為立即執(zhí)行,因此無論 -timeout 如何設(shè)置,成功的包測試結(jié)果都將被緩存和重用。
2.test flag
除 build 選項外,go test 本身處理的選項包括:
-args Pass the remainder of the command line (everything after -args) to the test binary, uninterpreted and unchanged. Because this flag consumes the remainder of the command line, the package list (if present) must appear before this flag. -c Compile the test binary to pkg.test but do not run it (where pkg is the last element of the package's import path). The file name can be changed with the -o flag. -exec xprog Run the test binary using xprog. The behavior is the same as in 'go run'. See 'go help run' for details. -i Install packages that are dependencies of the test. Do not run the test. The -i flag is deprecated. Compiled packages are cached automatically. -json Convert test output to JSON suitable for automated processing. See 'go doc test2json' for the encoding details. -o file Compile the test binary to the named file. The test still runs (unless -c or -i is specified).
有關(guān)構(gòu)建選項的更多信息,請參閱“go help build”。有關(guān)指定軟件包的更多信息,請參閱“go help packages”。
3.test/binary flags
以下選項同時支持測試二進制文件和 go test 命令。
主要分為兩類,一類控制測試行為,一類用于狀態(tài)分析。
控制測試行為選項:
-bench regexp Run only those benchmarks matching a regular expression. By default, no benchmarks are run. To run all benchmarks, use '-bench .' or '-bench=.'. The regular expression is split by unbracketed slash (/) characters into a sequence of regular expressions, and each part of a benchmark's identifier must match the corresponding element in the sequence, if any. Possible parents of matches are run with b.N=1 to identify sub-benchmarks. For example, given -bench=X/Y, top-level benchmarks matching X are run with b.N=1 to find any sub-benchmarks matching Y, which are then run in full. -benchtime t Run enough iterations of each benchmark to take t, specified as a time.Duration (for example, -benchtime 1h30s). The default is 1 second (1s). The special syntax Nx means to run the benchmark N times (for example, -benchtime 100x). -count n Run each test and benchmark n times (default 1). If -cpu is set, run n times for each GOMAXPROCS value. Examples are always run once. -cover Enable coverage analysis. Note that because coverage works by annotating the source code before compilation, compilation and test failures with coverage enabled may report line numbers that don't correspond to the original sources. -covermode set,count,atomic Set the mode for coverage analysis for the package[s] being tested. The default is "set" unless -race is enabled, in which case it is "atomic". The values: set: bool: does this statement run? count: int: how many times does this statement run? atomic: int: count, but correct in multithreaded tests; significantly more expensive. Sets -cover. -coverpkg pattern1,pattern2,pattern3 Apply coverage analysis in each test to packages matching the patterns. The default is for each test to analyze only the package being tested. See 'go help packages' for a description of package patterns. Sets -cover. -cpu 1,2,4 Specify a list of GOMAXPROCS values for which the tests or benchmarks should be executed. The default is the current value of GOMAXPROCS. -failfast Do not start new tests after the first test failure. -list regexp List tests, benchmarks, or examples matching the regular expression. No tests, benchmarks or examples will be run. This will only list top-level tests. No subtest or subbenchmarks will be shown. -parallel n Allow parallel execution of test functions that call t.Parallel. The value of this flag is the maximum number of tests to run simultaneously; by default, it is set to the value of GOMAXPROCS. Note that -parallel only applies within a single test binary. The 'go test' command may run tests for different packages in parallel as well, according to the setting of the -p flag (see 'go help build'). -run regexp Run only those tests and examples matching the regular expression. For tests, the regular expression is split by unbracketed slash (/) characters into a sequence of regular expressions, and each part of a test's identifier must match the corresponding element in the sequence, if any. Note that possible parents of matches are run too, so that -run=X/Y matches and runs and reports the result of all tests matching X, even those without sub-tests matching Y, because it must run them to look for those sub-tests. -short Tell long-running tests to shorten their run time. It is off by default but set during all.bash so that installing the Go tree can run a sanity check but not spend time running exhaustive tests. -shuffle off,on,N Randomize the execution order of tests and benchmarks. It is off by default. If -shuffle is set to on, then it will seed the randomizer using the system clock. If -shuffle is set to an integer N, then N will be used as the seed value. In both cases, the seed will be reported for reproducibility. -timeout d If a test binary runs longer than duration d, panic. If d is 0, the timeout is disabled. The default is 10 minutes (10m). -v Verbose output: log all tests as they are run. Also print all text from Log and Logf calls even if the test succeeds. -vet list Configure the invocation of "go vet" during "go test" to use the comma-separated list of vet checks. If list is empty, "go test" runs "go vet" with a curated list of checks believed to be always worth addressing. If list is "off", "go test" does not run "go vet" at all.
狀態(tài)分析選項:
-benchmem Print memory allocation statistics for benchmarks. -blockprofile block.out Write a goroutine blocking profile to the specified file when all tests are complete. Writes test binary as -c would. -blockprofilerate n Control the detail provided in goroutine blocking profiles by calling runtime.SetBlockProfileRate with n. See 'go doc runtime.SetBlockProfileRate'. The profiler aims to sample, on average, one blocking event every n nanoseconds the program spends blocked. By default, if -test.blockprofile is set without this flag, all blocking events are recorded, equivalent to -test.blockprofilerate=1. -coverprofile cover.out Write a coverage profile to the file after all tests have passed. Sets -cover. -cpuprofile cpu.out Write a CPU profile to the specified file before exiting. Writes test binary as -c would. -memprofile mem.out Write an allocation profile to the file after all tests have passed. Writes test binary as -c would. -memprofilerate n Enable more precise (and expensive) memory allocation profiles by setting runtime.MemProfileRate. See 'go doc runtime.MemProfileRate'. To profile all memory allocations, use -test.memprofilerate=1. -mutexprofile mutex.out Write a mutex contention profile to the specified file when all tests are complete. Writes test binary as -c would. -mutexprofilefraction n Sample 1 in n stack traces of goroutines holding a contended mutex. -outputdir directory Place output files from profiling in the specified directory, by default the directory in which "go test" is running. -trace trace.out Write an execution trace to the specified file before exiting.
4.常用選項
-bench regexp 只執(zhí)行匹配對應(yīng)正則表達式的 benchmark 函數(shù),如執(zhí)行所有性能測試 "-bench ." 或 "-bench=." -benchtime t 對每個 benchmark 函數(shù)運行指定時間。如 -benchtime 1h30,默認(rèn)值為 1s。特殊語法 Nx 表示運行基準(zhǔn)測試 N 次(如 -benchtime 100x) -run regexp 只運行匹配對應(yīng)正則表達式的 test 和 example 函數(shù),例如 "-run Array" 那么就執(zhí)行函數(shù)名包含 Array 的單測函數(shù) -cover 開啟測試覆蓋率 -v 顯示測試的詳細命令
5.示例
假設(shè)在文件 add.go 有一個被測試函數(shù)
package hello func Add(a, b int) int { return a + b }
測試函數(shù)(test function)
在測試文件 add_test.go 添加一個單元測試函數(shù) TestAdd:
package hello func TestAdd(t *testing.T) { sum := Add(5, 5) if sum == 10 { t.Log("the result is ok") } else { t.Fatal("the result is wrong") } }
比如使用 -run 來運行指定單元測試函數(shù),發(fā)現(xiàn)只運行了 TestAdd 測試函數(shù)。
go test -v -run TestAdd main/hello === RUN TestAdd add_test.go:16: the result is ok --- PASS: TestAdd (0.00s) PASS ok main/hello 0.170s
基準(zhǔn)函數(shù)(benchmark function)
添加一個性能測試函數(shù) BenchmarkAdd:
package hello func BenchmarkAdd(b *testing.B) { for n := 0; n < b.N; n++ { Add(1, 2) } }
運行指定基準(zhǔn)函數(shù):
go test -bench BenchmarkAdd main/hello goos: windows goarch: amd64 pkg: main/contain cpu: Intel(R) Core(TM) i7-9700 CPU @ 3.00GHz BenchmarkAdd-8 1000000000 0.2333 ns/op PASS ok main/contain 0.586s
示例函數(shù)(example function)
package hello func ExampleAdd() { fmt.Println(Add(1, 2)) // Output: 3 }
運行指定示例函數(shù):
go test -v -run ExampleAdd main/contain === RUN ExampleAdd --- PASS: ExampleAdd (0.00s) PASS ok main/contain (cached)
注意: 示例函數(shù)類似于測試函數(shù),但不是使用 *testing.T 來報告成功或失敗,而是將輸出打印到 os.Stdout。如果示例函數(shù)中的最后一條注釋以“Output:”開頭,則將輸出與注釋進行精確比較(參見上面的示例)。如果最后一條注釋以“Unordered output:”開頭,則將輸出與注釋進行比較,但忽略行的順序。編譯了一個沒有此類注釋的示例函數(shù),會被編譯但不會被執(zhí)行。如果在“Output:”之后沒有文本,示例函數(shù)仍會被編譯并執(zhí)行,并且預(yù)期不會產(chǎn)生任何輸出。
獲取每個函數(shù)的單測覆蓋率。
如果您想查找沒有被測試覆蓋的函數(shù),可以使用 -coverprofile 選項將覆蓋率報告輸出到文件中。
go test -coverprofile cover.out ./...
然后使用內(nèi)置的 go tool cover 命令來查看單測覆蓋率報告。
go tool cover -func cover.out
上面使用 -func 選項可以輸出每個函數(shù)的單測覆蓋率概要信息。
github.com/dablelv/cyan/cmp/cmp.go:21: Cmp 100.0% github.com/dablelv/cyan/cmp/cmp.go:35: Compare 95.5% github.com/dablelv/cyan/cmp/cmp.go:85: CompareLT 0.0% ...
查看具體代碼行的覆蓋情況。
如果想查看代碼行的單測覆蓋情況,可以使用內(nèi)置的 go tool cover 命令將覆蓋率報告轉(zhuǎn)換為 HTML 文件。然后通過瀏覽器打開查看。
go tool cover -html=coverage.out -o coverage.html
參考文獻
Command Documentation
go command documentation
到此這篇關(guān)于go test 命令示例詳解的文章就介紹到這了,更多相關(guān)go test 命令內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux中用shell快速安裝配置Go語言的開發(fā)環(huán)境
相信每位開發(fā)者都知道選擇一門開發(fā)語言,免不了需要安裝配置開發(fā)環(huán)境,所以這篇文章給大家分享了linux下使用shell一鍵安裝配置GO語言開發(fā)環(huán)境的方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。2016-10-10golang實現(xiàn)openssl自簽名雙向認(rèn)證的詳細步驟
這篇文章主要介紹了golang實現(xiàn)openssl自簽名雙向認(rèn)證的詳細步驟,本文分步驟給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-03-03利用golang實現(xiàn)封裝trycatch異常處理實例代碼
Go語言追求簡潔優(yōu)雅,所以go語言不支持傳統(tǒng)的 try…catch…finally 這種異常,最近發(fā)現(xiàn)了不錯的trycatch包,下面這篇文章主要跟大家分享了關(guān)于利用golang實現(xiàn)封裝trycatch異常處理的實例代碼,需要的朋友可以參考下。2017-07-07一文搞懂Golang文件操作增刪改查功能(基礎(chǔ)篇)
這篇文章主要介紹了一文搞懂Golang文件操作增刪改查功能(基礎(chǔ)篇),Golang 可以認(rèn)為是服務(wù)器開發(fā)語言發(fā)展的趨勢之一,特別是在流媒體服務(wù)器開發(fā)中,已經(jīng)占有一席之地,今天我們不聊特別深奧的機制和內(nèi)容,就來聊一聊 Golang 對于文件的基本操作2021-04-04使用golang腳本基于kubeadm創(chuàng)建新的token(問題分析)
這篇文章主要介紹了使用golang腳本基于kubeadm創(chuàng)建新的token(問題分析),本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-10-10Golang實現(xiàn)http server提供壓縮文件下載功能
這篇文章主要介紹了Golang實現(xiàn)http server提供壓縮文件下載功能,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01