From d648bef19e2e3892d6eaa0d44ac4e76a1eb27c8d Mon Sep 17 00:00:00 2001 From: jichangjun Date: Wed, 2 Sep 2020 22:21:16 +0800 Subject: [PATCH] add case for filterProfile func --- pkg/cover/server.go | 2 +- pkg/cover/server_test.go | 81 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 76 insertions(+), 7 deletions(-) diff --git a/pkg/cover/server.go b/pkg/cover/server.go index a039588..ac9b0f0 100644 --- a/pkg/cover/server.go +++ b/pkg/cover/server.go @@ -187,7 +187,7 @@ func profile(c *gin.Context) { } } -// filterProfile output profiles of the packages matching the coverPkg +// filterProfile filters profiles of the packages matching the coverPkg func filterProfile(coverPkg []string, profiles []*cover.Profile) ([]*cover.Profile, error) { var out = make([]*cover.Profile, 0) diff --git a/pkg/cover/server_test.go b/pkg/cover/server_test.go index 4df5c45..3754849 100644 --- a/pkg/cover/server_test.go +++ b/pkg/cover/server_test.go @@ -6,11 +6,13 @@ import ( "net/http/httptest" "net/url" "os" + "reflect" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" + "golang.org/x/tools/cover" ) // MockStore is mock store mainly for unittest @@ -216,10 +218,77 @@ func TestInitService(t *testing.T) { } func TestFilterProfile(t *testing.T) { - // var tcs = []struct { - // pattern []string - // profile []*cover.Profile - // expected []*cover.Profile - // err error - // }{} + var tcs = []struct { + name string + pattern []string + input []*cover.Profile + output []*cover.Profile + expectErr bool + }{ + { + name: "valid test", + pattern: []string{"some/fancy/gopath", "a/fancy/gopath"}, + input: []*cover.Profile{ + { + FileName: "some/fancy/gopath/a.go", + }, + { + FileName: "some/fancy/gopath/b/a.go", + }, + { + FileName: "a/fancy/gopath/a.go", + }, + { + FileName: "b/fancy/gopath/a.go", + }, + { + FileName: "b/a/fancy/gopath/a.go", + }, + }, + output: []*cover.Profile{ + { + FileName: "some/fancy/gopath/a.go", + }, + { + FileName: "some/fancy/gopath/b/a.go", + }, + { + FileName: "a/fancy/gopath/a.go", + }, + { + FileName: "b/a/fancy/gopath/a.go", + }, + }, + }, + } + + for _, tc := range tcs { + t.Run(tc.name, func(t *testing.T) { + out, err := filterProfile(tc.pattern, tc.input) + if err != nil { + if !tc.expectErr { + t.Errorf("Unexpected error: %v", err) + } + return + } + + if tc.expectErr { + t.Errorf("Expected an error, but got value %s", stringifyCoverProfile(out)) + } + + if !reflect.DeepEqual(out, tc.output) { + t.Errorf("Mismatched results. \nExpected: %s\nActual:%s", stringifyCoverProfile(tc.output), stringifyCoverProfile(out)) + } + + }) + } +} + +func stringifyCoverProfile(profiles []*cover.Profile) string { + res := make([]cover.Profile, 0, len(profiles)) + for _, p := range profiles { + res = append(res, *p) + } + + return fmt.Sprintf("%#v", res) }