msg_codec_test.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  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. // Lower readBytesLimit to make test pass in restricted resources environment
  23. originalLimit := readBytesLimit
  24. readBytesLimit = 1000
  25. defer func() {
  26. readBytesLimit = originalLimit
  27. }()
  28. tests := []struct {
  29. msg raftpb.Message
  30. encodeErr error
  31. decodeErr error
  32. }{
  33. {
  34. raftpb.Message{
  35. Type: raftpb.MsgApp,
  36. From: 1,
  37. To: 2,
  38. Term: 1,
  39. LogTerm: 1,
  40. Index: 3,
  41. Entries: []raftpb.Entry{{Term: 1, Index: 4}},
  42. },
  43. nil,
  44. nil,
  45. },
  46. {
  47. raftpb.Message{
  48. Type: raftpb.MsgProp,
  49. From: 1,
  50. To: 2,
  51. Entries: []raftpb.Entry{
  52. {Data: []byte("some data")},
  53. {Data: []byte("some data")},
  54. {Data: []byte("some data")},
  55. },
  56. },
  57. nil,
  58. nil,
  59. },
  60. {
  61. raftpb.Message{
  62. Type: raftpb.MsgProp,
  63. From: 1,
  64. To: 2,
  65. Entries: []raftpb.Entry{
  66. {Data: bytes.Repeat([]byte("a"), int(readBytesLimit+10))},
  67. },
  68. },
  69. nil,
  70. ErrExceedSizeLimit,
  71. },
  72. }
  73. for i, tt := range tests {
  74. b := &bytes.Buffer{}
  75. enc := &messageEncoder{w: b}
  76. if err := enc.encode(&tt.msg); err != tt.encodeErr {
  77. t.Errorf("#%d: encode message error expected %v, got %v", i, tt.encodeErr, err)
  78. continue
  79. }
  80. dec := &messageDecoder{r: b}
  81. m, err := dec.decode()
  82. if err != tt.decodeErr {
  83. t.Errorf("#%d: decode message error expected %v, got %v", i, tt.decodeErr, err)
  84. continue
  85. }
  86. if err == nil {
  87. if !reflect.DeepEqual(m, tt.msg) {
  88. t.Errorf("#%d: message = %+v, want %+v", i, m, tt.msg)
  89. }
  90. }
  91. }
  92. }