golang的表格驱动测试

一、leetcode的算法题

package main

import (
    "fmt"
    "strings"
)

func lengthOfNonRepeatingSubStr(s string)int{
    lastOccurred :=make(map[rune]int)
    start:=0
    maxLength:=0
    //将字符串转成 ASCII 码的切片,循环获取下标与值
    for i,ch:=range []rune(s){
        if lastI,ok:=lastOccurred[ch];ok && lastI>=start{
            start=lastOccurred[ch]+1
        }
        if i-start+1>maxLength {
            maxLength=i-start+1
        }
        lastOccurred[ch]=i
    }
    return maxLength
}
func main() {
    fmt.Println(
        lengthOfNonRepeatingSubStr("abcabcbb"),
        lengthOfNonRepeatingSubStr("bbbbb"),
        lengthOfNonRepeatingSubStr("阿斯顿法国规划开发阿斯顿发放"))

    fmt.Println([]byte("asfsawersd"))

    str1:="sdfsad asdfsadf sad;fasfd"
    s:=strings.Fields(str1)
    for index,value:=range s {
        fmt.Println(index,value)
    }
}

二、普通测试代码

package main

import "testing"

func TestSubstr(t *testing.T)  {
    tests:=[]struct{
        s string
        ans int
    }{
        {"abssafds",4},
        {"pwwkew",3},
        {"",0},
        {"b",1},
        {"bbbbbbbb",1},
        {"asadfasdf",4},
    }

    for _,tt:=range tests {
        actual:=lengthOfNonRepeatingSubStr(tt.s)
        if actual !=tt.ans{
            t.Errorf("got %d for input %s:"+"expected %d",actual,tt.s,tt.ans)
        }
    }
}

#测试通过
#=== RUN   TestSubstr
#--- PASS: TestSubstr (0.00s)
#PASS

#测试错误
#修改错误的数据{"pwwkew",2},
#=== RUN   TestSubstr
#--- FAIL: TestSubstr (0.00s)
#    leetcode_test.go:21: got 3 for input pwwkew:expected 2
#FAIL

三、性能测试代码

func BenchmarkSubstr(b *testing.B){
    s:="黑化肥挥发发灰会花飞灰化肥挥发发黑会飞花"
    ans:=8

    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)
        }
    }
}

#执行结果
#goos: windows
#goarch: amd64
#pkg: awesomeProject/leetcode
#运行了100万次,每次运行用了1362ns
#BenchmarkSubstr-8        1000000          1361 ns/op
#PASS

 

posted @ 2019-06-03 19:42  Maple_feng  阅读(651)  评论(0编辑  收藏  举报