...

Source file src/github.com/spf13/viper/internal/encoding/ini/codec_test.go

Documentation: github.com/spf13/viper/internal/encoding/ini

     1  package ini
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  	"github.com/stretchr/testify/require"
     8  )
     9  
    10  // original form of the data.
    11  const original = `; key-value pair
    12  key=value ; key-value pair
    13  
    14  # map
    15  [map] # map
    16  key=%(key)s
    17  
    18  `
    19  
    20  // encoded form of the data.
    21  const encoded = `key=value
    22  
    23  [map]
    24  key=value
    25  `
    26  
    27  // decoded form of the data.
    28  //
    29  // In case of INI it's slightly different from Viper's internal representation
    30  // (e.g. top level keys land in a section called default).
    31  var decoded = map[string]any{
    32  	"DEFAULT": map[string]any{
    33  		"key": "value",
    34  	},
    35  	"map": map[string]any{
    36  		"key": "value",
    37  	},
    38  }
    39  
    40  // data is Viper's internal representation.
    41  var data = map[string]any{
    42  	"key": "value",
    43  	"map": map[string]any{
    44  		"key": "value",
    45  	},
    46  }
    47  
    48  func TestCodec_Encode(t *testing.T) {
    49  	t.Run("OK", func(t *testing.T) {
    50  		codec := Codec{}
    51  
    52  		b, err := codec.Encode(data)
    53  		require.NoError(t, err)
    54  
    55  		assert.Equal(t, encoded, string(b))
    56  	})
    57  
    58  	t.Run("Default", func(t *testing.T) {
    59  		codec := Codec{}
    60  
    61  		data := map[string]any{
    62  			"default": map[string]any{
    63  				"key": "value",
    64  			},
    65  			"map": map[string]any{
    66  				"key": "value",
    67  			},
    68  		}
    69  
    70  		b, err := codec.Encode(data)
    71  		require.NoError(t, err)
    72  
    73  		assert.Equal(t, encoded, string(b))
    74  	})
    75  }
    76  
    77  func TestCodec_Decode(t *testing.T) {
    78  	t.Run("OK", func(t *testing.T) {
    79  		codec := Codec{}
    80  
    81  		v := map[string]any{}
    82  
    83  		err := codec.Decode([]byte(original), v)
    84  		require.NoError(t, err)
    85  
    86  		assert.Equal(t, decoded, v)
    87  	})
    88  
    89  	t.Run("InvalidData", func(t *testing.T) {
    90  		codec := Codec{}
    91  
    92  		v := map[string]any{}
    93  
    94  		err := codec.Decode([]byte(`invalid data`), v)
    95  		require.Error(t, err)
    96  
    97  		t.Logf("decoding failed as expected: %s", err)
    98  	})
    99  }
   100  

View as plain text