You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

116 lines
2.2 KiB

  1. package msgpack_test
  2. import (
  3. "reflect"
  4. "testing"
  5. "github.com/vmihailenco/msgpack"
  6. "github.com/vmihailenco/msgpack/codes"
  7. )
  8. func init() {
  9. msgpack.RegisterExt(9, (*ExtTest)(nil))
  10. }
  11. func TestRegisterExtPanic(t *testing.T) {
  12. defer func() {
  13. r := recover()
  14. if r == nil {
  15. t.Fatalf("panic expected")
  16. }
  17. got := r.(error).Error()
  18. wanted := "msgpack: ext with id=9 is already registered"
  19. if got != wanted {
  20. t.Fatalf("got %q, wanted %q", got, wanted)
  21. }
  22. }()
  23. msgpack.RegisterExt(9, (*ExtTest)(nil))
  24. }
  25. type ExtTest struct {
  26. S string
  27. }
  28. var _ msgpack.CustomEncoder = (*ExtTest)(nil)
  29. var _ msgpack.CustomDecoder = (*ExtTest)(nil)
  30. func (ext ExtTest) EncodeMsgpack(e *msgpack.Encoder) error {
  31. return e.EncodeString("hello " + ext.S)
  32. }
  33. func (ext *ExtTest) DecodeMsgpack(d *msgpack.Decoder) error {
  34. var err error
  35. ext.S, err = d.DecodeString()
  36. return err
  37. }
  38. func TestExt(t *testing.T) {
  39. for _, v := range []interface{}{ExtTest{"world"}, &ExtTest{"world"}} {
  40. b, err := msgpack.Marshal(v)
  41. if err != nil {
  42. t.Fatal(err)
  43. }
  44. var dst interface{}
  45. err = msgpack.Unmarshal(b, &dst)
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. v, ok := dst.(*ExtTest)
  50. if !ok {
  51. t.Fatalf("got %#v, wanted ExtTest", dst)
  52. }
  53. wanted := "hello world"
  54. if v.S != wanted {
  55. t.Fatalf("got %q, wanted %q", v.S, wanted)
  56. }
  57. ext := new(ExtTest)
  58. err = msgpack.Unmarshal(b, ext)
  59. if err != nil {
  60. t.Fatal(err)
  61. }
  62. if ext.S != wanted {
  63. t.Fatalf("got %q, wanted %q", ext.S, wanted)
  64. }
  65. }
  66. }
  67. func TestUnknownExt(t *testing.T) {
  68. b := []byte{byte(codes.FixExt1), 1, 0}
  69. var dst interface{}
  70. err := msgpack.Unmarshal(b, &dst)
  71. if err == nil {
  72. t.Fatalf("got nil, wanted error")
  73. }
  74. got := err.Error()
  75. wanted := "msgpack: unregistered ext id=1"
  76. if got != wanted {
  77. t.Fatalf("got %q, wanted %q", got, wanted)
  78. }
  79. }
  80. func TestDecodeExtWithMap(t *testing.T) {
  81. type S struct {
  82. I int
  83. }
  84. msgpack.RegisterExt(2, S{})
  85. b, err := msgpack.Marshal(&S{I: 42})
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. var got map[string]interface{}
  90. if err := msgpack.Unmarshal(b, &got); err != nil {
  91. t.Fatal(err)
  92. }
  93. wanted := map[string]interface{}{"I": int8(42)}
  94. if !reflect.DeepEqual(got, wanted) {
  95. t.Fatalf("got %#v, but wanted %#v", got, wanted)
  96. }
  97. }