util_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 raft
  15. import (
  16. "math"
  17. "reflect"
  18. "strings"
  19. "testing"
  20. pb "github.com/coreos/etcd/raft/raftpb"
  21. )
  22. var testFormatter EntryFormatter = func(data []byte) string {
  23. return strings.ToUpper(string(data))
  24. }
  25. func TestDescribeEntry(t *testing.T) {
  26. entry := pb.Entry{
  27. Term: 1,
  28. Index: 2,
  29. Type: pb.EntryNormal,
  30. Data: []byte("hello\x00world"),
  31. }
  32. defaultFormatted := DescribeEntry(entry, nil)
  33. if defaultFormatted != "1/2 EntryNormal \"hello\\x00world\"" {
  34. t.Errorf("unexpected default output: %s", defaultFormatted)
  35. }
  36. customFormatted := DescribeEntry(entry, testFormatter)
  37. if customFormatted != "1/2 EntryNormal HELLO\x00WORLD" {
  38. t.Errorf("unexpected custom output: %s", customFormatted)
  39. }
  40. }
  41. func TestLimitSize(t *testing.T) {
  42. ents := []pb.Entry{{Index: 4, Term: 4}, {Index: 5, Term: 5}, {Index: 6, Term: 6}}
  43. tests := []struct {
  44. maxsize uint64
  45. wentries []pb.Entry
  46. }{
  47. {math.MaxUint64, []pb.Entry{{Index: 4, Term: 4}, {Index: 5, Term: 5}, {Index: 6, Term: 6}}},
  48. // even if maxsize is zero, the first entry should be returned
  49. {0, []pb.Entry{{Index: 4, Term: 4}}},
  50. // limit to 2
  51. {uint64(ents[0].Size() + ents[1].Size()), []pb.Entry{{Index: 4, Term: 4}, {Index: 5, Term: 5}}},
  52. // limit to 2
  53. {uint64(ents[0].Size() + ents[1].Size() + ents[2].Size()/2), []pb.Entry{{Index: 4, Term: 4}, {Index: 5, Term: 5}}},
  54. {uint64(ents[0].Size() + ents[1].Size() + ents[2].Size() - 1), []pb.Entry{{Index: 4, Term: 4}, {Index: 5, Term: 5}}},
  55. // all
  56. {uint64(ents[0].Size() + ents[1].Size() + ents[2].Size()), []pb.Entry{{Index: 4, Term: 4}, {Index: 5, Term: 5}, {Index: 6, Term: 6}}},
  57. }
  58. for i, tt := range tests {
  59. if !reflect.DeepEqual(limitSize(ents, tt.maxsize), tt.wentries) {
  60. t.Errorf("#%d: entries = %v, want %v", i, limitSize(ents, tt.maxsize), tt.wentries)
  61. }
  62. }
  63. }