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

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