1
0

process_test.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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. )
  22. func TestProcess(t *testing.T) {
  23. assert := assert.New(t)
  24. var (
  25. msg Message
  26. resMsg Message
  27. err error
  28. )
  29. // empty struct
  30. msg = &Ping{}
  31. buffer := bytes.NewBuffer(nil)
  32. err = WriteMsg(buffer, msg)
  33. assert.NoError(err)
  34. resMsg, err = ReadMsg(buffer)
  35. assert.NoError(err)
  36. assert.Equal(reflect.TypeOf(resMsg).Elem(), TypeMap[TypePing])
  37. // normal message
  38. msg = &StartWorkConn{
  39. ProxyName: "test",
  40. }
  41. buffer = bytes.NewBuffer(nil)
  42. err = WriteMsg(buffer, msg)
  43. assert.NoError(err)
  44. resMsg, err = ReadMsg(buffer)
  45. assert.NoError(err)
  46. assert.Equal(reflect.TypeOf(resMsg).Elem(), TypeMap[TypeStartWorkConn])
  47. startWorkConnMsg, ok := resMsg.(*StartWorkConn)
  48. assert.True(ok)
  49. assert.Equal("test", startWorkConnMsg.ProxyName)
  50. // ReadMsgInto correct
  51. msg = &Pong{}
  52. buffer = bytes.NewBuffer(nil)
  53. err = WriteMsg(buffer, msg)
  54. assert.NoError(err)
  55. err = ReadMsgInto(buffer, msg)
  56. assert.NoError(err)
  57. // ReadMsgInto error type
  58. content := []byte(`{"run_id": 123}`)
  59. buffer = bytes.NewBuffer(nil)
  60. buffer.WriteByte(TypeNewWorkConn)
  61. binary.Write(buffer, binary.BigEndian, int64(len(content)))
  62. buffer.Write(content)
  63. resMsg = &NewWorkConn{}
  64. err = ReadMsgInto(buffer, resMsg)
  65. assert.Error(err)
  66. // message format error
  67. buffer = bytes.NewBuffer([]byte("1234"))
  68. resMsg = &NewProxyResp{}
  69. err = ReadMsgInto(buffer, resMsg)
  70. assert.Error(err)
  71. // MaxLength, real message length is 2
  72. MaxMsgLength = 1
  73. msg = &Ping{}
  74. buffer = bytes.NewBuffer(nil)
  75. err = WriteMsg(buffer, msg)
  76. assert.NoError(err)
  77. _, err = ReadMsg(buffer)
  78. assert.Error(err)
  79. return
  80. }