Go 测试笔记

简介
“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/



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值