测试
传统测试or表格测试
传统测试
- 测试数据和测试逻辑混在一起
- 出错信息不明确
- 一旦一个信息出错,整个测试结束
表格驱动测试
- 分离的测试数据和测试逻辑
- 明确的出错信息
- 可以部分失败
Example:
func TestLenOfNorepeatingSubStr(t *testing.T) {
tests := []struct {
str string
len int
} {
// normal case
{"pwwkew", 3},
{"abdfddsa", 4},
// chinese support
{"一二而已一", 4},
{"捡垃圾三个逻辑天天脚", 8},
}
for _, tb := range tests {
if actual := lenOfNorepeatingSubStr(tb.str); actual != tb.len {
t.Errorf("str = %s, test max substr len = %d, actual max substrlen = %d",
tb.str, tb.len, actual)
}
}
}
测试文件目录下运行go test .
即可测试,控制台输出”ok study/repeating 0.006s”
代码覆盖率
- 运行
got test -coverprofile=c.out
- 运行
go tool cover -html=c.out
性能测试
func BenchmarkLenOfNorepeatingSubStr(b *testing.B) {
str := "捡垃圾三个逻辑天天脚"
len := 8
for i:=0; i < b.N; i++ {
if actual := lenOfNorepeatingSubStr(str); actual != len {
b.Errorf("str = %s, test max substr len = %d, actual max substrlen = %d",
str, len, actual)
}
}
}
- 运行
go test -bench .
性能调优
- 运行
go test -bench . -cpuprofile=cpu.out
// 获取性能数据 - 运行
go tool pprof cpu.out
// 查看性能数据 - 执行
web
(执行web提示:Failed to execute dot. Is Graphviz installed? Error: exec: “dot”: executable file not found in $PATH,安装Graphviz即可)
不重复子串优化 原始版本
var lastChIndex = make([]int, 0xffff)
func lenOfNorepeatingSubStr(str string) int {
for i:=0; i < len(lastChIndex); i++ {
lastChIndex[i] = -1
}
startIndex := 0
maxLeng := 0
for index, ch := range []rune(str) {
if ci := lastChIndex[ch]; lastChIndex[ch] != -1 && ci >= startIndex {
startIndex = lastChIndex[ch] + 1
}
if index - startIndex + 1 > maxLeng {
maxLeng = index - startIndex + 1
}
lastChIndex[ch] = index
}
return maxLeng
}