本文整理汇总了Java中akka.testkit.TestActorRef.underlyingActor方法的典型用法代码示例。如果您正苦于以下问题:Java TestActorRef.underlyingActor方法的具体用法?Java TestActorRef.underlyingActor怎么用?Java TestActorRef.underlyingActor使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类akka.testkit.TestActorRef
的用法示例。
在下文中一共展示了TestActorRef.underlyingActor方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testAddServerWithInstallSnapshotTimeout
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testAddServerWithInstallSnapshotTimeout() throws Exception {
LOG.info("testAddServerWithInstallSnapshotTimeout starting");
setupNewFollower();
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(1);
// Drop the InstallSnapshot message so it times out
newFollowerRaftActor.underlyingActor().setDropMessageOfType(InstallSnapshot.class);
leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
leaderActor.tell(new UnInitializedFollowerSnapshotReply("bogus"), leaderActor);
AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.TIMEOUT, addServerReply.getStatus());
assertEquals("Leader peers size", 0, leaderActorContext.getPeerIds().size());
assertEquals("Leader followers size", 0,
((AbstractLeader)leaderRaftActor.getCurrentBehavior()).getFollowerIds().size());
LOG.info("testAddServerWithInstallSnapshotTimeout ending");
}
示例2: verifyTrimmedLog
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
protected void verifyTrimmedLog(String name, TestActorRef<TestRaftActor> actorRef, long lastIndex,
long replicatedToAllIndex) {
TestRaftActor actor = actorRef.underlyingActor();
RaftActorContext context = actor.getRaftActorContext();
long snapshotIndex = lastIndex - 1;
assertEquals(name + " snapshot term", snapshotIndex < 0 ? -1 : currentTerm,
context.getReplicatedLog().getSnapshotTerm());
assertEquals(name + " snapshot index", snapshotIndex, context.getReplicatedLog().getSnapshotIndex());
assertEquals(name + " journal log size", 1, context.getReplicatedLog().size());
assertEquals(name + " journal last index", lastIndex, context.getReplicatedLog().lastIndex());
assertEquals(name + " commit index", lastIndex, context.getCommitIndex());
assertEquals(name + " last applied", lastIndex, context.getLastApplied());
assertEquals(name + " replicatedToAllIndex", replicatedToAllIndex,
actor.getCurrentBehavior().getReplicatedToAllIndex());
}
示例3: testInitialChangeListenerEventWhenNotInitiallyLeader
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testInitialChangeListenerEventWhenNotInitiallyLeader() throws Exception {
new ShardTestKit(getSystem()) {
{
final TestActorRef<Shard> actor = actorFactory.createTestActor(
newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
"testInitialChangeListenerEventWhenNotInitiallyLeader");
waitUntilLeader(actor);
final Shard shard = actor.underlyingActor();
mergeToStore(shard.getDataStore(), TEST_PATH,
testNodeWithOuter(outerNode(outerNodeEntry(1, innerNode("one", "two")),
outerNodeEntry(2, innerNode("three", "four")))));
final MockDataChangeListener listener = new MockDataChangeListener(0);
final YangInstanceIdentifier path = OUTER_LIST_PATH.node(OUTER_LIST_QNAME).node(INNER_LIST_QNAME)
.node(INNER_LIST_QNAME);
final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
"testInitialChangeListenerEventWhenNotInitiallyLeader-DataChangeListener");
final DataChangeListenerSupport support = new DataChangeListenerSupport(shard);
support.onMessage(new RegisterChangeListener(path, dclActor, DataChangeScope.ONE, false), false, true);
listener.expectNoMoreChanges("Unexpected initial change event");
listener.reset(1);
support.onLeadershipChange(true, true);
listener.waitForChangeEvents();
listener.verifyCreatedData(0, innerEntryPath(1, "one"));
listener.verifyCreatedData(0, innerEntryPath(1, "two"));
listener.verifyCreatedData(0, innerEntryPath(2, "three"));
listener.verifyCreatedData(0, innerEntryPath(2, "four"));
}
};
}
示例4: testUpdateElectionTermPersistedWithPersistenceDisabled
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testUpdateElectionTermPersistedWithPersistenceDisabled() throws Exception {
final JavaTestKit kit = new JavaTestKit(getSystem());
String persistenceId = factory.generateActorId("follower-");
DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
config.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
config.setElectionTimeoutFactor(1);
InMemoryJournal.addWriteMessagesCompleteLatch(persistenceId, 1);
TestActorRef<MockRaftActor> ref = factory.createTestActor(MockRaftActor.props(persistenceId,
ImmutableMap.<String, String>builder().put("member1", "address").build(),
config, createProvider())
.withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
InMemoryJournal.waitForWriteMessagesComplete(persistenceId);
List<UpdateElectionTerm> entries = InMemoryJournal.get(persistenceId, UpdateElectionTerm.class);
assertEquals("UpdateElectionTerm entries", 1, entries.size());
final UpdateElectionTerm updateEntry = entries.get(0);
factory.killActor(ref, kit);
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
ref = factory.createTestActor(MockRaftActor.props(persistenceId,
ImmutableMap.<String, String>builder().put("member1", "address").build(), config,
createProvider()).withDispatcher(Dispatchers.DefaultDispatcherId()),
factory.generateActorId("follower-"));
MockRaftActor actor = ref.underlyingActor();
actor.waitForRecoveryComplete();
RaftActorContext newContext = actor.getRaftActorContext();
assertEquals("electionTerm", updateEntry.getCurrentTerm(),
newContext.getTermInformation().getCurrentTerm());
assertEquals("votedFor", updateEntry.getVotedFor(), newContext.getTermInformation().getVotedFor());
entries = InMemoryJournal.get(persistenceId, UpdateElectionTerm.class);
assertEquals("UpdateElectionTerm entries", 1, entries.size());
}
示例5: testConfigCustomizations
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testConfigCustomizations() {
AkkaConfigurationReader reader = new TestConfigReader();
final int expectedCapacity = 100;
String timeOutVal = "10ms";
FiniteDuration expectedTimeout = FiniteDuration.create(10, TimeUnit.MILLISECONDS);
RemoteRpcProviderConfig config = new RemoteRpcProviderConfig.Builder("unit-test")
.metricCaptureEnabled(true)//enable metric capture
.mailboxCapacity(expectedCapacity)
.mailboxPushTimeout(timeOutVal)
.withConfigReader(reader)
.build();
Assert.assertTrue(config.isMetricCaptureEnabled());
Assert.assertEquals(expectedCapacity, config.getMailBoxCapacity().intValue());
Assert.assertEquals(expectedTimeout.toMillis(), config.getMailBoxPushTimeout().toMillis());
//Now check this config inside an actor
ActorSystem system = ActorSystem.create("unit-test", config.get());
TestActorRef<ConfigTestActor> configTestActorTestActorRef =
TestActorRef.create(system, Props.create(ConfigTestActor.class));
ConfigTestActor actor = configTestActorTestActorRef.underlyingActor();
Config actorConfig = actor.getConfig();
config = new RemoteRpcProviderConfig(actorConfig);
Assert.assertTrue(config.isMetricCaptureEnabled());
Assert.assertEquals(expectedCapacity, config.getMailBoxCapacity().intValue());
Assert.assertEquals(expectedTimeout.toMillis(), config.getMailBoxPushTimeout().toMillis());
}
示例6: testInitialChangeListenerEventWithListPath
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testInitialChangeListenerEventWithListPath() throws Exception {
new ShardTestKit(getSystem()) {
{
final TestActorRef<Shard> actor = actorFactory.createTestActor(
newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
"testInitialChangeListenerEventWithListPath");
waitUntilLeader(actor);
final Shard shard = actor.underlyingActor();
mergeToStore(shard.getDataStore(), TEST_PATH, testNodeWithOuter(1, 2));
final MockDataChangeListener listener = new MockDataChangeListener(1);
final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, OUTER_LIST_PATH),
"testInitialChangeListenerEventWithListPath-DataChangeListener");
final DataChangeListenerSupport support = new DataChangeListenerSupport(shard);
support.onMessage(new RegisterChangeListener(OUTER_LIST_PATH, dclActor, DataChangeScope.ONE, false),
true, true);
listener.waitForChangeEvents();
assertEquals("Outer entry 1 present", true, NormalizedNodes
.findNode(listener.getCreatedData(0, OUTER_LIST_PATH), outerEntryKey(1)).isPresent());
assertEquals("Outer entry 2 present", true, NormalizedNodes
.findNode(listener.getCreatedData(0, OUTER_LIST_PATH), outerEntryKey(2)).isPresent());
}
};
}
示例7: testOnRegisterCandidateLocalWithIsolatedLeader
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testOnRegisterCandidateLocalWithIsolatedLeader() throws Exception {
testLog.info("testOnRegisterCandidateLocalWithIsolatedLeader starting");
final ShardTestKit kit = new ShardTestKit(getSystem());
dataStoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(2)
.shardIsolatedLeaderCheckIntervalInMillis(50);
ShardIdentifier leaderId = newShardId(LOCAL_MEMBER_NAME);
ShardIdentifier peerId = newShardId(PEER_MEMBER_1_NAME);
TestActorRef<TestEntityOwnershipShard> peer = actorFactory.createTestActor(TestEntityOwnershipShard.props(
newShardBuilder(peerId, peerMap(leaderId.toString()), PEER_MEMBER_1_NAME)), peerId.toString());
TestEntityOwnershipShard peerShard = peer.underlyingActor();
peerShard.startDroppingMessagesOfType(ElectionTimeout.class);
TestActorRef<EntityOwnershipShard> leader = actorFactory.createTestActor(
newShardProps(leaderId, peerMap(peerId.toString()), LOCAL_MEMBER_NAME));
ShardTestKit.waitUntilLeader(leader);
// Drop AppendEntries and wait enough time for the shard to switch to IsolatedLeader.
peerShard.startDroppingMessagesOfType(AppendEntries.class);
verifyRaftState(leader, state ->
assertEquals("getRaftState", RaftState.IsolatedLeader.toString(), state.getRaftState()));
YangInstanceIdentifier entityId = ENTITY_ID1;
DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
leader.tell(new RegisterCandidateLocal(entity), kit.getRef());
kit.expectMsgClass(SuccessReply.class);
// Resume AppendEntries - the candidate write should now be committed.
peerShard.stopDroppingMessagesOfType(AppendEntries.class);
verifyCommittedEntityCandidate(leader, ENTITY_TYPE, entityId, LOCAL_MEMBER_NAME);
verifyOwner(leader, ENTITY_TYPE, entityId, LOCAL_MEMBER_NAME);
testLog.info("testOnRegisterCandidateLocalWithIsolatedLeader ending");
}
示例8: testInitialChangeListenerEventWithWildcardedListPath
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testInitialChangeListenerEventWithWildcardedListPath() throws Exception {
new ShardTestKit(getSystem()) {
{
final TestActorRef<Shard> actor = actorFactory.createTestActor(
newShardProps().withDispatcher(Dispatchers.DefaultDispatcherId()),
"testInitialChangeListenerEventWithWildcardedListPath");
waitUntilLeader(actor);
final Shard shard = actor.underlyingActor();
mergeToStore(shard.getDataStore(), TEST_PATH, testNodeWithOuter(1, 2));
writeToStore(shard.getDataStore(), OUTER_CONTAINER_PATH,
ImmutableNodes.containerNode(OUTER_CONTAINER_QNAME));
final MockDataChangeListener listener = new MockDataChangeListener(1);
final YangInstanceIdentifier path = OUTER_LIST_PATH.node(OUTER_LIST_QNAME);
final ActorRef dclActor = actorFactory.createActor(DataChangeListener.props(listener, path),
"testInitialChangeListenerEventWithWildcardedListPath-DataChangeListener");
final DataChangeListenerSupport support = new DataChangeListenerSupport(shard);
support.onMessage(new RegisterChangeListener(path, dclActor, DataChangeScope.ONE, false), true, true);
listener.waitForChangeEvents();
listener.verifyCreatedData(0, outerEntryPath(1));
listener.verifyCreatedData(0, outerEntryPath(2));
listener.verifyNoCreatedData(0, OUTER_CONTAINER_PATH);
}
};
}
示例9: testOnApplyState
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testOnApplyState() {
LOG.info("testOnApplyState starting");
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
RaftActorServerConfigurationSupport support = new RaftActorServerConfigurationSupport(
noLeaderActor.underlyingActor());
ReplicatedLogEntry serverConfigEntry = new SimpleReplicatedLogEntry(1, 1,
new ServerConfigurationPayload(Collections.<ServerInfo>emptyList()));
boolean handled = support.handleMessage(new ApplyState(null, null, serverConfigEntry), ActorRef.noSender());
assertEquals("Message handled", true, handled);
ReplicatedLogEntry nonServerConfigEntry = new SimpleReplicatedLogEntry(1, 1,
new MockRaftActorContext.MockPayload("1"));
handled = support.handleMessage(new ApplyState(null, null, nonServerConfigEntry), ActorRef.noSender());
assertEquals("Message handled", false, handled);
LOG.info("testOnApplyState ending");
}
示例10: testGetSnapshot
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testGetSnapshot() throws Exception {
LOG.info("testGetSnapshot starting");
JavaTestKit kit = new JavaTestKit(getSystem());
MockConfiguration mockConfig = new MockConfiguration(ImmutableMap.<String, List<String>>builder()
.put("shard1", Arrays.asList("member-1")).put("shard2", Arrays.asList("member-1"))
.put("astronauts", Collections.<String>emptyList()).build());
TestActorRef<TestShardManager> shardManager = actorFactory.createTestActor(newShardMgrProps(mockConfig)
.withDispatcher(Dispatchers.DefaultDispatcherId()));
shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
Failure failure = kit.expectMsgClass(Failure.class);
assertEquals("Failure cause type", IllegalStateException.class, failure.cause().getClass());
shardManager.tell(new UpdateSchemaContext(TestModel.createTestContext()), ActorRef.noSender());
waitForShardInitialized(shardManager, "shard1", kit);
waitForShardInitialized(shardManager, "shard2", kit);
shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
DatastoreSnapshot datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");
assertEquals("getType", shardMrgIDSuffix, datastoreSnapshot.getType());
assertNull("Expected null ShardManagerSnapshot", datastoreSnapshot.getShardManagerSnapshot());
Function<ShardSnapshot, String> shardNameTransformer = ShardSnapshot::getName;
assertEquals("Shard names", Sets.newHashSet("shard1", "shard2"), Sets.newHashSet(
Lists.transform(datastoreSnapshot.getShardSnapshots(), shardNameTransformer)));
// Add a new replica
JavaTestKit mockShardLeaderKit = new JavaTestKit(getSystem());
TestShardManager shardManagerInstance = shardManager.underlyingActor();
shardManagerInstance.setMessageInterceptor(newFindPrimaryInterceptor(mockShardLeaderKit.getRef()));
shardManager.tell(new AddShardReplica("astronauts"), kit.getRef());
mockShardLeaderKit.expectMsgClass(AddServer.class);
mockShardLeaderKit.reply(new AddServerReply(ServerChangeStatus.OK, ""));
kit.expectMsgClass(Status.Success.class);
waitForShardInitialized(shardManager, "astronauts", kit);
// Send another GetSnapshot and verify
shardManager.tell(GetSnapshot.INSTANCE, kit.getRef());
datastoreSnapshot = expectMsgClassOrFailure(DatastoreSnapshot.class, kit, "GetSnapshot");
assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"), Sets.newHashSet(
Lists.transform(datastoreSnapshot.getShardSnapshots(), shardNameTransformer)));
ShardManagerSnapshot snapshot = datastoreSnapshot.getShardManagerSnapshot();
assertNotNull("Expected ShardManagerSnapshot", snapshot);
assertEquals("Shard names", Sets.newHashSet("shard1", "shard2", "astronauts"),
Sets.newHashSet(snapshot.getShardList()));
LOG.info("testGetSnapshot ending");
}
示例11: testRaftActorForwardsToRaftActorRecoverySupport
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testRaftActorForwardsToRaftActorRecoverySupport() {
String persistenceId = factory.generateActorId("leader-");
DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
Collections.<String, String>emptyMap(), config), persistenceId);
MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
// Wait for akka's recovery to complete so it doesn't interfere.
mockRaftActor.waitForRecoveryComplete();
RaftActorRecoverySupport mockSupport = mock(RaftActorRecoverySupport.class);
mockRaftActor.setRaftActorRecoverySupport(mockSupport);
Snapshot snapshot = Snapshot.create(ByteState.of(new byte[]{1}),
Collections.<ReplicatedLogEntry>emptyList(), 3, 1, 3, 1, -1, null, null);
SnapshotOffer snapshotOffer = new SnapshotOffer(new SnapshotMetadata("test", 6, 12345), snapshot);
mockRaftActor.handleRecover(snapshotOffer);
ReplicatedLogEntry logEntry = new SimpleReplicatedLogEntry(1, 1, new MockRaftActorContext.MockPayload("1", 5));
mockRaftActor.handleRecover(logEntry);
ApplyJournalEntries applyJournalEntries = new ApplyJournalEntries(2);
mockRaftActor.handleRecover(applyJournalEntries);
DeleteEntries deleteEntries = new DeleteEntries(1);
mockRaftActor.handleRecover(deleteEntries);
UpdateElectionTerm updateElectionTerm = new UpdateElectionTerm(5, "member2");
mockRaftActor.handleRecover(updateElectionTerm);
verify(mockSupport).handleRecoveryMessage(same(snapshotOffer), any(PersistentDataProvider.class));
verify(mockSupport).handleRecoveryMessage(same(logEntry), any(PersistentDataProvider.class));
verify(mockSupport).handleRecoveryMessage(same(applyJournalEntries), any(PersistentDataProvider.class));
verify(mockSupport).handleRecoveryMessage(same(deleteEntries), any(PersistentDataProvider.class));
verify(mockSupport).handleRecoveryMessage(same(updateElectionTerm), any(PersistentDataProvider.class));
}
示例12: testChangeToVotingWithNoLeaderAndOtherLeaderElected
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testChangeToVotingWithNoLeaderAndOtherLeaderElected() {
LOG.info("testChangeToVotingWithNoLeaderAndOtherLeaderElected starting");
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
configParams.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
configParams.setElectionTimeoutFactor(100000);
final String node1ID = "node1";
final String node2ID = "node2";
configParams.setPeerAddressResolver(peerId -> peerId.equals(node1ID)
? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
? actorFactory.createTestActorPath(node2ID) : null);
ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
new ServerInfo(node1ID, false), new ServerInfo(node2ID, true)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, 1, persistedServerConfig);
InMemoryJournal.addEntry(node1ID, 1, new UpdateElectionTerm(1, "node1"));
InMemoryJournal.addEntry(node1ID, 2, persistedServerConfigEntry);
InMemoryJournal.addEntry(node2ID, 1, new UpdateElectionTerm(1, "node1"));
InMemoryJournal.addEntry(node2ID, 2, persistedServerConfigEntry);
ActorRef node1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
ActorRef node2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
// Send a ChangeServersVotingStatus message to node1 to change node1 to voting. This should cause
// node1 to try to elect itself as leader in order to apply the new server config. But we'll drop
// RequestVote messages in node2 and make it the leader so node1 should forward the server change
// request to node2 when node2 is elected.
node2RaftActor.setDropMessageOfType(RequestVote.class);
ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true,
node2ID, true));
node1RaftActorRef.tell(changeServers, testKit.getRef());
MessageCollectorActor.expectFirstMatching(node2Collector, RequestVote.class);
node2RaftActorRef.tell(TimeoutNow.INSTANCE, ActorRef.noSender());
ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
MessageCollectorActor.expectFirstMatching(node1Collector, ApplyJournalEntries.class);
verifyServerConfigurationPayloadEntry(node1RaftActor.getRaftActorContext().getReplicatedLog(),
votingServer(node1ID), votingServer(node2ID));
assertEquals("isVotingMember", true, node1RaftActor.getRaftActorContext().isVotingMember());
assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
MessageCollectorActor.expectFirstMatching(node2Collector, ApplyJournalEntries.class);
verifyServerConfigurationPayloadEntry(node2RaftActor.getRaftActorContext().getReplicatedLog(),
votingServer(node1ID), votingServer(node2ID));
assertEquals("getRaftState", RaftState.Leader, node2RaftActor.getRaftState());
LOG.info("testChangeToVotingWithNoLeaderAndOtherLeaderElected ending");
}
示例13: testApplyJournalEntriesCallsDataPersistence
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testApplyJournalEntriesCallsDataPersistence() throws Exception {
String persistenceId = factory.generateActorId("leader-");
DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId);
MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
mockRaftActor.waitForInitializeBehaviorComplete();
mockRaftActor.waitUntilLeader();
mockRaftActor.onReceiveCommand(new ApplyJournalEntries(10));
verify(dataPersistenceProvider).persistAsync(any(ApplyJournalEntries.class), any(Procedure.class));
}
示例14: testAddServerWithOperationInProgress
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testAddServerWithOperationInProgress() throws Exception {
LOG.info("testAddServerWithOperationInProgress starting");
setupNewFollower();
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
final RaftActorContext leaderActorContext = leaderRaftActor.getRaftActorContext();
final ActorRef leaderCollectorActor = newLeaderCollectorActor(leaderRaftActor);
RaftActorContext follower2ActorContext = newFollowerContext(NEW_SERVER_ID2, followerActor);
Follower newFollower2 = new Follower(follower2ActorContext);
followerActor.underlyingActor().setBehavior(newFollower2);
MockNewFollowerRaftActor newFollowerRaftActorInstance = newFollowerRaftActor.underlyingActor();
newFollowerRaftActorInstance.setDropMessageOfType(InstallSnapshot.class);
leaderActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true), testKit.getRef());
// Wait for leader's install snapshot and capture it
InstallSnapshot installSnapshot = expectFirstMatching(newFollowerCollectorActor, InstallSnapshot.class);
// Send a second AddServer - should get queued
JavaTestKit testKit2 = new JavaTestKit(getSystem());
leaderActor.tell(new AddServer(NEW_SERVER_ID2, followerActor.path().toString(), false), testKit2.getRef());
// Continue the first AddServer
newFollowerRaftActorInstance.setDropMessageOfType(null);
newFollowerRaftActor.tell(installSnapshot, leaderActor);
// Verify both complete successfully
AddServerReply addServerReply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
addServerReply = testKit2.expectMsgClass(JavaTestKit.duration("5 seconds"), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
// Verify ServerConfigurationPayload entries in leader's log
expectMatching(leaderCollectorActor, ApplyState.class, 2);
assertEquals("Leader journal last index", 1, leaderActorContext.getReplicatedLog().lastIndex());
assertEquals("Leader commit index", 1, leaderActorContext.getCommitIndex());
assertEquals("Leader last applied index", 1, leaderActorContext.getLastApplied());
verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(),
votingServer(LEADER_ID), votingServer(NEW_SERVER_ID), nonVotingServer(NEW_SERVER_ID2));
// Verify ServerConfigurationPayload entry in the new follower
expectMatching(newFollowerCollectorActor, ApplyState.class, 2);
assertEquals("New follower peers", Sets.newHashSet(LEADER_ID, NEW_SERVER_ID2),
newFollowerActorContext.getPeerIds());
LOG.info("testAddServerWithOperationInProgress ending");
}
示例15: testChangeToVotingWithNoLeaderAndElectionTimeout
import akka.testkit.TestActorRef; //导入方法依赖的package包/类
@Test
public void testChangeToVotingWithNoLeaderAndElectionTimeout() {
LOG.info("testChangeToVotingWithNoLeaderAndElectionTimeout starting");
final String node1ID = "node1";
final String node2ID = "node2";
final PeerAddressResolver peerAddressResolver = peerId -> peerId.equals(node1ID)
? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
? actorFactory.createTestActorPath(node2ID) : null;
ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
new ServerInfo(node1ID, false), new ServerInfo(node2ID, true)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, 1, persistedServerConfig);
InMemoryJournal.addEntry(node1ID, 1, new UpdateElectionTerm(1, "node1"));
InMemoryJournal.addEntry(node1ID, 2, persistedServerConfigEntry);
InMemoryJournal.addEntry(node2ID, 1, new UpdateElectionTerm(1, "node1"));
InMemoryJournal.addEntry(node2ID, 2, persistedServerConfigEntry);
DefaultConfigParamsImpl configParams1 = new DefaultConfigParamsImpl();
configParams1.setHeartBeatInterval(new FiniteDuration(100, TimeUnit.MILLISECONDS));
configParams1.setElectionTimeoutFactor(1);
configParams1.setPeerAddressResolver(peerAddressResolver);
ActorRef node1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams1,
PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
DefaultConfigParamsImpl configParams2 = new DefaultConfigParamsImpl();
configParams2.setElectionTimeoutFactor(1000000);
configParams2.setPeerAddressResolver(peerAddressResolver);
ActorRef node2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams2,
PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
// Send a ChangeServersVotingStatus message to node1 to change mode1 to voting. This should cause
// node1 to try to elect itself as leader in order to apply the new server config. But we'll drop
// RequestVote messages in node2 which should cause node1 to time out and revert back to the previous
// server config and fail with NO_LEADER. Note that node1 shouldn't forward the request to node2 b/c
// node2 was previously voting.
node2RaftActor.setDropMessageOfType(RequestVote.class);
ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true));
node1RaftActorRef.tell(changeServers, testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(JavaTestKit.duration("5 seconds"), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.NO_LEADER, reply.getStatus());
assertEquals("Server config", Sets.newHashSet(nonVotingServer(node1ID), votingServer(node2ID)),
Sets.newHashSet(node1RaftActor.getRaftActorContext().getPeerServerInfo(true).getServerConfig()));
assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
LOG.info("testChangeToVotingWithNoLeaderAndElectionTimeout ending");
}