美文网首页
golang 测试

golang 测试

作者: cli1871 | 来源:发表于2019-03-25 17:56 被阅读0次

说到测试,我们应该首先问自己这几个问题? 

  How:  怎么测试

  What: 测试什么

  Why:  为什么测试

怎么测?

下面这个例子:

package split

import "strings"

// Split slices into all substrings separated by sep and

// returns a slice of the substrings between those separators

func Split(s, sep string) []string {

        var result []string

        i := strings.Index(s, sep)

        for i > -1 {

                result =append(result, s[:i])

                s = s[i+len(sep):]

                i = strings.Index(s, sep)

        }   

        return append(result, s)

}

1. 测试函数必须以 Test开头

2. 测试函数必须有一个*testing.T参数,这个类型*testing.T 就是testing package注入类型(提供print,skip, fail the test方式) 

3. 测试代码应该单独起一个文件,后缀是_test.go

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        got := Split("a/b/c", "/")

        want := []string{"a", "b", "c"}

        if !reflect.DeepEqual(want, got) {

                t.Fatalf("expected: %v, got: %v", want, got)

        }   

}

怎么运行测试: 

go test 将运行当前目录下的测试

ccli@ccli-mac:split$ ls

split.go split_test.go

ccli@ccli-mac:unittest$ go test

PASS

ok _/Users/ccli/test/go/src/split 0.005s

如果你想运行项目下的多个package 测试,你可以用这个命令

go test ./...

ccli@ccli-mac:splitt$ go test ./...

ok _/Users/ccli/test/go/src/split 0.005s

怎么统计code coverage

export GOPATH=/Users/ccli/test/go

ccli@ccli-mac:split$ go test -coverprofile=cover.out

PASS

coverage: 100.0% of statements

ok split 0.005s

ccli@ccli-mac:split$ go tool cover -func=cover.out

split/split.go:7: Split 100.0%

total: (statements) 100.0%

ccli@ccli-mac:split$ go tool cover -html=cover.out -o cover.html

ccli@ccli-mac:split$ ls

cover.html cover.out split.go split_test.go

ccli@ccli-mac:split$

code coverage is 100%, 但是其实测试是欠缺的,我们并没有测试边界条件

1. 测试以逗号',"分开

2. 测试没有分隔符的源串

3. 测试以下划线结尾的源串

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests := []struct {

                inputstring

                sep  string

                want  []string

        }{ 

                {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                {input:"a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for i, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Fatalf("test %d: expected: %v, got: %v", i+1, tc.want, got)

                }   

        }   

}

Test case里含有索引来表明第几个case failed

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:22: test 3: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.005s

还有一种例子是以case名字来表示。

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests := []struct {

                namestring

                inputstring

                sep  string

                want  []string

        }{

                {name:"simple", input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                {name:"wrong sep", input: "a/b/c", sep: ",", want: []string{"a/b/c"}},

                {name:"trailing sep", input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                {name:"no sep", input: "abc", sep: "/", want: []string{"abc"}},

        }

        for _, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Fatalf("case: %s: expected: %v, got: %v", tc.name, tc.want, got)

                }

        }

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:23: case: trailing sep: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.007s

还有一种是以map来存储case, as we know, map key is not predefined order, 更利于测试的随机性,来发现固定顺序不能发现的错误

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                namestring

                inputstring

                sep  string

                want  []string

        }{ 

                "simple": {input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep": {input: "a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep": {input: "abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Fatalf("case: %s: expected: %v, got: %v", name, tc.want, got)

                }   

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:23: case: trailing sep: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.005s

Fatalf 会终止测试函数,这样会导致后面case并没有跑到,不能一次看到all test case结果,因此可以用Errorf

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                namestring

                inputstring

                sep  string

                want  []string

        }{ 

                "simple": {input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep": {input: "a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep": {input: "abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                got := Split(tc.input, tc.sep)

                if !reflect.DeepEqual(tc.want, got) {

                        t.Errorf("case: %s: expected: %v, got: %v", name, tc.want, got)

                }   

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

--- FAIL: TestSplit (0.00s)

split_test.go:23: case: trailing sep: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.005s

令人开心的是,sub test 在go 1.7版本中诞生了

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{ 

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        if !reflect.DeepEqual(tc.want, got) {

                                t.Fatalf("expected: %v, got: %v", tc.want, got)

                        }   

                }) 

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- FAIL: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:24: expected: [a b c], got: [a b c ]

    --- PASS: TestSplit/no_sep (0.00s)

FAIL

exit status 1

FAIL split 0.005s

You can also run sub tests by name using the `-run` flag

ccli@ccli-mac:split$ go test -run=.*/trailing -v

=== RUN  TestSplit

=== RUN  TestSplit/trailing_sep

--- FAIL: TestSplit (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:24: expected: [a b c], got: [a b c ]

FAIL

exit status 1

FAIL split 0.006s

从结果上,我们并不能清晰的看出错误结果的区别在哪里。

package split

import (

        "reflect"

        "testing"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{ 

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        if !reflect.DeepEqual(tc.want, got) {

                                t.Fatalf("expected: %#v, got: %#v", tc.want, got)

                        }   

                }) 

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- FAIL: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:24: expected: []string{"a", "b", "c"}, got: []string{"a", "b", "c", ""}

    --- PASS: TestSplit/no_sep (0.00s)

FAIL

exit status 1

FAIL split 0.006s

如果想打印的更加直观,大家可以用下面这几个package

https://github.com/k0kubun/pp

https://github.com/davecgh/go-spew

https://github.com/google/go-cmp

package split

import (

        "testing"

        "github.com/google/go-cmp/cmp"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        diff := cmp.Diff(tc.want, got)

                        if diff != "" {

                        t.Fatalf(diff)

                        }

                })

        }

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- FAIL: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- FAIL: TestSplit/trailing_sep (0.00s)

split_test.go:25:   []string{

"a",

"b",

"c",

+ "",

}

    --- PASS: TestSplit/no_sep (0.00s)

FAIL

exit status 1

FAIL split 0.006s

现在可以fix程序来解决这个failure了

package split

import "strings"

// Split slices into all substrings separated by sep and

// returns a slice of the substrings between those separators

func Split(s, sep string) []string {

        var result []string

        i := strings.Index(s, sep)

        for i > -1 {

                result =append(result, s[:i])

                s = s[i+len(sep):]

                i = strings.Index(s, sep)

        }   

        if len(s) > 0{ 

                result =append(result, s)

        }   

        return result

}

package split

import (

        "testing"

        "github.com/google/go-cmp/cmp"

)

func TestSplit(t *testing.T) {

        tests :=map[string]struct {

                name  string

                inputstring

                sep  string

                want  []string

        }{ 

                "simple":      {input:"a/b/c", sep: "/", want: []string{"a", "b", "c"}},

                "wrong sep":    {input:"a/b/c", sep: ",", want: []string{"a/b/c"}},

                "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},

                "no sep":      {input:"abc", sep: "/", want: []string{"abc"}},

        }   

        for name, tc := range tests {

                t.Run(name,func(t *testing.T) {

                        got := Split(tc.input, tc.sep)

                        diff := cmp.Diff(tc.want, got)

                        if diff != "" {

                        t.Fatalf(diff)

                        }   

                }) 

        }   

}

ccli@ccli-mac:split$ go test -v

=== RUN  TestSplit

=== RUN  TestSplit/simple

=== RUN  TestSplit/wrong_sep

=== RUN  TestSplit/trailing_sep

=== RUN  TestSplit/no_sep

--- PASS: TestSplit (0.00s)

    --- PASS: TestSplit/simple (0.00s)

    --- PASS: TestSplit/wrong_sep (0.00s)

    --- PASS: TestSplit/trailing_sep (0.00s)

    --- PASS: TestSplit/no_sep (0.00s)

PASS

ok split 0.005s

测试什么?

C code unit is function 函数

Java code unit is class

Golang code unit is package

Test the behaviour of your unit, not its implementation, So we should test our packages behaviour via their public api

为什么测试

如果你不测试,那么产品最终被用户使用,用户使用也可以说验收测试,那时的问题将极大影响产品的信誉,因此尽早发现测试是软件从业者的目标。

测试应当由开发人员来承担,而不应该由专门的测试人员负责,测试应该是自动化的,这样一方面make sure 产品质量,另一方面也能提高开发效率,这里并没有说不需要的测试人员,而是说单元测试,功能测试集成测试都应该mock环境尽可能自动化。特殊情况下才有极少的专门测试人员来负责相应测试。

测试进阶

展示了怎么写Unit Test及怎么统计coverage, 为了方便写UT,最好exposed Api is Method not function,为了更好的帮助大家理解,给出了一个例子方便大家参考。例子分为三部分,source code, unit test code, Makefile.

Code 目录

mkdir -p ~/test/src/gounit/etcd

source code

package etcd

import (

        "context"

        "log"

        "time"

        "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"

        "go.etcd.io/etcd/clientv3"

)

type KV interface {

        Put(ctx context.Context, key, valstring, opts ...clientv3.OpOption) (*clientv3.PutResponse, error)

}

type etcdClient struct {

        kv KV

}

const (

        DefaultOperationTimeout =3 * time.Second

)

var (

        endpoints = []string{"localhost:2379"}

)

func (ec *etcdClient) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {

        ctx, cancel := context.WithTimeout(ctx, DefaultOperationTimeout)

        resp, err := ec.kv.Put(ctx, key, val, opts...)

        cancel()

        if err != nil {

                switch err {

                case context.Canceled:

                        log.Printf("[ETCD] ctx is canceled by another routine: %v", err)

                case context.DeadlineExceeded:

                        log.Printf("[ETCD] ctx is attached with a deadline is exceeded: %v", err)

                case rpctypes.ErrEmptyKey:

                        log.Printf("[ETCD] client-side error: %v", err)

                default:

                        log.Printf("[ETCD] bad cluster endpoints, which are not etcd servers: %v", err)

                }

        }

        return resp, err

}

Unit Test code

package etcd

import (

        "context"

        "errors"

        "testing"

        "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"

        "github.com/stretchr/testify/assert"

        "go.etcd.io/etcd/clientv3"

)

type mockEtcdClient struct {

}

var (

        defaultErr = errors.New("default err")

)

func (mec *mockEtcdClient) Put(ctx context.Context, key, val string, opts ...clientv3.OpOption) (*clientv3.PutResponse, error) {

        switch key {

        case "canceled":

                return nil, context.Canceled

        case "deadline_exceeded":

                return nil, context.

        case "err_empty_key":

                return nil, rpctypes.ErrEmptyKey

        case "default":

                return nil, defaultErr

        default:

                return nil, nil

        }

}

type putResult struct {

        putResponse *clientv3.PutResponse

        err        error

}

func TestPut(t *testing.T) {

        api := &etcdClient{kv: &mockEtcdClient{}}

        tests := []struct {

                key    string

                expect putResult

        }{

                {

                        key:"canceled",

                        expect: putResult{

                                putResponse:nil,

                                err:        context.Canceled,

                        },

                },

                {

                        key:"deadline_exceeded",

                        expect: putResult{

                                putResponse:nil,

                                err:        context.DeadlineExceeded,

                        },

                },

                {

                        key:"err_empty_key",

                        expect: putResult{

                                putResponse:nil,

                                err:        rpctypes.ErrEmptyKey,

                        },

                },

                {

                        key:"default",

                        expect: putResult{

                                putResponse:nil,

                                err:        defaultErr,

                        },

                },

                {

                        key:"fine",

                        expect: putResult{

                                putResponse:nil,

                                err:        nil,

                        },

                },

        }

        for index, test := range tests {

                _, err := api.Put(context.Background(), test.key,"oktestut")

                assert.EqualValuesf(t, test.expect.err, err,"case: %d", index)

        }

}

Makefile

export GOPATH = $(shell pwd)/../../..

TEST_FLAGS=-test.short -v

PKGS = gounit/etcd

print:

        echo$(GOPATH)

dep:

        go get "go.etcd.io/etcd/clientv3"

        go get "github.com/coreos/etcd/etcdserver/api/v3rpc/rpctypes"

        go get "github.com/stretchr/testify/assert"

vet:dep 

        go fmt ./...

        go vet ./...

test:vet 

        go test --cover$(PKGS)

cover-tool:

        go get github.com/jstemmer/go-junit-report

        go get golang.org/x/tools/cmd/cover

        go get github.com/axw/gocov/gocov

        go get github.com/AlekSi/gocov-xml

        go get github.com/wadey/gocovmerge

unit-coverage: dep cover-tool

        mkdir -p report

        cat /dev/null > report/utest.out

        $(foreach i,$(PKGS),go test $(i) $(TEST_FLAGS) --covermode=count -coverprofile=report/cover-`echo $(i) |sed 's/\//./g'`.out >> report/utest.out;)

        cat report/utest.out | go-junit-report > report/unit_test_report.xml

        gocovmerge report/cover-*.out > report/unit_test_coverage.out

        gocov convert report/unit_test_coverage.out | gocov-xml > report/unit_test_coverage.xml

        go tool cover -html=report/unit_test_coverage.out -o report/unit_test_coverage.html

        rm report/{cover-*,utest}.out

clean:

        rm -rf report 

相关文章

网友评论

      本文标题:golang 测试

      本文链接:https://www.haomeiwen.com/subject/gbpbvqtx.html