Created
December 26, 2018 06:44
-
-
Save laurenchen0631/d351b055068d8b4431264253405fe989 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package renderer | |
import ( | |
"github.com/stretchr/testify/assert" | |
"reflect" | |
"testing" | |
) | |
type T struct { | |
Apple int | |
PlayStation string | |
NestMap Deep | |
Empty Deep | |
Ptr *Deep | |
} | |
type Deep struct { | |
SuperMario string | |
Array []int | |
} | |
func TestConvertStructToMap(t *testing.T) { | |
t.Run("no extra map", func(t *testing.T) { | |
s := T{ | |
Apple: 10, | |
PlayStation: "God of War", | |
NestMap: Deep{ | |
SuperMario: "Odyssey", | |
Array: []int{1, 2, 3}, | |
}, | |
Ptr: &Deep{ | |
SuperMario: "Bros", | |
}, | |
} | |
jsonMap := ConvertStructToMap(reflect.ValueOf(s)) | |
assert.Equal( | |
t, | |
map[string]interface{}{ | |
"apple": 10, | |
"playStation": "God of War", | |
"nestMap": map[string]interface{}{ | |
"superMario": "Odyssey", | |
"array": []int{1, 2, 3}, | |
}, | |
"ptr": map[string]interface{}{ | |
"superMario": "Bros", | |
}, | |
}, | |
jsonMap, | |
) | |
}) | |
t.Run("pointer to struct", func(t *testing.T) { | |
s := &T{ | |
Apple: 20, | |
Ptr: nil, | |
} | |
assert.Equal( | |
t, | |
map[string]interface{}{ | |
"apple": 20, | |
}, | |
ConvertStructToMap(reflect.ValueOf(s)), | |
) | |
}) | |
t.Run("with extra map", func(t *testing.T) { | |
s := T{ | |
Apple: 10, | |
PlayStation: "God of War", | |
NestMap: Deep{ | |
SuperMario: "Odyssey", | |
Array: []int{1, 2, 3}, | |
}, | |
} | |
jsonMap := ConvertStructToMap(reflect.ValueOf(s), map[string]interface{}{"nestMap": 100}) | |
assert.Equal( | |
t, | |
map[string]interface{}{ | |
"apple": 10, | |
"playStation": "God of War", | |
"nestMap": 100, | |
}, | |
jsonMap, | |
) | |
}) | |
t.Run("input is not struct", func(t *testing.T) { | |
jsonMap := ConvertStructToMap(reflect.ValueOf("hello world")) | |
assert.Nil(t, jsonMap) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment