github.com/ShaleApps/viper@v1.15.1-concurrent/internal/encoding/javaproperties/codec_test.go (about)

     1  package javaproperties
     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  map.key = value
    12  `
    13  
    14  // encoded form of the data
    15  const encoded = `key = value
    16  map.key = value
    17  `
    18  
    19  // Viper's internal representation
    20  var data = map[string]interface{}{
    21  	"key": "value",
    22  	"map": map[string]interface{}{
    23  		"key": "value",
    24  	},
    25  }
    26  
    27  func TestCodec_Encode(t *testing.T) {
    28  	codec := Codec{}
    29  
    30  	b, err := codec.Encode(data)
    31  	if err != nil {
    32  		t.Fatal(err)
    33  	}
    34  
    35  	if encoded != string(b) {
    36  		t.Fatalf("decoded value does not match the expected one\nactual:   %#v\nexpected: %#v", string(b), encoded)
    37  	}
    38  }
    39  
    40  func TestCodec_Decode(t *testing.T) {
    41  	t.Run("OK", func(t *testing.T) {
    42  		codec := Codec{}
    43  
    44  		v := map[string]interface{}{}
    45  
    46  		err := codec.Decode([]byte(original), v)
    47  		if err != nil {
    48  			t.Fatal(err)
    49  		}
    50  
    51  		if !reflect.DeepEqual(data, v) {
    52  			t.Fatalf("decoded value does not match the expected one\nactual:   %#v\nexpected: %#v", v, data)
    53  		}
    54  	})
    55  
    56  	t.Run("InvalidData", func(t *testing.T) {
    57  		t.Skip("TODO: needs invalid data example")
    58  
    59  		codec := Codec{}
    60  
    61  		v := map[string]interface{}{}
    62  
    63  		codec.Decode([]byte(``), v)
    64  
    65  		if len(v) > 0 {
    66  			t.Fatalf("expected map to be empty when data is invalid\nactual: %#v", v)
    67  		}
    68  	})
    69  }
    70  
    71  func TestCodec_DecodeEncode(t *testing.T) {
    72  	codec := Codec{}
    73  
    74  	v := map[string]interface{}{}
    75  
    76  	err := codec.Decode([]byte(original), v)
    77  	if err != nil {
    78  		t.Fatal(err)
    79  	}
    80  
    81  	b, err := codec.Encode(data)
    82  	if err != nil {
    83  		t.Fatal(err)
    84  	}
    85  
    86  	if original != string(b) {
    87  		t.Fatalf("encoded value does not match the original\nactual:   %#v\nexpected: %#v", string(b), original)
    88  	}
    89  }