2019-12-06 09:53:24 +00:00
|
|
|
package encoding
|
|
|
|
|
|
|
|
import (
|
2021-07-15 21:47:20 +00:00
|
|
|
"reflect"
|
2019-12-06 09:53:24 +00:00
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
type decoder struct {
|
2023-09-26 14:59:38 +00:00
|
|
|
v map[string]any
|
2019-12-06 09:53:24 +00:00
|
|
|
}
|
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
func (d decoder) Decode(_ []byte, v map[string]any) error {
|
2021-07-15 21:47:20 +00:00
|
|
|
for key, value := range d.v {
|
|
|
|
v[key] = value
|
|
|
|
}
|
2019-12-06 09:53:24 +00:00
|
|
|
|
|
|
|
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{
|
2023-09-26 14:59:38 +00:00
|
|
|
v: map[string]any{
|
2021-07-15 21:47:20 +00:00
|
|
|
"key": "value",
|
|
|
|
},
|
2019-12-06 09:53:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err := registry.RegisterDecoder("myformat", decoder)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
v := map[string]any{}
|
2019-12-06 09:53:24 +00:00
|
|
|
|
2021-07-15 21:47:20 +00:00
|
|
|
err = registry.Decode("myformat", []byte("key: value"), v)
|
2019-12-06 09:53:24 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2021-07-15 21:47:20 +00:00
|
|
|
if !reflect.DeepEqual(decoder.v, v) {
|
|
|
|
t.Fatalf("decoded value does not match the expected one\nactual: %+v\nexpected: %+v", v, decoder.v)
|
2019-12-06 09:53:24 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("DecoderNotFound", func(t *testing.T) {
|
|
|
|
registry := NewDecoderRegistry()
|
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
v := map[string]any{}
|
2019-12-06 09:53:24 +00:00
|
|
|
|
2021-07-15 21:47:20 +00:00
|
|
|
err := registry.Decode("myformat", nil, v)
|
2019-12-06 09:53:24 +00:00
|
|
|
if err != ErrDecoderNotFound {
|
|
|
|
t.Fatalf("expected ErrDecoderNotFound, got: %v", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|