Browse Source

fix: IsNil fails on struct value

Moritz Johner 4 years ago
parent
commit
12a25fca8b
2 changed files with 94 additions and 1 deletions
  1. 8 1
      pkg/utils/utils.go
  2. 86 0
      pkg/utils/utils_test.go

+ 8 - 1
pkg/utils/utils.go

@@ -39,7 +39,14 @@ func MergeStringMap(dest, src map[string]string) {
 
 // IsNil checks if an Interface is nil.
 func IsNil(i interface{}) bool {
-	return i == nil || reflect.ValueOf(i).IsNil()
+	if i == nil {
+		return true
+	}
+	value := reflect.ValueOf(i)
+	if value.Type().Kind() == reflect.Ptr {
+		return value.IsNil()
+	}
+	return false
 }
 
 // ObjectHash calculates md5 sum of the data contained in the secret.

+ 86 - 0
pkg/utils/utils_test.go

@@ -17,6 +17,7 @@ package utils
 import (
 	"testing"
 
+	vault "github.com/oracle/oci-go-sdk/v45/vault"
 	v1 "k8s.io/api/core/v1"
 )
 
@@ -60,3 +61,88 @@ func TestObjectHash(t *testing.T) {
 		})
 	}
 }
+
+func TestIsNil(t *testing.T) {
+	tbl := []struct {
+		name string
+		val  interface{}
+		exp  bool
+	}{
+		{
+			name: "simple nil val",
+			val:  nil,
+			exp:  true,
+		},
+		{
+			name: "nil slice",
+			val:  (*[]struct{})(nil),
+			exp:  true,
+		},
+		{
+			name: "struct pointer",
+			val:  &testing.T{},
+			exp:  false,
+		},
+		{
+			name: "struct",
+			val:  testing.T{},
+			exp:  false,
+		},
+		{
+			name: "slice of struct",
+			val:  []struct{}{{}},
+			exp:  false,
+		},
+		{
+			name: "slice of ptr",
+			val:  []*testing.T{nil},
+			exp:  false,
+		},
+		{
+			name: "slice",
+			val:  []struct{}(nil),
+			exp:  false,
+		},
+		{
+			name: "int default value",
+			val:  0,
+			exp:  false,
+		},
+		{
+			name: "empty str",
+			val:  "",
+			exp:  false,
+		},
+		{
+			name: "oracle vault",
+			val:  vault.VaultsClient{},
+			exp:  false,
+		},
+		{
+			name: "func",
+			val: func() {
+				// noop for testing and to make linter happy
+			},
+			exp: false,
+		},
+		{
+			name: "channel",
+			val:  make(chan struct{}),
+			exp:  false,
+		},
+		{
+			name: "map",
+			val:  map[string]string{},
+			exp:  false,
+		},
+	}
+
+	for _, row := range tbl {
+		t.Run(row.name, func(t *testing.T) {
+			res := IsNil(row.val)
+			if res != row.exp {
+				t.Errorf("IsNil(%#v)=%t, expected %t", row.val, res, row.exp)
+			}
+		})
+	}
+}