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