github.com/hyperledger/aries-framework-go@v0.3.2/pkg/doc/util/json/json_test.go (about) 1 /* 2 Copyright SecureKey Technologies Inc. All Rights Reserved. 3 SPDX-License-Identifier: Apache-2.0 4 */ 5 6 package json 7 8 import ( 9 "encoding/json" 10 "testing" 11 12 "github.com/stretchr/testify/require" 13 ) 14 15 type testJSON struct { 16 S []string `json:"stringSlice"` 17 I int `json:"intValue"` 18 } 19 20 type testJSONInvalid struct { 21 I []string `json:"intValue"` 22 S int `json:"stringSlice"` 23 } 24 25 func Test_marshalJSON(t *testing.T) { 26 t.Run("Successful JSON marshaling", func(t *testing.T) { 27 v := testJSON{ 28 S: []string{"a", "b", "c"}, 29 I: 7, 30 } 31 32 cf := map[string]interface{}{ 33 "boolValue": false, 34 "intValue": 8, 35 } 36 actual, err := MarshalWithCustomFields(&v, cf) 37 require.NoError(t, err) 38 39 expectedMap := map[string]interface{}{ 40 "stringSlice": []string{"a", "b", "c"}, 41 "intValue": 7, 42 "boolValue": false, 43 } 44 expected, err := json.Marshal(expectedMap) 45 require.NoError(t, err) 46 47 require.Equal(t, expected, actual) 48 }) 49 50 t.Run("Failed JSON marshall", func(t *testing.T) { 51 // artificial example - pass smth which cannot be marshalled 52 jsonBytes, err := MarshalWithCustomFields(make(chan int), map[string]interface{}{}) 53 require.Error(t, err) 54 require.Nil(t, jsonBytes) 55 }) 56 } 57 58 func Test_unmarshalJSON(t *testing.T) { 59 originalMap := map[string]interface{}{ 60 "stringSlice": []string{"a", "b", "c"}, 61 "intValue": 7, 62 "boolValue": false, 63 } 64 65 data, err := json.Marshal(originalMap) 66 require.NoError(t, err) 67 68 t.Run("Successful JSON unmarshalling", func(t *testing.T) { 69 v := new(testJSON) 70 cf := make(map[string]interface{}) 71 err := UnmarshalWithCustomFields(data, v, cf) 72 require.NoError(t, err) 73 74 expectedV := testJSON{ 75 S: []string{"a", "b", "c"}, 76 I: 7, 77 } 78 expectedEf := map[string]interface{}{ 79 "boolValue": false, 80 } 81 require.Equal(t, expectedV, *v) 82 require.Equal(t, expectedEf, cf) 83 }) 84 85 t.Run("Failed JSON unmarshalling", func(t *testing.T) { 86 cf := make(map[string]interface{}) 87 88 // invalid JSON 89 err := UnmarshalWithCustomFields([]byte("not JSON"), "", cf) 90 require.Error(t, err) 91 92 // unmarshallable value 93 err = UnmarshalWithCustomFields(data, make(chan int), cf) 94 require.Error(t, err) 95 96 // incompatible structure of value 97 err = UnmarshalWithCustomFields(data, new(testJSONInvalid), cf) 98 require.Error(t, err) 99 }) 100 } 101 102 func Test_toMaps(t *testing.T) { 103 v := []interface{}{ 104 struct { 105 S string 106 I int 107 }{"12", 5}, 108 109 map[string]interface{}{ 110 "a": "b", 111 }, 112 } 113 114 maps, err := ToMaps(v) 115 require.NoError(t, err) 116 require.Len(t, maps, 2) 117 require.Equal(t, []map[string]interface{}{ 118 {"S": "12", "I": 5.}, 119 {"a": "b"}, 120 }, maps) 121 122 maps, err = ToMaps([]interface{}{make(chan int)}) 123 require.Error(t, err) 124 require.Empty(t, maps) 125 }