Go 测试

测试

传统测试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”

代码覆盖率

  1. 运行got test -coverprofile=c.out
  2. 运行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)
        }
    }
}
  1. 运行go test -bench .

性能调优

  1. 运行go test -bench . -cpuprofile=cpu.out // 获取性能数据
  2. 运行go tool pprof cpu.out // 查看性能数据
  3. 执行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
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值