Go单元测试&性能测试

Go自带了测试框架和工具,在testing包中,以便完成单元测试(T类型)和性能测试(B类型)。

一般测试代码放在*_test.go文件中,与被测代码放于同一个包中。

单元测试

测试函数名称格式是:Test[^a-z],即以Test开头,跟上非小写字母开头的字符串。每个测试函数都接受一个*testing.T类型参数,用于输出信息或中断测试。

测试方法有:

  • Fail: 标记失败,但继续执行当前测试函数
  • FailNow: 失败,立即终止当前测试函数执行
  • Log: 输出错误信息
  • Error: Fail + Log
  • Fatal: FailNow + Log
  • Skip: 跳过当前函数,通常用于未完成的测试用例

测试代码:

// filename: add_test.go

package test
import (
    "testing"
)

func Add(a, b int) int {
    return a + b
}

func TestAdd1(t *testing.T) {
    if Add(2, 3) != 5 {
         t.Error("result is wrong!")
    } else {
         t.Log("result is right")
    }
}

func TestAdd2(t *testing.T) {
    if Add(2, 3) != 6 {
         t.Fatal("result is wrong!")
    } else {
         t.Log("result is right")
    }
}

运行以下命令,自动搜集所有的测试文件(*_test.go),提取全部测试函数。

$ go test
输出:
--- FAIL: TestAdd2 (0.00s)
    add_test.go:20: result is wrong!
FAIL
exit status 1
FAIL    _/Users/golang_learning/testTB  0.006s

输出结果包括:出错的测试函数名称,执行时长和错误信息。

go test还有以下参数:

  • -v:显示所有测试函数运行细节
$ go test -v
输出:
=== RUN   TestAdd1
--- PASS: TestAdd1 (0.00s)
    add_test.go:14: result is right
=== RUN   TestAdd2
--- FAIL: TestAdd2 (0.00s)
    add_test.go:20: result is wrong!
FAIL
exit status 1
FAIL    _/Users/golang_learning/testTB  0.007s
  • -run regex:指定要执行的测试函数
$ go test -run TestAdd2
输出:
--- FAIL: TestAdd2 (0.00s)
    add_test.go:20: result is wrong!
FAIL
exit status 1
FAIL    _/Users/golang_learning/testTB  0.006s

性能测试

性能测试函数以Benchmark 开头,参数类型是 *testing.B,可与Test函数放在同个文件中。默认情况下,go test不执行Benchmark测试,必须用“-bench <pattern>”指定性能测试函数。

测试代码:

// filename: add_test.go
package test
import (
    "testing"
)

func Add(a, b int) int {
    return a + b
}

func Benchmark(b *testing.B) {
    for i := 0; i < b.N; i++ { // b.N,测试循环次数
        Add(4, 5)
    }
}

执行命令测试:

$ go test -bench=.
输出:
goos: darwin
goarch: amd64
Benchmark-4     2000000000           0.35 ns/op
PASS
ok      _/Users/golang_learning/testTB  0.753s

B类型也有以下参数:

  • benchmem:输出内存分配统计
  • benchtime:指定测试时间
  • cpu:指定GOMAXPROCS
  • timeout:超市限制
$ go test -v -bench=. -cpu=8 -benchtime="3s" -timeout="5s" -benchmem
输出:
goos: darwin
goarch: amd64
Benchmark-8     5000000000           0.34 ns/op        0 B/op          0 allocs/op
PASS
ok      _/Users/golang_learning/testTB  1.766s
  • Benchmark-8:-cpu参数指定,-8表示8个CPU线程执行
  • 5000000000:表示总共执行了5000000000次
  • 0.34 ns/op:表示每次执行耗时0.34纳秒
  • 0 B/op:表示每次执行分配的内存(字节)
  • 0 allocs/op:表示每次执行分配了多少次对象

pprof

go tools继承了pprof,以便进行性能测试并找出瓶颈。

测试数据文件生成有两种方法:命令行和代码

1、命令行生成测试数据文件

$ go test -bench=. -cpuprofile cpu.out
输出:
goos: darwin
goarch: amd64
Benchmark-4     2000000000           0.35 ns/op
PASS
ok      _/Users/golang_learning/testTB  0.911s
$ ls 
输出:(上一条命令生成cpu.out和testTB.test)
add_test.go     cpu.out     testTB.test

用命令行分析

$ go tool pprof -text mem.out 
输出:
Main binary filename not available.
Type: inuse_space
Time: May 22, 2018 at 3:36pm (CST)
Showing nodes accounting for 1.16MB, 100% of 1.16MB total
      flat  flat%   sum%        cum   cum%
    1.16MB   100%   100%     1.16MB   100%  runtime/pprof.StartCPUProfile
         0     0%   100%     1.16MB   100%  main.main
         0     0%   100%     1.16MB   100%  runtime.main

pprof交互模式分析

$ go tool pprof testTB.test cpu.out 
输出:
File: testTB.test
Type: cpu
Time: May 22, 2018 at 3:08pm (CST)
Duration: 906.10ms, Total samples = 670ms (73.94%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top
输出:
Showing nodes accounting for 670ms, 100% of 670ms total
      flat  flat%   sum%        cum   cum%
     670ms   100%   100%      670ms   100%  _/Users/golang_learning/testTB.Benchmark
         0     0%   100%      670ms   100%  testing.(*B).launch
         0     0%   100%      670ms   100%  testing.(*B).runN
(pprof) quit

以上性能指标含义:

  • 函数本地采样数量(不包含其调用的其他函数)
  • 函数本地采样数量所占百分比
  • 前几个函数(包括当前函数)本地采样总和所占百分比
  • 函数(包括其调用的函数)采样总数量
  • 函数采样总数量所占百分比

pprof交互模式命令:

  • top、top10: 显示前几条信息;
  • web:以svg文件展示。

pdf或者svg分析

$ go tool pprof -svg cpu.out > cpu.svg
$ go tool pprof -pdf cpu.out > cpu.pdf
$ ls(以上命令生成cpu.pdf和cpu.svg文件)
add_test.go   cpu.out    cpu.pdf        cpu.svg     testTB.test

打开cpu.pdf或者cpu.svg文件:


image

2、代码生成测试数据文件

用runtime/pprof包生成cpu和mem文件:

// filename: pprof.go
package main
import (
    "os"
    "runtime/pprof"
)

func main() {
    w, _ := os.Create("cpu.out")
    defer w.Close()
    pprof.StartCPUProfile(w)
    defer pprof.StopCPUProfile()

    w2, _ := os.Create("mem.out")
    defer w2.Close()
    defer pprof.WriteHeapProfile(w2)

    Sum(3, 5)

}

func Sum(a, b int) int {
    return a + b
}

编译并执行以上文件:

$ go build pprof.go 
$ ./pprof 
$ ls(./pprof命令生成cpu.out和mem.out文件)
cpu.out     mem.out     pprof       pprof.go

生成pdf文件:

$ go tool pprof -pdf cpu.out > cpu.pdf
$ go tool pprof -pdf mem.out > mem.pdf
cpu.pdf
mem.pdf

net/http/pprof

若是测量http server的性能,则需要使用net/http/pprof包。只需要在源文件中加入代码:

import (
    _ "net/http/pprof"
)

CPU分析

启动http server,然后在浏览器中访问链接:http://localhost:【port】/debug/pprof/
就能看到prof信息了:

image

若要生成CPU状态分析图,可使用以下命令:

$ go tool pprof http://localhost:port/debug/pprof/profile

就会进入30秒的profile收集时间,在这段事件内向服务器连续发送多次请求,尽量让cpu占用性能产生数据。

$ go tool pprof http://localhost:8080/debug/pprof/profile
输出:
Fetching profile over HTTP from http://localhost:8080/debug/pprof/profile
// 这里会阻塞30s收集profile,在这段时间应多发请求
Saved profile in /Users/pprof/pprof.samples.cpu.002.pb.gz
Type: cpu
Time: May 22, 2018 at 7:16pm (CST)
Duration: 30s, Total samples = 330ms ( 1.10%)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top10
输出:(前10条信息)
Showing nodes accounting for 330ms, 100% of 330ms total
Showing top 10 nodes out of 39
      flat  flat%   sum%        cum   cum%
     100ms 30.30% 30.30%      100ms 30.30%  runtime.mach_semaphore_signal
      60ms 18.18% 48.48%       60ms 18.18%  runtime.mach_semaphore_timedwait
      60ms 18.18% 66.67%       60ms 18.18%  runtime.mach_semaphore_wait
      ... ... 
(pprof) web
// 在浏览器中以svg文件的方式展示cpu占用图
image

内存分析

启动服务器,访问链接http://localhost:port/debug/pprof/heap,就会自动下载heap文件,调用以下命令,进入pprof交互模式:

$ go tool pprof heap 
Main binary filename not available.
Type: inuse_space
Time: May 24, 2018 at 11:30pm (CST)
Entering interactive mode (type "help" for commands, "o" for options)
(pprof) top5
Showing nodes accounting for 62.02MB, 98.20% of 63.16MB total
Showing top 5 nodes out of 26
      flat  flat%   sum%        cum   cum%
   21.67MB 34.31% 34.31%    21.67MB 34.31%  bytes.makeSlice
   20.50MB 32.46% 66.77%    20.50MB 32.46%  reflect.unsafe_New
      15MB 23.75% 90.52%       15MB 23.75%  github.com/golang/protobuf/proto.(*word32Slice).Append
    2.85MB  4.51% 95.03%     2.85MB  4.51%  github.com/golang/protobuf/proto.(*structPointerSlice).Append
       2MB  3.17% 98.20%        2MB  3.17%  github.com/golang/protobuf/proto.word32_Set
(pprof) web
内存分析
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269