2019-12-06 12:53:24 +03:00
|
|
|
package encoding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
2023-10-07 22:28:36 +03:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2019-12-06 12:53:24 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
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{})
|
2023-10-07 22:28:36 +03:00
|
|
|
require.NoError(t, err)
|
2019-12-06 12:53:24 +03:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("AlreadyRegistered", func(t *testing.T) {
|
|
|
|
registry := NewDecoderRegistry()
|
|
|
|
|
|
|
|
err := registry.RegisterDecoder("myformat", decoder{})
|
2023-10-07 22:28:36 +03:00
|
|
|
require.NoError(t, err)
|
2019-12-06 12:53:24 +03:00
|
|
|
|
|
|
|
err = registry.RegisterDecoder("myformat", decoder{})
|
2023-10-07 22:28:36 +03:00
|
|
|
assert.ErrorIs(t, err, ErrDecoderFormatAlreadyRegistered)
|
2019-12-06 12:53:24 +03:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
2023-10-07 22:28:36 +03:00
|
|
|
require.NoError(t, err)
|
2019-12-06 12:53:24 +03:00
|
|
|
|
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)
|
2023-10-07 22:28:36 +03:00
|
|
|
require.NoError(t, err)
|
2019-12-06 12:53:24 +03:00
|
|
|
|
2023-10-07 22:28:36 +03:00
|
|
|
assert.Equal(t, decoder.v, 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)
|
2023-10-07 22:28:36 +03:00
|
|
|
assert.ErrorIs(t, err, ErrDecoderNotFound)
|
2019-12-06 12:53:24 +03:00
|
|
|
})
|
|
|
|
}
|