diff --git a/pkg/dynamic/iterate.go b/pkg/dynamic/iterate.go index 47be50891..765616392 100644 --- a/pkg/dynamic/iterate.go +++ b/pkg/dynamic/iterate.go @@ -11,6 +11,10 @@ type StructFieldIterator func(tag string, ft reflect.StructField, fv reflect.Val var ErrCanNotIterateNilPointer = errors.New("can not iterate struct on a nil pointer") func IterateFields(obj interface{}, cb func(ft reflect.StructField, fv reflect.Value) error) error { + if obj == nil { + return errors.New("can not iterate field, given object is nil") + } + sv := reflect.ValueOf(obj) st := reflect.TypeOf(obj) diff --git a/pkg/dynamic/iterate_test.go b/pkg/dynamic/iterate_test.go index 61cdc66cc..b15b74bf8 100644 --- a/pkg/dynamic/iterate_test.go +++ b/pkg/dynamic/iterate_test.go @@ -9,17 +9,36 @@ import ( ) func TestIterateFields(t *testing.T) { - var a = struct { - A int - B float64 - C *os.File - }{} - cnt := 0 - err := IterateFields(&a, func(ft reflect.StructField, fv reflect.Value) error { - cnt++ - return nil + t.Run("basic", func(t *testing.T) { + var a = struct { + A int + B float64 + C *os.File + }{} + + cnt := 0 + err := IterateFields(&a, func(ft reflect.StructField, fv reflect.Value) error { + cnt++ + return nil + }) + assert.NoError(t, err) + assert.Equal(t, 3, cnt) }) - assert.NoError(t, err) - assert.Equal(t, 3, cnt) + + t.Run("non-ptr", func(t *testing.T) { + err := IterateFields(struct{}{}, func(ft reflect.StructField, fv reflect.Value) error { + return nil + }) + assert.Error(t, err) + }) + + t.Run("nil", func(t *testing.T) { + err := IterateFields(nil, func(ft reflect.StructField, fv reflect.Value) error { + return nil + }) + assert.Error(t, err) + }) + + }