akka.testkit.TestProbe Java Examples

The following examples show how to use akka.testkit.TestProbe. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RetrieveConnectionLogsAggregatorActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void withTimeoutWithMessages() {
    new TestKit(actorSystem) {{
        final TestProbe sender = TestProbe.apply(actorSystem);
        final Duration aggregatorTimeout = Duration.ofSeconds(5);
        final FiniteDuration expectMessageTimeout =
                FiniteDuration.apply(aggregatorTimeout.getSeconds() + 1, TimeUnit.SECONDS);

        // create connection with more clients than responses
        final Connection connection = createConnectionWithClients(2);

        final ActorRef underTest = childActorOf(
                RetrieveConnectionLogsAggregatorActor.props(connection, sender.ref(), DITTO_HEADERS,
                        aggregatorTimeout, LOGGER_CONFIG.maxLogSizeInBytes()));

        // only send one response
        final RetrieveConnectionLogsResponse expectedResponse =
                createRetrieveConnectionLogsResponse(connection.getId(), Instant.now().minusSeconds(123),
                        Instant.now().plusSeconds(444));

        underTest.tell(expectedResponse, getRef());

        // expect that known response will be sent, ignoring missing responses
        sender.expectMsg(expectMessageTimeout, expectedResponse);
    }};
}
 
Example #2
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConnectionHandling() {
    new TestKit(actorSystem) {{
        final TestProbe aggregator = new TestProbe(actorSystem);

        final Props props =
                AmqpClientActor.propsForTests(connection, getRef(), getRef(),
                        (connection1, exceptionListener) -> mockConnection);
        final ActorRef amqpClientActor = actorSystem.actorOf(props);
        watch(amqpClientActor);

        amqpClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
        expectMsg(CONNECTED_SUCCESS);

        amqpClientActor.tell(RetrieveConnectionStatus.of(CONNECTION_ID, DittoHeaders.empty()), aggregator.ref());
        aggregator.expectMsgClass(ResourceStatus.class);

        amqpClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
        expectMsg(DISCONNECTED_SUCCESS);

        amqpClientActor.tell(RetrieveConnectionStatus.of(CONNECTION_ID, DittoHeaders.empty()), aggregator.ref());
        aggregator.expectMsgClass(ResourceStatus.class);
    }};
}
 
Example #3
Source File: AkkademyDbTest.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
@Test
public void itShouldPlaceKeyValuesFromListOfSetMessageIntoMap() {
    TestProbe testProbe = TestProbe.apply(system);
    TestActorRef<AkkademyDb> actorRef = TestActorRef.create(system, Props.create(AkkademyDb.class));
    AkkademyDb akkademyDb = actorRef.underlyingActor();

    List list = Arrays.asList(
            new SetRequest("key2", "value2", testProbe.ref()),
            new SetRequest("key3", "value3", testProbe.ref()));
    actorRef.tell(list, ActorRef.noSender());

    assertEquals(akkademyDb.map.get("key2"), "value2");
    assertEquals(akkademyDb.map.get("key3"), "value3");

    testProbe.expectMsg(new Status.Success("key2"));
    testProbe.expectMsg(new Status.Success("key3"));
}
 
Example #4
Source File: KafkaClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testConnect() {
    new TestKit(actorSystem) {{
        final TestProbe probe = new TestProbe(getSystem());
        final Props props = getKafkaClientActorProps(probe.ref(), connection);
        final ActorRef kafkaClientActor = actorSystem.actorOf(props);

        kafkaClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), getRef());
        expectMsg(CONNECTED_SUCCESS);

        kafkaClientActor.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), getRef());
        expectMsg(DISCONNECTED_SUCCESS);

        expectPublisherReceivedShutdownSignal(probe);
    }};
}
 
Example #5
Source File: MessageAggregatorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void aggregateMessagesAndStopSelf() {
    new TestKit(actorSystem) {{
        final TestProbe initialReceiver = TestProbe.apply(actorSystem);

        final ActorRef underTest =
                actorSystem.actorOf(MessageAggregator.props(initialReceiver.ref(), Integer.class, 3, ONE_DAY));

        watch(underTest);

        underTest.tell(true, getRef());
        underTest.tell(0, getRef());
        underTest.tell(1, getRef());
        underTest.tell(2, getRef());
        initialReceiver.expectMsg(true);
        expectMsg(Arrays.asList(0, 1, 2));
        expectTerminated(underTest);
    }};
}
 
Example #6
Source File: PubSubFactoryTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void watchForLocalActorTermination() {
    new TestKit(system2) {{
        final DistributedPub<String> pub = factory1.startDistributedPub();
        final DistributedSub sub = factory2.startDistributedSub();
        final TestProbe publisher = TestProbe.apply(system1);
        final TestProbe subscriber = TestProbe.apply(system2);
        watch(subscriber.ref());

        // GIVEN: a pub-sub channel is set up
        sub.subscribeWithAck(singleton("hello"), subscriber.ref()).toCompletableFuture().join();
        pub.publish("hello", publisher.ref());
        subscriber.expectMsg("hello");

        // WHEN: subscriber terminates
        system2.stop(subscriber.ref());
        expectMsgClass(Terminated.class);

        // THEN: the subscriber is removed
        Awaitility.await().untilAsserted(() ->
                assertThat(factory1.getSubscribers("hello").toCompletableFuture().join())
                        .describedAs("subscriber should be removed from ddata after termination")
                        .isEmpty()
        );
    }};
}
 
Example #7
Source File: JmsConnectionHandlingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void handleJmsDisconnect() throws JMSException {
    new TestKit(actorSystem) {{

        final Props props = JMSConnectionHandlingActor.props(connection, e -> {}, jmsConnectionFactory);
        final ActorRef connectionHandlingActor = watch(actorSystem.actorOf(props));

        final TestProbe origin = TestProbe.apply(actorSystem);

        connectionHandlingActor.tell(new AmqpClientActor.JmsDisconnect(origin.ref(), mockConnection), getRef());

        final ClientDisconnected disconnected = expectMsgClass(ClientDisconnected.class);
        assertThat(disconnected.getOrigin()).contains(origin.ref());

        verify(mockConnection).close();
    }};
}
 
Example #8
Source File: JmsConnectionHandlingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void handleRecoverSession() throws JMSException {
    new TestKit(actorSystem) {{

        final Props props = JMSConnectionHandlingActor.props(connection, e -> {}, jmsConnectionFactory);
        final ActorRef connectionHandlingActor = watch(actorSystem.actorOf(props));

        final TestProbe origin = TestProbe.apply(actorSystem);

        final JmsSession existingSession = Mockito.mock(JmsSession.class);
        connectionHandlingActor.tell(new AmqpClientActor.JmsRecoverSession(origin.ref(), mockConnection, existingSession),
                getRef());

        final AmqpClientActor.JmsSessionRecovered recovered = expectMsgClass(AmqpClientActor.JmsSessionRecovered.class);
        assertThat(recovered.getOrigin()).contains(origin.ref());
        assertThat(recovered.getSession()).isSameAs(mockSession);

        verify(existingSession).close();
        verify(mockConnection).createSession(Session.CLIENT_ACKNOWLEDGE);
        verify(mockSession, times(connection.getSources()
                .stream()
                .mapToInt(s -> s.getAddresses().size() * s.getConsumerCount())
                .sum())).createConsumer(any());
    }};
}
 
Example #9
Source File: JmsConnectionHandlingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void handleFailureWhenCreatingConsumers() throws JMSException {
    new TestKit(actorSystem) {{

        final IllegalStateException exception = new IllegalStateException("failureOnCreateConsumer");
        doThrow(exception).when(mockSession).createConsumer(any());

        final Props props = JMSConnectionHandlingActor.props(connection, e -> {}, jmsConnectionFactory);
        final ActorRef connectionHandlingActor = watch(actorSystem.actorOf(props));

        final TestProbe origin = TestProbe.apply(actorSystem);

        connectionHandlingActor.tell(new AmqpClientActor.JmsConnect(origin.ref()), getRef());

        final ConnectionFailure connectionFailure1 = expectMsgClass(ConnectionFailure.class);
        assertThat(connectionFailure1.getOrigin()).contains(origin.ref());
        assertThat(connectionFailure1.getFailure().cause()).isSameAs(exception);
    }};
}
 
Example #10
Source File: JmsConnectionHandlingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void handleFailureOnJmsConnect() throws JMSException {
    new TestKit(actorSystem) {{

        final IllegalStateException exception = new IllegalStateException("failureOnJmsConnect");
        doThrow(exception).when(mockConnection).start();

        final Props props = JMSConnectionHandlingActor.props(connection, e -> {}, jmsConnectionFactory);
        final ActorRef connectionHandlingActor = watch(actorSystem.actorOf(props));

        final TestProbe origin = TestProbe.apply(actorSystem);

        connectionHandlingActor.tell(new AmqpClientActor.JmsConnect(origin.ref()), getRef());

        final ConnectionFailure connectionFailure1 = expectMsgClass(ConnectionFailure.class);
        assertThat(connectionFailure1.getOrigin()).contains(origin.ref());
        assertThat(connectionFailure1.getFailure().cause()).isSameAs(exception);
    }};
}
 
Example #11
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testResetConnectionMetrics() {
    new TestKit(actorSystem) {{
        final TestProbe probe = TestProbe.apply(actorSystem);
        final ActorRef underTest =
                TestConstants.createConnectionSupervisorActor(connectionId, actorSystem, pubSubMediator,
                        conciergeForwarder,
                        (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()));
        watch(underTest);

        // create connection
        underTest.tell(createConnection, getRef());
        probe.expectMsg(openConnection);
        expectMsg(createConnectionResponse);

        // reset metrics
        underTest.tell(resetConnectionMetrics, getRef());
        probe.expectMsg(resetConnectionMetrics);

        final ResetConnectionMetricsResponse resetResponse =
                ResetConnectionMetricsResponse.of(connectionId, DittoHeaders.empty());
        expectMsg(resetResponse);
    }};
}
 
Example #12
Source File: ReconnectActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRecoverConnectionsIsNotStartedTwice() {
    new TestKit(actorSystem) {{
        final TestProbe probe = new TestProbe(actorSystem);
        final Props props = ReconnectActor.props(probe.ref(),
                () -> Source.from(Arrays.asList(
                        ConnectionPersistenceActor.PERSISTENCE_ID_PREFIX + "connection-1",
                        ConnectionPersistenceActor.PERSISTENCE_ID_PREFIX + "connection-2",
                        ConnectionPersistenceActor.PERSISTENCE_ID_PREFIX + "connection-3")));

        final ActorRef reconnectActor = actorSystem.actorOf(props);
        reconnectActor.tell(ReconnectActor.ReconnectMessages.START_RECONNECT, getRef());

        probe.expectMsgClass(RetrieveConnectionStatus.class);
        probe.expectMsgClass(RetrieveConnectionStatus.class);
        probe.expectMsgClass(RetrieveConnectionStatus.class);
        probe.expectNoMessage();
    }};
}
 
Example #13
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void createConnectionAfterDeleted() {
    new TestKit(actorSystem) {{
        final TestProbe clientActorMock = TestProbe.apply(actorSystem);
        final ActorRef underTest =
                TestConstants.createConnectionSupervisorActor(connectionId, actorSystem, pubSubMediator,
                        conciergeForwarder,
                        (connection, concierge, connectionActor) -> MockClientActor.props(clientActorMock.ref()));
        watch(underTest);

        // create connection
        underTest.tell(createConnection, getRef());
        clientActorMock.expectMsg(openConnection);
        expectMsg(createConnectionResponse);

        // delete connection
        underTest.tell(deleteConnection, getRef());
        expectMsg(deleteConnectionResponse);

        // create connection again (while ConnectionActor is in deleted state)
        underTest.tell(createConnection, getRef());
        expectMsg(createConnectionResponse);
        clientActorMock.expectMsg(openConnection);
    }};
}
 
Example #14
Source File: RetrieveConnectionLogsAggregatorActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void withMultipleClients() {
    new TestKit(actorSystem) {{
        final TestProbe sender = TestProbe.apply(actorSystem);
        final Connection connection = createConnectionWithClients(3);

        final Instant since = Instant.now().minusSeconds(333);
        final Instant until = Instant.now().plusSeconds(555);
        final Collection<RetrieveConnectionLogsResponse> responses = Arrays.asList(
                createRetrieveConnectionLogsResponse(connection.getId(), since, until),
                createRetrieveConnectionLogsResponse(connection.getId(), since, until),
                createRetrieveConnectionLogsResponse(connection.getId(), since, until)
        );
        final RetrieveConnectionLogsResponse expectedResponse = createExpectedResponse(responses);

        final ActorRef underTest = childActorOf(
                RetrieveConnectionLogsAggregatorActor.props(connection, sender.ref(), DITTO_HEADERS,
                        DEFAULT_TIMEOUT, LOGGER_CONFIG.maxLogSizeInBytes()));

        responses.forEach(response -> underTest.tell(response, getRef()));

        sender.expectMsg(expectedResponse);
    }};
}
 
Example #15
Source File: BaseAkkaTestCase.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
public ActorRef expectActor(JavaTestKit kit, String path) {
    final ActorRef[] actor = {null};
    kit.new AwaitCond(kit.duration("3 seconds"), kit.duration("150 millis"), "No actor found with " + path) {
        @Override
        protected boolean cond() {
            TestProbe probe = new TestProbe(system);
            system.actorSelection(path).tell(new akka.actor.Identify(101), probe.ref());
            ActorIdentity i = probe.expectMsgClass(kit.duration("100 millis"), ActorIdentity.class);
            actor[0] = i.getRef();
            return i.getRef() != null;
        }
    };
    return actor[0];
}
 
Example #16
Source File: BaseAkkaTestCase.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
public ActorRef expectActor(JavaTestKit kit, String path) {
    final ActorRef[] actor = {null};
    kit.new AwaitCond(kit.duration("3 seconds"), kit.duration("150 millis"), "No actor found with " + path) {
        @Override
        protected boolean cond() {
            TestProbe probe = new TestProbe(system);
            system.actorSelection(path).tell(new akka.actor.Identify(101), probe.ref());
            ActorIdentity i = probe.expectMsgClass(kit.duration("100 millis"), ActorIdentity.class);
            actor[0] = i.getRef();
            return i.getRef() != null;
        }
    };
    return actor[0];
}
 
Example #17
Source File: AkkaPersistence.java    From ts-reaktive with MIT License 5 votes vote down vote up
public void awaitPersistenceInit() {
    AtomicInteger n = new AtomicInteger();
    TestProbe probe = TestProbe.apply(system);
    within(45, TimeUnit.SECONDS).eventuallyDo(() -> {
        system.actorOf(Props.create(AwaitPersistenceInit.class), "persistenceInit" + n.incrementAndGet()).tell("hello", probe.ref());
        probe.expectMsg(FiniteDuration.create(5, TimeUnit.SECONDS), "hello");            
    });
}
 
Example #18
Source File: BaseClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void handlesOpenConnectionInConnectingState() {
    new TestKit(actorSystem) {{
        final ConnectionId randomConnectionId = TestConstants.createRandomConnectionId();
        final Connection connection =
                TestConstants.createConnection(randomConnectionId, new Target[0]);
        final Props props = DummyClientActor.props(connection, getRef(), getRef(), getRef(), delegate);

        final ActorRef dummyClientActor = watch(actorSystem.actorOf(props));

        final TestProbe probe1 = TestProbe.apply(actorSystem);
        final TestProbe probe2 = TestProbe.apply(actorSystem);

        whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
                probe1.ref());
        thenExpectConnectClientCalled();

        // send another OpenConnection command while connecting
        whenOpeningConnection(dummyClientActor, OpenConnection.of(randomConnectionId, DittoHeaders.empty()),
                probe2.ref());

        andConnectionSuccessful(dummyClientActor, probe1.ref());

        // both recipients get responses
        probe1.expectMsg(CONNECTED_STATUS);
        probe2.expectMsg(CONNECTED_STATUS);
    }};
}
 
Example #19
Source File: AbstractMqttClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testRetrieveConnectionMetrics() {
    new TestKit(actorSystem) {{
        final Source mqttSource = ConnectivityModelFactory.newSourceBuilder()
                .authorizationContext(AUTHORIZATION_CONTEXT)
                .index(2)
                .consumerCount(1)
                .address("topic1")
                .address("topic2")
                .qos(1)
                .build();

        final Connection connectionWithAdditionalSources = connection.toBuilder()
                .sources(singletonList(mqttSource)).build();
        final String modifyThing = TestConstants.modifyThing();

        final Props props = createClientActorWithMessages(connectionWithAdditionalSources, getRef(),
                singletonList(mqttMessage(SOURCE_ADDRESS, modifyThing)));
        final ActorRef underTest = actorSystem.actorOf(props);

        final TestProbe controlProbe = TestProbe.apply(actorSystem);
        underTest.tell(OpenConnection.of(connection.getId(), DittoHeaders.empty()), controlProbe.ref());
        LOGGER.info("Waiting for connected...");
        controlProbe.expectMsg(CONNECTED_SUCCESS);

        expectMsgClass(ModifyThing.class);

        underTest.tell(RetrieveConnectionMetrics.of(connectionId, DittoHeaders.empty()), getRef());

        final RetrieveConnectionMetricsResponse metricsResponse =
                expectMsgClass(RetrieveConnectionMetricsResponse.class);

        LOGGER.info("metrics: {}", metricsResponse);
    }};
}
 
Example #20
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void retrieveMetricsInClosedStateDoesNotStartClientActor() {
    new TestKit(actorSystem) {{
        final TestProbe probe = TestProbe.apply(actorSystem);
        final ActorRef underTest =
                TestConstants.createConnectionSupervisorActor(connectionId, actorSystem, pubSubMediator,
                        conciergeForwarder,
                        (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()));
        watch(underTest);

        // create connection
        underTest.tell(createClosedConnection, getRef());
        expectMsg(createClosedConnectionResponse);
        probe.expectNoMessage();

        // retrieve metrics
        underTest.tell(RetrieveConnectionMetrics.of(connectionId, DittoHeaders.empty()), getRef());
        probe.expectNoMessage();

        final RetrieveConnectionMetricsResponse metricsResponse =
                RetrieveConnectionMetricsResponse.getBuilder(connectionId, DittoHeaders.empty())
                        .connectionMetrics(ConnectivityModelFactory.emptyConnectionMetrics())
                        .sourceMetrics(ConnectivityModelFactory.emptySourceMetrics())
                        .targetMetrics(ConnectivityModelFactory.emptyTargetMetrics())
                        .build();
        expectMsg(metricsResponse);
    }};
}
 
Example #21
Source File: BaseAkkaTestCase.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
public ActorRef expectActor(JavaTestKit kit, String path) {
    final ActorRef[] actor = {null};
    kit.new AwaitCond(kit.duration("3 seconds"), kit.duration("150 millis"), "No actor found with " + path) {
        @Override
        protected boolean cond() {
            TestProbe probe = new TestProbe(system);
            system.actorSelection(path).tell(new akka.actor.Identify(101), probe.ref());
            ActorIdentity i = probe.expectMsgClass(kit.duration("100 millis"), ActorIdentity.class);
            actor[0] = i.getRef();
            return i.getRef() != null;
        }
    };
    return actor[0];
}
 
Example #22
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@SafeVarargs
private void sendCommandWithEnabledBlacklist(
        final Map.Entry<ConnectivityCommand<?>, Consumer<Object>>... commands) {
    final Config configWithBlacklist =
            TestConstants.CONFIG.withValue("ditto.connectivity.connection.blacklisted-hostnames",
                    ConfigValueFactory.fromAnyRef("127.0.0.1"));
    final ActorSystem systemWithBlacklist = ActorSystem.create(getClass().getSimpleName() + "WithBlacklist",
            configWithBlacklist);
    final ActorRef pubSubMediator = DistributedPubSub.get(systemWithBlacklist).mediator();
    final ActorRef conciergeForwarder =
            systemWithBlacklist.actorOf(TestConstants.ConciergeForwarderActorMock.props());

    try {
        new TestKit(systemWithBlacklist) {{
            final TestProbe probe = TestProbe.apply(systemWithBlacklist);
            final ActorRef underTest =
                    TestConstants.createConnectionSupervisorActor(connectionId, systemWithBlacklist,
                            pubSubMediator,
                            conciergeForwarder,
                            (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()));
            watch(underTest);

            for (final Map.Entry<ConnectivityCommand<?>, Consumer<Object>> command : commands) {
                underTest.tell(command.getKey(), getRef());
                command.getValue().accept(expectMsgClass(Duration.ofSeconds(10), Object.class));
            }

            // assert that client actor is not called for closed connection
            probe.expectNoMessage();
        }};
    } finally {
        TestKit.shutdownActorSystem(systemWithBlacklist);
    }
}
 
Example #23
Source File: DataGeneratorWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void testExceptionForInvalidDocumentTypeMessage() {
	final Props props = Props.create(DataGeneratorWorkerActor.class,
			sampleDataGeneratorService);
	final TestActorRef<DataGeneratorWorkerActor> ref = TestActorRef.create(
			system, props);

	ElasticSearchIndexConfig config = ElasticSearchIndexConfig.COM_WEBSITE;

	// invalid document type
	IndexDocumentType documentType = null;
	String indexName = "trialindexName";
	IndexDocumentTypeMessageVO indexDocumentTypeMessageVO = new IndexDocumentTypeMessageVO()
			.config(config).documentType(documentType)
			.newIndexName(indexName);

	replay(sampleDataGeneratorService);

	TestProbe testProbe = TestProbe.apply(system);
	ref.tell(indexDocumentTypeMessageVO, testProbe.ref());
	verify(sampleDataGeneratorService);

	testProbe.expectMsgClass(DocumentTypeDataGenerationException.class);
	TestActor.Message message = testProbe.lastMessage();
	DocumentTypeDataGenerationException resultMsg = (DocumentTypeDataGenerationException) message
			.msg();
	assertEquals(documentType, resultMsg.getIndexDocumentType());
}
 
Example #24
Source File: HiveMqtt5PublisherActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void setupMocks(final TestProbe probe) {
    mqtt5Client = mock(Mqtt5Client.class);
    final Mqtt5AsyncClient asyncClient = mock(Mqtt5AsyncClient.class);
    when(mqtt5Client.toAsync()).thenReturn(asyncClient);
    when(asyncClient.publish(any(Mqtt5Publish.class))).thenAnswer(i -> {
        final Mqtt5Publish msg = i.getArgument(0);
        received.add(msg);
        return CompletableFuture.completedFuture(msg);
    });
}
 
Example #25
Source File: BaseAkkaTestCase.java    From oreilly-reactive-architecture-student with Apache License 2.0 5 votes vote down vote up
public ActorRef expectActor(JavaTestKit kit, String path) {
    final ActorRef[] actor = {null};
    kit.new AwaitCond(kit.duration("3 seconds"), kit.duration("150 millis"), "No actor found with " + path) {
        @Override
        protected boolean cond() {
            TestProbe probe = new TestProbe(system);
            system.actorSelection(path).tell(new akka.actor.Identify(101), probe.ref());
            ActorIdentity i = probe.expectMsgClass(kit.duration("100 millis"), ActorIdentity.class);
            actor[0] = i.getRef();
            return i.getRef() != null;
        }
    };
    return actor[0];
}
 
Example #26
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void manageConnectionWith2Clients() throws Exception {
    startSecondActorSystemAndJoinCluster();
    new TestKit(actorSystem) {{
        final TestProbe probe = TestProbe.apply(actorSystem);
        final ActorRef underTest =
                TestConstants.createConnectionSupervisorActor(connectionId, actorSystem, pubSubMediator,
                        conciergeForwarder,
                        (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()));
        watch(underTest);

        // create closed connection
        underTest.tell(createClosedConnectionWith2Clients, getRef());
        expectMsgClass(CreateConnectionResponse.class);

        // open connection: only local client actor is asked for a response.
        underTest.tell(openConnection, getRef());
        probe.expectMsg(openConnection);
        expectMsgClass(OpenConnectionResponse.class);

        // forward signal once
        underTest.tell(thingModified, getRef());
        final Object outboundSignal = probe.expectMsgClass(Object.class);
        assertThat(outboundSignal).isInstanceOf(OutboundSignal.class);
        // probe.expectMsg(OutboundSignal.class); // does not work for some reason

        // close connection: at least 1 client actor gets the command; the other may or may not be started.
        underTest.tell(closeConnection, getRef());
        probe.expectMsg(closeConnection);
        expectMsg(closeConnectionResponse);

        // delete connection
        underTest.tell(deleteConnection, getRef());
        expectMsg(deleteConnectionResponse);
        expectTerminated(underTest);
    }};
}
 
Example #27
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void deleteConnectionUpdatesSubscriptions() {
    new TestKit(actorSystem) {{
        final TestProbe probe = TestProbe.apply(actorSystem);
        final ActorRef underTest = TestConstants.createConnectionSupervisorActor(
                connectionId, actorSystem, conciergeForwarder,
                (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()),
                TestConstants.dummyDittoProtocolSub(pubSubMediator, dittoProtocolSubMock),
                pubSubMediator
        );
        watch(underTest);

        // create connection
        underTest.tell(createConnection, getRef());
        probe.expectMsg(openConnection);
        expectMsg(createConnectionResponse);
        expectRemoveSubscriber(1);
        expectSubscribe(TWIN_AND_LIVE_EVENTS, SUBJECTS);

        // delete connection
        underTest.tell(deleteConnection, getRef());
        expectMsg(deleteConnectionResponse);
        expectRemoveSubscriber(2);
        probe.expectNoMessage();
        expectTerminated(underTest);
    }};

}
 
Example #28
Source File: HotswapClientActorTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldGet() throws Exception {
    TestActorRef<AkkademyDb> dbRef = TestActorRef.create(system, Props.create(AkkademyDb.class));
    AkkademyDb db = dbRef.underlyingActor();
    db.map.put("testkey", "testvalue");

    TestProbe probe = TestProbe.apply(system);
    TestActorRef<HotswapClientActor> clientRef =
            TestActorRef.create(system, Props.create(HotswapClientActor.class, dbRef.path().toString()));


    clientRef.tell(new GetRequest("testkey"), probe.ref());
    probe.expectMsg("testvalue");
}
 
Example #29
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void manageConnection() {
    new TestKit(actorSystem) {{
        final TestProbe probe = TestProbe.apply(actorSystem);
        final ActorRef underTest = TestConstants.createConnectionSupervisorActor(
                connectionId, actorSystem, conciergeForwarder,
                (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()),
                TestConstants.dummyDittoProtocolSub(pubSubMediator, dittoProtocolSubMock),
                pubSubMediator
        );
        watch(underTest);

        // create connection
        underTest.tell(createConnection, getRef());
        probe.expectMsg(openConnection);
        expectMsg(createConnectionResponse);
        expectRemoveSubscriber(1);
        expectSubscribe(TWIN_AND_LIVE_EVENTS, SUBJECTS);

        // close connection
        underTest.tell(closeConnection, getRef());
        probe.expectMsg(closeConnection);
        expectMsg(closeConnectionResponse);
        expectRemoveSubscriber(2);

        // delete connection
        underTest.tell(deleteConnection, getRef());
        expectMsg(deleteConnectionResponse);
        probe.expectNoMessage();
        expectTerminated(underTest);
    }};
}
 
Example #30
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testConnectionActorRespondsToCleanupCommand() {
    new TestKit(actorSystem) {{

        final TestProbe probe = TestProbe.apply(actorSystem);
        final ActorRef underTest =
                TestConstants.createConnectionSupervisorActor(connectionId, actorSystem, pubSubMediator,
                        conciergeForwarder,
                        (connection, concierge, connectionActor) -> MockClientActor.props(probe.ref()));
        watch(underTest);

        // create connection
        underTest.tell(createConnection, getRef());
        probe.expectMsg(openConnection);
        expectMsg(createConnectionResponse);

        // send cleanup command
        underTest.tell(
                CleanupPersistence.of(DefaultEntityId.of(
                        ConnectionPersistenceActor.PERSISTENCE_ID_PREFIX + connectionId),
                        DittoHeaders.empty()),
                getRef());
        expectMsg(CleanupPersistenceResponse.success(
                DefaultEntityId.of(ConnectionPersistenceActor.PERSISTENCE_ID_PREFIX + connectionId),
                DittoHeaders.empty()));
    }};
}