Skip to content

Commit 87f3af4

Browse files
committed
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 <[email protected]>
1 parent 4d6d981 commit 87f3af4

File tree

2 files changed

+22
-2
lines changed

2 files changed

+22
-2
lines changed

pkg/test/param_expander.go

+12
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,12 @@ func (pe *ParamExpander) ExpandObject(obj interface{}, out interface{}) error {
7474
vout.Set(val)
7575

7676
case reflect.Map:
77+
if vin.IsNil() {
78+
// handle nil maps, eg. map[T]U(nil)
79+
vout.Set(vin)
80+
break
81+
}
82+
7783
val := reflect.MakeMap(vin.Type())
7884
iter := vin.MapRange()
7985
for iter.Next() {
@@ -112,6 +118,12 @@ func (pe *ParamExpander) ExpandObject(obj interface{}, out interface{}) error {
112118
vout.Set(val.Elem())
113119

114120
case reflect.Slice:
121+
if vin.IsNil() {
122+
// handle nil slices, eg. []T(nil)
123+
vout.Set(vin)
124+
break
125+
}
126+
115127
elemType := vin.Type().Elem()
116128
len := vin.Len()
117129

pkg/test/param_expander_test.go

+10-2
Original file line numberDiff line numberDiff line change
@@ -165,12 +165,18 @@ func TestParamExpander(t *testing.T) {
165165

166166
t.Run("nulls", func(t *testing.T) {
167167
type testObj struct {
168-
Str *string
169-
Intf any
168+
Str *string
169+
Intf any
170+
Ints []int
171+
IntMap map[int]int
170172
}
171173

172174
// both fields null
173175
input := &testObj{}
176+
require.Nil(t, input.Str)
177+
require.Nil(t, input.Intf)
178+
require.Nil(t, input.Ints)
179+
require.Nil(t, input.IntMap)
174180

175181
e := NewParamExpander(target, &mockVars{})
176182

@@ -180,5 +186,7 @@ func TestParamExpander(t *testing.T) {
180186

181187
require.Nil(t, out.Str)
182188
require.Nil(t, out.Intf)
189+
require.Nil(t, out.Ints)
190+
require.Nil(t, out.IntMap)
183191
})
184192
}

0 commit comments

Comments
 (0)