Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add unit tests #4

Merged
merged 13 commits into from
Mar 10, 2022
Merged
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,4 @@ mould.log

.env

testdata

.synapse.json
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ require (
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/objx v0.2.0 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
github.com/ugorji/go/codec v1.1.7 // indirect
github.com/ulikunitz/xz v0.5.9 // indirect
Expand Down
1 change: 1 addition & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -802,6 +802,7 @@ github.com/stefanberger/go-pkcs11uri v0.0.0-20201008174630-78d3cae3a980/go.mod h
github.com/stretchr/objx v0.0.0-20180129172003-8a3f7159479f/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v0.0.0-20180303142811-b89eecf5ca5d/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
Expand Down
215 changes: 215 additions & 0 deletions pkg/diffmanager/setup_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
// Package diffmanager is used for cloning repo
package diffmanager

import (
"context"
"math/rand"
"net/http"
"net/http/httptest"
"reflect"
"testing"

"github.com/LambdaTest/synapse/pkg/core"
"github.com/LambdaTest/synapse/pkg/global"
"github.com/LambdaTest/synapse/testutils"
)

func Test_updateWithOr(t *testing.T) {
check := func(t *testing.T) {
dm := &diffManager{}
m := make(map[string]int)
key := "key"
val := rand.Intn(1000)
dm.updateWithOr(m, key, val)
if ans, exists := m[key]; !exists || ans != val {
t.Errorf("Expected: %v, received: %v", val, m[key])
}
newVal := rand.Intn(1000)
dm.updateWithOr(m, key, newVal)
if ans, exists := m[key]; !exists || ans != (val|newVal) {
t.Errorf("Expected: %v, received: %v", val|newVal, m[key])
}
}
t.Run("Test_updateWithOr", func(t *testing.T) {
check(t)
})
}

func Test_diffManager_GetChangedFiles_PRDiff(t *testing.T) {
server := httptest.NewServer( // mock server
http.FileServer(http.Dir("../../testutils")), // mock data stored at testutils/testdata
)
defer server.Close()

logger, err := testutils.GetLogger()
if err != nil {
t.Errorf("Can't get logger, received: %s", err)
}
config, err := testutils.GetConfig()
if err != nil {
t.Errorf("Can't get logger, received: %s", err)
}

dm := NewDiffManager(config, logger)
type args struct {
ctx context.Context
payload *core.Payload
cloneToken string
}
tests := []struct {
name string
args args
want map[string]int
wantErr bool
}{
// expects to hit Server.URL/testdata/pulls/2
{"Test GetChangedFile for PRdiff for github gitprovider", args{ctx: context.TODO(), payload: &core.Payload{RepoSlug: "/testdata", RepoLink: server.URL + "/testdata", GitProvider: "github", PrivateRepo: false, EventType: "pull-request", Diff: "xyz", PullRequestNumber: 2}, cloneToken: ""}, map[string]int{}, false},

// expects to hit Server.URL/testdata/merge_requests/2/changes
{"Test GetChangedFile for PRdiff for gitlab gitprovider", args{ctx: context.TODO(), payload: &core.Payload{RepoSlug: "/testdata", RepoLink: server.URL + "/testdata", GitProvider: "gitlab", PrivateRepo: false, EventType: "pull-request", Diff: "xyz", PullRequestNumber: 2}, cloneToken: ""}, map[string]int{}, false},

{"Test GetChangedFile for Commitdiff for unsupported gitprovider", args{ctx: context.TODO(), payload: &core.Payload{GitProvider: "unsupported"}}, map[string]int{}, true},

{"Test GetChangedFile for PRdiff for unsupported gitprovider", args{ctx: context.TODO(), payload: &core.Payload{GitProvider: "unsupported", EventType: "pull-request"}}, map[string]int{}, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
global.APIHostURLMap[tt.args.payload.GitProvider] = server.URL
resp, err := dm.GetChangedFiles(tt.args.ctx, tt.args.payload, tt.args.cloneToken)

if tt.wantErr {
if err == nil {
t.Errorf("GetChangedFiles() error = %v, wantErr %v", err, tt.wantErr)
}
return
}

expResp := testutils.GetGitDiff()
if err != nil {
t.Errorf("error in getting changed files, error %v", err.Error())
} else if tt.args.payload.GitProvider == "github" && !reflect.DeepEqual(resp, expResp) {
t.Errorf("Expected: %+v, received: %+v", expResp, resp)
} else if tt.args.payload.GitProvider == "gitlab" && len(resp) != 17 {
t.Errorf("Expected map entries: 17, received: %v, received map: %v", len(resp), resp)
}
})
}
}

func Test_diffManager_GetChangedFiles_CommitDiff_Github(t *testing.T) {
server := httptest.NewServer( // mock server
http.FileServer(http.Dir("../../testutils")),
)
defer server.Close()

logger, err := testutils.GetLogger()
if err != nil {
t.Errorf("Can't get logger, received: %s", err)
}
config, err := testutils.GetConfig()
if err != nil {
t.Errorf("Can't get logger, received: %s", err)
}

dm := NewDiffManager(config, logger)
type args struct {
ctx context.Context
payload *core.Payload
cloneToken string
}
tests := []struct {
name string
args args
want map[string]int
wantErr bool
}{
// expects to hit serverURL/testdata/compare/abc...xyz
{"Test GetChangedFile for CommitDiff for github gitprovider", args{ctx: context.TODO(), payload: &core.Payload{RepoSlug: "/testdata", RepoLink: server.URL + "/testdata", BuildTargetCommit: "xyz", BuildBaseCommit: "abc", GitProvider: "github", EventType: "push", Diff: "xyz", PullRequestNumber: 2}}, map[string]int{}, false},

{"Test GetChangedFile for CommitDiff for github provider and empty base commit", args{ctx: context.TODO(), payload: &core.Payload{RepoSlug: "/testdata", RepoLink: server.URL + "/testdata", BuildBaseCommit: "", GitProvider: "gitlab", EventType: "push"}}, map[string]int{}, true},

{"Test GetChangedFile for CommitDiff for github provider for non 200 response", args{ctx: context.TODO(), payload: &core.Payload{RepoLink: server.URL + "/notfound/", BuildTargetCommit: "xyz", BuildBaseCommit: "abc", GitProvider: "gitlab", EventType: "push"}}, map[string]int{}, true},

{"Test GetChangedFile for CommitDiff for non supported git provider", args{ctx: context.TODO(), payload: &core.Payload{RepoSlug: "/notfound/", RepoLink: server.URL + "/notfound/", BuildTargetCommit: "xyz", BuildBaseCommit: "abc", GitProvider: "gittest", EventType: "push"}}, map[string]int{}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
global.APIHostURLMap[tt.args.payload.GitProvider] = server.URL
resp, err := dm.GetChangedFiles(tt.args.ctx, tt.args.payload, tt.args.cloneToken)
// t.Errorf("")
if tt.args.payload.GitProvider == "gittest" {
if resp != nil || err == nil {
t.Errorf("Expected error: 'unsupoorted git provider', received: %v\nexpected response: nil, received: %v", err, resp)
}
return
}
if tt.wantErr {
if err == nil {
t.Errorf("Expected error: %v, Received error: %v, response: %v", tt.wantErr, err, resp)
}
return
}
expResp := make(map[string]int)
if err != nil {
t.Errorf("error in getting changed files, error %v", err.Error())
} else if !reflect.DeepEqual(resp, expResp) {
t.Errorf("Expected: %+v, received: %+v", expResp, resp)
}
})
}
}

func Test_diffManager_GetChangedFiles_CommitDiff_Gitlab(t *testing.T) {
data, err := testutils.GetGitlabCommitDiff()
if err != nil {
t.Errorf("Received error in getting test gitlab commit diff, error: %v", err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/testdata/repository/compare" {
t.Errorf("Expected to request, got: %v", r.URL.Path)
}
w.WriteHeader(200)
w.Header().Set("Content-Type", "application/json")
_, err2 := w.Write(data)
if err2 != nil {
t.Errorf("Error in writing response data, error: %v", err)
}
}))
defer server.Close()

logger, err := testutils.GetLogger()
if err != nil {
t.Errorf("Can't get logger, received: %s", err)
}
config, err := testutils.GetConfig()
if err != nil {
t.Errorf("Can't get logger, received: %s", err)
}

dm := NewDiffManager(config, logger)
type args struct {
ctx context.Context
payload *core.Payload
cloneToken string
}
tests := []struct {
name string
args args
want map[string]int
}{
// expects to hit serverURL/testdata/repository/compare?from=abc&to=abcd
{"Test GetChangedFile for CommitDiff for gitlab gitprovider", args{ctx: context.TODO(), payload: &core.Payload{RepoSlug: "/testdata", RepoLink: server.URL + "/testdata", BuildTargetCommit: "abcd", BuildBaseCommit: "abc", TaskID: "taskid", BranchName: "branchname", BuildID: "buildid", RepoID: "repoid", OrgID: "orgid", GitProvider: "gitlab", PrivateRepo: false, EventType: "push", Diff: "xyz", PullRequestNumber: 2}, cloneToken: ""}, map[string]int{}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
global.APIHostURLMap[tt.args.payload.GitProvider] = server.URL
resp, err := dm.GetChangedFiles(tt.args.ctx, tt.args.payload, tt.args.cloneToken)

if err != nil {
t.Errorf("error in getting changed files, error %v", err.Error())
} else if len(resp) != 202 {
t.Errorf("Expected map length: 202, received: %v\nreceived map: %v", len(resp), resp)
}
})
}
}
42 changes: 42 additions & 0 deletions pkg/errs/nucleus_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package errs

import (
"testing"
)

func TestError_Error(t *testing.T) {
e := New("A secret message")
got := e.Error()
want := "A secret message"
if got != want {
t.Errorf("Received: %v, Expected: %v", got, want)
}
}

func TestErr_Error(t *testing.T) {
e := &Err{
Code: "fmt.Print(error)",
Message: "This is the message",
}
got := e.Error()
want := "fmt.Print(error) : This is the message "
if got != want {
t.Errorf("Received: %v, Expected: %v", got, want)
}
}

func Test_ErrInvalidPayload(t *testing.T) {
got := ErrInvalidPayload("Error for invalid nucleus payload")
want := "Error for invalid nucleus payload"
if got.Error() != want {
t.Errorf("Received: %v, Expected: %v", got, want)
}
}

func TestErrSecretNotFound(t *testing.T) {
got := ErrSecretNotFound("SECRET_STRING")
want := "secret with name SECRET_STRING not found"
if got.Error() != want {
t.Errorf("Received: %v, Expected: %v", got, want)
}
}
Loading