diff --git a/masterelection/masterelection_test.go b/masterelection/masterelection_test.go index a98247f412c2373d7120b74b1bd0b6464c141bf5..21c5b4f7ef91ad64b225dcd3e3f3b403c3587dfe 100644 --- a/masterelection/masterelection_test.go +++ b/masterelection/masterelection_test.go @@ -2,7 +2,9 @@ package masterelection import ( "fmt" + "log" "math/rand" + "os" "testing" "time" @@ -26,7 +28,9 @@ func countMasters(nodes []*MasterElection) int { func verifyMasterData(t *testing.T, nodes []*MasterElection) { tmp := make(map[string]struct{}) for _, n := range nodes { - tmp[n.GetMasterData()] = struct{}{} + if n != nil { + tmp[n.GetMasterData()] = struct{}{} + } } if len(tmp) != 1 { t.Errorf("master data propagation error: >1 values: %v", tmp) @@ -49,18 +53,36 @@ func TestMasterElection(t *testing.T) { fmt.Sprintf("%d", i), 1, nil) - m.LogPrefix = fmt.Sprintf("node%d: masterelection", i+1) + m.Log = log.New(os.Stderr, fmt.Sprintf("node%d: masterelection: ", i+1), 0) go m.Run(stopCh) nodes = append(nodes, m) stop = append(stop, stopCh) } + // Force master transitions by shutting down the nodes one by + // one as the become the master, and verify that there is a + // single master among the remaining ones. for i := 0; i < n; i++ { time.Sleep(100 * time.Millisecond) - if nm := countMasters(nodes[i:len(nodes)]); nm != 1 { - t.Errorf("@%d: masters=%d (expected <= 1)", i, nm) + + masterIdx := -1 + numMasters := 0 + for i, m := range nodes { + if m == nil { + continue + } + if m.IsMaster() { + numMasters++ + masterIdx = i + } } - verifyMasterData(t, nodes[i:len(nodes)]) - close(stop[i]) + + if numMasters != 1 { + t.Fatalf("masters=%d (expected 1): %#v", numMasters, nodes) + } + verifyMasterData(t, nodes) + + close(stop[masterIdx]) + nodes[masterIdx] = nil } }