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