2019-12-06 09:53:24 +00:00
|
|
|
package encoding
|
|
|
|
|
|
|
|
import (
|
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
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{})
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
|
|
|
|
t.Run("AlreadyRegistered", func(t *testing.T) {
|
|
|
|
registry := NewEncoderRegistry()
|
|
|
|
|
|
|
|
err := registry.RegisterEncoder("myformat", encoder{})
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
err = registry.RegisterEncoder("myformat", encoder{})
|
|
|
|
if err != ErrEncoderFormatAlreadyRegistered {
|
|
|
|
t.Fatalf("expected ErrEncoderFormatAlreadyRegistered, got: %v", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
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)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2023-09-26 14:59:38 +00:00
|
|
|
b, err := registry.Encode("myformat", map[string]any{"key": "value"})
|
2019-12-06 09:53:24 +00:00
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2021-07-15 22:26:30 +00:00
|
|
|
if string(b) != "key: value" {
|
|
|
|
t.Fatalf("expected 'key: value', got: %#v", 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"})
|
2019-12-06 09:53:24 +00:00
|
|
|
if err != ErrEncoderNotFound {
|
|
|
|
t.Fatalf("expected ErrEncoderNotFound, got: %v", err)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|