go test test & benchmark

开发程序其中很重要的一点是测试,咱们如何保证代码的质量,如何保证每一个函数是可运行,运行结果是正确的,又如何保证写出来的代码性能是好的,咱们知道单元测试的重点在于发现程序设计或实现的逻辑错误,使问题及早暴露,便于问题的定位解决,而性能测试的重点在于发现程序设计上的一些问题,让线上的程序可以在高并发的状况下还能保持稳定。本小节将带着这一连串的问题来说解Go语言中如何来实现单元测试和性能测试。git

Go语言中自带有一个轻量级的测试框架testing和自带的go test命令来实现单元测试和性能测试,testing框架和其余语言中的测试框架相似,你能够基于这个框架写针对相应函数的测试用例,也能够基于该框架写相应的压力测试用例,那么接下来让咱们一一来看一下怎么写。github

如何编写测试用例

因为go test命令只能在一个相应的目录下执行全部文件,因此咱们接下来新建一个项目目录gotest,这样咱们全部的代码和测试代码都在这个目录下。golang

接下来咱们在该目录下面建立两个文件:gotest.go和gotest_test.goweb

  1. gotest.go:这个文件里面咱们是建立了一个包,里面有一个函数实现了除法运算:数据库

    package gotest
    
    import (
        "errors"
    )
    
    func Division(a, b float64) (float64, error) {
        if b == 0 {
            return 0, errors.New("除数不能为0")
        }
    
        return a / b, nil
    }
  2. gotest_test.go:这是咱们的单元测试文件,可是记住下面的这些原则:ruby

    • 文件名必须是_test.go结尾的,这样在执行go test的时候才会执行到相应的代码
    • 你必须import testing这个包
    • 全部的测试用例函数必须是Test开头
    • 测试用例会按照源代码中写的顺序依次执行
    • 测试函数TestXxx()的参数是testing.T,咱们可使用该类型来记录错误或者是测试状态
    • 测试格式:func TestXxx (t *testing.T),Xxx部分能够为任意的字母数字的组合,可是首字母不能是小写字母[a-z],例如Testintdiv是错误的函数名。
    • 函数中经过调用testing.TErrorErrorfFailNowFatalFatalIf方法,说明测试不经过,调用Log方法用来记录测试的信息。

    下面是咱们的测试用例的代码:并发

    package gotest
    
    import (
        "testing"
    )
    
    func Test_Division_1(t *testing.T) {
        if i, e := Division(6, 2); i != 3 || e != nil { //try a unit test on function
            t.Error("除法函数测试没经过") // 若是不是如预期的那么就报错
        } else {
            t.Log("第一个测试经过了") //记录一些你指望记录的信息
        }
    }
    
    func Test_Division_2(t *testing.T) {
        t.Error("就是不经过")
    }

    咱们在项目目录下面执行go test,就会显示以下信息:app

    --- FAIL: Test_Division_2 (0.00 seconds)
        gotest_test.go:16: 就是不经过
    FAIL
    exit status 1
    FAIL    gotest  0.013s

    从这个结果显示测试没有经过,由于在第二个测试函数中咱们写死了测试不经过的代码t.Error,那么咱们的第一个函数执行的状况怎么样呢?默认状况下执行go test是不会显示测试经过的信息的,咱们须要带上参数go test -v,这样就会显示以下信息:框架

    === RUN Test_Division_1
    --- PASS: Test_Division_1 (0.00 seconds)
        gotest_test.go:11: 第一个测试经过了
    === RUN Test_Division_2
    --- FAIL: Test_Division_2 (0.00 seconds)
        gotest_test.go:16: 就是不经过
    FAIL
    exit status 1
    FAIL    gotest  0.012s

    上面的输出详细的展现了这个测试的过程,咱们看到测试函数1Test_Division_1测试经过,而测试函数2Test_Division_2测试失败了,最后得出结论测试不经过。接下来咱们把测试函数2修改为以下代码:函数

    func Test_Division_2(t *testing.T) {
        if _, e := Division(6, 0); e == nil { //try a unit test on function
            t.Error("Division did not work as expected.") // 若是不是如预期的那么就报错
        } else {
            t.Log("one test passed.", e) //记录一些你指望记录的信息
        }
    }   

    而后咱们执行go test -v,就显示以下信息,测试经过了:

    === RUN Test_Division_1
    --- PASS: Test_Division_1 (0.00 seconds)
        gotest_test.go:11: 第一个测试经过了
    === RUN Test_Division_2
    --- PASS: Test_Division_2 (0.00 seconds)
        gotest_test.go:20: one test passed. 除数不能为0
    PASS
    ok      gotest  0.013s

如何编写压力测试

压力测试用来检测函数(方法)的性能,和编写单元功能测试的方法相似,此处再也不赘述,但须要注意如下几点:

  • 压力测试用例必须遵循以下格式,其中XXX能够是任意字母数字的组合,可是首字母不能是小写字母

    func BenchmarkXXX(b *testing.B) { ... }
  • go test不会默认执行压力测试的函数,若是要执行压力测试须要带上参数-test.bench,语法:-test.bench="test_name_regex",例如go test -test.bench=".*"表示测试所有的压力测试函数

  • 在压力测试用例中,请记得在循环体内使用testing.B.N,以使测试能够正常的运行
  • 文件名也必须以_test.go结尾

下面咱们新建一个压力测试文件webbench_test.go,代码以下所示:

package gotest

import (
    "testing"
)

func Benchmark_Division(b *testing.B) {
    for i := 0; i < b.N; i++ { //use b.N for looping 
        Division(4, 5)
    }
}

func Benchmark_TimeConsumingFunction(b *testing.B) {
    b.StopTimer() //调用该函数中止压力测试的时间计数

    //作一些初始化的工做,例如读取文件数据,数据库链接之类的,
    //这样这些时间不影响咱们测试函数自己的性能

    b.StartTimer() //从新开始时间
    for i := 0; i < b.N; i++ {
        Division(4, 5)
    }
}

咱们执行命令go test -test.bench=".*",能够看到以下结果:

 

PASS
Benchmark_Division  500000000            7.76 ns/op
Benchmark_TimeConsumingFunction 500000000            7.80 ns/op
ok      gotest  9.364s  

上面的结果显示咱们没有执行任何TestXXX的单元测试函数,显示的结果只执行了压力测试函数,第一条显示了Benchmark_Division执行了500000000次,每次的执行平均时间是7.76纳秒,第二条显示了Benchmark_TimeConsumingFunction执行了500000000,每次的平均执行时间是7.80纳秒。最后一条显示总共的执行时间。

咱们执行命令go test -test.bench=".*" -count=5,能够看到以下结果: (使用-count能够指定执行多少次)

 

PASS
Benchmark_Division-2                 300000000             4.60 ns/op
Benchmark_Division-2                 300000000             4.57 ns/op
Benchmark_Division-2                 300000000             4.63 ns/op
Benchmark_Division-2                 300000000             4.60 ns/op
Benchmark_Division-2                 300000000             4.63 ns/op
Benchmark_TimeConsumingFunction-2    300000000             4.64 ns/op
Benchmark_TimeConsumingFunction-2    300000000             4.61 ns/op
Benchmark_TimeConsumingFunction-2    300000000             4.60 ns/op
Benchmark_TimeConsumingFunction-2    300000000             4.59 ns/op
Benchmark_TimeConsumingFunction-2    300000000             4.60 ns/op
ok      _/home/diego/GoWork/src/app/testing    18.546s

 

go test -run=文件名字 -bench=bench名字 -cpuprofile=生产的cprofile文件名称 文件夹

 

例子:

testBenchMark下有个popcnt文件夹,popcnt中有文件popcunt_test.go

➜  testBenchMark ls
popcnt

popcunt_test.go的问价内容:

ackage popcnt

import (
    "testing"
)

const m1 = 0x5555555555555555
const m2 = 0x3333333333333333
const m4 = 0x0f0f0f0f0f0f0f0f
const h01 = 0x0101010101010101

func popcnt(x uint64) uint64 {
    x -= (x >> 1) & m1
    x = (x & m2) + ((x >> 2) & m2)
    x = (x + (x >> 4)) & m4
    return (x * h01) >> 56
}

func BenchmarkPopcnt(b *testing.B) {
    for i := 0; i < b.N; i++ {
        x := i
        x -= (x >> 1) & m1
        x = (x & m2) + ((x >> 2) & m2)
        x = (x + (x >> 4)) & m4
        _ = (x * h01) >> 56
    }
}

而后运行go test -bench=".*" -cpuprofile=cpu.profile ./popcnt

 

➜  testBenchMark go test -bench=".*" -cpuprofile=cpu.profile ./popcnt
testing: warning: no tests to run
PASS
BenchmarkPopcnt-8    1000000000             2.01 ns/op
ok      app/testBenchMark/popcnt    2.219s
➜  testBenchMark ll
total 6704
drwxr-xr-x  5 diego  staff      170  5  6 13:57 .
drwxr-xr-x  3 diego  staff      102  5  6 11:12 ..
-rw-r--r--  1 diego  staff     5200  5  6 13:57 cpu.profile
drwxr-xr-x  4 diego  staff      136  5  6 11:47 popcnt
-rwxr-xr-x  1 diego  staff  3424176  5  6 13:57 popcnt.test
➜  testBenchMark

生产 cpu.profile问价和popcnt.test 文件

➜  testBenchMark ll
total 6704
drwxr-xr-x  5 diego  staff      170  5  6 13:57 .
drwxr-xr-x  3 diego  staff      102  5  6 11:12 ..
-rw-r--r--  1 diego  staff     5200  5  6 13:57 cpu.profile
drwxr-xr-x  3 diego  staff      102  5  6 14:01 popcnt
-rwxr-xr-x  1 diego  staff  3424176  5  6 13:57 popcnt.test
➜  testBenchMark
go tool pprof popcnt.test cpu.profile 进入交互模式
➜  testBenchMark go tool pprof popcnt.test cpu.profile
Entering interactive mode (type "help" for commands)
(pprof) top
1880ms of 1880ms total (  100%)
      flat  flat%   sum%        cum   cum%
    1790ms 95.21% 95.21%     1790ms 95.21%  app/testBenchMark/popcnt.BenchmarkPopcnt
      90ms  4.79%   100%       90ms  4.79%  runtime.usleep
         0     0%   100%     1790ms 95.21%  runtime.goexit
         0     0%   100%       90ms  4.79%  runtime.mstart
         0     0%   100%       90ms  4.79%  runtime.mstart1
         0     0%   100%       90ms  4.79%  runtime.sysmon
         0     0%   100%     1790ms 95.21%  testing.(*B).launch
         0     0%   100%     1790ms 95.21%  testing.(*B).runN
(pprof)

 

go tool pprof --web popcnt.test cpu.profile 进入web模式

$ go tool pprof --text mybin http://myserver:6060:/debug/pprof/profile 

 

这有几个可用的输出类型,最有用的几个为: --text,--web 和 --list 。运行 go tool pprof 来获得最完整的列表。

 

小结

经过上面对单元测试和压力测试的学习,咱们能够看到testing包很轻量,编写单元测试和压力测试用例很是简单,配合内置的go test命令就能够很是方便的进行测试,这样在咱们每次修改完代码,执行一下go test就能够简单的完成回归测试了。

相关文章
相关标签/搜索