欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

一步步教你编写可测试的Go语言代码

程序员文章站 2022-07-05 08:45:15
第一个测试 “hello test!” 首先,在我们$gopath/src目录下创建hello目录,作为本文涉及到的所有示例代码的根目录。 然后,新建名为hello.g...

第一个测试 “hello test!”

首先,在我们$gopath/src目录下创建hello目录,作为本文涉及到的所有示例代码的根目录。

然后,新建名为hello.go的文件,定义一个函数hello() ,功能是返回一个由若干单词拼接成句子:

package hello

func hello() string {
 words := []string{"hello", "func", "in", "package", "hello"}
 wl := len(words)

 sentence := ""
 for key, word := range words {
  sentence += word
  if key < wl-1 {
   sentence += " "
  } else {
   sentence += "."
  }
 }
 return sentence
}

接着,新建名为hello_test.go的文件,填入如下内容:

package hello

import (
 "fmt"
 "testing"
)

func testhello(t *testing.t) {
 got := hello()
 expect := "hello func in package hello."

 if got != expect {
  t.errorf("got [%s] expected [%s]", got, expect)
 }
}

func benchmarkhello(b *testing.b) {
 for i := 0; i < b.n; i++ {
  hello()
 }
}

func examplehello() {
 hl := hello()
 fmt.println(hl)
 // output: hello func in package hello.
}

最后,打开终端,进入hello目录,输入go test命令并回车,可以看到如下输出:

pass
ok  hello 0.007s

编写测试代码

golang的测试代码位于某个包的源代码中名称以_test.go结尾的源文件里,测试代码包含测试函数、测试辅助代码和示例函数;测试函数有以test开头的功能测试函数和以benchmark开头的性能测试函数两种,测试辅助代码是为测试函数服务的公共函数、初始化函数、测试数据等,示例函数则是以example开头的说明被测试函数用法的函数。

大部分情况下,测试代码是作为某个包的一部分,意味着它可以访问包中不可导出的元素。但在有需要的时候(如避免循环依赖)也可以修改测试文件的包名,如package hello的测试文件,包名可以设为package hello_test。

功能测试函数

功能测试函数需要接收*testing.t类型的单一参数t,testing.t 类型用来管理测试状态和支持格式化的测试日志。测试日志在测试执行过程中积累起来,完成后输出到标准错误输出。

下面是从go标准库摘抄的 testing.t类型的常用方法的用法:

测试函数中的某条测试用例执行结果与预期不符时,调用t.error()t.errorf()方法记录日志并标记测试失败

# /usr/local/go/src/bytes/compare_test.go
func testcompareidenticalslice(t *testing.t) {
 var b = []byte("hello gophers!")
 if compare(b, b) != 0 {
  t.error("b != b")
 }
 if compare(b, b[:1]) != 1 {
  t.error("b > b[:1] failed")
 }
}

使用t.fatal()t.fatalf()方法,在某条测试用例失败后就跳出该测试函数

# /usr/local/go/src/bytes/reader_test.go
func testreadafterbigseek(t *testing.t) {
 r := newreader([]byte("0123456789"))
 if _, err := r.seek(1<<31+5, os.seek_set); err != nil {
  t.fatal(err)
 }
 if n, err := r.read(make([]byte, 10)); n != 0 || err != io.eof {
  t.errorf("read = %d, %v; want 0, eof", n, err)
 }
}

使用t.skip()t.skipf()方法,跳过某条测试用例的执行

# /usr/local/go/src/archive/zip/zip_test.go
func testzip64(t *testing.t) {
 if testing.short() {
  t.skip("slow test; skipping")
 }
 const size = 1 << 32 // before the "end\n" part
 buf := testzip64(t, size)
 testzip64directoryrecordlength(buf, t)
}

执行测试用例的过程中通过t.log()t.logf()记录日志

# /usr/local/go/src/regexp/exec_test.go
func testfowler(t *testing.t) {
 files, err := filepath.glob("testdata/*.dat")
 if err != nil {
  t.fatal(err)
 }
 for _, file := range files {
  t.log(file)
  testfowler(t, file)
 }
}

使用t.parallel()标记需要并发执行的测试函数

# /usr/local/go/src/runtime/stack_test.go
func teststackgrowth(t *testing.t) {
 t.parallel()
 var wg sync.waitgroup

 // in a normal goroutine
 wg.add(1)
 go func() {
  defer wg.done()
  growstack()
 }()
 wg.wait()

 // ...
}

性能测试函数

性能测试函数需要接收*testing.b类型的单一参数b,性能测试函数中需要循环b.n次调用被测函数。testing.b 类型用来管理测试时间和迭代运行次数,也支持和testing.t相同的方式管理测试状态和格式化的测试日志,不一样的是testing.b的日志总是会输出。

下面是从go标准库摘抄的 testing.b类型的常用方法的用法:

在函数中调用t.reportallocs() ,启用内存使用分析

# /usr/local/go/src/bufio/bufio_test.go
func benchmarkwriterflush(b *testing.b) {
 b.reportallocs()
 bw := newwriter(ioutil.discard)
 str := strings.repeat("x", 50)
 for i := 0; i < b.n; i++ {
  bw.writestring(str)
  bw.flush()
 }
}

通过 b.stoptimer() b.resettimer() b.starttimer()来停止、重置、启动 时间经过和内存分配计数

# /usr/local/go/src/fmt/scan_test.go
func benchmarkscanints(b *testing.b) {
 b.resettimer()
 ints := makeints(intcount)
 var r recursiveint
 for i := b.n - 1; i >= 0; i-- {
  buf := bytes.newbuffer(ints)
  b.starttimer()
  scanints(&r, buf)
  b.stoptimer()
 }
}

调用b.setbytes()记录在一个操作中处理的字节数

# /usr/local/go/src/testing/benchmark.go
func benchmarkfields(b *testing.b) {
 b.setbytes(int64(len(fieldsinput)))
 for i := 0; i < b.n; i++ {
  fields(fieldsinput)
 }
}

通过b.runparallel()方法和 *testing.pb类型的next()方法来并发执行被测对象

# /usr/local/go/src/sync/atomic/value_test.go
func benchmarkvalueread(b *testing.b) {
 var v value
 v.store(new(int))
 b.runparallel(func(pb *testing.pb) {
  for pb.next() {
   x := v.load().(*int)
   if *x != 0 {
    b.fatalf("wrong value: got %v, want 0", *x)
   }
  }
 })
}

测试辅助代码

测试辅助代码是编写测试代码过程中因代码重用和代码质量考虑而产生的。主要包括如下方面:

引入依赖的外部包,如每个测试文件都需要的 testing 包等:

# /usr/local/go/src/log/log_test.go:
import (
 "bytes"
 "fmt"
 "os"
 "regexp"
 "strings"
 "testing"
 "time"
)

定义多次用到的常量和变量,测试用例数据等:

# /usr/local/go/src/log/log_test.go:
const (
 rdate   = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
 rtime   = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
 rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
 rline   = `(57|59):` // must update if the calls to l.printf / l.print below move
 rlongfile  = `.*/[a-za-z0-9_\-]+\.go:` + rline
 rshortfile = `[a-za-z0-9_\-]+\.go:` + rline
)

// ...

var tests = []tester{
 // individual pieces:
 {0, "", ""},
 {0, "xxx", "xxx"},
 {ldate, "", rdate + " "},
 {ltime, "", rtime + " "},
 {ltime | lmicroseconds, "", rtime + rmicroseconds + " "},
 {lmicroseconds, "", rtime + rmicroseconds + " "}, // microsec implies time
 {llongfile, "", rlongfile + " "},
 {lshortfile, "", rshortfile + " "},
 {llongfile | lshortfile, "", rshortfile + " "}, // shortfile overrides longfile
 // everything at once:
 {ldate | ltime | lmicroseconds | llongfile, "xxx", "xxx" + rdate + " " + rtime + rmicroseconds + " " + rlongfile + " "},
 {ldate | ltime | lmicroseconds | lshortfile, "xxx", "xxx" + rdate + " " + rtime + rmicroseconds + " " + rshortfile + " "},
}

和普通的golang源代码一样,测试代码中也能定义init函数,init函数会在引入外部包、定义常量、声明变量之后被自动调用,可以在init函数里编写测试相关的初始化代码。

# /usr/local/go/src/bytes/buffer_test.go
func init() {
 testbytes = make([]byte, n)
 for i := 0; i < n; i++ {
  testbytes[i] = 'a' + byte(i%26)
 }
 data = string(testbytes)
}

封装测试专用的公共函数,抽象测试专用的结构体等:

# /usr/local/go/src/log/log_test.go:
type tester struct {
 flag int
 prefix string
 pattern string // regexp that log output must match; we add ^ and expected_text$ always
}

// ...

func testprint(t *testing.t, flag int, prefix string, pattern string, useformat bool) {
 // ...
}

示例函数

示例函数无需接收参数,但需要使用注释的 output: 标记说明示例函数的输出值,未指定output:标记或输出值为空的示例函数不会被执行。

示例函数需要归属于某个 包/函数/类型/类型 的方法,具体命名规则如下:

func example() { ... }  # 包的示例函数
func examplef() { ... }  # 函数f的示例函数
func examplet() { ... }  # 类型t的示例函数
func examplet_m() { ... } # 类型t的m方法的示例函数

# 多示例函数 需要跟下划线加小写字母开头的后缀
func example_suffix() { ... }
func examplef_suffix() { ... }
func examplet_suffix() { ... }
func examplet_m_suffix() { ... }

go doc 工具会解析示例函数的函数体作为对应 包/函数/类型/类型的方法 的用法。

测试函数的相关说明,可以通过go help testfunc来查看帮助文档。

使用 go test 工具

golang中通过命令行工具go test来执行测试代码,打开shell终端,进入需要测试的包所在的目录执行 go test,或者直接执行go test $pkg_name_in_gopath即可对指定的包执行测试。

通过形如go test github.com/tabalt/...的命令可以执行$gopath/github.com/tabalt/目录下所有的项目的测试。go test std命令则可以执行golang标准库的所有测试。

如果想查看执行了哪些测试函数及函数的执行结果,可以使用-v参数:

[tabalt@localhost hello] go test -v
=== run testhello
--- pass: testhello (0.00s)
=== run examplehello
--- pass: examplehello (0.00s)
pass
ok  hello 0.006s

假设我们有很多功能测试函数,但某次测试只想执行其中的某一些,可以通过-run参数,使用正则表达式来匹配要执行的功能测试函数名。如下面指定参数后,功能测试函数testhello不会执行到。

[tabalt@localhost hello] go test -v -run=xxx
pass
ok  hello 0.006s

性能测试函数默认并不会执行,需要添加-bench参数,并指定匹配性能测试函数名的正则表达式;例如,想要执行某个包中所有的性能测试函数可以添加参数-bench . 或 -bench=.。

[tabalt@localhost hello] go test -bench=.
pass
benchmarkhello-8  2000000   657 ns/op
ok  hello 1.993s

想要查看性能测试时的内存情况,可以再添加参数-benchmem:

[tabalt@localhost hello] go test -bench=. -benchmem
pass
benchmarkhello-8  2000000   666 ns/op   208 b/op   9 allocs/op
ok  hello 2.014s

参数-cover可以用来查看我们编写的测试对代码的覆盖率:


详细的覆盖率信息,可以通过-coverprofile输出到文件,并使用go tool cover来查看,用法请参考go tool cover -help

更多go test命令的参数及用法,可以通过go help testflag来查看帮助文档。

高级测试技术

io相关测试

testing/iotest包中实现了常用的出错的reader和writer,可供我们在io相关的测试中使用。主要有:

触发数据错误dataerrreader,通过dataerrreader()函数创建

读取一半内容的halfreader,通过halfreader()函数创建

读取一个byte的onebytereader,通过onebytereader()函数创建

触发超时错误的timeoutreader,通过timeoutreader()函数创建

写入指定位数内容后停止的truncatewriter,通过truncatewriter()函数创建

读取时记录日志的readlogger,通过newreadlogger()函数创建

写入时记录日志的writelogger,通过newwritelogger()函数创建

黑盒测试

testing/quick包实现了帮助黑盒测试的实用函数 check和checkequal。

check函数的第1个参数是要测试的只返回bool值的黑盒函数f,check会为f的每个参数设置任意值并多次调用,如果f返回false,check函数会返回错误值 *checkerror。check函数的第2个参数 可以指定一个quick.config类型的config,传nil则会默认使用quick.defaultconfig。quick.config结构体包含了测试运行的选项。

# /usr/local/go/src/math/big/int_test.go
func checkmul(a, b []byte) bool {
 var x, y, z1 int
 x.setbytes(a)
 y.setbytes(b)
 z1.mul(&x, &y)

 var z2 int
 z2.setbytes(mulbytes(a, b))

 return z1.cmp(&z2) == 0
}

func testmul(t *testing.t) {
 if err := quick.check(checkmul, nil); err != nil {
  t.error(err)
 }
}

checkequal函数是比较给定的两个黑盒函数是否相等,函数原型如下:

func checkequal(f, g interface{}, config *config) (err error)

http测试

net/http/httptest包提供了http相关代码的工具,我们的测试代码中可以创建一个临时的httptest.server来测试发送http请求的代码:

ts := httptest.newserver(http.handlerfunc(func(w http.responsewriter, r *http.request) {
 fmt.fprintln(w, "hello, client")
}))
defer ts.close()

res, err := http.get(ts.url)
if err != nil {
 log.fatal(err)
}

greeting, err := ioutil.readall(res.body)
res.body.close()
if err != nil {
 log.fatal(err)
}

fmt.printf("%s", greeting)

还可以创建一个应答的记录器httptest.responserecorder来检测应答的内容:

handler := func(w http.responsewriter, r *http.request) {
 http.error(w, "something failed", http.statusinternalservererror)
}

req, err := http.newrequest("get", "http://example.com/foo", nil)
if err != nil {
 log.fatal(err)
}

w := httptest.newrecorder()
handler(w, req)

fmt.printf("%d - %s", w.code, w.body.string())

测试进程操作行为

当我们被测函数有操作进程的行为,可以将被测程序作为一个子进程执行测试。下面是一个例子:

//被测试的进程退出函数
func crasher() {
 fmt.println("going down in flames!")
 os.exit(1)
}

//测试进程退出函数的测试函数
func testcrasher(t *testing.t) {
 if os.getenv("be_crasher") == "1" {
  crasher()
  return
 }
 cmd := exec.command(os.args[0], "-test.run=testcrasher")
 cmd.env = append(os.environ(), "be_crasher=1")
 err := cmd.run()
 if e, ok := err.(*exec.exiterror); ok && !e.success() {
  return
 }
 t.fatalf("process ran with err %v, want exit status 1", err)
}

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家学习或者使用go语言能有所帮助,如果有疑问大家可以留言交流。