zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    C++里面关于虚函数的一些注意点
    HDOJ 2736 Surprising Strings
    hdu
    hdu 4404 Worms(多边形与圆的交)
    HTC one/M7电信802d 毒蛇ViperOne2.1.0/高级毒蛇工具/完美root,精简/更多自定义,稳定,流畅ROM
    Replace
    Centos环境下部署游戏服务器-权限
    jdk1.6与1.7垃圾回收
    java--基于socket的网络传输开发
    番外:android模拟器连不上网
  • 原文地址:https://www.cnblogs.com/angelyan/p/10969624.html
Copyright © 2011-2022 走看看