spf13--viper/internal/encoding/decoder_test.go

70 lines
1.4 KiB
Go
Raw Normal View History

package encoding
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type decoder struct {
2023-09-26 14:59:38 +00:00
v map[string]any
}
2023-09-26 14:59:38 +00:00
func (d decoder) Decode(_ []byte, v map[string]any) error {
for key, value := range d.v {
v[key] = value
}
return nil
}
func TestDecoderRegistry_RegisterDecoder(t *testing.T) {
t.Run("OK", func(t *testing.T) {
registry := NewDecoderRegistry()
err := registry.RegisterDecoder("myformat", decoder{})
require.NoError(t, err)
})
t.Run("AlreadyRegistered", func(t *testing.T) {
registry := NewDecoderRegistry()
err := registry.RegisterDecoder("myformat", decoder{})
require.NoError(t, err)
err = registry.RegisterDecoder("myformat", decoder{})
assert.ErrorIs(t, err, ErrDecoderFormatAlreadyRegistered)
})
}
func TestDecoderRegistry_Decode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
registry := NewDecoderRegistry()
decoder := decoder{
2023-09-26 14:59:38 +00:00
v: map[string]any{
"key": "value",
},
}
err := registry.RegisterDecoder("myformat", decoder)
require.NoError(t, err)
2023-09-26 14:59:38 +00:00
v := map[string]any{}
err = registry.Decode("myformat", []byte("key: value"), v)
require.NoError(t, err)
assert.Equal(t, decoder.v, v)
})
t.Run("DecoderNotFound", func(t *testing.T) {
registry := NewDecoderRegistry()
2023-09-26 14:59:38 +00:00
v := map[string]any{}
err := registry.Decode("myformat", nil, v)
assert.ErrorIs(t, err, ErrDecoderNotFound)
})
}