github.com/DominikUrban/viper@v0.0.0-20220730150717-aaf74638bd32/internal/encoding/toml/codec2_test.go (about) 1 //go:build !viper_toml1 2 // +build !viper_toml1 3 4 package toml 5 6 import ( 7 "reflect" 8 "testing" 9 ) 10 11 // original form of the data 12 const original = `# key-value pair 13 key = "value" 14 list = ["item1", "item2", "item3"] 15 16 [map] 17 key = "value" 18 19 # nested 20 # map 21 [nested_map] 22 [nested_map.map] 23 key = "value" 24 list = [ 25 "item1", 26 "item2", 27 "item3", 28 ] 29 ` 30 31 // encoded form of the data 32 const encoded = `key = 'value' 33 list = ['item1', 'item2', 'item3'] 34 [map] 35 key = 'value' 36 37 [nested_map] 38 [nested_map.map] 39 key = 'value' 40 list = ['item1', 'item2', 'item3'] 41 42 43 ` 44 45 // Viper's internal representation 46 var data = map[string]interface{}{ 47 "key": "value", 48 "list": []interface{}{ 49 "item1", 50 "item2", 51 "item3", 52 }, 53 "map": map[string]interface{}{ 54 "key": "value", 55 }, 56 "nested_map": map[string]interface{}{ 57 "map": map[string]interface{}{ 58 "key": "value", 59 "list": []interface{}{ 60 "item1", 61 "item2", 62 "item3", 63 }, 64 }, 65 }, 66 } 67 68 func TestCodec_Encode(t *testing.T) { 69 codec := Codec{} 70 71 b, err := codec.Encode(data) 72 if err != nil { 73 t.Fatal(err) 74 } 75 76 if encoded != string(b) { 77 t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", string(b), encoded) 78 } 79 } 80 81 func TestCodec_Decode(t *testing.T) { 82 t.Run("OK", func(t *testing.T) { 83 codec := Codec{} 84 85 v := map[string]interface{}{} 86 87 err := codec.Decode([]byte(original), v) 88 if err != nil { 89 t.Fatal(err) 90 } 91 92 if !reflect.DeepEqual(data, v) { 93 t.Fatalf("decoded value does not match the expected one\nactual: %#v\nexpected: %#v", v, data) 94 } 95 }) 96 97 t.Run("InvalidData", func(t *testing.T) { 98 codec := Codec{} 99 100 v := map[string]interface{}{} 101 102 err := codec.Decode([]byte(`invalid data`), v) 103 if err == nil { 104 t.Fatal("expected decoding to fail") 105 } 106 107 t.Logf("decoding failed as expected: %s", err) 108 }) 109 }