From d494b086ed83b569a26fe059ad3f8db9664cbb14 Mon Sep 17 00:00:00 2001 From: mimir-d Date: Thu, 9 May 2024 15:20:20 +0100 Subject: [PATCH] handle nils correctly in ParamExpander - previously, for types that can be nil (specifically slice, map; interface and pointer are correct), a new value of backing type was created instead of making a new nil - this is incorrect because it affects the structure of the object; more specifically the failure observed was with a struct having a field of type `[]string`. Instead of keeping a `[]string(nil)` here, this would transform into an empty slice `[]string{}` Signed-off-by: mimir-d --- pkg/test/param_expander.go | 12 ++++++++++++ pkg/test/param_expander_test.go | 12 ++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/pkg/test/param_expander.go b/pkg/test/param_expander.go index d16a56a3..2f6ee821 100644 --- a/pkg/test/param_expander.go +++ b/pkg/test/param_expander.go @@ -74,6 +74,12 @@ func (pe *ParamExpander) ExpandObject(obj interface{}, out interface{}) error { vout.Set(val) case reflect.Map: + if vin.IsNil() { + // handle nil maps, eg. map[T]U(nil) + vout.Set(vin) + break + } + val := reflect.MakeMap(vin.Type()) iter := vin.MapRange() for iter.Next() { @@ -112,6 +118,12 @@ func (pe *ParamExpander) ExpandObject(obj interface{}, out interface{}) error { vout.Set(val.Elem()) case reflect.Slice: + if vin.IsNil() { + // handle nil slices, eg. []T(nil) + vout.Set(vin) + break + } + elemType := vin.Type().Elem() len := vin.Len() diff --git a/pkg/test/param_expander_test.go b/pkg/test/param_expander_test.go index bc25680e..db4ddb0c 100644 --- a/pkg/test/param_expander_test.go +++ b/pkg/test/param_expander_test.go @@ -165,12 +165,18 @@ func TestParamExpander(t *testing.T) { t.Run("nulls", func(t *testing.T) { type testObj struct { - Str *string - Intf any + Str *string + Intf any + Ints []int + IntMap map[int]int } // both fields null input := &testObj{} + require.Nil(t, input.Str) + require.Nil(t, input.Intf) + require.Nil(t, input.Ints) + require.Nil(t, input.IntMap) e := NewParamExpander(target, &mockVars{}) @@ -180,5 +186,7 @@ func TestParamExpander(t *testing.T) { require.Nil(t, out.Str) require.Nil(t, out.Intf) + require.Nil(t, out.Ints) + require.Nil(t, out.IntMap) }) }