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

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

单元测试

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

Package testing provides support for automated testing of Go packages. It is intended to be used in concert with the “go test” command, which automates execution of any function of the form

测试用例写法

函数名称必须以Test开头,例如
func TestXxx(*testing.T)

where Xxx can be any alphanumeric string (but the first letter must not be in [a-z]) and serves to identify the test routine. These TestXxx routines should be declared within the package they are testing.

go文件命名

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

举例, funcs_test.go

package mytest

import "testing"

func TestSomething(t *testing.T) {

     //call some function

}

func TestAnotherthing(t *testing.T) {

     //call some function

}

测试所有的文件

go test

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

 

测试某个文件

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

go test  -file b_test.go

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

warning: GOPATH set to GOROOT (c:\go) has no effect

PASS

ok      _/F_/workspace/goSample01/src/test      0.359s

 

测试某个方法

go test  -run=’ TestSomething’

 

Benchmark性能测试:

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

Benchmark测试用例写法

函数命名必须以Benchmark打头。例如,
func BenchmarkXxx(*testing.B)

are considered benchmarks, and are executed by the "go test" command when the -test.bench flag is provided.

A sample benchmark function looks like this:

func BenchmarkHello(b *testing.B) {
    for i := 0; i < b.N; i++ {
        fmt.Sprintf("hello")
    }
}
 

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

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

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

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

warning: GOPATH set to GOROOT (c:\go) has no effect

PASS

BenchmarkUpdate   500000              4906 ns/op

BenchmarkManual   200000              8750 ns/op

BenchmarkUnroll   500000              4531 ns/op

BenchmarkLoop   2000000000               0.00 ns/op

BenchmarkIteratively     1000000              2078 ns/op

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

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

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

warning: GOPATH set to GOROOT (c:\go) has no effect

PASS

BenchmarkUpdate   500000              4562 ns/op

BenchmarkManual   200000              9062 ns/op

BenchmarkUnroll   500000              4187 ns/op

ok      command-line-arguments  6.953s

 

 

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

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

The benchmark package will vary b.N until the benchmark function lasts long enough to be timed reliably. The output

testing.BenchmarkHello    10000000    282 ns/op

means that the loop ran 10000000 times at a speed of 282 ns per loop.

 

2、计时器可以手工控制

If a benchmark needs some expensive setup before running, the timer may be stopped:

func BenchmarkBigLen(b *testing.B) {
    b.StopTimer()
    big := NewBig()
    b.StartTimer()
    for i := 0; i < b.N; i++ {
        big.Len()
    }
}

 

GooglePerformanceTools------ Google's pprof C++ profiler. 

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

附录

Test packages测试包帮助

Usage:

go test [-c] [-i] [build flags] [packages] [flags for test binary]

'Go test' automates testing the packages named by the import paths. It prints a summary of the test results in the format:

ok   archive/tar   0.011s
FAIL archive/zip   0.022s
ok   compress/gzip 0.033s
...

followed by detailed output for each failed package.

'Go test' recompiles each package along with any files with names matching the file pattern "*_test.go". These additional files can contain test functions, benchmark functions, and example functions. See 'go help testfunc' for more.

By default, go test needs no arguments. It compiles and tests the package with source in the current directory, including tests, and runs the tests.

The package is built in a temporary directory so it does not interfere with the non-test installation.

In addition to the build flags, the flags handled by 'go test' itself are:

-c  Compile the test binary to pkg.test but do not run it.
 
-i
    Install packages that are dependencies of the test.
    Do not run the test.

The test binary also accepts flags that control execution of the test; these flags are also accessible by 'go test'. See 'go help testflag' for details.

For more about build flags, see 'go help build'. For more about specifying packages, see 'go help packages'.

See also: go build, go vet.

 

 

go help testflag命令行测试参数

 

The 'go test' command takes both flags that apply to 'go test' itself

and flags that apply to the resulting test binary.

 

The test binary, called pkg.test, where pkg is the name of the

directory containing the package sources, has its own flags:

 

        -test.v

            Verbose output: log all tests as they are run.

 

        -test.run pattern

            Run only those tests and examples matching the regular

            expression.

 

        -test.bench pattern

            Run benchmarks matching the regular expression.

            By default, no benchmarks run.

 

        -test.cpuprofile cpu.out

            Write a CPU profile to the specified file before exiting.

 

        -test.memprofile mem.out

            Write a memory profile to the specified file when all tests

            are complete.

 

        -test.memprofilerate n

            Enable more precise (and expensive) memory profiles by setting

            runtime.MemProfileRate.  See 'godoc runtime MemProfileRate'.

            To profile all memory allocations, use -test.memprofilerate=1

            and set the environment variable GOGC=off to disable the

            garbage collector, provided the test can run in the available

            memory without garbage collection.

 

        -test.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.

 

        -test.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.

 

        -test.timeout t

                If a test runs longer than t, panic.

 

        -test.benchtime n

                Run enough iterations of each benchmark to take n seconds.

                The default is 1 second.

 

        -test.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.

 

For convenience, each of these -test.X flags of the test binary is

also available as the flag -X in 'go test' itself.  Flags not listed

here are passed through unaltered.  For instance, the command

 

        go test -x -v -cpuprofile=prof.out -dir=testdata -update

 

will compile the test binary and then run it as

 

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

 

go help testfunc

The 'go test' command expects to find test, benchmark, and example functions

in the "*_test.go" files corresponding to the package under test.

 

A test function is one named TestXXX (where XXX is any alphanumeric string

not starting with a lower case letter) and should have the signature,

 

        func TestXXX(t *testing.T) { ... }

 

A benchmark function is one named BenchmarkXXX and should have the signature,

 

        func BenchmarkXXX(b *testing.B) { ... }

 

An example function is similar to a test function but, instead of using *testing

.T

to report success or failure, prints output to os.Stdout and os.Stderr.

That output is compared against the function's "Output:" comment, which

must be the last comment in the function body (see example below). An

example with no such comment, or with no text after "Output:" is compiled

but not executed.

 

Godoc displays the body of ExampleXXX to demonstrate the use

of the function, constant, or variable XXX.  An example of a method M with

receiver type T or *T is named ExampleT_M.  There may be multiple examples

for a given function, constant, or variable, distinguished by a trailing _xxx,

where xxx is a suffix not beginning with an upper case letter.

 

Here is an example of an example:

 

        func ExamplePrintln() {

                Println("The output of\nthis example.")

                // Output: The output of

                // this example.

        }

 

The entire test file is presented as the example when it contains a single

example function, at least one other function, type, variable, or constant

declaration, and no test or benchmark functions.

 

See the documentation of the testing package for more information.

 

 

你可能感兴趣的:(单元测试,性能测试,go语言)