akka.testkit.javadsl.TestKit Java Examples

The following examples show how to use akka.testkit.javadsl.TestKit. 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: UserExternalIdManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testUpsertUserExternalIdentityDetailsAddSuccess() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);

  Request request = new Request();
  request.setOperation(UserActorOperations.UPSERT_USER_EXTERNAL_IDENTITY_DETAILS.getValue());

  HashMap<String, Object> innerMap = new HashMap<>();
  innerMap.put(JsonKey.OPERATION_TYPE, "UPDATE");

  List<Map<String, Object>> list = new ArrayList<>();
  Map<String, Object> extIdMap = new HashMap<>();
  extIdMap.put(JsonKey.OPERATION, "ADD");
  extIdMap.put(JsonKey.ID_TYPE, "anyIdType");
  extIdMap.put(JsonKey.PROVIDER, "anyProvider");
  list.add(extIdMap);
  innerMap.put(JsonKey.EXTERNAL_IDS, list);
  request.setRequest(innerMap);

  subject.tell(request, probe.getRef());
  Response response = probe.expectMsgClass(duration("100 second"), Response.class);
  Assert.assertTrue(null != response && response.getResponseCode() == ResponseCode.OK);
}
 
Example #2
Source File: SystemSettingsActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Before
public void setUp() {
  system = ActorSystem.create("system");
  probe = new TestKit(system);
  PowerMockito.mockStatic(ServiceFactory.class);
  cassandraOperation = PowerMockito.mock(CassandraOperationImpl.class);
  when(ServiceFactory.getInstance()).thenReturn(cassandraOperation);
  props = Props.create(SystemSettingsActor.class);
  subject = system.actorOf(props);
  actorMessage = new Request();
  PowerMockito.mockStatic(EsClientFactory.class);
  esUtil = PowerMockito.mock(ElasticSearchRestHighImpl.class);
  Response resp = new Response();
  List<Map<String, Object>> list = new ArrayList<>();
  list.add(getOrgData());
  resp.put(JsonKey.RESPONSE, list);
  when(cassandraOperation.getRecordsByIndexedProperty(
          KEYSPACE_NAME, TABLE_NAME, JsonKey.FIELD, ROOT_ORG_ID))
      .thenReturn(resp);
  when(cassandraOperation.getRecordsByIndexedProperty(
          KEYSPACE_NAME, TABLE_NAME, JsonKey.FIELD, KEYSPACE_NAME))
      .thenReturn(new Response());
}
 
Example #3
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 #4
Source File: GeoLocationManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void createGeoLocationFailureWithInvalidData() {

  List<Map<String, Object>> dataList = new ArrayList<>();

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();

  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, userId);
  actorMessage.setOperation(ActorOperations.CREATE_GEO_LOCATION.getValue());

  actorMessage.getRequest().put(JsonKey.DATA, dataList);
  actorMessage.getRequest().put(JsonKey.ROOT_ORG_ID, orgId);

  subject.tell(actorMessage, probe.getRef());
  ProjectCommonException exc =
      probe.expectMsgClass(duration("10 second"), ProjectCommonException.class);
  assertTrue(exc.getCode().equals(ResponseCode.invalidRequestData.getErrorCode()));
}
 
Example #5
Source File: ThingsUpdaterTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void forwardUpdateThingOnCommand() {
    new TestKit(actorSystem) {{
        final DittoHeaders dittoHeaders = DittoHeaders.newBuilder().randomCorrelationId().build();
        final ActorRef underTest = createThingsUpdater();
        final Collection<NamespacedEntityId> thingIds = IntStream.range(0, 10)
                .mapToObj(i -> ThingId.of("a:" + i))
                .collect(Collectors.toList());
        underTest.tell(ThingsOutOfSync.of(thingIds, dittoHeaders), getRef());

        // command order not guaranteed due to namespace blocking
        final Set<EntityId> expectedIds = new HashSet<>(thingIds);
        for (final NamespacedEntityId ignored : thingIds) {
            final ShardedMessageEnvelope envelope =
                    shardMessageReceiver.expectMsgClass(ShardedMessageEnvelope.class);
            final EntityId envelopeId = envelope.getEntityId();
            assertThat(expectedIds).contains(envelopeId);
            expectedIds.remove(envelopeId);
            assertThat(envelope.getDittoHeaders()).isEqualTo(dittoHeaders);
            assertThat(envelope.getMessage())
                    .isEqualTo(UpdateThing.of(ThingId.of(envelopeId), dittoHeaders).toJson());
        }
    }};
}
 
Example #6
Source File: AbstractPersistentActorWithTimersAndCleanupTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testDeleteMessagesFails() {
    new TestKit(actorSystem) {{
        // GIVEN: persistence actor with some messages and snapshots
        final ActorRef persistenceActor = childActorOf(DummyPersistentActor.props(FAIL_DELETE_MESSAGE));

        modifyDummyAndWaitForSnapshotSuccess(this, persistenceActor, 8);

        persistenceActor.tell(CleanupPersistence.of(DefaultEntityId.of(FAIL_DELETE_MESSAGE), DittoHeaders.empty()), getRef());
        final CleanupCommandResponse cleanupCommandResponse = expectMsgClass(CleanupCommandResponse.class);

        assertThat(cleanupCommandResponse.getStatusCode()).isEqualTo(HttpStatusCode.INTERNAL_SERVER_ERROR);

        verifyPersistencePluginCalledWithCorrectArguments(FAIL_DELETE_MESSAGE, 4);
    }};
}
 
Example #7
Source File: GeoLocationManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void sendNotificationGeoLocationSuccess() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();

  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, userId);
  actorMessage.getRequest().put(JsonKey.LOCATION, "updated location");
  actorMessage.getRequest().put(JsonKey.TYPE, type);
  actorMessage.getRequest().put(JsonKey.LOCATION_ID, id);
  actorMessage.setOperation(ActorOperations.SEND_NOTIFICATION.getValue());

  subject.tell(actorMessage, probe.getRef());
  Response res = probe.expectMsgClass(duration("100 second"), Response.class);
  Assert.assertTrue(null != res.get(JsonKey.RESPONSE));
}
 
Example #8
Source File: LiveSignalEnforcementTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rejectLiveThingCommandByPolicy() {
    final PolicyId policyId = PolicyId.of("empty", "policy");
    final JsonObject thingWithEmptyPolicy = newThingWithPolicyId(policyId);
    final JsonObject emptyPolicy = PoliciesModelFactory.newPolicyBuilder(policyId)
            .setRevision(1L)
            .build()
            .toJson(FieldType.all());
    final SudoRetrieveThingResponse sudoRetrieveThingResponse =
            SudoRetrieveThingResponse.of(thingWithEmptyPolicy, DittoHeaders.empty());
    final SudoRetrievePolicyResponse sudoRetrievePolicyResponse =
            SudoRetrievePolicyResponse.of(policyId, emptyPolicy, DittoHeaders.empty());

    new TestKit(system) {{
        mockEntitiesActorInstance.setReply(THING_SUDO, sudoRetrieveThingResponse);
        mockEntitiesActorInstance.setReply(POLICY_SUDO, sudoRetrievePolicyResponse);

        final ActorRef underTest = newEnforcerActor(getRef());
        underTest.tell(readCommand(), getRef());
        fishForMsgClass(this, ThingNotAccessibleException.class);

        underTest.tell(writeCommand(), getRef());
        expectMsgClass(FeatureNotModifiableException.class);
    }};
}
 
Example #9
Source File: ThingUpdaterTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void policyIdChangeTriggersSync() {
    final PolicyId policyId1 = PolicyId.of("policy", "1");
    final PolicyId policyId2 = PolicyId.of("policy", "2");

    new TestKit(actorSystem) {
        {
            final ActorRef underTest = createThingUpdaterActor();

            // establish policy ID
            underTest.tell(PolicyReferenceTag.of(THING_ID, PolicyTag.of(policyId1, 99L)),
                    ActorRef.noSender());
            changeQueueTestProbe.expectMsg(Metadata.of(THING_ID, -1L, policyId1, 99L));

            underTest.tell(PolicyReferenceTag.of(THING_ID, PolicyTag.of(policyId2, 9L)),
                    ActorRef.noSender());
            changeQueueTestProbe.expectMsg(Metadata.of(THING_ID, -1L, policyId2, 9L));
        }
    };
}
 
Example #10
Source File: HiveMqtt3ClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testSubscribeFails() {
    new TestKit(actorSystem) {{
        final MockHiveMqtt3ClientFactory clientFactory = mockHiveMqtt3ClientFactory
                .withTestProbe(getRef())
                .withFailingSubscribe();

        final Props props = HiveMqtt3ClientActor.props(connection, getRef(), getRef(), clientFactory);
        final ActorRef mqttClientActor = actorSystem.actorOf(props, "mqttClientActor-testSubscribeFails");

        mqttClientActor.tell(OpenConnection.of(connectionId, DittoHeaders.empty()), getRef());
        expectMsgClass(Status.Failure.class);

        mqttClientActor.tell(CloseConnection.of(connectionId, DittoHeaders.empty()), getRef());
        expectMsg(DISCONNECTED_SUCCESS);
    }};
}
 
Example #11
Source File: ThingUpdaterTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void policyReferenceTagTriggersPolicyUpdate() {
    final long newPolicyRevision = REVISION + 2L;
    new TestKit(actorSystem) {
        {
            final ActorRef underTest = createThingUpdaterActor();

            final PolicyId policyId = PolicyId.of(THING_ID);
            underTest.tell(PolicyReferenceTag.of(THING_ID, PolicyTag.of(policyId, newPolicyRevision)),
                    ActorRef.noSender());
            changeQueueTestProbe.expectMsg(Metadata.of(THING_ID, -1L, policyId, newPolicyRevision));

            underTest.tell(PolicyReferenceTag.of(THING_ID, PolicyTag.of(policyId, REVISION)),
                    ActorRef.noSender());
            changeQueueTestProbe.expectNoMessage();
        }
    };
}
 
Example #12
Source File: AriEventProcessingTest.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
@Test
void verifyGetCallContextWorksAsExpected() {
	new TestKit(system)
	{
		{
			final Future<Try<String>> callContext = Future.of(() -> AriEventProcessing.getCallContext("RESOURCE_ID", getRef(),
					ProviderPolicy.CREATE_IF_MISSING));

			final ProvideCallContext provideCallContext = expectMsgClass(ProvideCallContext.class);

			assertThat(provideCallContext.policy(), is(ProviderPolicy.CREATE_IF_MISSING));
			assertThat(provideCallContext.resourceId(), is("RESOURCE_ID"));
			reply(new CallContextProvided("CALL_CONTEXT"));

			assertThat(callContext.await().get().get(), is("CALL_CONTEXT"));
		}
	};
}
 
Example #13
Source File: TenantPreferenceManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testUpdateTanentPreferenceSuccessWithDifferentKey() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();
  List<Map<String, Object>> reqList = new ArrayList<>();

  Map<String, Object> map = new HashMap<>();
  map.put(JsonKey.KEY, "differentKey");
  map.put(JsonKey.DATA, "anyData");
  reqList.add(map);

  actorMessage.getRequest().put(JsonKey.TENANT_PREFERENCE, reqList);
  actorMessage.getRequest().put(JsonKey.ROOT_ORG_ID, orgId);
  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, USER_ID);
  actorMessage.setOperation(ActorOperations.UPDATE_TENANT_PREFERENCE.getValue());

  subject.tell(actorMessage, probe.getRef());
  Response res = probe.expectMsgClass(duration("10 second"), Response.class);
  Assert.assertTrue(null != res.get(JsonKey.RESPONSE));
}
 
Example #14
Source File: GeoLocationManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void updateGeoLocationSuccess() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();

  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, userId);
  actorMessage.getRequest().put(JsonKey.LOCATION, "updated location");
  actorMessage.getRequest().put(JsonKey.TYPE, type);
  actorMessage.getRequest().put(JsonKey.LOCATION_ID, id);
  actorMessage.setOperation(ActorOperations.UPDATE_GEO_LOCATION.getValue());

  subject.tell(actorMessage, probe.getRef());
  Response res = probe.expectMsgClass(duration("100 second"), Response.class);
  Assert.assertTrue(null != res.get(JsonKey.RESPONSE));
}
 
Example #15
Source File: GeoLocationManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void createGeoLocationFailureWithNullOrgId() {

  List<Map<String, Object>> dataList = new ArrayList<>();

  Map<String, Object> dataMap = new HashMap<>();
  dataMap.put(JsonKey.LOCATION, "location");
  dataMap.put(JsonKey.TYPE, type);

  dataList.add(dataMap);

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();

  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, userId);
  actorMessage.setOperation(ActorOperations.CREATE_GEO_LOCATION.getValue());

  actorMessage.getRequest().put(JsonKey.DATA, dataList);
  actorMessage.getRequest().put(JsonKey.ROOT_ORG_ID, null);

  subject.tell(actorMessage, probe.getRef());
  ProjectCommonException exc =
      probe.expectMsgClass(duration("10 second"), ProjectCommonException.class);
  assertTrue(exc.getCode().equals(ResponseCode.invalidOrgId.getErrorCode()));
}
 
Example #16
Source File: DefaultPersistenceStreamingActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void retrieveNonEmptyStream() {
    new TestKit(actorSystem) {{
        final Source<String, NotUsed> mockedSource = Source.single(ID.toString());
        final ActorRef underTest = createPersistenceQueriesActor(mockedSource);
        final Command<?> command = createStreamingRequest();

        sendCommand(this, underTest, command);

        final SourceRef<Object> sourceRef = expectMsgClass(SourceRef.class);

        final Object expectedMessage =
                BatchedEntityIdWithRevisions.of(SimpleEntityIdWithRevision.class,
                        Collections.singletonList(new SimpleEntityIdWithRevision(ID, 0L)));

        sourceRef.getSource()
                .runWith(TestSink.probe(actorSystem), materializer())
                .request(1000L)
                .expectNext(expectedMessage)
                .expectComplete();
    }};
}
 
Example #17
Source File: GeoLocationManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void getGeoLocationFailureWithInvalidType() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();

  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, userId);
  actorMessage.getRequest().put(JsonKey.TYPE, "Invalid type");
  actorMessage.getRequest().put(JsonKey.ID, orgId);
  actorMessage.setOperation(ActorOperations.GET_GEO_LOCATION.getValue());

  actorMessage.getRequest().put(JsonKey.ROOT_ORG_ID, orgId);

  subject.tell(actorMessage, probe.getRef());

  ProjectCommonException exc =
      probe.expectMsgClass(duration("10 second"), ProjectCommonException.class);
  assertTrue(exc.getCode().equals(ResponseCode.invalidTypeValue.getErrorCode()));
}
 
Example #18
Source File: RabbitMQClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testReconnection() {
    new TestKit(actorSystem) {{
        final Props props = createClientActor(getRef(), getConnection(false));
        final ActorRef rabbitClientActor = actorSystem.actorOf(props);

        // reconnect a few times
        for (int i = 0; i < 3; ++i) {
            rabbitClientActor.tell(OpenConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
            expectMsg(CONNECTED_SUCCESS);

            rabbitClientActor.tell(CloseConnection.of(CONNECTION_ID, DittoHeaders.empty()), getRef());
            expectMsg(DISCONNECTED_SUCCESS);
        }
    }};
}
 
Example #19
Source File: UserProfileActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testSetProfileVisibilitySuccess() {
  final String userId = "USER-ID";
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Promise<Map<String, Object>> promise = Futures.promise();
  promise.success(createGetResponse(true));
  when(esUtil.getDataByIdentifier(ProjectUtil.EsType.user.getTypeName(), userId))
      .thenReturn(promise.future());
  when(ElasticSearchHelper.getResponseFromFuture(Mockito.any()))
      .thenReturn(createGetResponse(true));
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.PROFILE_VISIBILITY.getValue());
  reqObj.put(JsonKey.USER_ID, userId);
  subject.tell(reqObj, probe.getRef());
  Response res = probe.expectMsgClass(duration("10 second"), Response.class);
  Assert.assertTrue(null != res && res.getResponseCode() == ResponseCode.OK);
}
 
Example #20
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 #21
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 #22
Source File: ThingPersistenceActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void createThingInV1AndUpdateWithV2WithoutPolicyId() {
    final ThingId thingId = ThingId.of("test.ns.v1", "createThingInV1AndUpdateWithV2WithoutPolicyId");
    final Thing thingV1 = buildThing(thingId, JsonSchemaVersion.V_1);
    final Thing thingV2WithoutPolicyId = buildThing(thingId, JsonSchemaVersion.V_2)
            .toBuilder()
            .removePolicyId()
            .build();
    new TestKit(actorSystem) {{

        testCreateAndModify(thingV1,
                JsonSchemaVersion.V_1,
                thingV2WithoutPolicyId,
                JsonSchemaVersion.V_2,
                this,
                modifyThing -> PolicyIdMissingException.fromThingIdOnUpdate(thingId,
                        appendETagToDittoHeaders(thingV2WithoutPolicyId, modifyThing.getDittoHeaders())));
        expectNoMessage();
    }};
}
 
Example #23
Source File: TenantPreferenceManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testUpdateTanentPreferenceSuccessWithoutKeyValue() {

  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request actorMessage = new Request();
  List<Map<String, Object>> reqList = new ArrayList<>();

  Map<String, Object> map = new HashMap<>();
  map.put(JsonKey.ROLE, "admin");
  reqList.add(map);

  actorMessage.getRequest().put(JsonKey.TENANT_PREFERENCE, reqList);
  actorMessage.getRequest().put(JsonKey.ROOT_ORG_ID, orgId);
  actorMessage.getRequest().put(JsonKey.REQUESTED_BY, USER_ID);
  actorMessage.setOperation(ActorOperations.UPDATE_TENANT_PREFERENCE.getValue());

  subject.tell(actorMessage, probe.getRef());
  Response res = probe.expectMsgClass(duration("10 second"), Response.class);
  Assert.assertTrue(null != res.get(JsonKey.RESPONSE));
}
 
Example #24
Source File: ConnectionPersistenceActorRecoveryTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testRecoveryOfConnectionWithBlacklistedHost() {

    // enable blacklist for this test
    when(blacklistedHosts.unwrapped()).thenReturn("127.0.0.1");

    new TestKit(actorSystem) {{

        final Queue<ConnectivityEvent> existingEvents = new LinkedList<>(List.of(connectionCreated));
        final Props fakeProps = FakePersistenceActor.props(connectionId, getRef(), existingEvents);

        actorSystem.actorOf(fakeProps);
        expectMsgEquals("persisted");

        final ActorRef underTest = TestConstants.createConnectionSupervisorActor(connectionId, actorSystem,
                pubSubMediator, conciergeForwarder);

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

        final ConnectionConfigurationInvalidException exception =
                expectMsgClass(ConnectionConfigurationInvalidException.class);
        assertThat(exception)
                .hasMessageContaining("The configured host '127.0.0.1' may not be used for the connection");
    }};
}
 
Example #25
Source File: BulkUploadManagementActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testBulkUploadGetStatus() {
  Response response = getCassandraRecordByIdForBulkUploadResponse();
  when(cassandraOperation.getRecordById(
          Mockito.anyString(), Mockito.anyString(), Mockito.anyString(), Mockito.anyList()))
      .thenReturn(response);
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.GET_BULK_OP_STATUS.getValue());
  reqObj.getRequest().put(JsonKey.PROCESS_ID, PROCESS_ID);
  subject.tell(reqObj, probe.getRef());
  Response res = probe.expectMsgClass(duration("10 second"), Response.class);
  List<Map<String, Object>> list = (List<Map<String, Object>>) res.get(JsonKey.RESPONSE);
  if (!list.isEmpty()) {
    Map<String, Object> map = list.get(0);
    String processId = (String) map.get(JsonKey.PROCESS_ID);
    Assert.assertTrue(null != processId);
  }
}
 
Example #26
Source File: ThingCommandEnforcementTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rejectCreateByOwnPolicy() {
    final PolicyId policyId = PolicyId.of("empty:policy");
    final Policy policy = PoliciesModelFactory.newPolicyBuilder(policyId)
            .forLabel("dummy")
            .setSubject(GOOGLE, "not-subject")
            .setGrantedPermissions(PoliciesResourceType.policyResource("/"), READ.name(), WRITE.name())
            .build();
    final Thing thing = newThing().build();

    new TestKit(system) {{
        mockEntitiesActorInstance.setReply(THING_SUDO,
                ThingNotAccessibleException.newBuilder(THING_ID).build());

        final ActorRef underTest = newEnforcerActor(getRef());
        final CreateThing createThing = CreateThing.of(thing, policy.toJson(), headers(V_2));
        underTest.tell(createThing, getRef());
        fishForMsgClass(this, ThingNotModifiableException.class);
    }};

}
 
Example #27
Source File: ThingUpdaterTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void acknowledgesSkippedSync() {
    final long thingTagRevision = 59L;
    final long outdatedRevision = 5L;

    new TestKit(actorSystem) {
        {
            final ActorRef underTest = createThingUpdaterActor();

            // GIVEN: a ThingTag with nonempty sender triggered synchronization
            final ThingTag thingTag = ThingTag.of(THING_ID, thingTagRevision);
            underTest.tell(thingTag, getRef());
            expectMsgEquals(StreamAck.success(thingTag.asIdentifierString()));
            changeQueueTestProbe.expectMsgClass(Metadata.class);

            // WHEN: updater receives outdated ThingTag
            final ThingTag outdatedThingTag = ThingTag.of(THING_ID, outdatedRevision);
            underTest.tell(outdatedThingTag, getRef());

            // THEN: success is acknowledged
            expectMsgEquals(StreamAck.success(outdatedThingTag.asIdentifierString()));
        }
    };
}
 
Example #28
Source File: DbOperationActorTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testA5Search() {
  TestKit probe = new TestKit(system);
  ActorRef subject = system.actorOf(props);
  Request reqObj = new Request();
  reqObj.setOperation(ActorOperations.SEARCH_DATA.getValue());
  Map<String, Object> map = new HashMap<>();
  map.put("entityName", "announcement");
  List<String> list = new ArrayList<>();
  list.add("id");
  map.put("requiredFields", list);
  Map<String, Object> filter = new HashMap<>();
  map.put(JsonKey.FILTERS, filter);
  reqObj.setRequest(map);
  subject.tell(reqObj, probe.getRef());
  Response res = probe.expectMsgClass(duration("20 second"), Response.class);
  Assert.assertTrue(null != res.get(JsonKey.RESPONSE));
}
 
Example #29
Source File: ThingCommandEnforcementTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void rejectByAcl() {
    final JsonObject thingWithEmptyAcl = newThing()
            .setPermissions(AccessControlList.newBuilder().build())
            .build()
            .toJson(V_1, FieldType.all());
    final SudoRetrieveThingResponse response =
            SudoRetrieveThingResponse.of(thingWithEmptyAcl, DittoHeaders.empty());

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

        final ActorRef underTest = newEnforcerActor(getRef());
        underTest.tell(getReadCommand(), getRef());
        fishForMsgClass(this, ThingNotAccessibleException.class);

        underTest.tell(getModifyCommand(), getRef());
        expectMsgClass(FeatureNotModifiableException.class);
    }};
}
 
Example #30
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void testCloseConnectionFails() throws JMSException {
    new TestKit(actorSystem) {{
        doThrow(JMS_EXCEPTION).when(mockConnection).close();
        final Props props =
                AmqpClientActor.propsForTests(connection, getRef(),
                        getRef(), (ac, el) -> mockConnection);
        final ActorRef amqpClientActor = actorSystem.actorOf(props);

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

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