1
0

pack_test.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2016 fatedier, fatedier@gmail.com
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package msg
  15. import (
  16. "bytes"
  17. "encoding/binary"
  18. "reflect"
  19. "testing"
  20. "github.com/stretchr/testify/assert"
  21. "github.com/fatedier/frp/utils/errors"
  22. )
  23. type TestStruct struct{}
  24. func TestPack(t *testing.T) {
  25. assert := assert.New(t)
  26. var (
  27. msg Message
  28. buffer []byte
  29. err error
  30. )
  31. // error type
  32. msg = &TestStruct{}
  33. buffer, err = Pack(msg)
  34. assert.Error(err, errors.ErrMsgType.Error())
  35. // correct
  36. msg = &Ping{}
  37. buffer, err = Pack(msg)
  38. assert.NoError(err)
  39. b := bytes.NewBuffer(nil)
  40. b.WriteByte(TypePing)
  41. binary.Write(b, binary.BigEndian, int64(2))
  42. b.WriteString("{}")
  43. assert.True(bytes.Equal(b.Bytes(), buffer))
  44. }
  45. func TestUnPack(t *testing.T) {
  46. assert := assert.New(t)
  47. var (
  48. msg Message
  49. err error
  50. )
  51. // error message type
  52. msg, err = UnPack('-', []byte("{}"))
  53. assert.Error(err)
  54. // correct
  55. msg, err = UnPack(TypePong, []byte("{}"))
  56. assert.NoError(err)
  57. assert.Equal(reflect.TypeOf(msg).Elem(), reflect.TypeOf(Pong{}))
  58. }
  59. func TestUnPackInto(t *testing.T) {
  60. assert := assert.New(t)
  61. var err error
  62. // correct type
  63. pongMsg := &Pong{}
  64. err = UnPackInto([]byte("{}"), pongMsg)
  65. assert.NoError(err)
  66. // wrong type
  67. loginMsg := &Login{}
  68. err = UnPackInto([]byte(`{"version": 123}`), loginMsg)
  69. assert.Error(err)
  70. }