简介
“testing“ Go自带测试框架,引入“testing“ 同时编写相关测试用例,代码放保存在被测试包
的目录下,文件以_test.go结尾,通过go test执行,可以指定特定的测试文件或函数。
测试用例
单元测试*testing.T 命名TestXxx
压力测试*testing.B 命名BenchmarkXxx 循环体内使用testing.B.N
测试控制,信息输出(用fmt或log -v就无效了)
t.Log()
//记录日志
t.Logf()
//记录日志
t.Error
//标记失败,记录日志,输出错误信息
t.Errorf //标记失败,记录日志,输出错误信息
t.Fatal //标记失败,中断,输出错误信息
t.Fatalf
//标记失败,中断,输出错误信息
t.Skip
//跳过当前测试用例,记录日志
t.Skipf
//跳过当前测试用例,记录日志
t.Parallel //标记为可并行运算
b.ReportAllocs
执行参数
go test [$path] //直接执行[指定包路径]
go test -v
//打印详情
go test -run=xxx //指定测试用例
go test -bench=. [-benchmem|-cover]//执行压力测试[查看内存|查看覆盖率]
性能监控
WEB
package main
import "net/http"
import "fmt"
import _ "net/http/pprof"
func main() {
http.HandleFunc("/hello", hello)
http.ListenAndServe(":8787", nil)
}
func hello(w http.ResponseWriter,r *http.Request) {
fmt.Println("world")
}
http://localhost:8787/debug/pprof/
GIN
package main
import (
"github.com/gin-gonic/gin"
"github.com/DeanThompson/ginpprof"
)
func main() {
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
// automatically add routers for net/http/pprof
// e.g. /debug/pprof, /debug/pprof/heap, etc.
//ginpprof.Wrap(router)
// ginpprof also plays well with *gin.RouterGroup
group := router.Group("/debug/pprof")
ginpprof.WrapGroup(group)
router.Run(":8787")
}
http://localhost:8787/debug/pprof/
RUNTIME
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
flag.Parse()
if *cpuprofile != "" {
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
defer pprof.StopCPUProfile()
}
./testpprof -cpuprofile=cpu.pprof
PPROf
使用go tool pprof 进入到pprof,使用web命令就会在/tmp下生成svg文件(svg生成需要安装graphviz)
WEB
go tool pprof [-alloc_space|--alloc_objects] http://localhost:8787/debug/pprof/heap //数据分析[常驻内存|临时内存]
RUNTIME
go tool pprof testpprof cpu.pprof
参考学习
https://blog.golang.org/profiling-go-programs
http://io.upyun.com/2018/01/21/debug-golang-application-with-pprof-and-flame-graph/