您的位置:首页 > 编程语言 > Go语言

Go语言单元和性能测试的相关文档

2012-05-14 00:00 351 查看
为了帮助开发者对代码进行测试,Go语言也提供了相关的单元测试的基础框架。除此之外,Go语言还提供了简单的性能测试框架,给开发者提供了对比和改善算法的便利手段。Go语言的性能测试框架据说是参考了2002年JavaOne的《HowNOTToWriteAMicrobenchmark》,它的基本测试机理是在一定时间内循环运行测试程序,并最终得出测试程序每次运行的平均时间。不仅如此,性能测试框架还支持输出用于性能调优用的了cpu和内存相关数据。从这方面看,我觉得要比Java、Scala好。

单元测试

单元测试很重要,Go语言提供了相关的单元测试框架。允许对单个和一系列文件进行自动化测试。

PackagetestingprovidessupportforautomatedtestingofGopackages.Itisintendedtobeusedinconcertwiththe“gotest”command,whichautomatesexecutionofanyfunctionoftheform

测试用例写法

函数名称必须以Test开头,例如

funcTestXxx(*testing.T)

whereXxxcanbeanyalphanumericstring(butthefirstlettermustnotbein[a-z])andservestoidentifythetestroutine.TheseTestXxxroutinesshouldbedeclaredwithinthepackagetheyaretesting.

go文件命名

必须是_test.go为后缀(*_test.go)。此外,package名最好不要用main.

举例,funcs_test.go

packagemytest

import"testing"

funcTestSomething(t*testing.T){

//callsomefunction

}

funcTestAnotherthing(t*testing.T){

//callsomefunction

}

测试所有的文件

gotest

将对当前目录下的所有*_test.go文件进行编译并自动运行测试。

测试某个文件

使用”-file”参数。gotest–file**.go。例如,

gotest-fileb_test.go

”-file”参数不是必须的,可以省略。如果你输入gotestb_test.go也会得到一样的效果

warning:GOPATHsettoGOROOT(c:\go)hasnoeffect

PASS

ok_/F_/workspace/goSample01/src/test0.359s

测试某个方法

gotest-run=’TestSomething’

Benchmark性能测试:

性能测试对于对比和改进算法很有帮助。因此,Go语言提供了相关的函数性能测试框架。当然,Go只是提供了基本测试框架,真正的测试代码还得由程序员来完成。

Benchmark测试用例写法

函数命名必须以Benchmark打头。例如,

funcBenchmarkXxx(*testing.B)

areconsideredbenchmarks,andareexecutedbythe"gotest"commandwhenthe-test.benchflagisprovided.

Asamplebenchmarkfunctionlookslikethis:

funcBenchmarkHello(b*testing.B){

fori:=0;i<b.N;i++{

fmt.Sprintf("hello")

}

}


对目录下所有go文件进行benchmark测试

在命令行里输入:gotest.-bench="."

(注意:同一个包里面不能有相同的方法名。否则,可能会编译出错)

F:\workspace\goSample01\src\test>gotest.-bench="."

warning:GOPATHsettoGOROOT(c:\go)hasnoeffect

PASS

BenchmarkUpdate5000004906ns/op

BenchmarkManual2000008750ns/op

BenchmarkUnroll5000004531ns/op

BenchmarkLoop20000000000.00ns/op

BenchmarkIteratively10000002078ns/op

单独对某个go文件进行benchmark测试

在命令行里输入:gotestb_test.go-bench="."

F:\workspace\goSample01\src\test>gotestb_test.go-bench="."

warning:GOPATHsettoGOROOT(c:\go)hasnoeffect

PASS

BenchmarkUpdate5000004562ns/op

BenchmarkManual2000009062ns/op

BenchmarkUnroll5000004187ns/op

okcommand-line-arguments6.953s

性能测试结果的一些说明:

1、循环次数和每次操作的时间

Thebenchmarkpackagewillvaryb.Nuntilthebenchmarkfunctionlastslongenoughtobetimedreliably.Theoutput

testing.BenchmarkHello10000000282ns/op

meansthattheloopran10000000timesataspeedof282nsperloop.

2、计时器可以手工控制

Ifabenchmarkneedssomeexpensivesetupbeforerunning,thetimermaybestopped:

funcBenchmarkBigLen(b*testing.B){

b.StopTimer()

big:=NewBig()

b.StartTimer()

fori:=0;i<b.N;i++{

big.Len()

}

}


GooglePerformanceTools------Google'spprofC++profiler.

http://code.google.com/p/gperftools/wiki/GooglePerformanceTools?redir=1



附录

Testpackages测试包帮助

Usage:

gotest[-c][-i][buildflags][packages][flagsfortestbinary]

'Gotest'automatestestingthepackagesnamedbytheimportpaths.Itprintsasummaryofthetestresultsintheformat:

okarchive/tar0.011s

FAILarchive/zip0.022s

okcompress/gzip0.033s

...

followedbydetailedoutputforeachfailedpackage.

'Gotest'recompileseachpackagealongwithanyfileswithnamesmatchingthefilepattern"*_test.go".Theseadditionalfilescancontaintestfunctions,benchmarkfunctions,andexamplefunctions.See'gohelptestfunc'formore.

Bydefault,gotestneedsnoarguments.Itcompilesandteststhepackagewithsourceinthecurrentdirectory,includingtests,andrunsthetests.

Thepackageisbuiltinatemporarydirectorysoitdoesnotinterferewiththenon-testinstallation.

Inadditiontothebuildflags,theflagshandledby'gotest'itselfare:

-cCompilethetestbinarytopkg.testbutdonotrunit.


-i

Installpackagesthataredependenciesofthetest.

Donotrunthetest.

Thetestbinaryalsoacceptsflagsthatcontrolexecutionofthetest;theseflagsarealsoaccessibleby'gotest'.See'gohelptestflag'fordetails.

Formoreaboutbuildflags,see'gohelpbuild'.Formoreaboutspecifyingpackages,see'gohelppackages'.

Seealso:gobuild,govet.

gohelptestflag命令行测试参数

The'gotest'commandtakesbothflagsthatapplyto'gotest'itself

andflagsthatapplytotheresultingtestbinary.

Thetestbinary,calledpkg.test,wherepkgisthenameofthe

directorycontainingthepackagesources,hasitsownflags:

-test.v

Verboseoutput:logalltestsastheyarerun.

-test.runpattern

Runonlythosetestsandexamplesmatchingtheregular

expression.

-test.benchpattern

Runbenchmarksmatchingtheregularexpression.

Bydefault,nobenchmarksrun.

-test.cpuprofilecpu.out

WriteaCPUprofiletothespecifiedfilebeforeexiting.

-test.memprofilemem.out

Writeamemoryprofiletothespecifiedfilewhenalltests

arecomplete.

-test.memprofileraten

Enablemoreprecise(andexpensive)memoryprofilesbysetting

runtime.MemProfileRate.See'godocruntimeMemProfileRate'.

Toprofileallmemoryallocations,use-test.memprofilerate=1

andsettheenvironmentvariableGOGC=offtodisablethe

garbagecollector,providedthetestcanrunintheavailable

memorywithoutgarbagecollection.

-test.paralleln

Allowparallelexecutionoftestfunctionsthatcallt.Parallel.

Thevalueofthisflagisthemaximumnumberofteststorun

simultaneously;bydefault,itissettothevalueofGOMAXPROCS.

-test.short

Telllong-runningteststoshortentheirruntime.

Itisoffbydefaultbutsetduringall.bashsothatinstalling

theGotreecanrunasanitycheckbutnotspendtimerunning

exhaustivetests.

-test.timeoutt

Ifatestrunslongerthant,panic.

-test.benchtimen

Runenoughiterationsofeachbenchmarktotakenseconds.

Thedefaultis1second.

-test.cpu1,2,4

SpecifyalistofGOMAXPROCSvaluesforwhichthetestsor

benchmarksshouldbeexecuted.Thedefaultisthecurrentvalue

ofGOMAXPROCS.

Forconvenience,eachofthese-test.Xflagsofthetestbinaryis

alsoavailableastheflag-Xin'gotest'itself.Flagsnotlisted

herearepassedthroughunaltered.Forinstance,thecommand

gotest-x-v-cpuprofile=prof.out-dir=testdata-update

willcompilethetestbinaryandthenrunitas

pkg.test-test.v-test.cpuprofile=prof.out-dir=testdata-update

gohelptestfunc

The'gotest'commandexpectstofindtest,benchmark,andexamplefunctions

inthe"*_test.go"filescorrespondingtothepackageundertest.

AtestfunctionisonenamedTestXXX(whereXXXisanyalphanumericstring

notstartingwithalowercaseletter)andshouldhavethesignature,

funcTestXXX(t*testing.T){...}

AbenchmarkfunctionisonenamedBenchmarkXXXandshouldhavethesignature,

funcBenchmarkXXX(b*testing.B){...}

Anexamplefunctionissimilartoatestfunctionbut,insteadofusing*testing

.T

toreportsuccessorfailure,printsoutputtoos.Stdoutandos.Stderr.

Thatoutputiscomparedagainstthefunction's"Output:"comment,which

mustbethelastcommentinthefunctionbody(seeexamplebelow).An

examplewithnosuchcomment,orwithnotextafter"Output:"iscompiled

butnotexecuted.

GodocdisplaysthebodyofExampleXXXtodemonstratetheuse

ofthefunction,constant,orvariableXXX.AnexampleofamethodMwith

receivertypeTor*TisnamedExampleT_M.Theremaybemultipleexamples

foragivenfunction,constant,orvariable,distinguishedbyatrailing_xxx,

wherexxxisasuffixnotbeginningwithanuppercaseletter.

Hereisanexampleofanexample:

funcExamplePrintln(){

Println("Theoutputof\nthisexample.")

//Output:Theoutputof

//thisexample.

}

Theentiretestfileispresentedastheexamplewhenitcontainsasingle

examplefunction,atleastoneotherfunction,type,variable,orconstant

declaration,andnotestorbenchmarkfunctions.

Seethedocumentationofthetestingpackageformoreinformation.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息