msg_codec_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2015 The etcd Authors
  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 rafthttp
  15. import (
  16. "bytes"
  17. "reflect"
  18. "testing"
  19. "github.com/coreos/etcd/raft/raftpb"
  20. )
  21. func TestMessage(t *testing.T) {
  22. tests := []struct {
  23. msg raftpb.Message
  24. encodeErr error
  25. decodeErr error
  26. }{
  27. {
  28. raftpb.Message{
  29. Type: raftpb.MsgApp,
  30. From: 1,
  31. To: 2,
  32. Term: 1,
  33. LogTerm: 1,
  34. Index: 3,
  35. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  36. },
  37. nil,
  38. nil,
  39. },
  40. {
  41. raftpb.Message{
  42. Type: raftpb.MsgProp,
  43. From: 1,
  44. To: 2,
  45. Entries: []raftpb.Entry{
  46. {Data: []byte("some data")},
  47. {Data: []byte("some data")},
  48. {Data: []byte("some data")},
  49. },
  50. },
  51. nil,
  52. nil,
  53. },
  54. {
  55. raftpb.Message{
  56. Type: raftpb.MsgProp,
  57. From: 1,
  58. To: 2,
  59. Entries: []raftpb.Entry{
  60. {Data: bytes.Repeat([]byte("a"), int(readBytesLimit+10))},
  61. },
  62. },
  63. nil,
  64. ErrExceedSizeLimit,
  65. },
  66. }
  67. for i, tt := range tests {
  68. b := &bytes.Buffer{}
  69. enc := &messageEncoder{w: b}
  70. if err := enc.encode(&tt.msg); err != tt.encodeErr {
  71. t.Errorf("#%d: encode message error expected %v, got %v", i, tt.encodeErr, err)
  72. continue
  73. }
  74. dec := &messageDecoder{r: b}
  75. m, err := dec.decode()
  76. if err != tt.decodeErr {
  77. t.Errorf("#%d: decode message error expected %v, got %v", i, tt.decodeErr, err)
  78. continue
  79. }
  80. if err == nil {
  81. if !reflect.DeepEqual(m, tt.msg) {
  82. t.Errorf("#%d: message = %+v, want %+v", i, m, tt.msg)
  83. }
  84. }
  85. }
  86. }