惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
I
InfoQ
The Register - Security
The Register - Security
L
LangChain Blog
H
Help Net Security
The GitHub Blog
The GitHub Blog
S
Schneier on Security
博客园 - 【当耐特】
W
WeLiveSecurity
Attack and Defense Labs
Attack and Defense Labs
IT之家
IT之家
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Google DeepMind News
Google DeepMind News
The Cloudflare Blog
H
Heimdal Security Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Y
Y Combinator Blog
雷峰网
雷峰网
N
Netflix TechBlog - Medium
Security Archives - TechRepublic
Security Archives - TechRepublic
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
L
Lohrmann on Cybersecurity
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
T
The Exploit Database - CXSecurity.com
P
Privacy & Cybersecurity Law Blog
G
GRAHAM CLULEY
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
V
Visual Studio Blog
博客园 - 聂微东
PCI Perspectives
PCI Perspectives
Last Week in AI
Last Week in AI
A
Arctic Wolf
宝玉的分享
宝玉的分享
T
The Blog of Author Tim Ferriss
S
Secure Thoughts
T
Threat Research - Cisco Blogs
GbyAI
GbyAI
云风的 BLOG
云风的 BLOG
D
Darknet – Hacking Tools, Hacker News & Cyber Security
S
SegmentFault 最新的问题
SecWiki News
SecWiki News
月光博客
月光博客
大猫的无限游戏
大猫的无限游戏
Schneier on Security
Schneier on Security
P
Proofpoint News Feed
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
AI
AI
Engineering at Meta
Engineering at Meta

ZDDHUB

PixelsMeasure 开发第二年总结 PixelsMeasure 开发一年总结 Swift/SwiftUI 踩坑记 为什么说 GPT 利好程序员 ChatGPT 编程实现 Web 数字水印 Web 数字水印探究 Micro Frontends for Mobile URL 加载系统(URL Loading System) Protocol Buffers GraphQL 从 0 到 1 开发一款 IOS 应用 - Swift MV* 软件设计架构 学习一个新技巧需要多久? 不停机数据库迁移 Rspec 如何 mock update 方法更新自己? Rails 使用 mysql2 出现的段错误 使用 Docker-compose 部署 Rails 应用到生产环境 Cocoa troubleshooting 独孤九剑 Dit (0x05) - 终端篇 Gem-based Jekyll theme 开发小记 Miscellaneous 前端手记 TodoMVC 之 Redux 篇 前端手记 TodoMVC 之 Server 篇 前端手记 TodoMVC 之 React 篇 前端手记 TodoMVC 之 CSS 篇 独孤九剑 Dit (0x03) - 缓存篇 英语小抄 LLDB debug Golang Make mistakes 大牛俱乐部上线啦 独孤九剑 Dit (0x02) - 数据结构篇 独孤九剑 Dit (0x01) - 总决 独孤九剑 Dit (0x00) - 我为什么要做 Dit 零值强制类型转换的使用 终端颜色输出重定向 Go语法简略 - 正则表达式 Makefile Go语法简略 - Duck框架探索 Go语法简略 - 依赖注入 Go语法简略 - web应用框架 Go语法简略 - 反射 Go语法简略 - 面向对象 Go语法简略 - goroutine Go语法简略 - 方法和接口 Go语法简略 - 基础篇 大牛 轻松科研 未来这几年 为 Android Studio 创建图标 Shell Git Vim 金庸答百问 论拖延症 Flex, A fast scanner generator 有理想的人 从虚拟到现实 常用视频转接口 Recognizer configuration on CentOS 整个世界清静了 《Python源码剖析》读书笔记
独孤九剑 Dit (0x04) - 测试篇
zddhub · 2016-06-26 · via ZDDHUB

《南皮县志·风土志下·歌谣》:“兵马不动,粮草先行”。作战时兵马还没出动,军用粮草的运输要先行一步。在开发新功能之前,先编写测试代码,然后只编写使测试通过的功能代码,这种以测试驱动开发的开发模式是我非常推荐的。

对 Dit 的贡献要求需要通过单元测试,编写 Dit 的任意模块,都需要一并编写测试用例。本文先简述一下 Go 对测试的支持,后续会陆续提供 Dit 的测试方案和测试报告。

Go 对测试的支持

Go 自带的测试框架 testing 支持单元测试和性能测试。Go 规定测试文件以 _test.go 为后缀,使用命令 go test 命令自动运行测试用例。

单元测试

Test 开头的方法为一个测试用例,并拥有一个参数 *testing.T, 写法如下:

Xxx 部分为任意的字母数字组合,首字母不能是小写字母。*testing.T 可记录错误或者标记错误状态。可通过 Short 判断略过一部分测试,加快测试时间。如下:

func TestTimeConsuming(t *testing.T) {
  if testing.Short() {
    t.Skip("skipping test in short mode.")
  }
  ...
}

性能测试

性能测试用例以 Benchmark 开始,参数为 *testing.B, 写法如下:

func BenchmarkXxx(*testing.B)

使用 go test 运行性能测试用例时,需要加上参数 -bench

在编写性能测试用例时,需牢记在循环体内使用 testing.B.N , 以使测试可以正常的运行:

func BenchmarkHello(b *testing.B) {
  for i := 0; i < b.N; i++ {
    fmt.Sprintf("hello")
  }
}

对耗时的初始化操作,可在测试用例内部重置计时器 ResetTimer,确保引入不必要的误差:

func BenchmarkBigLen(b *testing.B) {
  big := NewBig()
  b.ResetTimer()
  for i := 0; i < b.N; i++ {
    big.Len()
  }
}

使用 RunParallel 测试并行模块, 运行时需要加上参数 -cpu:

func BenchmarkTemplateParallel(b *testing.B) {
  templ := template.Must(template.New("test").Parse("Hello, \{\{.}}!"))
  b.RunParallel(func(pb *testing.PB) {
    var buf bytes.Buffer
    for pb.Next() {
      buf.Reset()
      templ.Execute(&buf, "World")
    }
  })
}

标准输出测试

testing 包提供对标准终端输出的测试, 测试用例以 Example 开始,结果使用注释的方式,写在 Output: 之后:

func ExampleHello() {
  fmt.Println("hello")
  // Output: hello
}

Example 用例的命名规则:

func Example() { ... }
func ExampleF() { ... } // F - function
func ExampleT() { ... } // T - type
func ExampleT_M() { ... } // T_M - method M on type T

// 多个 example 可用后缀区分,The suffix must start with a lower-case letter.
func Example_suffix() { ... }
func ExampleF_suffix() { ... }
func ExampleT_suffix() { ... }
func ExampleT_M_suffix() { ... }

Main 测试

当需要批量 setup 或 teardown 测试环境时,可使用:

func TestMain(m *testing.M)

TestMain 简单实现如下:

func TestMain(m *testing.M) {
  flag.Parse()
  os.Exit(m.Run())
}

Demo

写一个简单的示例,来 Demo 一下 testing 测试框架的用法。

// div.go
package test

import (
  "errors"
)

func div(a, b int) (int, error) {
  if b == 0 {
    return 0, errors.New("b must NOT be 0")
  }
  return a / b, nil
}

// div_test.go
package test

import (
  "errors"
  "flag"
  "fmt"
  "os"
  "testing"
  "time"
)

func TestDivNormal(t *testing.T) {
  ret, err := div(6, 2)
  if err != nil || ret != 3 {
    t.Error("6/2=3")
  }
}

func TestDivZero(t *testing.T) {
  _, err := div(6, 0)
  if err.Error() != errors.New("b must NOT be 0").Error() {
    t.Error("zero div error")
  }
}

func BenchmarkDiv(b *testing.B) {
  b.Log("run times:", b.N)
  for i := 0; i < b.N; i++ {
    div(6, 2)
  }
}

func BenchmarkDiv_Sleep(b *testing.B) {
  b.Log("run times:", b.N)
  time.Sleep(3000) // 模拟费时操作
  b.ResetTimer()
  for i := 0; i < b.N; i++ {
    div(6, 2)
  }
}

func ExampleOutput() {
  ret, _ := div(6, 2)
  fmt.Println("6 / 2 =", ret)
  // Output:
  // 6 / 2 = 3
}

func TestMain(m *testing.M) {
  flag.Parse()
  fmt.Println("Setup ... Done")
  ret := m.Run()
  fmt.Println("Teardown ... Done")
  os.Exit(ret)
}

运行 go test -v, 结果如下:

localhost:test zdd$ go test -v
Setup ... Done
=== RUN TestDivNormal
--- PASS: TestDivNormal (0.00s)
=== RUN TestDivZero
--- PASS: TestDivZero (0.00s)
=== RUN: ExampleOutput
--- PASS: ExampleOutput (0.00s)
PASS
Teardown ... Done
ok    github.com/zddhub/hellogo/test  0.005s

默认不执行性能测试用例,使用 go test -v -bench . 执行:

localhost:test zdd$ go test -v -bench .
Setup ... Done
=== RUN TestDivNormal
--- PASS: TestDivNormal (0.00s)
=== RUN TestDivZero
--- PASS: TestDivZero (0.00s)
=== RUN: ExampleOutput
--- PASS: ExampleOutput (0.00s)
PASS
BenchmarkDiv  100000000         16.2 ns/op
--- BENCH: BenchmarkDiv
  div_test.go:27: run times: 1
  div_test.go:27: run times: 100
  div_test.go:27: run times: 10000
  div_test.go:27: run times: 1000000
  div_test.go:27: run times: 100000000
BenchmarkDiv_Sleep  100000000         16.4 ns/op
--- BENCH: BenchmarkDiv_Sleep
  div_test.go:34: run times: 1
  div_test.go:34: run times: 100
  div_test.go:34: run times: 10000
  div_test.go:34: run times: 1000000
  div_test.go:34: run times: 100000000
Teardown ... Done
ok    github.com/zddhub/hellogo/test  3.305s

如果你喜欢这篇文章,欢迎赞赏作者以示鼓励