node_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package raft
  2. import (
  3. "reflect"
  4. "testing"
  5. "github.com/coreos/etcd/raft/raftpb"
  6. "github.com/coreos/etcd/third_party/code.google.com/p/go.net/context"
  7. )
  8. func TestNode(t *testing.T) {
  9. ctx, cancel := context.WithCancel(context.Background())
  10. defer cancel()
  11. wants := []Ready{
  12. {
  13. State: raftpb.State{Term: 1, Commit: 1, LastIndex: 1},
  14. Entries: []raftpb.Entry{{Term: 1, Index: 1}},
  15. CommittedEntries: []raftpb.Entry{{Term: 1, Index: 1}},
  16. },
  17. {
  18. State: raftpb.State{Term: 1, Commit: 2, LastIndex: 2},
  19. Entries: []raftpb.Entry{{Term: 1, Index: 2, Data: []byte("foo")}},
  20. CommittedEntries: []raftpb.Entry{{Term: 1, Index: 2, Data: []byte("foo")}},
  21. },
  22. }
  23. n := Start(1, []int64{1}, 0, 0)
  24. n.Campaign(ctx)
  25. if g := <-n.Ready(); !reflect.DeepEqual(g, wants[0]) {
  26. t.Errorf("#%d: g = %+v,\n w %+v", 1, g, wants[0])
  27. }
  28. n.Propose(ctx, []byte("foo"))
  29. if g := <-n.Ready(); !reflect.DeepEqual(g, wants[1]) {
  30. t.Errorf("#%d: g = %+v,\n w %+v", 2, g, wants[1])
  31. }
  32. select {
  33. case rd := <-n.Ready():
  34. t.Errorf("unexpected Ready: %+v", rd)
  35. default:
  36. }
  37. }
  38. func TestNodeRestart(t *testing.T) {
  39. entries := []raftpb.Entry{
  40. {Term: 1, Index: 1},
  41. {Term: 1, Index: 2, Data: []byte("foo")},
  42. }
  43. st := raftpb.State{Term: 1, Commit: 1, LastIndex: 2}
  44. want := Ready{
  45. State: emptyState,
  46. // commit upto index commit index in st
  47. CommittedEntries: entries[:st.Commit],
  48. }
  49. n := Restart(1, []int64{1}, 0, 0, st, entries)
  50. if g := <-n.Ready(); !reflect.DeepEqual(g, want) {
  51. t.Errorf("g = %+v,\n w %+v", g, want)
  52. }
  53. select {
  54. case rd := <-n.Ready():
  55. t.Errorf("unexpected Ready: %+v", rd)
  56. default:
  57. }
  58. }