spf13--viper/internal/encoding/decoder_test.go
Mark Sagi-Kazar e54e7a53a5 feat(encoding)!: accept a map in the decoder interface
This interface is specific to decoding data into Viper's internal,
so it's okay to make it Viper specific.

BREAKING CHANGE: the decoder interface now accepts a map instead of an
interface

Signed-off-by: Mark Sagi-Kazar <mark.sagikazar@gmail.com>
2021-12-15 22:31:11 +01:00

81 lines
1.6 KiB
Go

package encoding
import (
"reflect"
"testing"
)
type decoder struct {
v map[string]interface{}
}
func (d decoder) Decode(_ []byte, v map[string]interface{}) 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{})
if err != nil {
t.Fatal(err)
}
})
t.Run("AlreadyRegistered", func(t *testing.T) {
registry := NewDecoderRegistry()
err := registry.RegisterDecoder("myformat", decoder{})
if err != nil {
t.Fatal(err)
}
err = registry.RegisterDecoder("myformat", decoder{})
if err != ErrDecoderFormatAlreadyRegistered {
t.Fatalf("expected ErrDecoderFormatAlreadyRegistered, got: %v", err)
}
})
}
func TestDecoderRegistry_Decode(t *testing.T) {
t.Run("OK", func(t *testing.T) {
registry := NewDecoderRegistry()
decoder := decoder{
v: map[string]interface{}{
"key": "value",
},
}
err := registry.RegisterDecoder("myformat", decoder)
if err != nil {
t.Fatal(err)
}
v := map[string]interface{}{}
err = registry.Decode("myformat", []byte("key: value"), v)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(decoder.v, v) {
t.Fatalf("decoded value does not match the expected one\nactual: %+v\nexpected: %+v", v, decoder.v)
}
})
t.Run("DecoderNotFound", func(t *testing.T) {
registry := NewDecoderRegistry()
v := map[string]interface{}{}
err := registry.Decode("myformat", nil, v)
if err != ErrDecoderNotFound {
t.Fatalf("expected ErrDecoderNotFound, got: %v", err)
}
})
}