go 自动化测试
// a + b
func calcTriangle( a,b int) int {
var c int
c = int(math.Sqrt(float64(a*a + b*b)))
return c
}
package main
import "testing"
// go 自动识别,通过t 打印测试错误信息
func TestTriangle( t *testing.T){
tests :=[]struct{a,b,c int}{
{3,4,5},
{5,12,13},
{8,15,17},
{12,35,37},
}
for _ , tt := range tests {
if actual := calcTriangle(tt.a,tt.b); actual != tt.c{
t.Errorf("calcTriangle(%d, %d) ; got %d; expected %d",tt.a,tt.b,actual,tt.c)
}
}
}
terminal 下测试
go test . //会执行当前目录下所有测试用例
如: go test .
ok learngo/basic 0.742s
测试代码覆盖率
命令行执行 ,生成c.out 文件
go test -coverprofile=c.out
以html 方式查询 代码覆盖率报告文件
go tool cover -html=c.out
性能测试
// Benchmark 固定写法
func BenchmarkDubstr(b *testing.B) {
s :="以html 方式查询 代码覆盖率报告文件码覆盖率报"
ans := 14
for i := 0 ; i < b.N; i++{
actual := lengthOfNonRepeatingSubStr(s)
if actual != ans {
b.Errorf("got %d for input %s : expected %d ",actual,s,ans)
}
}
}
命令行执行性能测试 go test -bench .
结果 : MacBook-Air:nonrepeating$ go test -bench .
goos: darwin
goarch: amd64
pkg: learngo/nonrepeating
BenchmarkDubstr-4 445730 2695 ns/op
PASS
ok learngo/nonrepeating 2.392s
//获取性能数据
MacBook-Air:nonrepeating$** go test -bench . -cpuprofile cpu.out**
// 查看性能数据
MacBook-Air:nonrepeating$ go tool pprof cpu.out
Type: cpu Time: Jan 12, 2022 at 11:42pm (CST) Duration: 1.30s, Total samples = 1.08s (82.91%) Entering interactive mode (type "help" for commands, "o" for options) (pprof) web //输入web 分析性能数据,未安装Graphviz工具如下提示:
failed to execute dot. Is Graphviz installed? Error: exec: "dot": executable file not found in $PATH
Graphviz 下载地址: http://www.graphviz.org/
调优前: