|
|
package codec
|
|
|
|
|
|
import (
|
|
|
"testing"
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
"github.com/stretchr/testify/require"
|
|
|
)
|
|
|
|
|
|
func TestMessagePackCodec(t *testing.T) {
|
|
|
codec := NewMessagePackCodec()
|
|
|
|
|
|
// 测试名称
|
|
|
assert.Equal(t, "msgpack", codec.Name(), "Expected name to be 'msgpack'")
|
|
|
|
|
|
// 测试编码
|
|
|
type TestStruct struct {
|
|
|
Name string `json:"name"`
|
|
|
Value int `json:"value"`
|
|
|
}
|
|
|
|
|
|
data := TestStruct{
|
|
|
Name: "test",
|
|
|
Value: 42,
|
|
|
}
|
|
|
|
|
|
encoded, err := codec.Encode(data)
|
|
|
require.NoError(t, err, "Expected no error when encoding")
|
|
|
assert.NotEmpty(t, encoded, "Expected encoded data to be non-empty")
|
|
|
|
|
|
// 测试解码
|
|
|
var decoded TestStruct
|
|
|
err = codec.Decode(encoded, &decoded)
|
|
|
require.NoError(t, err, "Expected no error when decoding")
|
|
|
assert.Equal(t, data.Name, decoded.Name, "Expected name to match")
|
|
|
assert.Equal(t, data.Value, decoded.Value, "Expected value to match")
|
|
|
}
|
|
|
|
|
|
func TestMessagePackCodecPrimitives(t *testing.T) {
|
|
|
codec := NewMessagePackCodec()
|
|
|
|
|
|
// 测试编码字符串
|
|
|
encoded, err := codec.Encode("hello")
|
|
|
require.NoError(t, err)
|
|
|
assert.NotEmpty(t, encoded)
|
|
|
|
|
|
var str string
|
|
|
err = codec.Decode(encoded, &str)
|
|
|
require.NoError(t, err)
|
|
|
assert.Equal(t, "hello", str)
|
|
|
}
|
|
|
|
|
|
func TestMessagePackCodecInvalidData(t *testing.T) {
|
|
|
codec := NewMessagePackCodec()
|
|
|
|
|
|
// 测试无效数据(虽然msgpack使用JSON作为fallback,但仍需测试)
|
|
|
var result interface{}
|
|
|
err := codec.Decode([]byte("invalid"), &result)
|
|
|
// 由于使用JSON fallback,可能会成功或失败,这里只测试不会panic
|
|
|
_ = err
|
|
|
}
|
|
|
|