Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🐛 Add nil pointer check in UnstructuredUnmarshalField #6334

Merged
merged 1 commit into from
Mar 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,10 @@ func refersTo(ref *metav1.OwnerReference, obj client.Object) bool {
// UnstructuredUnmarshalField is a wrapper around json and unstructured objects to decode and copy a specific field
// value into an object.
func UnstructuredUnmarshalField(obj *unstructured.Unstructured, v interface{}, fields ...string) error {
if obj == nil || obj.Object == nil {
return errors.Errorf("failed to unmarshal unstructured object: object is nil")
}

value, found, err := unstructured.NestedFieldNoCopy(obj.Object, fields...)
if err != nil {
return errors.Wrapf(err, "failed to retrieve field %q from %q", strings.Join(fields, "."), obj.GroupVersionKind())
Expand Down
25 changes: 25 additions & 0 deletions util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -881,3 +881,28 @@ func TestRemoveOwnerRef(t *testing.T) {
})
}
}

func TestUnstructuredUnmarshalField(t *testing.T) {
tests := []struct {
name string
obj *unstructured.Unstructured
v interface{}
fields []string
wantErr bool
}{
{
"return error if object is nil",
nil,
nil,
nil,
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if err := UnstructuredUnmarshalField(tt.obj, tt.v, tt.fields...); (err != nil) != tt.wantErr {
t.Errorf("UnstructuredUnmarshalField() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}