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