编写可测试的Go代码

前端之家收集整理的这篇文章主要介绍了编写可测试的Go代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

原文链接http://tabalt.net/blog/golang...

Golang作为一门标榜工程化的语言,提供了非常简便、实用的编写单元测试的能力。本文通过Golang源码包中的用法,来学习在实际项目中如何编写可测试的Go代码

第一个测试 “Hello Test!”

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

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

  1. package hello
  2.  
  3. func hello() string {
  4. words := []string{"hello","func","in","package","hello"}
  5. wl := len(words)
  6.  
  7. sentence := ""
  8. for key,word := range words {
  9. sentence += word
  10. if key < wl-1 {
  11. sentence += " "
  12. } else {
  13. sentence += "."
  14. }
  15. }
  16. return sentence
  17. }

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

  1. package hello
  2.  
  3. import (
  4. "fmt"
  5. "testing"
  6. )
  7.  
  8. func TestHello(t *testing.T) {
  9. got := hello()
  10. expect := "hello func in package hello."
  11.  
  12. if got != expect {
  13. t.Errorf("got [%s] expected [%s]",got,expect)
  14. }
  15. }
  16.  
  17. func BenchmarkHello(b *testing.B) {
  18. for i := 0; i < b.N; i++ {
  19. hello()
  20. }
  21. }
  22.  
  23. func ExampleHello() {
  24. hl := hello()
  25. fmt.Println(hl)
  26. // Output: hello func in package hello.
  27. }

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

  1. PASS
  2. 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()方法记录日志并标记测试失败

  1. # /usr/local/go/src/bytes/compare_test.go
  2. func TestCompareIdenticalSlice(t *testing.T) {
  3. var b = []byte("Hello Gophers!")
  4. if Compare(b,b) != 0 {
  5. t.Error("b != b")
  6. }
  7. if Compare(b,b[:1]) != 1 {
  8. t.Error("b > b[:1] Failed")
  9. }
  10. }
  • 使用t.Fatal()和t.Fatalf()方法,在某条测试用例失败后就跳出该测试函数

  1. # /usr/local/go/src/bytes/reader_test.go
  2. func TestReadAfterBigSeek(t *testing.T) {
  3. r := NewReader([]byte("0123456789"))
  4. if _,err := r.Seek(1<<31+5,os.SEEK_SET); err != nil {
  5. t.Fatal(err)
  6. }
  7. if n,err := r.Read(make([]byte,10)); n != 0 || err != io.EOF {
  8. t.Errorf("Read = %d,%v; want 0,EOF",n,err)
  9. }
  10. }
  • 使用t.Skip()和t.Skipf()方法,跳过某条测试用例的执行

  1. # /usr/local/go/src/archive/zip/zip_test.go
  2. func TestZip64(t *testing.T) {
  3. if testing.Short() {
  4. t.Skip("slow test; skipping")
  5. }
  6. const size = 1 << 32 // before the "END\n" part
  7. buf := testZip64(t,size)
  8. testZip64DirectoryRecordLength(buf,t)
  9. }
  • 执行测试用例的过程中通过t.Log()和t.Logf()记录日志

  1. # /usr/local/go/src/regexp/exec_test.go
  2. func TestFowler(t *testing.T) {
  3. files,err := filepath.Glob("testdata/*.dat")
  4. if err != nil {
  5. t.Fatal(err)
  6. }
  7. for _,file := range files {
  8. t.Log(file)
  9. testFowler(t,file)
  10. }
  11. }
  1. # /usr/local/go/src/runtime/stack_test.go
  2. func TestStackGrowth(t *testing.T) {
  3. t.Parallel()
  4. var wg sync.WaitGroup
  5.  
  6. // in a normal goroutine
  7. wg.Add(1)
  8. go func() {
  9. defer wg.Done()
  10. growStack()
  11. }()
  12. wg.Wait()
  13.  
  14. // ...
  15. }

性能测试函数

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

下面是从Go标准库摘抄的 testing.B类型的常用方法用法

  • 函数调用t.ReportAllocs(),启用内存使用分析

  1. # /usr/local/go/src/bufio/bufio_test.go
  2. func BenchmarkWriterFlush(b *testing.B) {
  3. b.ReportAllocs()
  4. bw := NewWriter(IoUtil.Discard)
  5. str := strings.Repeat("x",50)
  6. for i := 0; i < b.N; i++ {
  7. bw.WriteString(str)
  8. bw.Flush()
  9. }
  10. }
  • 通过 b.StopTimer()、b.ResetTimer()、b.StartTimer()来停止、重置、启动 时间经过和内存分配计数

  1. # /usr/local/go/src/fmt/scan_test.go
  2. func BenchmarkScanInts(b *testing.B) {
  3. b.ResetTimer()
  4. ints := makeInts(intCount)
  5. var r RecursiveInt
  6. for i := b.N - 1; i >= 0; i-- {
  7. buf := bytes.NewBuffer(ints)
  8. b.StartTimer()
  9. scanInts(&r,buf)
  10. b.StopTimer()
  11. }
  12. }
  • 调用b.SetBytes()记录在一个操作中处理的字节数

  1. # /usr/local/go/src/testing/benchmark.go
  2. func BenchmarkFields(b *testing.B) {
  3. b.SetBytes(int64(len(fieldsInput)))
  4. for i := 0; i < b.N; i++ {
  5. Fields(fieldsInput)
  6. }
  7. }
  • 通过b.RunParallel()方法和 *testing.PB类型的Next()方法来并发执行被测对象

  1. # /usr/local/go/src/sync/atomic/value_test.go
  2. func BenchmarkValueRead(b *testing.B) {
  3. var v Value
  4. v.Store(new(int))
  5. b.RunParallel(func(pb *testing.PB) {
  6. for pb.Next() {
  7. x := v.Load().(*int)
  8. if *x != 0 {
  9. b.Fatalf("wrong value: got %v,want 0",*x)
  10. }
  11. }
  12. })
  13. }

测试辅助代码

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

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

  1. # /usr/local/go/src/log/log_test.go:
  2. import (
  3. "bytes"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "strings"
  8. "testing"
  9. "time"
  10. )
  • 定义多次用到的常量和变量,测试用例数据等:

  1. # /usr/local/go/src/log/log_test.go:
  2. const (
  3. Rdate = `[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]`
  4. Rtime = `[0-9][0-9]:[0-9][0-9]:[0-9][0-9]`
  5. Rmicroseconds = `\.[0-9][0-9][0-9][0-9][0-9][0-9]`
  6. Rline = `(57|59):` // must update if the calls to l.Printf / l.Print below move
  7. Rlongfile = `.*/[A-Za-z0-9_\-]+\.go:` + Rline
  8. Rshortfile = `[A-Za-z0-9_\-]+\.go:` + Rline
  9. )
  10.  
  11. // ...
  12.  
  13. var tests = []tester{
  14. // individual pieces:
  15. {0,"",""},{0,"XXX","XXX"},{Ldate,Rdate + " "},{Ltime,Rtime + " "},{Ltime | Lmicroseconds,Rtime + Rmicroseconds + " "},{Lmicroseconds,// microsec implies time
  16. {Llongfile,Rlongfile + " "},{Lshortfile,Rshortfile + " "},{Llongfile | Lshortfile,// shortfile overrides longfile
  17. // everything at once:
  18. {Ldate | Ltime | Lmicroseconds | Llongfile,"XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rlongfile + " "},{Ldate | Ltime | Lmicroseconds | Lshortfile,"XXX" + Rdate + " " + Rtime + Rmicroseconds + " " + Rshortfile + " "},}
  1. # /usr/local/go/src/bytes/buffer_test.go
  2. func init() {
  3. testBytes = make([]byte,N)
  4. for i := 0; i < N; i++ {
  5. testBytes[i] = 'a' + byte(i%26)
  6. }
  7. data = string(testBytes)
  8. }
  • 封装测试专用的公共函数,抽象测试专用的结构体等:

  1. # /usr/local/go/src/log/log_test.go:
  2. type tester struct {
  3. flag int
  4. prefix string
  5. pattern string // regexp that log output must match; we add ^ and expected_text$ always
  6. }
  7.  
  8. // ...
  9.  
  10. func testPrint(t *testing.T,flag int,prefix string,pattern string,useFormat bool) {
  11. // ...
  12. }

示例函数

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

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

  1. func Example() { ... } # 包的示例函数
  2. func ExampleF() { ... } # 函数F的示例函数
  3. func ExampleT() { ... } # 类型T的示例函数
  4. func ExampleT_M() { ... } # 类型T的M方法的示例函数
  5.  
  6. # 多示例函数 需要跟下划线加小写字母开头的后缀
  7. func Example_suffix() { ... }
  8. func ExampleF_suffix() { ... }
  9. func ExampleT_suffix() { ... }
  10. 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参数:

  1. [tabalt@localhost hello] go test -v
  2. === RUN TestHello
  3. --- PASS: TestHello (0.00s)
  4. === RUN ExampleHello
  5. --- PASS: ExampleHello (0.00s)
  6. PASS
  7. ok hello 0.006s

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

  1. [tabalt@localhost hello] go test -v -run=xxx
  2. PASS
  3. ok hello 0.006s

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

  1. [tabalt@localhost hello] go test -bench=.
  2. PASS
  3. BenchmarkHello-8 2000000 657 ns/op
  4. ok hello 1.993s

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

  1. [tabalt@localhost hello] go test -bench=. -benchmem
  2. PASS
  3. BenchmarkHello-8 2000000 666 ns/op 208 B/op 9 allocs/op
  4. ok hello 2.014s

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

  1. [tabalt@localhost hello] go test -cover
  2. PASS
  3. coverage: 100.0% of statements
  4. ok hello 0.006s

详细的覆盖率信息,可以通过-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结构体包含了测试运行的选项。

  1. # /usr/local/go/src/math/big/int_test.go
  2. func checkMul(a,b []byte) bool {
  3. var x,y,z1 Int
  4. x.SetBytes(a)
  5. y.SetBytes(b)
  6. z1.Mul(&x,&y)
  7.  
  8. var z2 Int
  9. z2.SetBytes(mulBytes(a,b))
  10.  
  11. return z1.Cmp(&z2) == 0
  12. }
  13.  
  14. func TestMul(t *testing.T) {
  15. if err := quick.Check(checkMul,nil); err != nil {
  16. t.Error(err)
  17. }
  18. }

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

  1. func CheckEqual(f,g interface{},config *Config) (err error)

HTTP测试

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

  1. ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) {
  2. fmt.Fprintln(w,"Hello,client")
  3. }))
  4. defer ts.Close()
  5.  
  6. res,err := http.Get(ts.URL)
  7. if err != nil {
  8. log.Fatal(err)
  9. }
  10.  
  11. greeting,err := IoUtil.ReadAll(res.Body)
  12. res.Body.Close()
  13. if err != nil {
  14. log.Fatal(err)
  15. }
  16.  
  17. fmt.Printf("%s",greeting)

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

  1. handler := func(w http.ResponseWriter,r *http.Request) {
  2. http.Error(w,"something Failed",http.StatusInternalServerError)
  3. }
  4.  
  5. req,err := http.NewRequest("GET","http://example.com/foo",nil)
  6. if err != nil {
  7. log.Fatal(err)
  8. }
  9.  
  10. w := httptest.NewRecorder()
  11. handler(w,req)
  12.  
  13. fmt.Printf("%d - %s",w.Code,w.Body.String())

测试进程操作行为

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

  1. //被测试的进程退出函数
  2. func Crasher() {
  3. fmt.Println("Going down in flames!")
  4. os.Exit(1)
  5. }
  6.  
  7. //测试进程退出函数的测试函数
  8. func TestCrasher(t *testing.T) {
  9. if os.Getenv("BE_CRASHER") == "1" {
  10. Crasher()
  11. return
  12. }
  13. cmd := exec.Command(os.Args[0],"-test.run=TestCrasher")
  14. cmd.Env = append(os.Environ(),"BE_CRASHER=1")
  15. err := cmd.Run()
  16. if e,ok := err.(*exec.ExitError); ok && !e.Success() {
  17. return
  18. }
  19. t.Fatalf("process ran with err %v,want exit status 1",err)
  20. }

参考资料

https://talks.golang.org/2014...
https://golang.org/pkg/testing/
https://golang.org/pkg/testin...
https://golang.org/pkg/testin...
https://golang.org/pkg/net/ht...

原文链接http://tabalt.net/blog/golang...

猜你在找的Go相关文章