raft: add a test for randElectionTimeout

This commit is contained in:
Xiang Li 2014-10-07 20:34:15 +08:00
parent d7d6f84f64
commit f65d117462

View File

@ -3,6 +3,7 @@ package raft
import (
"bytes"
"fmt"
"math"
"math/rand"
"reflect"
"sort"
@ -492,6 +493,38 @@ func TestCommit(t *testing.T) {
}
}
func TestIsElectionTimeout(t *testing.T) {
tests := []struct {
elapse int
wpossibility float64
round bool
}{
{5, 0, false},
{13, 0.3, true},
{15, 0.5, true},
{18, 0.8, true},
{20, 1, false},
}
for i, tt := range tests {
sm := newRaft(1, []int64{1}, 10, 1)
sm.elapsed = tt.elapse
c := 0
for j := 0; j < 10000; j++ {
if sm.isElectionTimeout() {
c++
}
}
got := float64(c) / 10000.0
if tt.round {
got = math.Floor(got*10+0.5) / 10.0
}
if got != tt.wpossibility {
t.Errorf("#%d: possibility = %v, want %v", i, got, tt.wpossibility)
}
}
}
// ensure that the Step function ignores the message from old term and does not pass it to the
// acutal stepX function.
func TestStepIgnoreOldTermMsg(t *testing.T) {