raft: move logic to separate func

This commit is contained in:
Yicheng Qin 2014-09-24 10:19:41 -07:00
parent b07be74a82
commit 1ca03d8e9d
2 changed files with 21 additions and 25 deletions

View File

@ -265,9 +265,7 @@ func (r *raft) appendEntry(e pb.Entry) {
// tickElection is ran by followers and candidates after r.electionTimeout.
func (r *raft) tickElection() {
// promotable indicates whether state machine can be promoted to leader,
// which is true when its own id is in progress list.
if _, promotable := r.prs[r.id]; !promotable {
if !r.promotable() {
r.elapsed = 0
return
}
@ -536,6 +534,13 @@ func (r *raft) delProgress(id int64) {
delete(r.prs, id)
}
// promotable indicates whether state machine can be promoted to leader,
// which is true when its own id is in progress list.
func (r *raft) promotable() bool {
_, ok := r.prs[r.id]
return ok
}
func (r *raft) loadEnts(ents []pb.Entry) {
r.raftLog.load(ents)
}

View File

@ -1053,33 +1053,24 @@ func TestRemoveNode(t *testing.T) {
}
}
func TestTickElectionElapsed(t *testing.T) {
electionTimeout := 10
func TestPromotable(t *testing.T) {
id := int64(1)
tests := []struct {
promotable bool
e int
we int
peers []int64
wp bool
}{
{true, 0, 1},
{true, electionTimeout - 1, electionTimeout},
{true, electionTimeout, 0},
{false, 0, 0},
{false, 1, 0},
{[]int64{1}, true},
{[]int64{1, 2, 3}, true},
{[]int64{}, false},
{[]int64{2, 3}, false},
}
for i, tt := range tests {
r := &raft{
id: 1,
raftLog: newLog(),
prs: make(map[int64]*progress),
electionTimeout: electionTimeout,
elapsed: tt.e,
r := &raft{id: id, prs: make(map[int64]*progress)}
for _, id := range tt.peers {
r.prs[id] = &progress{}
}
if tt.promotable {
r.prs[r.id] = &progress{}
}
r.tickElection()
if r.elapsed != tt.we {
t.Errorf("#%d: elapsed = %d, want %d", i, r.elapsed, tt.we)
if g := r.promotable(); g != tt.wp {
t.Errorf("#%d: promotable = %v, want %v", i, g, tt.wp)
}
}
}