From f81ea9decfa1d9a81d89cb9f934debe4480d31f5 Mon Sep 17 00:00:00 2001 From: Simao Gomes Viana Date: Wed, 1 Sep 2021 10:52:55 +0200 Subject: [PATCH] Fix map/slice regression caused by #32 Maps and slices that are nil are empty and valid. The change introduced by #32 which fixes #31 has changed how nil slices and maps are marshaled (`null` instead of `[]`). Fix this regression by removing maps and slices from the check. --- sheriff.go | 2 +- sheriff_test.go | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/sheriff.go b/sheriff.go index 022a8d7..7fc8441 100644 --- a/sheriff.go +++ b/sheriff.go @@ -218,7 +218,7 @@ func marshalValue(options *Options, v reflect.Value) (interface{}, error) { k := v.Kind() switch k { - case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice: + case reflect.Interface, reflect.Ptr: if v.IsNil() { return val, nil } diff --git a/sheriff_test.go b/sheriff_test.go index a009b7b..e305278 100644 --- a/sheriff_test.go +++ b/sheriff_test.go @@ -630,8 +630,8 @@ func TestMarshal_ArrayOfInterfaceable(t *testing.T) { type TestInlineStruct struct { // explicitly testing unexported fields // golangci-lint complains about it and that's ok to ignore. - tableName struct{ Test string } `json:"-"` //nolint - tableNameWithTag struct{ Test string } `json:"foo"` //nolint + tableName struct{ Test string } `json:"-"` //nolint + tableNameWithTag struct{ Test string } `json:"foo"` //nolint Field string `json:"field"` Field2 *string `json:"field2"` @@ -733,3 +733,31 @@ func TestMarshal_BooleanPtrMap(t *testing.T) { assert.Equal(t, string(marshal), string(expect)) } + +func TestMarshal_NilSlice(t *testing.T) { + var stringSlice []string // nil slice + + marshalSlice, err := Marshal(&Options{}, stringSlice) + assert.NoError(t, err) + + jsonResult, err := json.Marshal(marshalSlice) + assert.NoError(t, err) + + expect := "[]" + + assert.Equal(t, expect, string(jsonResult)) +} + +func TestMarshal_NilMap(t *testing.T) { + var stringMap map[string]string // nil map + + marshalMap, err := Marshal(&Options{}, stringMap) + assert.NoError(t, err) + + jsonResult, err := json.Marshal(marshalMap) + assert.NoError(t, err) + + expect := "{}" + + assert.Equal(t, expect, string(jsonResult)) +}