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;
10 import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
11 import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
13 import java.util.Collections;
16 import static junit.framework.TestCase.assertEquals;
18 public class RaftActorTest extends AbstractActorTest {
21 public static class MockRaftActor extends RaftActor {
23 public MockRaftActor(String id,
24 Map<String, String> peerAddresses) {
25 super(id, peerAddresses);
28 public static Props props(final String id, final Map<String, String> peerAddresses){
29 return Props.create(new Creator<MockRaftActor>(){
31 @Override public MockRaftActor create() throws Exception {
32 return new MockRaftActor(id, peerAddresses);
37 @Override protected void applyState(ActorRef clientActor,
42 @Override protected Object createSnapshot() {
43 throw new UnsupportedOperationException("createSnapshot");
46 @Override protected void applySnapshot(Object snapshot) {
47 throw new UnsupportedOperationException("applySnapshot");
50 @Override protected void onStateChanged() {
53 @Override public String persistenceId() {
60 private static class RaftActorTestKit extends JavaTestKit {
61 private final ActorRef raftActor;
63 public RaftActorTestKit(ActorSystem actorSystem, String actorName) {
66 raftActor = this.getSystem()
67 .actorOf(MockRaftActor.props(actorName,
68 Collections.EMPTY_MAP), actorName);
73 public boolean waitForStartup(){
74 // Wait for a specific log message to show up
76 new JavaTestKit.EventFilter<Boolean>(Logging.Info.class
78 protected Boolean run() {
81 }.from(raftActor.path().toString())
82 .message("Switching from state Candidate to Leader")
83 .occurrences(1).exec();
88 public void findLeader(final String expectedLeader){
91 new Within(duration("1 seconds")) {
92 protected void run() {
94 raftActor.tell(new FindLeader(), getRef());
96 String s = new ExpectMsg<String>(duration("1 seconds"),
98 // do not put code outside this method, will run afterwards
99 protected String match(Object in) {
100 if (in instanceof FindLeaderReply) {
101 return ((FindLeaderReply) in).getLeaderActor();
106 }.get();// this extracts the received message
108 assertEquals(expectedLeader, s);
116 public ActorRef getRaftActor() {
124 public void testConstruction() {
125 boolean started = new RaftActorTestKit(getSystem(), "testConstruction").waitForStartup();
126 assertEquals(true, started);
130 public void testFindLeaderWhenLeaderIsSelf(){
131 RaftActorTestKit kit = new RaftActorTestKit(getSystem(), "testFindLeader");
132 kit.waitForStartup();
133 kit.findLeader(kit.getRaftActor().path().toString());