Java Code Examples for akka.testkit.TestProbe#expectMsg()

The following examples show how to use akka.testkit.TestProbe#expectMsg() . 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: MessageAggregatorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void stopSelfIfExpectNoMessage() {
    new TestKit(actorSystem) {{
        final TestProbe initialReceiver = TestProbe.apply(actorSystem);

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

        watch(underTest);

        underTest.tell(true, getRef());
        initialReceiver.expectMsg(true);
        expectMsg(Collections.emptyList());
        expectTerminated(underTest);
    }};
}
 
Example 2
Source File: MessageAggregatorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void ignoreIrrelevantMessages() {
    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("hello", getRef());
        underTest.tell(0, getRef());
        underTest.tell(new Object(), getRef());
        underTest.tell(1, getRef());
        underTest.tell(false, getRef());
        underTest.tell(2, getRef());
        initialReceiver.expectMsg(true);
        expectMsg(Arrays.asList(0, 1, 2));
        expectTerminated(underTest);
    }};
}
 
Example 3
Source File: MessageAggregatorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void reportPartialMessagesOnTimeout() {
    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(MessageAggregator.TIMEOUT, getRef());
        initialReceiver.expectMsg(true);
        expectMsg(Arrays.asList(0, 1));
        expectTerminated(underTest);
    }};

}
 
Example 4
Source File: ChatroomTest.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldSendUpdateWhenUserPosts() {
    //Given
    Props props = Props.create(Chatroom.class);
    TestActorRef<Chatroom> ref = TestActorRef.create(system, props);
    Chatroom chatroom = ref.underlyingActor();

    final TestProbe probe = new TestProbe(system);
    UserRef userRef = new UserRef(probe.ref(), "user");
    chatroom.joinChatroom(new Messages.JoinChatroom(userRef));

    //When
    Messages.PostToChatroom msg = new Messages.PostToChatroom("test", "user");
    ref.tell(msg, probe.ref());

    //Then
    probe.expectMsg(msg);
}
 
Example 5
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 6
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void disabledConnectionLogsAreNotEnabledAfterModify() {
    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);

        // modify connection
        underTest.tell(modifyConnection, getRef());
        probe.expectMsg(closeConnection);
        probe.expectMsg(openConnection);
        expectMsg(modifyConnectionResponse);

        probe.expectNoMsg();
    }};
}
 
Example 7
Source File: RetrieveConnectionLogsAggregatorActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void withOneClient() {
    new TestKit(actorSystem) {{
        final TestProbe sender = TestProbe.apply(actorSystem);
        final Connection connection = createConnectionWithClients(1);

        final RetrieveConnectionLogsResponse expectedResponse =
                createRetrieveConnectionLogsResponse(connection.getId(), Instant.now().minusSeconds(123),
                        Instant.now().plusSeconds(444));

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

        underTest.tell(expectedResponse, getRef());

        sender.expectMsg(expectedResponse);
    }};
}
 
Example 8
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 9
Source File: AbstractMqttClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPublishToReplyTarget() {
    connection = connection.toBuilder()
            .setSources(TestConstants.Sources.SOURCES_WITH_AUTH_CONTEXT)
            .build();
    new TestKit(actorSystem) {{
        final TestProbe controlProbe = TestProbe.apply(actorSystem);
        final Props props = createClientActor(getRef(), getConnection(false));
        final ActorRef underTest = actorSystem.actorOf(props);

        underTest.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
        controlProbe.expectMsg(CONNECTED_SUCCESS);

        final DittoHeaders dittoHeaders = DittoHeaders.newBuilder()
                .replyTarget(0)
                .build();
        final DeleteThingResponse deleteThingResponse =
                DeleteThingResponse.of(ThingId.of("thing", "id"), dittoHeaders);

        LOGGER.info("Sending DeleteThingResponse: {}", deleteThingResponse);
        final Object outboundSignal =
                OutboundSignalFactory.newOutboundSignal(deleteThingResponse, Collections.emptyList());

        underTest.tell(outboundSignal, getRef());

        final M receivedMessage = expectMsgClass(getMessageClass());
        assertThat(extractTopic(receivedMessage)).isEqualTo("replyTarget/thing:id");

        underTest.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
        controlProbe.expectMsg(DISCONNECTED_SUCCESS);
    }};
}
 
Example 10
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void modifyConnectionInClosedState() {
    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);

        // create connection
        underTest.tell(closeConnection, getRef());
        probe.expectMsg(closeConnection);
        expectMsg(closeConnectionResponse);

        // modify connection
        underTest.tell(modifyClosedConnection, getRef());
        // client actor is not informed about modification as it is not started
        probe.expectNoMessage();
        expectMsg(modifyConnectionResponse);
    }};
}
 
Example 11
Source File: HotswapClientActorTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldSet() throws Exception {
    TestActorRef<AkkademyDb> dbRef = TestActorRef.create(system, Props.create(AkkademyDb.class));
    AkkademyDb db = dbRef.underlyingActor();

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

    clientRef.tell(new SetRequest("testkey", "testvalue", probe.ref()), probe.ref());

    probe.expectMsg(new Status.Success("testkey"));
    assert(db.map.get("testkey") == "testvalue");
}
 
Example 12
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void recoverOpenConnection() {
    new TestKit(actorSystem) {{

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

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

        // wait for open connection of initial creation
        mockClientProbe.expectMsg(OpenConnection.of(connectionId, DittoHeaders.empty()));

        // stop actor
        getSystem().stop(underTest);
        expectTerminated(underTest);

        // recover actor
        final TestProbe recoveredMockClientProbe = TestProbe.apply(actorSystem);
        underTest = Retry.untilSuccess(
                () -> TestConstants.createConnectionSupervisorActor(connectionId, actorSystem, pubSubMediator,
                        conciergeForwarder, (connection, concierge, connectionActor) -> MockClientActor.props(
                                recoveredMockClientProbe.ref())));

        // connection is opened after recovery -> recovered client actor receives OpenConnection command
        recoveredMockClientProbe.expectMsg(OpenConnection.of(connectionId, DittoHeaders.empty()));

        // poll connection status until status is OPEN
        final ActorRef recoveredActor = underTest;
        Awaitility.await().untilAsserted(() -> {
            recoveredActor.tell(retrieveConnectionStatus, getRef());
            expectMsg(retrieveConnectionStatusOpenResponse);
        });
    }};
}
 
Example 13
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 14
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()));
    }};
}
 
Example 15
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 16
Source File: PubSubFactoryTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void startSeveralTimes() throws Exception {
    // This test simulates the situation where the root actor of a Ditto service restarts several times.
    new TestKit(system2) {{
        // GIVEN: many pub- and sub-factories start under different actors.
        for (int i = 0; i < 10; ++i) {
            TestPubSubFactory.of(newContext(system1));
            TestPubSubFactory.of(newContext(system2));
        }

        // WHEN: another pair of pub-sub factories were created.
        final DistributedPub<String> pub = TestPubSubFactory.of(newContext(system1)).startDistributedPub();
        final DistributedSub sub = TestPubSubFactory.of(newContext(system2)).startDistributedSub();
        final TestProbe publisher = TestProbe.apply(system1);
        final TestProbe subscriber = TestProbe.apply(system2);

        // THEN: they fulfill their function.
        final SubUpdater.Acknowledgement subAck =
                sub.subscribeWithAck(singleton("hello"), subscriber.ref()).toCompletableFuture().join();
        assertThat(subAck.getRequest()).isInstanceOf(SubUpdater.Subscribe.class);
        assertThat(subAck.getRequest().getTopics()).containsExactlyInAnyOrder("hello");

        Thread.sleep(500L); // give local subscriber a chance to receive most updated subscriptions
        pub.publish("hello", publisher.ref());
        subscriber.expectMsg("hello");
    }};
}
 
Example 17
Source File: PubSubFactoryTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void subscribeAndPublishAndUnsubscribe() {
    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);

        // WHEN: actor subscribes to a topic with acknowledgement
        final SubUpdater.Acknowledgement subAck =
                sub.subscribeWithAck(singleton("hello"), subscriber.ref()).toCompletableFuture().join();

        // THEN: subscription is acknowledged
        assertThat(subAck.getRequest()).isInstanceOf(SubUpdater.Subscribe.class);
        assertThat(subAck.getRequest().getTopics()).containsExactlyInAnyOrder("hello");

        // WHEN: a message is published on the subscribed topic
        pub.publish("hello", publisher.ref());

        // THEN: the subscriber receives it from the original sender's address
        subscriber.expectMsg("hello");
        assertThat(subscriber.sender().path().address()).isEqualTo(cluster1.selfAddress());
        assertThat(subscriber.sender().path().toStringWithoutAddress())
                .isEqualTo(publisher.ref().path().toStringWithoutAddress());

        // WHEN: subscription is relinquished
        final SubUpdater.Acknowledgement unsubAck =
                sub.unsubscribeWithAck(asList("hello", "world"), subscriber.ref()).toCompletableFuture().join();
        assertThat(unsubAck.getRequest()).isInstanceOf(SubUpdater.Unsubscribe.class);
        assertThat(unsubAck.getRequest().getTopics()).containsExactlyInAnyOrder("hello", "world");

        // THEN: the subscriber does not receive published messages any more
        pub.publish("hello", publisher.ref());
        pub.publish("hello world", publisher.ref());
        subscriber.expectNoMessage();
    }};
}
 
Example 18
Source File: LiveSignalEnforcementTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void acceptMessageCommandResponseByAcl() {
    final JsonObject thingWithAcl = newThing()
            .setPermissions(AclEntry.newInstance(SUBJECT, READ, WRITE, ADMINISTRATE))
            .build()
            .toJson(V_1, FieldType.all());
    final SudoRetrieveThingResponse response =
            SudoRetrieveThingResponse.of(thingWithAcl, DittoHeaders.empty());

    new TestKit(system) {{
        mockEntitiesActorInstance.setReply(THING_SUDO, response);

        final TestProbe responseProbe = TestProbe.apply(system);

        final ActorRef underTest = newEnforcerActor(getRef());
        final MessageCommand msgCommand = thingMessageCommand();
        mockEntitiesActorInstance.setReply(msgCommand);
        underTest.tell(msgCommand, responseProbe.ref());
        final DistributedPubSubMediator.Publish publish =
                fishForMsgClass(this, DistributedPubSubMediator.Publish.class);
        assertThat(publish.topic()).isEqualTo(StreamingType.MESSAGES.getDistributedPubSubTopic());

        final MessageCommandResponse messageCommandResponse =
                thingMessageCommandResponse((MessageCommand) publish.msg());

        underTest.tell(messageCommandResponse, responseProbe.ref());
        responseProbe.expectMsg(messageCommandResponse);
        assertThat(responseProbe.lastSender()).isEqualTo(responseProbe.ref());
    }};
}
 
Example 19
Source File: SubscriptionManagerTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void parallelSessions() {
    // Suppressing logs due to stacktrace for test4. Comment out to see logs.
    actorSystem.eventStream().setLogLevel(Attributes.logLevelOff());

    final ActorRef underTest = createSubscriptionManager();

    final TestProbe probe1 = TestProbe.apply("test1", actorSystem);
    final TestProbe probe2 = TestProbe.apply("test2", actorSystem);
    final TestProbe probe3 = TestProbe.apply("test3", actorSystem);
    final TestProbe probe4 = TestProbe.apply("test4", actorSystem);

    // expect success with results
    underTest.tell(createSubscription(1), probe1.ref());
    // expect success with prefix
    final String prefix = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    underTest.tell(createSubscription(2).setPrefix(prefix), probe2.ref());
    // expect cancellation
    underTest.tell(createSubscription(3), probe3.ref());
    // expect upstream failure
    underTest.tell(createSubscription(4), probe4.ref());

    final String sid1 = probe1.expectMsgClass(SubscriptionCreated.class).getSubscriptionId();
    final String sid2 = probe2.expectMsgClass(SubscriptionCreated.class).getSubscriptionId();
    final String sid3 = probe3.expectMsgClass(SubscriptionCreated.class).getSubscriptionId();
    final String sid4 = probe4.expectMsgClass(SubscriptionCreated.class).getSubscriptionId();

    final List<?> sources = List.of(
            Source.single("t:1"),
            Source.single("t:2"),
            Source.from(List.of("t:3", "t:4")),
            new AskTimeoutException("mock error")
    );

    underTest.tell(request(sid1), probe1.ref());
    underTest.tell(request(sid2), probe2.ref());
    underTest.tell(request(sid3), probe3.ref());
    underTest.tell(request(sid4), probe4.ref());

    // there should be no upstream request until downstream requests.
    for (int i = 0; i < 4; ++i) {
        final StreamThings streamThings = conciergeForwarderProbe.expectMsgClass(StreamThings.class);
        final ActorRef sender = conciergeForwarderProbe.sender();
        final Object source = sources.get(getTag(streamThings) - 1);
        if (source instanceof Source) {
            ((Source<?, ?>) source).runWith(StreamRefs.sourceRef(), materializer)
                    .thenAccept(sourceRef -> sender.tell(sourceRef, ActorRef.noSender()));
        } else {
            sender.tell(source, ActorRef.noSender());
        }
    }

    probe1.expectMsg(hasNext(sid1, "t:1"));
    probe1.expectMsg(subscriptionComplete(sid1));

    probe2.expectMsg(hasNext(sid2, "t:2"));
    probe2.expectMsg(subscriptionComplete(sid2));

    probe3.expectMsg(hasNext(sid3, "t:3"));
    underTest.tell(CancelSubscription.of(sid3, DittoHeaders.empty()), probe3.ref());

    assertThat(probe4.expectMsgClass(SubscriptionFailed.class).getError())
            .isInstanceOf(GatewayInternalErrorException.class);

    CompletableFuture.allOf(
            CompletableFuture.runAsync(
                    () -> probe3.expectNoMessage(FiniteDuration.apply(250L, TimeUnit.MILLISECONDS))),
            CompletableFuture.runAsync(
                    () -> probe4.expectNoMessage(FiniteDuration.apply(250L, TimeUnit.MILLISECONDS)))
    ).join();
}
 
Example 20
Source File: KafkaClientActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private static void expectPublisherReceivedShutdownSignal(final TestProbe probe) {
    probe.expectMsg(KafkaPublisherActor.GracefulStop.INSTANCE);
}