go?test?命令示例詳解
1.簡(jiǎn)介
go test 是 Go 用來(lái)執(zhí)行測(cè)試函數(shù)(test function)、基準(zhǔn)函數(shù)(benchmark function)和示例函數(shù)(example function)的命令。
執(zhí)行 go test 命令,它會(huì)在*_test.go
文件中尋找 test、benchmark 和 example 函數(shù)來(lái)執(zhí)行。測(cè)試函數(shù)名必須以 TestXXX 開(kāi)頭,基準(zhǔn)函數(shù)名必須以 BenchmarkXXX 開(kāi)頭,示例函數(shù)必須以 ExampleXXX 開(kāi)頭。
// test 測(cè)試函數(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)于更多測(cè)試函數(shù)的信息請(qǐng)查看go help testfunc
。
命令格式如下:
go test [build/test flags] [packages] [build/test flags & test binary flags]
go test 自動(dòng)測(cè)試指定的包。它以以下格式打印測(cè)試結(jié)果摘要:
ok archive/tar 0.011s
FAIL archive/zip 0.022s
ok compress/gzip 0.033s
...
然后是每個(gè)失敗包的詳細(xì)輸出。
go test 重新編譯每個(gè)包中后綴為_test.go
的文件。這些文件可以包含測(cè)試函數(shù)、基準(zhǔn)函數(shù)和示例函數(shù)。有關(guān)更多信息,請(qǐng)參閱“go help testfunc”。每個(gè)列出的包都會(huì)導(dǎo)致執(zhí)行一個(gè)單獨(dú)的測(cè)試二進(jìn)制文件。注意名稱(chēng)以_
或.
開(kāi)頭的文件即使后綴是_test.go
將被忽略。
測(cè)試文件中如果聲明的包后綴為_test
將被作為單獨(dú)的包來(lái)編譯,然后與主測(cè)試二進(jìn)制文件鏈接并運(yùn)行。
go test 命令還會(huì)忽略 testdata 目錄,該目錄用來(lái)保存測(cè)試需要用到的輔助數(shù)據(jù)。
go test 有兩種運(yùn)行模式:
(1)本地目錄模式,在沒(méi)有包參數(shù)(如 go test 或 go test -v)調(diào)用時(shí)發(fā)生。在此模式下,go test 編譯當(dāng)前目錄中找到的包和測(cè)試,然后運(yùn)行測(cè)試二進(jìn)制文件。在這種模式下,caching 是禁用的。在包測(cè)試完成后,go test 打印一個(gè)概要行,顯示測(cè)試狀態(tài)、包名和運(yùn)行時(shí)間。
(2)包列表模式,在使用顯示包參數(shù)調(diào)用 go test 時(shí)發(fā)生(例如 go test math,go test ./… 甚至是 go test .)。在此模式下,go 測(cè)試編譯并測(cè)試在命令上列出的每個(gè)包。如果一個(gè)包測(cè)試通過(guò),go test 只打印最終的 ok 總結(jié)行。如果一個(gè)包測(cè)試失敗,go test 將輸出完整的測(cè)試輸出。如果使用 -bench 或 -v 選項(xiàng),則 go test 會(huì)輸出完整的輸出,甚至是通過(guò)包測(cè)試,以顯示所請(qǐng)求的基準(zhǔn)測(cè)試結(jié)果或詳細(xì)日志記錄。
注意: 描述軟件包列表時(shí),命令使用三個(gè)點(diǎn)作為通配符。如測(cè)試當(dāng)前目錄及其子目錄中的所有軟件包。
go test ./...
僅在包列表模式下,go test 會(huì)緩存成功的包測(cè)試結(jié)果,以避免不必要的重復(fù)運(yùn)行測(cè)試。當(dāng)測(cè)試結(jié)果可以從緩存中恢復(fù)時(shí),go tes t將重新顯示以前的輸出,而不是再次運(yùn)行測(cè)試二進(jìn)制文件。發(fā)生這種情況時(shí),go test 打印 “(cached)” 以代替摘要行中的已用時(shí)間。
緩存中匹配的規(guī)則是,運(yùn)行涉及相同的測(cè)試二進(jìn)制文件,命令行上的選項(xiàng)完全來(lái)自一組受限的“可緩存”測(cè)試選項(xiàng),定義為 -benchtime、-cpu、-list、-parallel、-run、-short 和 -v。如果運(yùn)行 go test 時(shí)任何測(cè)試選項(xiàng)或非測(cè)試選項(xiàng)在此集合之外,則不會(huì)緩存結(jié)果。要禁用緩存,請(qǐng)使用除可緩存選項(xiàng)之外的任何測(cè)試選項(xiàng)或參數(shù)。明確禁用測(cè)試緩存的慣用方法是使用 -count=1。測(cè)試在包的根目錄(通常為 $GOPATH)打開(kāi)的文件和依賴(lài)的環(huán)境變量,只有不發(fā)生變化時(shí)才能匹配緩存。
被緩存的測(cè)試結(jié)果將被視為立即執(zhí)行,因此無(wú)論 -timeout 如何設(shè)置,成功的包測(cè)試結(jié)果都將被緩存和重用。
2.test flag
除 build 選項(xiàng)外,go test 本身處理的選項(xiàng)包括:
-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)建選項(xiàng)的更多信息,請(qǐng)參閱“go help build”。有關(guān)指定軟件包的更多信息,請(qǐng)參閱“go help packages”。
3.test/binary flags
以下選項(xiàng)同時(shí)支持測(cè)試二進(jìn)制文件和 go test 命令。
主要分為兩類(lèi),一類(lèi)控制測(cè)試行為,一類(lèi)用于狀態(tài)分析。
控制測(cè)試行為選項(xiàng):
-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)分析選項(xiàng):
-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.常用選項(xiàng)
-bench regexp 只執(zhí)行匹配對(duì)應(yīng)正則表達(dá)式的 benchmark 函數(shù),如執(zhí)行所有性能測(cè)試 "-bench ." 或 "-bench=." -benchtime t 對(duì)每個(gè) benchmark 函數(shù)運(yùn)行指定時(shí)間。如 -benchtime 1h30,默認(rèn)值為 1s。特殊語(yǔ)法 Nx 表示運(yùn)行基準(zhǔn)測(cè)試 N 次(如 -benchtime 100x) -run regexp 只運(yùn)行匹配對(duì)應(yīng)正則表達(dá)式的 test 和 example 函數(shù),例如 "-run Array" 那么就執(zhí)行函數(shù)名包含 Array 的單測(cè)函數(shù) -cover 開(kāi)啟測(cè)試覆蓋率 -v 顯示測(cè)試的詳細(xì)命令
5.示例
假設(shè)在文件 add.go 有一個(gè)被測(cè)試函數(shù)
package hello func Add(a, b int) int { return a + b }
測(cè)試函數(shù)(test function)
在測(cè)試文件 add_test.go 添加一個(gè)單元測(cè)試函數(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 來(lái)運(yùn)行指定單元測(cè)試函數(shù),發(fā)現(xiàn)只運(yùn)行了 TestAdd 測(cè)試函數(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)
添加一個(gè)性能測(cè)試函數(shù) BenchmarkAdd:
package hello func BenchmarkAdd(b *testing.B) { for n := 0; n < b.N; n++ { Add(1, 2) } }
運(yùn)行指定基準(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 }
運(yùn)行指定示例函數(shù):
go test -v -run ExampleAdd main/contain === RUN ExampleAdd --- PASS: ExampleAdd (0.00s) PASS ok main/contain (cached)
注意: 示例函數(shù)類(lèi)似于測(cè)試函數(shù),但不是使用 *testing.T 來(lái)報(bào)告成功或失敗,而是將輸出打印到 os.Stdout。如果示例函數(shù)中的最后一條注釋以“Output:”開(kāi)頭,則將輸出與注釋進(jìn)行精確比較(參見(jiàn)上面的示例)。如果最后一條注釋以“Unordered output:”開(kāi)頭,則將輸出與注釋進(jìn)行比較,但忽略行的順序。編譯了一個(gè)沒(méi)有此類(lèi)注釋的示例函數(shù),會(huì)被編譯但不會(huì)被執(zhí)行。如果在“Output:”之后沒(méi)有文本,示例函數(shù)仍會(huì)被編譯并執(zhí)行,并且預(yù)期不會(huì)產(chǎn)生任何輸出。
獲取每個(gè)函數(shù)的單測(cè)覆蓋率。
如果您想查找沒(méi)有被測(cè)試覆蓋的函數(shù),可以使用 -coverprofile 選項(xiàng)將覆蓋率報(bào)告輸出到文件中。
go test -coverprofile cover.out ./...
然后使用內(nèi)置的 go tool cover 命令來(lái)查看單測(cè)覆蓋率報(bào)告。
go tool cover -func cover.out
上面使用 -func 選項(xiàng)可以輸出每個(gè)函數(shù)的單測(cè)覆蓋率概要信息。
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% ...
查看具體代碼行的覆蓋情況。
如果想查看代碼行的單測(cè)覆蓋情況,可以使用內(nèi)置的 go tool cover 命令將覆蓋率報(bào)告轉(zhuǎn)換為 HTML 文件。然后通過(guò)瀏覽器打開(kāi)查看。
go tool cover -html=coverage.out -o coverage.html
參考文獻(xiàn)
Command Documentation
go command documentation
到此這篇關(guān)于go test 命令示例詳解的文章就介紹到這了,更多相關(guān)go test 命令內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
linux中用shell快速安裝配置Go語(yǔ)言的開(kāi)發(fā)環(huán)境
相信每位開(kāi)發(fā)者都知道選擇一門(mén)開(kāi)發(fā)語(yǔ)言,免不了需要安裝配置開(kāi)發(fā)環(huán)境,所以這篇文章給大家分享了linux下使用shell一鍵安裝配置GO語(yǔ)言開(kāi)發(fā)環(huán)境的方法,有需要的朋友們可以參考借鑒,下面來(lái)一起看看吧。2016-10-10Go語(yǔ)言sync.Map詳解及使用場(chǎng)景
Go語(yǔ)言中的sync.Map是一個(gè)高效的并發(fā)安全映射結(jié)構(gòu),適用于高并發(fā)讀多寫(xiě)少的場(chǎng)景,它通過(guò)讀寫(xiě)分離、無(wú)鎖讀取路徑、寫(xiě)入時(shí)的鎖保護(hù)等機(jī)制,提高了讀取性能并減少了鎖競(jìng)爭(zhēng),sync.Map不需要手動(dòng)管理鎖,降低了編程復(fù)雜性,適合需要簡(jiǎn)單并發(fā)訪問(wèn)的場(chǎng)合2024-10-10golang實(shí)現(xiàn)openssl自簽名雙向認(rèn)證的詳細(xì)步驟
這篇文章主要介紹了golang實(shí)現(xiàn)openssl自簽名雙向認(rèn)證的詳細(xì)步驟,本文分步驟給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-03-03利用golang實(shí)現(xiàn)封裝trycatch異常處理實(shí)例代碼
Go語(yǔ)言追求簡(jiǎn)潔優(yōu)雅,所以go語(yǔ)言不支持傳統(tǒng)的 try…catch…finally 這種異常,最近發(fā)現(xiàn)了不錯(cuò)的trycatch包,下面這篇文章主要跟大家分享了關(guān)于利用golang實(shí)現(xiàn)封裝trycatch異常處理的實(shí)例代碼,需要的朋友可以參考下。2017-07-07一文搞懂Golang文件操作增刪改查功能(基礎(chǔ)篇)
這篇文章主要介紹了一文搞懂Golang文件操作增刪改查功能(基礎(chǔ)篇),Golang 可以認(rèn)為是服務(wù)器開(kāi)發(fā)語(yǔ)言發(fā)展的趨勢(shì)之一,特別是在流媒體服務(wù)器開(kāi)發(fā)中,已經(jīng)占有一席之地,今天我們不聊特別深?yuàn)W的機(jī)制和內(nèi)容,就來(lái)聊一聊 Golang 對(duì)于文件的基本操作2021-04-04Go項(xiàng)目在linux服務(wù)器的部署詳細(xì)步驟
在今天的軟件開(kāi)發(fā)中,使用Linux作為操作系統(tǒng)的比例越來(lái)越高,而Golang語(yǔ)言則因?yàn)槠涓咝А⒑?jiǎn)潔和并發(fā)性能等特點(diǎn),也被越來(lái)越多的開(kāi)發(fā)者所青睞,這篇文章主要給大家介紹了關(guān)于Go項(xiàng)目在linux服務(wù)器的部署詳細(xì)步驟,需要的朋友可以參考下2023-09-09使用golang腳本基于kubeadm創(chuàng)建新的token(問(wèn)題分析)
這篇文章主要介紹了使用golang腳本基于kubeadm創(chuàng)建新的token(問(wèn)題分析),本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-10-10Golang實(shí)現(xiàn)http server提供壓縮文件下載功能
這篇文章主要介紹了Golang實(shí)現(xiàn)http server提供壓縮文件下載功能,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01golang Goroutine超時(shí)控制的實(shí)現(xiàn)
日常開(kāi)發(fā)中我們大概率會(huì)遇到超時(shí)控制的場(chǎng)景,比如一個(gè)批量耗時(shí)任務(wù)、網(wǎng)絡(luò)請(qǐng)求等,本文主要介紹了golang Goroutine超時(shí)控制的實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-09-09