From f65d11746288130d9deb2d4b00dd8996e275c4f0 Mon Sep 17 00:00:00 2001 From: Xiang Li Date: Tue, 7 Oct 2014 20:34:15 +0800 Subject: [PATCH] raft: add a test for randElectionTimeout --- raft/raft_test.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/raft/raft_test.go b/raft/raft_test.go index 2f424629d..adca3ad1d 100644 --- a/raft/raft_test.go +++ b/raft/raft_test.go @@ -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) {