github.com/safedep/dry@v0.0.0-20241016050132-a15651f0548b/config/encoder_test.go (about)

     1  package config
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/assert"
     7  )
     8  
     9  type simpleStruct struct {
    10  	Name string
    11  }
    12  
    13  func TestConfigJSONEncoder(t *testing.T) {
    14  	cases := []struct {
    15  		name  string
    16  		value any
    17  	}{
    18  		{
    19  			name:  "string",
    20  			value: "hello",
    21  		},
    22  		{
    23  			// Default type for numbers is float64
    24  			name:  "float64",
    25  			value: float64(42),
    26  		},
    27  		{
    28  			name:  "bool/true",
    29  			value: true,
    30  		},
    31  		{
    32  			name:  "bool/false",
    33  			value: false,
    34  		},
    35  	}
    36  
    37  	encoder := &JSONConfigEncoder[any]{}
    38  	for _, test := range cases {
    39  		t.Run(test.name, func(t *testing.T) {
    40  			encoded, err := encoder.Encode(test.value)
    41  			assert.NoError(t, err)
    42  
    43  			decoded, err := encoder.Decode(encoded)
    44  			assert.NoError(t, err)
    45  
    46  			assert.Equal(t, test.value, decoded)
    47  		})
    48  	}
    49  }
    50  
    51  func TestConfigJSONEncoderStruct(t *testing.T) {
    52  	v := simpleStruct{Name: "hello"}
    53  	encoder := &JSONConfigEncoder[simpleStruct]{}
    54  
    55  	encoded, err := encoder.Encode(v)
    56  	assert.NoError(t, err)
    57  
    58  	decoded, err := encoder.Decode(encoded)
    59  	assert.NoError(t, err)
    60  
    61  	assert.Equal(t, v, decoded)
    62  }