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

The following examples show how to use akka.testkit.TestProbe#apply() . 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: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void openConnectionAfterDeletedFails() {
    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);

        // open connection should fail
        underTest.tell(openConnection, getRef());
        expectMsg(connectionNotAccessibleException);
    }};
}
 
Example 2
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 3
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void enabledConnectionLogsAreEnabledAgainAfterModify() {
    final EnableConnectionLogs enableConnectionLogs = EnableConnectionLogs.of(connectionId, DittoHeaders.empty());
    final EnableConnectionLogsResponse enableConnectionLogsResponse =
            EnableConnectionLogsResponse.of(connectionId, enableConnectionLogs.getDittoHeaders());
    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);

        // Wait until connection is established
        expectAnySubscribe();

        // enable connection logs
        underTest.tell(enableConnectionLogs, getRef());
        probe.expectMsg(enableConnectionLogs);

        expectMsg(enableConnectionLogsResponse);

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

        // expect the message twice, once for each client
        probe.expectMsg(enableConnectionLogs);
    }};
}
 
Example 4
Source File: AbstractMqttClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testPublishToTopic() {
    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 ThingModifiedEvent thingModifiedEvent = TestConstants.thingModified(Collections.emptyList());
        final String expectedJson = TestConstants.signalToDittoProtocolJsonString(thingModifiedEvent);

        LOGGER.info("Sending thing modified message: {}", thingModifiedEvent);
        final OutboundSignal.Mapped mappedSignal =
                Mockito.mock(OutboundSignal.Mapped.class);
        when(mappedSignal.getTargets()).thenReturn(singletonList(TARGET));
        when(mappedSignal.getSource()).thenReturn(thingModifiedEvent);
        underTest.tell(mappedSignal, getRef());

        final M receivedMessage = expectMsgClass(getMessageClass());
        assertThat(extractTopic(receivedMessage)).isEqualTo(TARGET.getAddress());
        assertThat(extractPayload(receivedMessage)).isEqualTo(expectedJson);

        underTest.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), controlProbe.ref());
        controlProbe.expectMsg(DISCONNECTED_SUCCESS);
    }};
}
 
Example 5
Source File: AkkademyDbTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldPlaceKeyValueFromSetMessageIntoMap() {
    TestProbe testProbe = TestProbe.apply(system);
    TestActorRef<AkkademyDb> actorRef = TestActorRef.create(system, Props.create(AkkademyDb.class));
    AkkademyDb akkademyDb = actorRef.underlyingActor();

    actorRef.tell(new SetRequest("key", "value", testProbe.ref()), ActorRef.noSender());

    assertEquals(akkademyDb.map.get("key"), "value");
}
 
Example 6
Source File: QueryThingsPerRequestActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void startActorSystem() {
    actorSystem = ActorSystem.create();
    aggregatorProbe = TestProbe.apply("aggregator", actorSystem);
    originalSenderProbe = TestProbe.apply("originalSender", actorSystem);
    pubSubMediatorProbe = TestProbe.apply("pubSubMediator", actorSystem);
    dittoHeaders = DittoHeaders.newBuilder().randomCorrelationId().build();
}
 
Example 7
Source File: ConnectionPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void retrieveLogsIsAggregated() {
    final Instant now = Instant.now();
    final RetrieveConnectionLogsResponse innerResponse = RetrieveConnectionLogsResponse.of(connectionId,
            TestConstants.Monitoring.LOG_ENTRIES,
            now.minusSeconds(312),
            now.plusSeconds(123),
            DittoHeaders.empty());

    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);

        // retrieve logs
        final RetrieveConnectionLogs retrieveConnectionLogs =
                RetrieveConnectionLogs.of(connectionId, DittoHeaders.empty());
        underTest.tell(retrieveConnectionLogs, getRef());
        probe.expectMsg(retrieveConnectionLogs);

        // send answer to aggregator actor
        final ActorRef aggregatorActor = probe.sender();
        probe.send(aggregatorActor, innerResponse);

        expectMsg(innerResponse);
    }};
}
 
Example 8
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 9
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 10
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 11
Source File: RetrieveConnectionLogsAggregatorActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void withMultipleClientsRespectsMaxLogSize() throws InterruptedException {
    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, maxSizeLogEntries()),
                createRetrieveConnectionLogsResponse(connection.getId(), since, until, maxSizeLogEntries()),
                createRetrieveConnectionLogsResponse(connection.getId(), since, until, maxSizeLogEntries())
        );

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

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

        final RetrieveConnectionLogsResponse retrieveConnectionLogsResponse =
                sender.expectMsgClass(RetrieveConnectionLogsResponse.class);
        assertThat((Long) retrieveConnectionLogsResponse.getConnectionLogs().stream()
                .map(LogEntry::toJsonString)
                .map(String::length)
                .mapToLong(Integer::intValue)
                .sum())
                .isLessThan(LOGGER_CONFIG.maxLogSizeInBytes());
    }};
}
 
Example 12
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void handleIndexDocumentVOIndexDone() {
	final Props props = Props.create(SetupDocumentTypeWorkerActor.class,
			null, null);
	final TestActorRef<SetupDocumentTypeWorkerActor> ref = TestActorRef
			.create(system, props);
	final SetupDocumentTypeWorkerActor actor = ref.underlyingActor();
	// Mock the behavior of child/worker actors.
	TestProbe testProbeIndexDataWorker = TestProbe.apply(system);
	actor.setIndexDocumentWorkerRouter(testProbeIndexDataWorker.ref());
	ElasticSearchIndexConfig config = ElasticSearchIndexConfig.COM_WEBSITE;
	IndexDocumentType documentType = IndexDocumentType.PRODUCT;
	String indexName = "trialindexName";
	Long documentId = 1l;
	Product product = new Product();
	product.setId(documentId);
	IndexDocumentVO indexDocumentVO = new IndexDocumentVO().config(config)
			.documentType(documentType).newIndexName(indexName)
			.documentId(documentId);
	// send data back, index document.
	indexDocumentVO.product(product);
	indexDocumentVO.indexDone(true);
	// Actor state check
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	ref.tell(indexDocumentVO, null);
	testProbeIndexDataWorker.expectNoMsg();
	;
	assertEquals(1, actor.getTotalDocumentsToIndexDone());
}
 
Example 13
Source File: PubSubFactoryTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void broadcastMessageToManySubscribers() {
    new TestKit(system2) {{
        final DistributedPub<String> pub = factory1.startDistributedPub();
        final DistributedSub sub1 = factory1.startDistributedSub();
        final DistributedSub sub2 = factory2.startDistributedSub();
        final TestProbe publisher = TestProbe.apply(system1);
        final TestProbe subscriber1 = TestProbe.apply(system1);
        final TestProbe subscriber2 = TestProbe.apply(system2);
        final TestProbe subscriber3 = TestProbe.apply(system1);
        final TestProbe subscriber4 = TestProbe.apply(system2);

        // GIVEN: subscribers of different topics exist on both actor systems
        CompletableFuture.allOf(
                sub1.subscribeWithAck(asList("he", "av'n", "has", "no", "rage", "nor"), subscriber1.ref())
                        .toCompletableFuture(),
                sub2.subscribeWithAck(asList("hell", "a", "fury"), subscriber2.ref())
                        .toCompletableFuture(),
                sub1.subscribeWithAck(asList("like", "a", "woman", "scorn'd"), subscriber3.ref())
                        .toCompletableFuture(),
                sub2.subscribeWithAck(asList("exeunt", "omnes"), subscriber4.ref()).toCompletableFuture()
        ).join();

        // WHEN: many messages are published
        final int messages = 100;
        IntStream.range(0, messages).forEach(i -> pub.publish("hello" + i, publisher.ref()));

        // THEN: subscribers with relevant topics get the messages in the order they were published.
        IntStream.range(0, messages).forEach(i -> {
            subscriber1.expectMsg("hello" + i);
            subscriber2.expectMsg("hello" + i);
        });

        // THEN: subscribers without relevant topics get no message.
        subscriber3.expectNoMsg(Duration.Zero());
        subscriber4.expectNoMsg(Duration.Zero());
    }};
}
 
Example 14
Source File: AbstractMqttClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void initializeConnection() {
    actorSystem = ActorSystem.create("AkkaTestSystem", TestConstants.CONFIG);
    mockConnectionActor = TestProbe.apply("connectionActor", actorSystem);
    connectionId = TestConstants.createRandomConnectionId();
    serverHost = "tcp://localhost:" + FREE_PORT.getPort();
    connection = ConnectivityModelFactory.newConnectionBuilder(connectionId, connectionType,
            ConnectivityStatus.CLOSED, serverHost)
            .sources(singletonList(MQTT_SOURCE))
            .targets(singletonList(TARGET))
            .failoverEnabled(true)
            .build();
}
 
Example 15
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 16
Source File: MessageMappingProcessorActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    actorSystem = ActorSystem.create("AkkaTestSystem", TestConstants.CONFIG);
    protocolAdapterProvider = ProtocolAdapterProvider.load(TestConstants.PROTOCOL_CONFIG, actorSystem);
    connectionActorProbe = TestProbe.apply("connectionActor", actorSystem);
    MockConciergeForwarderActor.create(actorSystem);
}
 
Example 17
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void init() throws JMSException {
    Mockito.reset(mockConnection, mockSession, mockConsumer);
    when(mockConnection.createSession(Session.CLIENT_ACKNOWLEDGE)).thenReturn(mockSession);
    listenerArgumentCaptor = ArgumentCaptor.forClass(JmsConnectionListener.class);
    doNothing().when(mockConnection).addConnectionListener(listenerArgumentCaptor.capture());
    prepareSession(mockSession, mockConsumer);
    connectionActorProbe = TestProbe.apply("connectionActor", actorSystem);
    connectionActor = connectionActorProbe.ref();
}
 
Example 18
Source File: MessageMappingProcessorActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testSignalEnrichment() {
    // GIVEN: test probe actor started with configured values
    final TestProbe conciergeForwarderProbe = TestProbe.apply("mockConciergeForwarderProbe", actorSystem);
    setUpConciergeForwarder(conciergeForwarderProbe.ref());

    new TestKit(actorSystem) {{
        // GIVEN: MessageMappingProcessor started with a test probe as the configured enrichment provider
        final ActorRef underTest = createMessageMappingProcessorActor(this);

        // WHEN: a signal is received with 2 targets, one with enrichment and one without
        final JsonFieldSelector extraFields = JsonFieldSelector.newInstance("attributes/x", "attributes/y");
        final AuthorizationSubject targetAuthSubject = AuthorizationSubject.newInstance("target:auth-subject");
        final AuthorizationSubject targetAuthSubjectWithoutIssuer = AuthorizationSubject.newInstance("auth-subject");
        final Target targetWithEnrichment = ConnectivityModelFactory.newTargetBuilder()
                .address("target/address")
                .authorizationContext(AuthorizationContext.newInstance(DittoAuthorizationContextType.UNSPECIFIED,
                        targetAuthSubject))
                .topics(ConnectivityModelFactory.newFilteredTopicBuilder(Topic.TWIN_EVENTS)
                        .withExtraFields(extraFields)
                        .build())
                .build();
        final Target targetWithoutEnrichment = ConnectivityModelFactory.newTargetBuilder(targetWithEnrichment)
                .topics(Topic.TWIN_EVENTS)
                .build();
        final Signal<?> signal = TestConstants.thingModified(Collections.emptyList());
        final OutboundSignal outboundSignal = OutboundSignalFactory.newOutboundSignal(signal,
                Arrays.asList(targetWithEnrichment, targetWithoutEnrichment));
        underTest.tell(outboundSignal, getRef());

        // THEN: a mapped signal without enrichment arrives first
        expectPublishedMappedMessage(expectMsgClass(PublishMappedMessage.class), signal, targetWithoutEnrichment);

        // THEN: Receive a RetrieveThing command from the facade.
        final RetrieveThing retrieveThing = conciergeForwarderProbe.expectMsgClass(RetrieveThing.class);
        assertThat(retrieveThing.getSelectedFields()).contains(extraFields);
        assertThat(retrieveThing.getDittoHeaders().getAuthorizationContext()).containsExactly(targetAuthSubject, targetAuthSubjectWithoutIssuer);

        final JsonObject extra = JsonObject.newBuilder().set("/attributes/x", 5).build();
        conciergeForwarderProbe.reply(
                RetrieveThingResponse.of(retrieveThing.getEntityId(), extra, retrieveThing.getDittoHeaders()));

        // THEN: Receive an outbound signal with extra fields.
        expectPublishedMappedMessage(expectMsgClass(PublishMappedMessage.class), signal, targetWithEnrichment,
                mapped -> assertThat(mapped.getAdaptable().getPayload().getExtra()).contains(extra));
    }};
}
 
Example 19
Source File: AbstractConsumerActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Before
public void init() {
    connectionActorProbe = TestProbe.apply("connectionActor", actorSystem);
}
 
Example 20
Source File: ThingUpdaterTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
private void startActorSystem(final Config config) {
    shutdownActorSystem();
    actorSystem = ActorSystem.create("AkkaTestSystem", config);
    pubSubTestProbe = TestProbe.apply(actorSystem);
    changeQueueTestProbe = TestProbe.apply(actorSystem);
}