From 36c23ef6f5fff8a5269d5aca152eb697ff8206e5 Mon Sep 17 00:00:00 2001 From: "xian-jie.shen" <327411586@qq.com> Date: Sat, 13 Aug 2022 14:27:04 +0800 Subject: [PATCH] test: pkg-utils-slice Signed-off-by: xian-jie.shen <327411586@qq.com> --- pkg/utils/slice.go | 3 ++ pkg/utils/slice_test.go | 77 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 pkg/utils/slice_test.go diff --git a/pkg/utils/slice.go b/pkg/utils/slice.go index f35a3a841..0b5470e64 100644 --- a/pkg/utils/slice.go +++ b/pkg/utils/slice.go @@ -10,6 +10,9 @@ func ContainsString(slice []string, str string) bool { } func RemoveString(slice []string, str string) []string { + if len(slice) == 0 { + return slice + } var newSlice []string for _, item := range slice { if item != str { diff --git a/pkg/utils/slice_test.go b/pkg/utils/slice_test.go new file mode 100644 index 000000000..a3e2e86c2 --- /dev/null +++ b/pkg/utils/slice_test.go @@ -0,0 +1,77 @@ +package utils + +import ( + "reflect" + "testing" +) + +func TestContainsString(t *testing.T) { + tests := []struct { + name string + slice []string + str string + want bool + }{ + { + name: "slice is empty", + slice: []string{}, + str: "a", + want: false, + }, + { + name: "searching object exists the slice", + slice: []string{"a", "b"}, + str: "a", + want: true, + }, + { + name: "searching object doesn't exist the slice", + slice: []string{"a", "b"}, + str: "c", + want: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := ContainsString(tt.slice, tt.str); got != tt.want { + t.Errorf("ContainsString() = %v, want %v", got, tt.want) + } + }) + } +} + +func TestRemoveString(t *testing.T) { + tests := []struct { + name string + slice []string + str string + want []string + }{ + { + name: "removing object exists the slice", + slice: []string{"a", "b", "c"}, + str: "b", + want: []string{"a", "c"}, + }, + { + name: "remove object doesn't exist in the slice", + slice: []string{"a", "b", "c"}, + str: "d", + want: []string{"a", "b", "c"}, + }, + { + name: "the slice is empty", + slice: []string{}, + str: "d", + want: []string{}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := RemoveString(tt.slice, tt.str); !reflect.DeepEqual(got, tt.want) { + t.Errorf("RemoveString() = %v, want %v", got, tt.want) + } + }) + } +}