Java Code Examples for akka.testkit.TestActorRef#underlyingActor()

The following examples show how to use akka.testkit.TestActorRef#underlyingActor() . 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: 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 2
Source File: ChatroomTest.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldSendHistoryWhenUserJoin() {
    new JavaTestKit(system) {{
        //Given
        Props props = Props.create(Chatroom.class);
        TestActorRef<Chatroom> ref = TestActorRef.create(system, props);
        Chatroom chatroom = ref.underlyingActor();
        Messages.PostToChatroom msg = new Messages.PostToChatroom("test", "user");
        chatroom.chatHistory.add(msg);

        //When
        UserRef userRef = new UserRef(system.deadLetters(), "user");
        Messages.JoinChatroom request = new Messages.JoinChatroom(userRef);
        ref.tell(request, getRef());

        //Then
        List expected = new ArrayList<Messages.PostToChatroom>();
        expected.add(msg);
        expectMsgEquals(duration("1 second"), expected);
    }};
}
 
Example 3
Source File: ThingPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * The ThingPersistenceActor is created with a Thing ID. Any command it receives which belongs to a Thing with a
 * different ID should lead to an exception as the command was obviously sent to the wrong ThingPersistenceActor.
 */
@Test
public void tryToCreateThingWithDifferentThingId() {
    final ThingId thingIdOfActor = ThingId.of("test.ns", "23420815");
    final Thing thing = createThingV2WithRandomId();
    final CreateThing createThing = CreateThing.of(thing, null, dittoHeadersV2);

    final Props props = ThingPersistenceActor.props(thingIdOfActor, getDistributedPub());
    final TestActorRef<ThingPersistenceActor> underTest = TestActorRef.create(actorSystem, props);
    final ThingPersistenceActor thingPersistenceActor = underTest.underlyingActor();
    final PartialFunction<Object, BoxedUnit> receiveCommand = thingPersistenceActor.receiveCommand();

    try {
        receiveCommand.apply(createThing);
        fail("Expected IllegalArgumentException to be thrown.");
    } catch (final Exception e) {
        assertThat(e).isInstanceOf(IllegalArgumentException.class);
    }
}
 
Example 4
Source File: ChatroomTest.java    From learning-akka with Apache License 2.0 6 votes vote down vote up
@Test
public void testShouldAddUserToJoinedUsersWhenJoiningTest() {
    //Given a Chatroom has no users
    Props props = Props.create(Chatroom.class);
    TestActorRef<Chatroom> ref = TestActorRef.create(system, props);
    Chatroom chatroom = ref.underlyingActor();
    assertEquals(chatroom.joinedUsers.size(), 0);

    //When it receives a request from a user to join the chatroom
    UserRef userRef = new UserRef(system.deadLetters(), "user");
    Messages.JoinChatroom request = new Messages.JoinChatroom(userRef);
    ref.tell(request, system.deadLetters());

    //It should add the UserRef to its list of joined users
    assertEquals(chatroom.joinedUsers.get(0), userRef);
}
 
Example 5
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 6
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void handleIndexDocumentVODocumentGeneration() {
	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 testProbeDocumentGeneratorWorker = TestProbe.apply(system);
	actor.setDocumentGeneratorWorkerRouter(testProbeDocumentGeneratorWorker
			.ref());
	ElasticSearchIndexConfig config = ElasticSearchIndexConfig.COM_WEBSITE;
	IndexDocumentType documentType = IndexDocumentType.PRODUCT;
	String indexName = "trialindexName";
	Long documentId = 1l;
	IndexDocumentVO indexDocumentVO = new IndexDocumentVO().config(config)
			.documentType(documentType).newIndexName(indexName)
			.documentId(documentId);
	// Send data back to the sender, generate document
	assertEquals(0, actor.getTotalDocumentsToIndex());
	ref.tell(indexDocumentVO, null);
	testProbeDocumentGeneratorWorker.expectMsgClass(IndexDocumentVO.class);
	TestActor.Message messageDoc = testProbeDocumentGeneratorWorker
			.lastMessage();
	IndexDocumentVO resultMsgDoc = (IndexDocumentVO) messageDoc.msg();
	assertEquals(config, resultMsgDoc.getConfig());
	assertEquals(documentType, resultMsgDoc.getDocumentType());
	assertEquals(indexName, resultMsgDoc.getNewIndexName());
	assertEquals(documentId, resultMsgDoc.getDocumentId());
	assertEquals(0, actor.getTotalDocumentsToIndex());
}
 
Example 7
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void handleUnhandledMessage() {
	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());
	// Actor state check
	assertEquals(null, actor.getIndexDocumentType());
	// Subscribe first
	TestProbe subscriber = TestProbe.apply(system);
	system.eventStream()
			.subscribe(subscriber.ref(), UnhandledMessage.class);
	// garbage
	String invalidMessage = "blah blah";
	ref.tell(invalidMessage, null);
	// Expect the unhandled message now.
	FiniteDuration duration = Duration.create(1, TimeUnit.SECONDS);
	subscriber.expectMsgClass(duration, UnhandledMessage.class);
	TestActor.Message message = subscriber.lastMessage();
	UnhandledMessage resultMsg = (UnhandledMessage) message.msg();
	assertEquals(invalidMessage, resultMsg.getMessage());
	// Actor state check
	assertEquals(null, actor.getIndexDocumentType());
}
 
Example 8
Source File: ChatroomTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void testShouldAddUserToJoinedUsersWhenJoiningUnitTest() {
    Props props = Props.create(Chatroom.class);
    TestActorRef<Chatroom> ref = TestActorRef.create(system, props);
    Chatroom chatroom = ref.underlyingActor();

    UserRef userRef = new UserRef(system.deadLetters(), "user");
    Messages.JoinChatroom request = new Messages.JoinChatroom(userRef);
    chatroom.joinChatroom(request);

    assertEquals(chatroom.joinedUsers.get(0), userRef);
}
 
Example 9
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void sendExceptionToParent() {
	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 testProbeDocumentGeneratorWorker = TestProbe.apply(system);
	TestProbe testProbeIndexDataWorker = TestProbe.apply(system);
	// No data generator
	actor.setDataGeneratorWorkerRouter(null);
	actor.setDocumentGeneratorWorkerRouter(testProbeDocumentGeneratorWorker
			.ref());
	actor.setIndexDocumentWorkerRouter(testProbeIndexDataWorker.ref());
	ElasticSearchIndexConfig config = ElasticSearchIndexConfig.COM_WEBSITE;
	IndexDocumentType documentType = IndexDocumentType.PRODUCT;
	String indexName = "trialindexName";
	// no document type
	IndexDocumentTypeMessageVO indexDocumentTypeMessageVO = new IndexDocumentTypeMessageVO()
			.config(config).newIndexName(indexName)
			.documentType(documentType);
	assertEquals(0, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(null, actor.getIndexDocumentType());
	// parent Exception, NPE in data generator
	TestProbe testProbeParentActor = TestProbe.apply(system);
	String parentString = testProbeParentActor.ref().path().toString();
	actor.setParentActorPathString(parentString);
	ref.tell(indexDocumentTypeMessageVO, null);
	testProbeParentActor
			.expectMsgClass(DocumentTypeIndexingException.class);
	TestActor.Message testProbeParentActorMessage = testProbeParentActor
			.lastMessage();
	DocumentTypeIndexingException testProbeParentActorMessageType = (DocumentTypeIndexingException) testProbeParentActorMessage
			.msg();
	// doc type is not yet set
	assertEquals(documentType,
			testProbeParentActorMessageType.getIndexDocumentType());
}
 
Example 10
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 11
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 12
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 5 votes vote down vote up
@Test
public void handleIndexDocumentVOIndexData() {
	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);
	// This is controlled for doc generation, won;t change here.
	assertEquals(0, actor.getTotalDocumentsToIndex());
	ref.tell(indexDocumentVO, null);
	testProbeIndexDataWorker.expectMsgClass(IndexDocumentVO.class);
	TestActor.Message messageDocIndex = testProbeIndexDataWorker
			.lastMessage();
	IndexDocumentVO resultMsgDocIndex = (IndexDocumentVO) messageDocIndex
			.msg();
	assertEquals(config, resultMsgDocIndex.getConfig());
	assertEquals(documentType, resultMsgDocIndex.getDocumentType());
	assertEquals(indexName, resultMsgDocIndex.getNewIndexName());
	assertEquals(documentId, resultMsgDocIndex.getDocumentId());
	assertEquals(product, resultMsgDocIndex.getProduct());
	assertEquals(0, actor.getTotalDocumentsToIndex());
}
 
Example 13
Source File: AkkademyDbTest.java    From learning-akka with Apache License 2.0 5 votes vote down vote up
@Test
public void itShouldPlaceKeyValueFromSetMessageIntoMap() {
    TestActorRef<AkkademyDb> actorRef = TestActorRef.create(system, Props.create(AkkademyDb.class));
    actorRef.tell(new SetRequest("key", "value"), ActorRef.noSender());

    AkkademyDb akkademyDb = actorRef.underlyingActor();
    assertEquals(akkademyDb.map.get("key"), "value");
}
 
Example 14
Source File: ThingCommandEnforcementTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void init() {
    system = ActorSystem.create("test", ConfigFactory.load("test"));
    final TestActorRef<MockEntitiesActor> testActorRef =
            new TestActorRef<>(system, MockEntitiesActor.props(), system.guardian(), UUID.randomUUID().toString());
    mockEntitiesActorInstance = testActorRef.underlyingActor();
    mockEntitiesActor = testActorRef;
}
 
Example 15
Source File: PreEnforcementTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void init() {
    system = ActorSystem.create("test", ConfigFactory.load("test"));
    final TestActorRef<MockEntitiesActor> testActorRef =
            new TestActorRef<>(system, MockEntitiesActor.props(), system.guardian(), UUID
                    .randomUUID().toString());
    mockEntitiesActorInstance = testActorRef.underlyingActor();
    mockEntitiesActor = testActorRef;
}
 
Example 16
Source File: LiveSignalEnforcementTest.java    From ditto with Eclipse Public License 2.0 5 votes vote down vote up
@Before
public void init() {
    system = ActorSystem.create("test", ConfigFactory.load("test"));
    final TestActorRef<MockEntitiesActor> testActorRef =
            new TestActorRef<>(system, MockEntitiesActor.props(), system.guardian(), UUID.randomUUID().toString());
    mockEntitiesActorInstance = testActorRef.underlyingActor();
    mockEntitiesActor = testActorRef;
}
 
Example 17
Source File: MetricQueryServiceTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateDump() throws Exception {
	ActorSystem s = AkkaUtils.createLocalActorSystem(new Configuration());
	try {
		ActorRef serviceActor = MetricQueryService.startMetricQueryService(s, null, Long.MAX_VALUE);
		TestActorRef testActorRef = TestActorRef.create(s, Props.create(TestActor.class));
		TestActor testActor = (TestActor) testActorRef.underlyingActor();

		final Counter c = new SimpleCounter();
		final Gauge<String> g = () -> "Hello";
		final Histogram h = new TestHistogram();
		final Meter m = new TestMeter();

		final TaskManagerMetricGroup tm = UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup();

		MetricQueryService.notifyOfAddedMetric(serviceActor, c, "counter", tm);
		MetricQueryService.notifyOfAddedMetric(serviceActor, g, "gauge", tm);
		MetricQueryService.notifyOfAddedMetric(serviceActor, h, "histogram", tm);
		MetricQueryService.notifyOfAddedMetric(serviceActor, m, "meter", tm);
		serviceActor.tell(MetricQueryService.getCreateDump(), testActorRef);

		testActor.waitForResult();

		MetricDumpSerialization.MetricSerializationResult dump = testActor.getSerializationResult();

		assertTrue(dump.serializedCounters.length > 0);
		assertTrue(dump.serializedGauges.length > 0);
		assertTrue(dump.serializedHistograms.length > 0);
		assertTrue(dump.serializedMeters.length > 0);

		MetricQueryService.notifyOfRemovedMetric(serviceActor, c);
		MetricQueryService.notifyOfRemovedMetric(serviceActor, g);
		MetricQueryService.notifyOfRemovedMetric(serviceActor, h);
		MetricQueryService.notifyOfRemovedMetric(serviceActor, m);

		serviceActor.tell(MetricQueryService.getCreateDump(), testActorRef);

		testActor.waitForResult();

		MetricDumpSerialization.MetricSerializationResult emptyDump = testActor.getSerializationResult();

		assertEquals(0, emptyDump.serializedCounters.length);
		assertEquals(0, emptyDump.serializedGauges.length);
		assertEquals(0, emptyDump.serializedHistograms.length);
		assertEquals(0, emptyDump.serializedMeters.length);
	} finally {
		s.terminate();
	}
}
 
Example 18
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 4 votes vote down vote up
@Test
public void testConsumerRecreationFailureWhenConnected() throws JMSException {
    new TestKit(actorSystem) {{
        final Props props =
                AmqpClientActor.propsForTests(singleConsumerConnection(), getRef(), getRef(),
                        (ac, el) -> mockConnection);
        final TestActorRef<AmqpClientActor> amqpClientActorRef = TestActorRef.apply(props, actorSystem);
        final AmqpClientActor amqpClientActor = amqpClientActorRef.underlyingActor();

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

        // GIVEN: JMS session fails, but the JMS connection can create a new functional session
        final Session mockSession2 = Mockito.mock(Session.class);
        final MessageConsumer mockConsumer2 = Mockito.mock(JmsMessageConsumer.class);
        when(mockSession.createConsumer(any()))
                .thenThrow(new IllegalStateException("expected exception"));
        doReturn(mockSession2).when(mockConnection).createSession(anyInt());
        doReturn(mockConsumer2).when(mockSession2).createConsumer(any());

        // WHEN: consumer is closed and cannot be recreated
        final ActorRef amqpConsumerActor = amqpClientActor.context().children().toStream()
                .find(child -> child.path().name().startsWith(AmqpConsumerActor.ACTOR_NAME_PREFIX))
                .get();
        final Throwable error = new IllegalStateException("Forcibly detached");
        final Status.Failure failure = new Status.Failure(new AskTimeoutException("Consumer creation timeout"));
        amqpClientActor.connectionListener.onConsumerClosed(mockConsumer, error);
        verify(mockSession, atLeastOnce()).createConsumer(any());
        amqpConsumerActor.tell(failure, amqpConsumerActor);

        // THEN: connection gets restarted
        verify(mockConnection).createSession(anyInt());
        final ArgumentCaptor<MessageListener> captor = ArgumentCaptor.forClass(MessageListener.class);
        verify(mockConsumer2, timeout(1000).atLeastOnce()).setMessageListener(captor.capture());
        final MessageListener messageListener = captor.getValue();

        // THEN: recreated connection is working
        messageListener.onMessage(mockMessage());
        expectMsgClass(Command.class);
    }};
}
 
Example 19
Source File: SetupDocumentTypeWorkerActorTest.java    From searchanalytics-bigdata with MIT License 4 votes vote down vote up
@Test
public void handleFullFlow() {
	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 testProbeDataGeneratorWorker = TestProbe.apply(system);
	TestProbe testProbeDocumentGeneratorWorker = TestProbe.apply(system);
	TestProbe testProbeIndexDataWorker = TestProbe.apply(system);
	actor.setDataGeneratorWorkerRouter(testProbeDataGeneratorWorker.ref());
	actor.setDocumentGeneratorWorkerRouter(testProbeDocumentGeneratorWorker
			.ref());
	actor.setIndexDocumentWorkerRouter(testProbeIndexDataWorker.ref());
	ElasticSearchIndexConfig config = ElasticSearchIndexConfig.COM_WEBSITE;
	IndexDocumentType documentType = IndexDocumentType.PRODUCT;
	String indexName = "trialindexName";
	IndexDocumentTypeMessageVO indexDocumentTypeMessageVO = new IndexDocumentTypeMessageVO()
			.config(config).documentType(documentType)
			.newIndexName(indexName);
	assertEquals(0, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(null, actor.getIndexDocumentType());
	TestProbe testProbeOriginalSender = TestProbe.apply(system);
	ref.tell(indexDocumentTypeMessageVO, testProbeOriginalSender.ref());
	testProbeDataGeneratorWorker
			.expectMsgClass(IndexDocumentTypeMessageVO.class);
	TestActor.Message message = testProbeDataGeneratorWorker.lastMessage();
	IndexDocumentTypeMessageVO resultMsg = (IndexDocumentTypeMessageVO) message
			.msg();
	assertEquals(config, resultMsg.getConfig());
	assertEquals(documentType, resultMsg.getIndexDocumentType());
	assertEquals(indexName, resultMsg.getNewIndexName());
	// updated actor state
	assertEquals(0, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(documentType, actor.getIndexDocumentType());
	// Let's say total data to generate to 1
	ref.tell(Integer.valueOf(1), testProbeDataGeneratorWorker.ref());
	assertEquals(1, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(documentType, actor.getIndexDocumentType());
	Long documentId = 1l;
	IndexDocumentVO indexDocumentVO = new IndexDocumentVO()
			.config(resultMsg.getConfig())
			.documentType(indexDocumentTypeMessageVO.getIndexDocumentType())
			.newIndexName(indexDocumentTypeMessageVO.getNewIndexName())
			.documentId(documentId);
	// Send data back to the sender, generate document
	ref.tell(indexDocumentVO, testProbeDataGeneratorWorker.ref());
	testProbeDocumentGeneratorWorker.expectMsgClass(IndexDocumentVO.class);
	TestActor.Message messageDoc = testProbeDocumentGeneratorWorker
			.lastMessage();
	IndexDocumentVO resultMsgDoc = (IndexDocumentVO) messageDoc.msg();
	assertEquals(config, resultMsgDoc.getConfig());
	assertEquals(documentType, resultMsgDoc.getDocumentType());
	assertEquals(indexName, resultMsgDoc.getNewIndexName());
	assertEquals(documentId, resultMsgDoc.getDocumentId());
	assertEquals(1, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(documentType, actor.getIndexDocumentType());
	// send data back, index document.
	Product product = new Product();
	product.setId(documentId);
	resultMsgDoc.product(product);
	ref.tell(resultMsgDoc, testProbeDocumentGeneratorWorker.ref());
	testProbeIndexDataWorker.expectMsgClass(IndexDocumentVO.class);
	TestActor.Message messageDocIndex = testProbeIndexDataWorker
			.lastMessage();
	IndexDocumentVO resultMsgDocIndex = (IndexDocumentVO) messageDocIndex
			.msg();
	assertEquals(config, resultMsgDocIndex.getConfig());
	assertEquals(documentType, resultMsgDocIndex.getDocumentType());
	assertEquals(indexName, resultMsgDocIndex.getNewIndexName());
	assertEquals(documentId, resultMsgDocIndex.getDocumentId());
	assertEquals(product, resultMsgDocIndex.getProduct());
	assertEquals(1, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(documentType, actor.getIndexDocumentType());
	// Send back message, indexdone.
	resultMsgDocIndex.indexDone(true);
	TestProbe testProbeParent = TestProbe.apply(system);
	String string = testProbeParent.ref().path().toString();
	actor.setParentActorPathString(string);
	ref.tell(resultMsgDocIndex, null);
	// state is set back to initial and message sent to parent.
	testProbeParent.expectMsgClass(IndexDocumentType.class);
	TestActor.Message messageDocIndexDone = testProbeParent.lastMessage();
	IndexDocumentType resultMsgDocIndexDone = (IndexDocumentType) messageDocIndexDone
			.msg();
	// state reset
	assertEquals(documentType, resultMsgDocIndexDone);
	assertEquals(0, actor.getTotalDocumentsToIndex());
	assertEquals(0, actor.getTotalDocumentsToIndexDone());
	assertEquals(null, actor.getIndexDocumentType());
}
 
Example 20
Source File: MetricQueryServiceTest.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
@Test
public void testHandleOversizedMetricMessage() throws Exception {
	ActorSystem s = AkkaUtils.createLocalActorSystem(new Configuration());
	try {
		final long sizeLimit = 200L;
		ActorRef serviceActor = MetricQueryService.startMetricQueryService(s, null, sizeLimit);
		TestActorRef testActorRef = TestActorRef.create(s, Props.create(TestActor.class));
		TestActor testActor = (TestActor) testActorRef.underlyingActor();

		final TaskManagerMetricGroup tm = UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup();

		final String gaugeValue = "Hello";
		final long requiredGaugesToExceedLimit = sizeLimit / gaugeValue.length() + 1;
		List<Tuple2<String, Gauge<String>>> gauges = LongStream.range(0, requiredGaugesToExceedLimit)
			.mapToObj(x -> Tuple2.of("gauge" + x, (Gauge<String>) () -> "Hello" + x))
			.collect(Collectors.toList());
		gauges.forEach(gauge -> MetricQueryService.notifyOfAddedMetric(serviceActor, gauge.f1, gauge.f0, tm));

		MetricQueryService.notifyOfAddedMetric(serviceActor, new SimpleCounter(), "counter", tm);
		MetricQueryService.notifyOfAddedMetric(serviceActor, new TestHistogram(), "histogram", tm);
		MetricQueryService.notifyOfAddedMetric(serviceActor, new TestMeter(), "meter", tm);

		serviceActor.tell(MetricQueryService.getCreateDump(), testActorRef);
		testActor.waitForResult();

		MetricDumpSerialization.MetricSerializationResult dump = testActor.getSerializationResult();

		assertTrue(dump.serializedCounters.length > 0);
		assertEquals(1, dump.numCounters);
		assertTrue(dump.serializedMeters.length > 0);
		assertEquals(1, dump.numMeters);

		// gauges exceeded the size limit and will be excluded
		assertEquals(0, dump.serializedGauges.length);
		assertEquals(0, dump.numGauges);

		assertTrue(dump.serializedHistograms.length > 0);
		assertEquals(1, dump.numHistograms);

		// unregister all but one gauge to ensure gauges are reported again if the remaining fit
		for (int x = 1; x < gauges.size(); x++) {
			MetricQueryService.notifyOfRemovedMetric(serviceActor, gauges.get(x).f1);
		}

		serviceActor.tell(MetricQueryService.getCreateDump(), testActorRef);
		testActor.waitForResult();

		MetricDumpSerialization.MetricSerializationResult recoveredDump = testActor.getSerializationResult();

		assertTrue(recoveredDump.serializedCounters.length > 0);
		assertEquals(1, recoveredDump.numCounters);
		assertTrue(recoveredDump.serializedMeters.length > 0);
		assertEquals(1, recoveredDump.numMeters);
		assertTrue(recoveredDump.serializedGauges.length > 0);
		assertEquals(1, recoveredDump.numGauges);
		assertTrue(recoveredDump.serializedHistograms.length > 0);
		assertEquals(1, recoveredDump.numHistograms);
	} finally {
		s.terminate();
	}
}