From de0e7698346bbfcfb4c1519f0d2a6a706a7a1488 Mon Sep 17 00:00:00 2001 From: Ian Gulliver Date: Mon, 12 Jun 2023 19:34:22 -0700 Subject: [PATCH] Handle channel overflow, test channel data --- candidate.go | 6 +++++- elect_test.go | 25 +++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/candidate.go b/candidate.go index 40b88c0..77ac99b 100644 --- a/candidate.go +++ b/candidate.go @@ -215,7 +215,11 @@ func (c *Candidate) elect(v *vote) { ) c.state = state - c.c <- state + + select { + case c.c <- state: + default: + } }() if c.forceState != StateUndefined { diff --git a/elect_test.go b/elect_test.go index 372fd5c..e6f3fed 100644 --- a/elect_test.go +++ b/elect_test.go @@ -4,6 +4,7 @@ import ( "testing" "time" + "github.com/gopatchy/elect" "github.com/stretchr/testify/require" ) @@ -37,6 +38,10 @@ func TestThree(t *testing.T) { w.Wait() } + + require.Equal(t, <-ts.Candidate(0).C, elect.StateLeader) + require.Empty(t, ts.Candidate(1).C) + require.Empty(t, ts.Candidate(2).C) } func TestFailover(t *testing.T) { @@ -59,6 +64,10 @@ func TestFailover(t *testing.T) { w.Wait() } + require.Equal(t, <-ts.Candidate(0).C, elect.StateLeader) + require.Empty(t, ts.Candidate(1).C) + require.Empty(t, ts.Candidate(2).C) + ts.SetServer(1) require.Eventually(t, func() bool { return !ts.Candidate(0).IsLeader() }, 15*time.Second, 100*time.Millisecond) @@ -66,6 +75,10 @@ func TestFailover(t *testing.T) { require.False(t, ts.Candidate(1).IsLeader()) require.False(t, ts.Candidate(2).IsLeader()) + require.Equal(t, <-ts.Candidate(0).C, elect.StateNotLeader) + require.Empty(t, ts.Candidate(1).C) + require.Empty(t, ts.Candidate(2).C) + { w := NewWaiter() @@ -75,6 +88,10 @@ func TestFailover(t *testing.T) { w.Wait() } + + require.Equal(t, <-ts.Candidate(1).C, elect.StateLeader) + require.Empty(t, ts.Candidate(0).C) + require.Empty(t, ts.Candidate(2).C) } func TestPartialVotes(t *testing.T) { @@ -98,6 +115,10 @@ func TestPartialVotes(t *testing.T) { w.Wait() } + + require.Equal(t, <-ts.Candidate(0).C, elect.StateLeader) + require.Empty(t, ts.Candidate(1).C) + require.Empty(t, ts.Candidate(2).C) } func TestSplitVotes(t *testing.T) { @@ -122,4 +143,8 @@ func TestSplitVotes(t *testing.T) { w.Wait() } + + require.Equal(t, <-ts.Candidate(1).C, elect.StateLeader) + require.Empty(t, ts.Candidate(0).C) + require.Empty(t, ts.Candidate(2).C) }