github.com/ShaleApps/viper@v1.15.1-concurrent/internal/encoding/yaml/codec_test.go (about) 1 package yaml 2 3 import ( 4 "reflect" 5 "testing" 6 ) 7 8 // original form of the data 9 const original = `# key-value pair 10 key: value 11 list: 12 - item1 13 - item2 14 - item3 15 map: 16 key: value 17 18 # nested 19 # map 20 nested_map: 21 map: 22 key: value 23 list: 24 - item1 25 - item2 26 - item3 27 ` 28 29 // encoded form of the data 30 const encoded = `key: value 31 list: 32 - item1 33 - item2 34 - item3 35 map: 36 key: value 37 nested_map: 38 map: 39 key: value 40 list: 41 - item1 42 - item2 43 - item3 44 ` 45 46 // decoded form of the data 47 // 48 // in case of YAML it's slightly different from Viper's internal representation 49 // (eg. map is decoded into a map with interface key) 50 var decoded = map[string]interface{}{ 51 "key": "value", 52 "list": []interface{}{ 53 "item1", 54 "item2", 55 "item3", 56 }, 57 "map": map[string]interface{}{ 58 "key": "value", 59 }, 60 "nested_map": map[string]interface{}{ 61 "map": map[string]interface{}{ 62 "key": "value", 63 "list": []interface{}{ 64 "item1", 65 "item2", 66 "item3", 67 }, 68 }, 69 }, 70 } 71 72 // Viper's internal representation 73 var data = map[string]interface{}{ 74 "key": "value", 75 "list": []interface{}{ 76 "item1", 77 "item2", 78 "item3", 79 }, 80 "map": map[string]interface{}{ 81 "key": "value", 82 }, 83 "nested_map": map[string]interface{}{ 84 "map": map[string]interface{}{ 85 "key": "value", 86 "list": []interface{}{ 87 "item1", 88 "item2", 89 "item3", 90 }, 91 }, 92 }, 93 } 94 95 func TestCodec_Encode(t *testing.T) { 96 codec := Codec{} 97 98 b, err := codec.Encode(data) 99 if err != nil { 100 t.Fatal(err) 101 } 102 103 if encoded != string(b) { 104 t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded) 105 } 106 } 107 108 func TestCodec_Decode(t *testing.T) { 109 t.Run("OK", func(t *testing.T) { 110 codec := Codec{} 111 112 v := map[string]interface{}{} 113 114 err := codec.Decode([]byte(original), v) 115 if err != nil { 116 t.Fatal(err) 117 } 118 119 if !reflect.DeepEqual(decoded, v) { 120 t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, decoded) 121 } 122 }) 123 124 t.Run("InvalidData", func(t *testing.T) { 125 codec := Codec{} 126 127 v := map[string]interface{}{} 128 129 err := codec.Decode([]byte(`invalid data`), v) 130 if err == nil { 131 t.Fatal("expected decoding to fail") 132 } 133 134 t.Logf("decoding failed as expected: %s", err) 135 }) 136 }