2019-12-06 09:53:24 +00:00
|
|
|
package encoding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
2023-10-07 19:28:36 +00:00
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
"github.com/stretchr/testify/require"
|
2019-12-06 09:53:24 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type encoder struct {
|
|
|
|
b []byte
|
|
|
|
}
|
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
func (e encoder) Encode(_ map[string]any) ([]byte, error) {
|
2019-12-06 09:53:24 +00:00
|
|
|
return e.b, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestEncoderRegistry_RegisterEncoder(t *testing.T) {
|
|
|
|
t.Run("OK", func(t *testing.T) {
|
|
|
|
registry := NewEncoderRegistry()
|
|
|
|
|
|
|
|
err := registry.RegisterEncoder("myformat", encoder{})
|
2023-10-07 19:28:36 +00:00
|
|
|
require.NoError(t, err)
|
2019-12-06 09:53:24 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("AlreadyRegistered", func(t *testing.T) {
|
|
|
|
registry := NewEncoderRegistry()
|
|
|
|
|
|
|
|
err := registry.RegisterEncoder("myformat", encoder{})
|
2023-10-07 19:28:36 +00:00
|
|
|
require.NoError(t, err)
|
2019-12-06 09:53:24 +00:00
|
|
|
|
|
|
|
err = registry.RegisterEncoder("myformat", encoder{})
|
2023-10-07 19:28:36 +00:00
|
|
|
assert.ErrorIs(t, err, ErrEncoderFormatAlreadyRegistered)
|
2019-12-06 09:53:24 +00:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func TestEncoderRegistry_Decode(t *testing.T) {
|
|
|
|
t.Run("OK", func(t *testing.T) {
|
|
|
|
registry := NewEncoderRegistry()
|
|
|
|
encoder := encoder{
|
2021-07-15 22:26:30 +00:00
|
|
|
b: []byte("key: value"),
|
2019-12-06 09:53:24 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
err := registry.RegisterEncoder("myformat", encoder)
|
2023-10-07 19:28:36 +00:00
|
|
|
require.NoError(t, err)
|
2019-12-06 09:53:24 +00:00
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
b, err := registry.Encode("myformat", map[string]any{"key": "value"})
|
2023-10-07 19:28:36 +00:00
|
|
|
require.NoError(t, err)
|
2019-12-06 09:53:24 +00:00
|
|
|
|
2023-10-07 19:28:36 +00:00
|
|
|
assert.Equal(t, "key: value", string(b))
|
2019-12-06 09:53:24 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("EncoderNotFound", func(t *testing.T) {
|
|
|
|
registry := NewEncoderRegistry()
|
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
_, err := registry.Encode("myformat", map[string]any{"key": "value"})
|
2023-10-07 19:28:36 +00:00
|
|
|
assert.ErrorIs(t, err, ErrEncoderNotFound)
|
2019-12-06 09:53:24 +00:00
|
|
|
})
|
|
|
|
}
|