Add mockito-configuration to tests
[controller.git] / opendaylight / md-sal / sal-akka-raft / src / test / java / org / opendaylight / controller / cluster / raft / behaviors / CandidateTest.java
1 /*
2  * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8
9 package org.opendaylight.controller.cluster.raft.behaviors;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertTrue;
13 import akka.actor.ActorRef;
14 import akka.actor.Props;
15 import akka.testkit.TestActorRef;
16 import com.google.common.base.Stopwatch;
17 import java.util.ArrayList;
18 import java.util.Collections;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.concurrent.TimeUnit;
23 import org.junit.After;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.mockito.Mockito;
27 import org.opendaylight.controller.cluster.NonPersistentDataProvider;
28 import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
29 import org.opendaylight.controller.cluster.raft.ElectionTerm;
30 import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
31 import org.opendaylight.controller.cluster.raft.RaftActorContext;
32 import org.opendaylight.controller.cluster.raft.RaftActorContextImpl;
33 import org.opendaylight.controller.cluster.raft.RaftState;
34 import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
35 import org.opendaylight.controller.cluster.raft.VotingState;
36 import org.opendaylight.controller.cluster.raft.base.messages.ElectionTimeout;
37 import org.opendaylight.controller.cluster.raft.messages.AppendEntries;
38 import org.opendaylight.controller.cluster.raft.messages.AppendEntriesReply;
39 import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
40 import org.opendaylight.controller.cluster.raft.messages.RequestVote;
41 import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
42 import org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
45
46 public class CandidateTest extends AbstractRaftActorBehaviorTest {
47     static final Logger LOG = LoggerFactory.getLogger(CandidateTest.class);
48
49     private final TestActorRef<MessageCollectorActor> candidateActor = actorFactory.createTestActor(
50             Props.create(MessageCollectorActor.class), actorFactory.generateActorId("candidate"));
51
52     private TestActorRef<MessageCollectorActor>[] peerActors;
53
54     private RaftActorBehavior candidate;
55
56     @Before
57     public void setUp(){
58     }
59
60     @Override
61     @After
62     public void tearDown() throws Exception {
63         if(candidate != null) {
64             candidate.close();
65         }
66
67         super.tearDown();
68     }
69
70     @Test
71     public void testWhenACandidateIsCreatedItIncrementsTheCurrentTermAndVotesForItself(){
72         RaftActorContext raftActorContext = createActorContext();
73         long expectedTerm = raftActorContext.getTermInformation().getCurrentTerm();
74
75         candidate = new Candidate(raftActorContext);
76
77         assertEquals("getCurrentTerm", expectedTerm+1, raftActorContext.getTermInformation().getCurrentTerm());
78         assertEquals("getVotedFor", raftActorContext.getId(), raftActorContext.getTermInformation().getVotedFor());
79     }
80
81     @Test
82     public void testThatAnElectionTimeoutIsTriggered(){
83          MockRaftActorContext actorContext = createActorContext();
84          candidate = new Candidate(actorContext);
85
86          MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class,
87                  actorContext.getConfigParams().getElectionTimeOutInterval().$times(6).toMillis());
88     }
89
90     @Test
91     public void testHandleElectionTimeoutWhenThereAreZeroPeers(){
92         RaftActorContext raftActorContext = createActorContext();
93         candidate = new Candidate(raftActorContext);
94
95         RaftActorBehavior newBehavior =
96             candidate.handleMessage(candidateActor, new ElectionTimeout());
97
98         assertEquals("Behavior", RaftState.Leader, newBehavior.state());
99     }
100
101     @Test
102     public void testHandleElectionTimeoutWhenThereAreTwoNodeCluster(){
103         MockRaftActorContext raftActorContext = createActorContext();
104         raftActorContext.setPeerAddresses(setupPeers(1));
105         candidate = new Candidate(raftActorContext);
106
107         candidate = candidate.handleMessage(candidateActor, new ElectionTimeout());
108
109         assertEquals("Behavior", RaftState.Candidate, candidate.state());
110     }
111
112     @Test
113     public void testBecomeLeaderOnReceivingMajorityVotesInThreeNodeCluster(){
114         MockRaftActorContext raftActorContext = createActorContext();
115         raftActorContext.setPeerAddresses(setupPeers(2));
116         candidate = new Candidate(raftActorContext);
117
118         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, true));
119
120         assertEquals("Behavior", RaftState.Leader, candidate.state());
121     }
122
123     @Test
124     public void testBecomeLeaderOnReceivingMajorityVotesInFiveNodeCluster(){
125         MockRaftActorContext raftActorContext = createActorContext();
126         raftActorContext.getTermInformation().update(2L, "other");
127         raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().
128                 createEntries(0, 5, 1).build());
129         raftActorContext.setPeerAddresses(setupPeers(4));
130         candidate = new Candidate(raftActorContext);
131
132         RequestVote requestVote = MessageCollectorActor.expectFirstMatching(peerActors[0], RequestVote.class);
133         assertEquals("getTerm", 3L, requestVote.getTerm());
134         assertEquals("getCandidateId", raftActorContext.getId(), requestVote.getCandidateId());
135         assertEquals("getLastLogTerm", 1L, requestVote.getLastLogTerm());
136         assertEquals("getLastLogIndex", 4L, requestVote.getLastLogIndex());
137
138         MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
139         MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
140         MessageCollectorActor.expectFirstMatching(peerActors[3], RequestVote.class);
141
142         // First peers denies the vote.
143         candidate = candidate.handleMessage(peerActors[0], new RequestVoteReply(1, false));
144
145         assertEquals("Behavior", RaftState.Candidate, candidate.state());
146
147         candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, true));
148
149         assertEquals("Behavior", RaftState.Candidate, candidate.state());
150
151         candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
152
153         assertEquals("Behavior", RaftState.Leader, candidate.state());
154     }
155
156     @Test
157     public void testBecomeLeaderOnReceivingMajorityVotesWithNonVotingPeers(){
158         ElectionTerm mockElectionTerm = Mockito.mock(ElectionTerm.class);
159         Mockito.doReturn(1L).when(mockElectionTerm).getCurrentTerm();
160         Mockito.doNothing().when(mockElectionTerm).updateAndPersist(Mockito.any(long.class), Mockito.any(String.class));
161
162         RaftActorContext raftActorContext = new RaftActorContextImpl(candidateActor, candidateActor.actorContext(),
163                 "candidate", mockElectionTerm, -1, -1, setupPeers(4), new DefaultConfigParamsImpl(),
164                 new NonPersistentDataProvider(), LOG);
165         raftActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
166         raftActorContext.getPeerInfo("peer1").setVotingState(VotingState.NON_VOTING);
167         raftActorContext.getPeerInfo("peer4").setVotingState(VotingState.NON_VOTING);
168         candidate = new Candidate(raftActorContext);
169
170         MessageCollectorActor.expectFirstMatching(peerActors[1], RequestVote.class);
171         MessageCollectorActor.expectFirstMatching(peerActors[2], RequestVote.class);
172         MessageCollectorActor.assertNoneMatching(peerActors[0], RequestVote.class, 300);
173         MessageCollectorActor.assertNoneMatching(peerActors[3], RequestVote.class, 100);
174
175         candidate = candidate.handleMessage(peerActors[1], new RequestVoteReply(1, false));
176
177         assertEquals("Behavior", RaftState.Candidate, candidate.state());
178
179         candidate = candidate.handleMessage(peerActors[2], new RequestVoteReply(1, true));
180
181         assertEquals("Behavior", RaftState.Leader, candidate.state());
182     }
183
184     @Test
185     public void testResponseToHandleAppendEntriesWithLowerTerm() {
186         candidate = new Candidate(createActorContext());
187
188         setupPeers(1);
189         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(1, "test", 0, 0,
190                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
191
192         AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(
193                 peerActors[0], AppendEntriesReply.class);
194         assertEquals("isSuccess", false, reply.isSuccess());
195         assertEquals("getTerm", 2, reply.getTerm());
196         assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Candidate);
197     }
198
199     @Test
200     public void testResponseToHandleAppendEntriesWithHigherTerm() {
201         candidate = new Candidate(createActorContext());
202
203         setupPeers(1);
204         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(5, "test", 0, 0,
205                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
206
207         assertTrue("New Behavior : " + newBehavior, newBehavior instanceof Follower);
208     }
209
210     @Test
211     public void testResponseToHandleAppendEntriesWithEqualTerm() {
212         MockRaftActorContext actorContext = createActorContext();
213
214         candidate = new Candidate(actorContext);
215
216         setupPeers(1);
217         RaftActorBehavior newBehavior = candidate.handleMessage(peerActors[0], new AppendEntries(2, "test", 0, 0,
218                 Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short) 0));
219
220         assertTrue("New Behavior : " + newBehavior + " term = " + actorContext.getTermInformation().getCurrentTerm(),
221                 newBehavior instanceof Follower);
222     }
223
224
225     @Test
226     public void testResponseToRequestVoteWithLowerTerm() {
227         candidate = new Candidate(createActorContext());
228
229         setupPeers(1);
230         candidate.handleMessage(peerActors[0], new RequestVote(1, "test", 0, 0));
231
232         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
233                 peerActors[0], RequestVoteReply.class);
234         assertEquals("isVoteGranted", false, reply.isVoteGranted());
235         assertEquals("getTerm", 2, reply.getTerm());
236     }
237
238     @Test
239     public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForMatches() {
240         MockRaftActorContext context = createActorContext();
241         context.getTermInformation().update(1000, null);
242
243         // Once a candidate is created it will immediately increment the current term so after
244         // construction the currentTerm should be 1001
245         candidate = new Candidate(context);
246
247         setupPeers(1);
248         candidate.handleMessage(peerActors[0], new RequestVote(1001, context.getId(), 10000, 999));
249
250         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
251                 peerActors[0], RequestVoteReply.class);
252         assertEquals("isVoteGranted", true, reply.isVoteGranted());
253         assertEquals("getTerm", 1001, reply.getTerm());
254     }
255
256     @Test
257     public void testHandleRequestVoteWhenSenderTermEqualToCurrentTermAndVotedForDoesNotMatch() {
258         MockRaftActorContext context = createActorContext();
259         context.getTermInformation().update(1000, null);
260
261         // Once a candidate is created it will immediately increment the current term so after
262         // construction the currentTerm should be 1001
263         candidate = new Candidate(context);
264
265         setupPeers(1);
266
267         // RequestVote candidate ID ("candidate2") does not match this candidate's votedFor
268         // (it votes for itself)
269         candidate.handleMessage(peerActors[0], new RequestVote(1001, "candidate2", 10000, 999));
270
271         RequestVoteReply reply = MessageCollectorActor.expectFirstMatching(
272                 peerActors[0], RequestVoteReply.class);
273         assertEquals("isVoteGranted", false, reply.isVoteGranted());
274         assertEquals("getTerm", 1001, reply.getTerm());
275     }
276
277     @Test
278     public void testCandidateSchedulesElectionTimeoutImmediatelyWhenItHasNoPeers(){
279         MockRaftActorContext context = createActorContext();
280
281         Stopwatch stopwatch = Stopwatch.createStarted();
282
283         candidate = createBehavior(context);
284
285         MessageCollectorActor.expectFirstMatching(candidateActor, ElectionTimeout.class);
286
287         long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
288
289         assertTrue(elapsed < context.getConfigParams().getElectionTimeOutInterval().toMillis());
290     }
291
292     @Test
293     @Override
294     public void testHandleAppendEntriesAddSameEntryToLog() throws Exception {
295         MockRaftActorContext context = createActorContext();
296
297         context.getTermInformation().update(2, "test");
298
299         // Prepare the receivers log
300         MockRaftActorContext.MockPayload payload = new MockRaftActorContext.MockPayload("zero");
301         setLastLogEntry(context, 2, 0, payload);
302
303         List<ReplicatedLogEntry> entries = new ArrayList<>();
304         entries.add(new MockRaftActorContext.MockReplicatedLogEntry(2, 0, payload));
305
306         AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 2, -1, (short)0);
307
308         behavior = createBehavior(context);
309
310         // Resetting the Candidates term to make sure it will match
311         // the term sent by AppendEntries. If this was not done then
312         // the test will fail because the Candidate will assume that
313         // the message was sent to it from a lower term peer and will
314         // thus respond with a failure
315         context.getTermInformation().update(2, "test");
316
317         // Send an unknown message so that the state of the RaftActor remains unchanged
318         RaftActorBehavior expected = behavior.handleMessage(candidateActor, "unknown");
319         assertTrue(expected instanceof Candidate);
320
321         RaftActorBehavior raftBehavior = behavior.handleMessage(candidateActor, appendEntries);
322
323         assertEquals("Raft state", RaftState.Follower, raftBehavior.state());
324
325         assertEquals("ReplicatedLog size", 1, context.getReplicatedLog().size());
326
327         handleAppendEntriesAddSameEntryToLogReply(candidateActor);
328     }
329
330     @Override
331     protected RaftActorBehavior createBehavior(RaftActorContext actorContext) {
332         return new Candidate(actorContext);
333     }
334
335     @Override protected MockRaftActorContext createActorContext() {
336         return new MockRaftActorContext("candidate", getSystem(), candidateActor);
337     }
338
339     @SuppressWarnings("unchecked")
340     private Map<String, String> setupPeers(int count) {
341         Map<String, String> peerMap = new HashMap<>();
342         peerActors = new TestActorRef[count];
343         for(int i = 0; i < count; i++) {
344             peerActors[i] = actorFactory.createTestActor(Props.create(MessageCollectorActor.class),
345                     actorFactory.generateActorId("peer"));
346             peerMap.put("peer" + (i+1), peerActors[i].path().toString());
347         }
348
349         return peerMap;
350     }
351
352     @Override
353     protected void assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(RaftActorContext actorContext,
354             ActorRef actorRef, RaftRPC rpc) throws Exception {
355         super.assertStateChangesToFollowerWhenRaftRPCHasNewerTerm(actorContext, actorRef, rpc);
356         assertEquals("New votedFor", null, actorContext.getTermInformation().getVotedFor());
357     }
358 }