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
  • 相关阅读:
    【LeetCode】70. 爬楼梯
    C++Socket编程—socket网络模型之IOCP
    leetcode_买卖股票_dp状态机
    leetcode_买卖股票_暴力递归
    tensorflow正则化
    程序员掌握这些面试技巧,成功上岸!
    阶段二Linux 高级编程:Linux基础命令三019
    阶段二Linux 高级编程:Linux基础命令二018
    阶段二Linux 高级编程:Linux基础命令一017
    阶段一Python核心编程:面向对象版学员管理系统016
  • 原文地址:https://www.cnblogs.com/angelyan/p/10969624.html
Copyright © 2011-2022 走看看