1 package org.opendaylight.controller.cluster.raft;
3 import akka.actor.ActorRef;
4 import akka.actor.ActorSystem;
5 import akka.actor.Props;
6 import akka.event.Logging;
7 import akka.japi.Creator;
8 import akka.testkit.JavaTestKit;
9 import com.google.protobuf.ByteString;
10 import org.junit.Test;
11 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
12 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
14 import java.util.Collections;
17 import static junit.framework.TestCase.assertEquals;
19 public class RaftActorTest extends AbstractActorTest {
22 public static class MockRaftActor extends RaftActor {
24 public MockRaftActor(String id,
25 Map<String, String> peerAddresses) {
26 super(id, peerAddresses);
29 public static Props props(final String id, final Map<String, String> peerAddresses){
30 return Props.create(new Creator<MockRaftActor>(){
32 @Override public MockRaftActor create() throws Exception {
33 return new MockRaftActor(id, peerAddresses);
38 @Override protected void applyState(ActorRef clientActor,
43 @Override protected void createSnapshot() {
44 throw new UnsupportedOperationException("createSnapshot");
47 @Override protected void applySnapshot(ByteString snapshot) {
48 throw new UnsupportedOperationException("applySnapshot");
51 @Override protected void onStateChanged() {
54 @Override public String persistenceId() {
61 private static class RaftActorTestKit extends JavaTestKit {
62 private final ActorRef raftActor;
64 public RaftActorTestKit(ActorSystem actorSystem, String actorName) {
67 raftActor = this.getSystem()
68 .actorOf(MockRaftActor.props(actorName,
69 Collections.EMPTY_MAP), actorName);
74 public boolean waitForStartup(){
75 // Wait for a specific log message to show up
77 new JavaTestKit.EventFilter<Boolean>(Logging.Info.class
79 protected Boolean run() {
82 }.from(raftActor.path().toString())
83 .message("Switching from state Candidate to Leader")
84 .occurrences(1).exec();
89 public void findLeader(final String expectedLeader){
92 new Within(duration("1 seconds")) {
93 protected void run() {
95 raftActor.tell(new FindLeader(), getRef());
97 String s = new ExpectMsg<String>(duration("1 seconds"),
99 // do not put code outside this method, will run afterwards
100 protected String match(Object in) {
101 if (in instanceof FindLeaderReply) {
102 return ((FindLeaderReply) in).getLeaderActor();
107 }.get();// this extracts the received message
109 assertEquals(expectedLeader, s);
117 public ActorRef getRaftActor() {
125 public void testConstruction() {
126 boolean started = new RaftActorTestKit(getSystem(), "testConstruction").waitForStartup();
127 assertEquals(true, started);
131 public void testFindLeaderWhenLeaderIsSelf(){
132 RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader");
133 kit.waitForStartup();
134 kit.findLeader(kit.getRaftActor().path().toString());