예제 #1
0
  @Test
  public void cancelInOnMessageShouldInvokeStreamCancel() throws Exception {
    final ClientCallImpl<Void, Void> call =
        new ClientCallImpl<Void, Void>(
            DESCRIPTOR,
            MoreExecutors.directExecutor(),
            CallOptions.DEFAULT,
            provider,
            deadlineCancellationExecutor);
    final Exception cause = new Exception();
    ClientCall.Listener<Void> callListener =
        new ClientCall.Listener<Void>() {
          @Override
          public void onMessage(Void message) {
            call.cancel("foo", cause);
          }
        };

    call.start(callListener, new Metadata());
    call.halfClose();
    call.request(1);

    verify(stream).start(listenerArgumentCaptor.capture());
    ClientStreamListener streamListener = listenerArgumentCaptor.getValue();
    streamListener.onReady();
    streamListener.headersRead(new Metadata());
    streamListener.messageRead(new ByteArrayInputStream(new byte[0]));
    verify(stream).cancel(statusCaptor.capture());
    Status status = statusCaptor.getValue();
    assertEquals(Status.CANCELLED.getCode(), status.getCode());
    assertEquals("foo", status.getDescription());
    assertSame(cause, status.getCause());
  }
  @Test
  public void delete_characteristic() {
    DbSession batchSession = mock(DbSession.class);
    when(dbClient.openSession(true)).thenReturn(batchSession);

    when(ruleDao.findRulesByDebtSubCharacteristicId(batchSession, subCharacteristicDto.getId()))
        .thenReturn(
            newArrayList(
                new RuleDto()
                    .setSubCharacteristicId(subCharacteristicDto.getId())
                    .setRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.toString())
                    .setRemediationCoefficient("2h")
                    .setRemediationOffset("5min")));
    when(dao.selectCharacteristicsByParentId(1, batchSession))
        .thenReturn(newArrayList(subCharacteristicDto));
    when(dao.selectById(1, batchSession)).thenReturn(characteristicDto);

    service.delete(1);

    verify(ruleDao).update(eq(batchSession), ruleCaptor.capture());

    verify(dao, times(2)).update(characteristicCaptor.capture(), eq(batchSession));
    CharacteristicDto subCharacteristicDto = characteristicCaptor.getAllValues().get(0);
    CharacteristicDto characteristicDto = characteristicCaptor.getAllValues().get(1);

    // Sub characteristic is disable
    assertThat(subCharacteristicDto.getId()).isEqualTo(2);
    assertThat(subCharacteristicDto.isEnabled()).isFalse();
    assertThat(subCharacteristicDto.getUpdatedAt()).isEqualTo(now);

    // Characteristic is disable
    assertThat(characteristicDto.getId()).isEqualTo(1);
    assertThat(characteristicDto.isEnabled()).isFalse();
    assertThat(characteristicDto.getUpdatedAt()).isEqualTo(now);
  }
예제 #3
0
  @Test
  public void testRefreshMetaData() throws Exception {
    prepare(RefreshMetaDataCommand.class, GetMetaDataCommand.class);

    // failure tests
    pushToOutput("refreshMetaData");
    Assert.assertTrue(stream.toString().contains("No active Artificer artifact exists"));

    // populate the context
    pushToOutput("getMetaData --uuid %s", artifact.getUuid());

    // success tests
    pushToOutput("refreshMetaData");
    ArgumentCaptor<ArtifactType> type = ArgumentCaptor.forClass(ArtifactType.class);
    ArgumentCaptor<String> uuid = ArgumentCaptor.forClass(String.class);
    Mockito.verify(clientMock, Mockito.times(1))
        .getArtifactMetaData(type.capture(), uuid.capture());
    Assert.assertEquals(
        artifact.getArtifactType().value(), type.getValue().getArtifactType().getApiType().value());
    Assert.assertEquals(artifact.getUuid(), uuid.getValue());

    Assert.assertTrue(stream.toString().contains("Successfully refreshed meta-data for artifact"));
    Assert.assertTrue(stream.toString().contains("Type: " + artifactType.getType()));
    Assert.assertTrue(stream.toString().contains("Model: " + artifactType.getModel()));
    Assert.assertTrue(stream.toString().contains("UUID: " + artifact.getUuid()));
  }
  @Test
  public void testGetUpdatedObjects() throws Exception {
    SalesforceConnector connector = Mockito.spy(new SalesforceConnector());
    connector.setConnection(connection);
    when(connection.getConfig()).thenReturn(createConnectorConfig("userX"));
    connector.setObjectStoreHelper(objectStoreHelper);
    Calendar lastUpdateTime = createCalendar(4, 15);
    when(objectStoreHelper.getTimestamp("Account")).thenReturn(lastUpdateTime);
    setServerTime(connection, 5, 15);

    when(connection.getUpdated(anyString(), any(Calendar.class), any(Calendar.class)))
        .thenReturn(getUpdatedResult);
    Calendar latestDateCovered = createCalendar(5, 10);
    when(getUpdatedResult.getLatestDateCovered()).thenReturn(latestDateCovered);
    when(getUpdatedResult.getIds()).thenReturn(new String[] {"1", "3"});

    List<Map<String, Object>> updatedObjects = new ArrayList<Map<String, Object>>();
    doReturn(updatedObjects)
        .when(connector)
        .retrieve("Account", Arrays.asList("1", "3"), Arrays.asList("Id", "Name"));

    assertSame(
        updatedObjects, connector.getUpdatedObjects("Account", 60, Arrays.asList("Id", "Name")));

    verify(connection)
        .getUpdated(eq("Account"), startTimeCaptor.capture(), endTimeCaptor.capture());
    assertStartTime(4, 15);
    assertEndTime(5, 15);
    verify(objectStoreHelper).updateTimestamp(getUpdatedResult, "Account");
  }
예제 #5
0
  private void testUpdateCreate(boolean edit) throws ClassNotFoundException {
    final DateTime dtValue = DateUtil.now();

    mockSampleFields();
    mockDataService();
    mockEntity();
    when(motechDataService.retrieve("id", INSTANCE_ID)).thenReturn(new TestSample());

    List<FieldRecord> fieldRecords =
        asList(
            FieldTestHelper.fieldRecord("strField", String.class.getName(), "", "this is a test"),
            FieldTestHelper.fieldRecord("intField", Integer.class.getName(), "", 16),
            FieldTestHelper.fieldRecord("timeField", Time.class.getName(), "", "10:17"),
            FieldTestHelper.fieldRecord("dtField", DateTime.class.getName(), "", dtValue));

    Long id = (edit) ? INSTANCE_ID : null;
    EntityRecord record = new EntityRecord(id, ENTITY_ID, fieldRecords);

    MDSClassLoader.getInstance().loadClass(TestSample.class.getName());
    instanceService.saveInstance(record);

    ArgumentCaptor<TestSample> captor = ArgumentCaptor.forClass(TestSample.class);
    if (edit) {
      verify(motechDataService).update(captor.capture());
    } else {
      verify(motechDataService).create(captor.capture());
    }

    TestSample sample = captor.getValue();
    assertEquals("this is a test", sample.getStrField());
    assertEquals(Integer.valueOf(16), sample.getIntField());
    assertEquals(new Time(10, 17), sample.getTimeField());
    assertEquals(dtValue, sample.getDtField());
  }
  @Test
  public void testStatusUpdatingMessageHandler() {
    TimelineOperations timelineOperations = Mockito.mock(TimelineOperations.class);
    Mockito.when(this.twitter.timelineOperations()).thenReturn(timelineOperations);

    ArgumentCaptor<TweetData> argument = ArgumentCaptor.forClass(TweetData.class);

    this.in1.send(new GenericMessage<String>("foo"));

    Mockito.verify(timelineOperations).updateStatus(argument.capture());
    assertEquals("foo", argument.getValue().toRequestParameters().getFirst("status"));

    Mockito.reset(timelineOperations);

    ClassPathResource media = new ClassPathResource("log4j.properties");
    this.in2.send(
        MessageBuilder.withPayload(Collections.singletonMap("foo", "bar"))
            .setHeader("media", media)
            .build());

    Mockito.verify(timelineOperations).updateStatus(argument.capture());
    TweetData tweetData = argument.getValue();
    MultiValueMap<String, Object> requestParameters = tweetData.toRequestParameters();
    assertEquals("bar", requestParameters.getFirst("status"));
    assertNull(requestParameters.getFirst("media"));
    MultiValueMap<String, Object> uploadMediaParameters = tweetData.toUploadMediaParameters();
    assertEquals(media, uploadMediaParameters.getFirst("media"));
  }
  @Test
  @SuppressWarnings("unchecked")
  public void shouldSetAnyOtherExceptionResponse() throws Exception {

    // Given
    Request request = mock(Request.class);
    Response response = mock(Response.class);
    Exception exception = new Exception("MESSAGE");
    Status status = new Status(444, exception);

    given(response.getStatus()).willReturn(status);

    // When
    exceptionFilter.afterHandle(request, response);

    // Then
    ArgumentCaptor<JacksonRepresentation> exceptionResponseCaptor =
        ArgumentCaptor.forClass(JacksonRepresentation.class);
    verify(response).setEntity(exceptionResponseCaptor.capture());
    Map<String, String> responseBody =
        (Map<String, String>) exceptionResponseCaptor.getValue().getObject();
    assertThat(responseBody)
        .containsOnly(entry("error", "server_error"), entry("error_description", "MESSAGE"));

    ArgumentCaptor<Status> statusCaptor = ArgumentCaptor.forClass(Status.class);
    verify(response).setStatus(statusCaptor.capture());
    assertThat(statusCaptor.getValue().getCode()).isEqualTo(500);
    assertThat(statusCaptor.getValue().getThrowable()).isEqualTo(exception);
  }
  @Test
  public void testCreate() throws Exception {
    String input = "exec native('create;id=pk;type=table;attributes=one,two,three', 'one', 2, 3.0)";

    TranslationUtility util = FakeTranslationFactory.getInstance().getExampleTranslationUtility();
    Command command = util.parseCommand(input);
    ExecutionContext ec = Mockito.mock(ExecutionContext.class);
    RuntimeMetadata rm = Mockito.mock(RuntimeMetadata.class);
    SalesforceConnection connection = Mockito.mock(SalesforceConnection.class);

    ArgumentCaptor<DataPayload> payloadArgument = ArgumentCaptor.forClass(DataPayload.class);
    Mockito.stub(connection.create(payloadArgument.capture())).toReturn(23);

    DirectQueryExecution execution =
        (DirectQueryExecution) TRANSLATOR.createExecution(command, ec, rm, connection);
    execution.execute();

    Mockito.verify(connection).create(payloadArgument.capture());

    assertEquals("pk", payloadArgument.getValue().getID());
    assertEquals("table", payloadArgument.getValue().getType());
    assertEquals(3, payloadArgument.getValue().getMessageElements().size());

    assertArrayEquals(new Object[] {23}, (Object[]) execution.next().get(0));
  }
  @Test
  public void testIfNodeIsAddedIfThereWasOnlyOneNodeBefore() throws Exception {

    verify(routingTableService, never()).setNextHop(Matchers.<String>any(), Matchers.<String>any());
    verify(namingServiceMock, never()).addEntry(Matchers.<NamingEntry>any());

    setListenerState(ONE_NODE_ONE_NAME_NO_APPS);

    ArgumentCaptor<NamingEntry> namingEntryArgumentCaptor =
        ArgumentCaptor.forClass(NamingEntry.class);
    verify(namingServiceMock).addEntry(namingEntryArgumentCaptor.capture());
    assertEquals("urn:local:0xdcb0", namingEntryArgumentCaptor.getValue().getNodeName());
    assertEquals("tcp", namingEntryArgumentCaptor.getValue().getIface().getType());
    assertEquals("localhost:8888", namingEntryArgumentCaptor.getValue().getIface().getAddress());

    reset(namingServiceMock);
    reset(routingTableService);

    setListenerState(TWO_NODES_ONE_NAME_NO_APPS);

    verify(routingTableService, atLeastOnce()).setNextHop("urn:local:0xdcb2", "urn:local:0xdcb2");

    ArgumentCaptor<NamingEntry> namingEntryArgumentCaptor2 =
        ArgumentCaptor.forClass(NamingEntry.class);
    verify(namingServiceMock).addEntry(namingEntryArgumentCaptor2.capture());
    assertEquals("urn:local:0xdcb2", namingEntryArgumentCaptor2.getValue().getNodeName());
    assertEquals("tcp", namingEntryArgumentCaptor2.getValue().getIface().getType());
    assertEquals("localhost2:8888", namingEntryArgumentCaptor2.getValue().getIface().getAddress());
  }
  @Test
  public void testValidSubscription() {
    // add configuration
    // Mock the task scheduler and capture the runnable
    ArgumentCaptor<Runnable> runnableArg = ArgumentCaptor.forClass(Runnable.class);
    when(taskScheduler.scheduleWithFixedDelay(runnableArg.capture(), anyLong()))
        .thenReturn(Mockito.mock(ScheduledFuture.class));

    // Mock the response to the subsribeContext
    ArgumentCaptor<SuccessCallback> successArg = ArgumentCaptor.forClass(SuccessCallback.class);
    ListenableFuture<SubscribeContextResponse> responseFuture =
        Mockito.mock(ListenableFuture.class);
    doNothing().when(responseFuture).addCallback(successArg.capture(), any());

    Configuration configuration = getBasicConf();
    subscriptionManager.setConfiguration(configuration);

    // Capture the arg of subscription and return the mocked future
    ArgumentCaptor<String> urlProviderArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<SubscribeContext> subscribeContextArg =
        ArgumentCaptor.forClass(SubscribeContext.class);
    when(ngsiClient.subscribeContext(
            urlProviderArg.capture(), eq(null), subscribeContextArg.capture()))
        .thenReturn(responseFuture);

    // Execute scheduled runnable
    runnableArg.getValue().run();

    // Return the SubscribeContextResponse
    callSuccessCallback(successArg);

    // check ngsiClient.unsubscribe() is never called
    verify(ngsiClient, never()).unsubscribeContext(any(), any(), any());
    subscriptionManager.validateSubscriptionId("12345678", "http://iotAgent");
  }
예제 #11
0
  @Test
  public void contextCancellationCancelsStream() throws Exception {
    // Attach the context which is recorded when the call is created
    Context.CancellableContext cancellableContext = Context.current().withCancellation();
    Context previous = cancellableContext.attach();

    ClientCallImpl<Void, Void> call =
        new ClientCallImpl<Void, Void>(
                DESCRIPTOR,
                new SerializingExecutor(Executors.newSingleThreadExecutor()),
                CallOptions.DEFAULT,
                provider,
                deadlineCancellationExecutor)
            .setDecompressorRegistry(decompressorRegistry);

    previous.attach();

    call.start(callListener, new Metadata());

    Throwable t = new Throwable();
    cancellableContext.cancel(t);

    verify(stream, times(1)).cancel(statusArgumentCaptor.capture());

    verify(stream, times(1)).cancel(statusCaptor.capture());
    assertEquals(Status.Code.CANCELLED, statusCaptor.getValue().getCode());
  }
예제 #12
0
  @Test
  public void shouldSendEventWhenChannelWasDeleted() {
    Channel channel = new Channel("displayName", BUNDLE_SYMBOLIC_NAME, VERSION);

    when(channelsDataService.findByModuleName(channel.getModuleName())).thenReturn(channel);
    when(bundleContext.getBundles()).thenReturn(new Bundle[] {bundle});
    when(bundle.getSymbolicName()).thenReturn(BUNDLE_SYMBOLIC_NAME);

    ArgumentCaptor<MotechEvent> captor = ArgumentCaptor.forClass(MotechEvent.class);
    Channel deletedChannel = new Channel("displayName2", BUNDLE_SYMBOLIC_NAME, VERSION);
    channelService.delete(deletedChannel.getModuleName());

    ArgumentCaptor<TransactionCallback> transactionCaptor =
        ArgumentCaptor.forClass(TransactionCallback.class);
    verify(channelsDataService).doInTransaction(transactionCaptor.capture());
    transactionCaptor.getValue().doInTransaction(null);
    verify(channelsDataService).delete(channel);

    verify(eventRelay).sendEventMessage(captor.capture());

    MotechEvent event = captor.getValue();

    assertEquals(CHANNEL_DEREGISTER_SUBJECT, event.getSubject());
    assertEquals(BUNDLE_SYMBOLIC_NAME, event.getParameters().get(CHANNEL_MODULE_NAME));
  }
예제 #13
0
  @Test
  public void shouldSendEventWhenChannelWasUpdated() {
    Channel channel = new Channel("displayName", BUNDLE_SYMBOLIC_NAME, VERSION);

    EventParameter eventParameter = new EventParameter("displayName", "eventKey");
    TriggerEvent triggerEvent =
        new TriggerEvent("displayName", "subject", null, Arrays.asList(eventParameter), "");

    channel.getTriggerTaskEvents().add(triggerEvent);

    when(channelsDataService.findByModuleName(channel.getModuleName())).thenReturn(channel);

    when(bundleContext.getBundles()).thenReturn(new Bundle[] {bundle});
    when(bundle.getSymbolicName()).thenReturn(BUNDLE_SYMBOLIC_NAME);

    ArgumentCaptor<MotechEvent> captor = ArgumentCaptor.forClass(MotechEvent.class);
    Channel updatedChannel = new Channel("displayName2", BUNDLE_SYMBOLIC_NAME, VERSION);
    updatedChannel.getTriggerTaskEvents().add(triggerEvent);
    channelService.addOrUpdate(updatedChannel);

    ArgumentCaptor<TransactionCallback> transactionCaptor =
        ArgumentCaptor.forClass(TransactionCallback.class);
    verify(channelsDataService).doInTransaction(transactionCaptor.capture());
    transactionCaptor.getValue().doInTransaction(null);
    verify(channelsDataService).update(channel);

    verify(eventRelay).sendEventMessage(captor.capture());

    MotechEvent event = captor.getValue();

    assertEquals(CHANNEL_UPDATE_SUBJECT, event.getSubject());
    assertEquals(BUNDLE_SYMBOLIC_NAME, event.getParameters().get(CHANNEL_MODULE_NAME));
  }
예제 #14
0
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run MultipleActions with multiple actions, first success, and second failure.
  *   <li>Check to make sure the success callback is called for the first action
  *   <li>Check to make sure the failure callback is called for the second action
  * </ol>
  */
 @Test
 public void testrunMultipleActions_multipleaction_success_first_success_second_failure() {
   List<VdcActionType> actionTypes = new ArrayList<VdcActionType>();
   actionTypes.add(VdcActionType.AddDisk);
   actionTypes.add(VdcActionType.AddBricksToGlusterVolume);
   List<VdcActionParametersBase> testParameters = new ArrayList<VdcActionParametersBase>();
   testParameters.add(new VdcActionParametersBase());
   testParameters.add(new VdcActionParametersBase());
   List<IFrontendActionAsyncCallback> callbacks = new ArrayList<IFrontendActionAsyncCallback>();
   callbacks.add(mockActionCallback);
   callbacks.add(mockActionCallback);
   Object testState = new Object();
   frontend.runMultipleActions(
       actionTypes, testParameters, callbacks, mockActionFailureCallback, testState);
   verify(mockService)
       .runAction(eq(VdcActionType.AddDisk), eq(testParameters.get(0)), callbackAction.capture());
   VdcReturnValueBase returnValue = new VdcReturnValueBase();
   returnValue.setCanDoAction(true);
   returnValue.setSucceeded(true);
   callbackAction.getValue().onSuccess(returnValue);
   verify(mockActionCallback).executed(callbackParam.capture());
   assertEquals(callbackParam.getValue().getReturnValue(), returnValue);
   // Second call to runAction
   verify(mockService)
       .runAction(
           eq(VdcActionType.AddBricksToGlusterVolume),
           eq(testParameters.get(0)),
           callbackAction.capture());
   returnValue = new VdcReturnValueBase();
   returnValue.setCanDoAction(false);
   returnValue.setSucceeded(false);
   callbackAction.getValue().onSuccess(returnValue);
   verify(mockActionFailureCallback).executed(callbackParam.capture());
   assertEquals(callbackParam.getValue().getReturnValue(), returnValue);
 }
  @SuppressWarnings({"rawtypes", "unchecked"})
  @Test
  public void testDenyWithProjectMember() throws ServletException, IOException {
    String pathInfo =
        ProjectLinkGenerator.generateDenyInvitationParams(
            "*****@*****.**", 1, 1, "*****@*****.**", "*****@*****.**");
    when(request.getPathInfo()).thenReturn(pathInfo);
    when(response.getWriter()).thenReturn(mock(PrintWriter.class));

    when(projectService.findById(1, 1)).thenReturn(new SimpleProject());
    when(projectMemberService.findMemberByUsername(
            any(String.class), any(Integer.class), any(Integer.class)))
        .thenReturn(new SimpleProjectMember());

    denyInvitationHandler.onHandleRequest(request, response);

    ArgumentCaptor<Locale> localeArgument = ArgumentCaptor.forClass(Locale.class);

    ArgumentCaptor<String> strArgument = ArgumentCaptor.forClass(String.class);

    ArgumentCaptor<Map> mapArgument = ArgumentCaptor.forClass(Map.class);

    verify(denyInvitationHandler)
        .generatePageByTemplate(
            localeArgument.capture(), strArgument.capture(), mapArgument.capture());
    Assert.assertEquals(
        DenyProjectInvitationHandler.REFUSE_MEMBER_DENY_TEMPLATE, strArgument.getValue());
  }
예제 #16
0
  @Test
  public void testShowSimpleData() throws Exception {
    KBaseModel config = new KBaseModel();
    config.setName("Name");

    config.setEqualsBehavior(AssertBehaviorOption.EQUALITY);
    config.setEventProcessingMode(EventProcessingOption.CLOUD);

    config.getStatelessSessions().put("1", createStatelessKSession("1"));
    config.getStatelessSessions().put("2", createStatelessKSession("2"));
    config.getStatelessSessions().put("3", createStatelessKSession("3"));

    config.getStatefulSessions().put("4,", createStatefulKSession("4"));
    config.getStatefulSessions().put("5,", createStatefulKSession("5"));

    form.setModel(config);
    verify(view).setName("Name");

    ArgumentCaptor<Map> statelessSessionModelArgumentCaptor = ArgumentCaptor.forClass(Map.class);
    ArgumentCaptor<Map> statefulModelArgumentCaptor = ArgumentCaptor.forClass(Map.class);

    verify(view).setStatefulSessions(statefulModelArgumentCaptor.capture());
    verify(view).setStatelessSessions(statelessSessionModelArgumentCaptor.capture());

    verify(view, never()).setEventProcessingModeStream();
    verify(view).setEventProcessingModeCloud();
    verify(view, never()).setEqualsBehaviorIdentity();
    verify(view).setEqualsBehaviorEquality();

    assertEquals(3, statelessSessionModelArgumentCaptor.getValue().size());
    assertEquals(2, statefulModelArgumentCaptor.getValue().size());
  }
예제 #17
0
  @Test
  public void createConfigurationDataTest() throws UnsupportedEncodingException, ParseException {
    initMocking();
    RpcResult<TransactionStatus> rpcResult =
        new DummyRpcResult.Builder<TransactionStatus>().result(TransactionStatus.COMMITED).build();

    when(brokerFacade.commitConfigurationDataPost(
            any(YangInstanceIdentifier.class), any(NormalizedNode.class)))
        .thenReturn(mock(CheckedFuture.class));

    ArgumentCaptor<YangInstanceIdentifier> instanceIdCaptor =
        ArgumentCaptor.forClass(YangInstanceIdentifier.class);
    ArgumentCaptor<NormalizedNode> compNodeCaptor = ArgumentCaptor.forClass(NormalizedNode.class);

    String URI_1 = "/config";
    assertEquals(204, post(URI_1, Draft02.MediaTypes.DATA + XML, xmlTestInterface));
    verify(brokerFacade)
        .commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
    String identifier =
        "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces]";
    assertEquals(identifier, instanceIdCaptor.getValue().getPath().toString());

    String URI_2 = "/config/test-interface:interfaces";
    assertEquals(204, post(URI_2, Draft02.MediaTypes.DATA + XML, xmlBlockData));
    verify(brokerFacade, times(2))
        .commitConfigurationDataPost(instanceIdCaptor.capture(), compNodeCaptor.capture());
    identifier =
        "[(urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)interfaces, (urn:ietf:params:xml:ns:yang:test-interface?revision=2014-07-01)block]";
    assertEquals(identifier, instanceIdCaptor.getValue().getPath().toString());
  }
예제 #18
0
  @Test
  public void testScheduleWork() throws Exception {

    PingManager manager = new PingManager();
    manager.pinger = new Pinger();

    Resource urlResource = PingerTestUtils.createTestResource();

    manager.urlChangesCollector.getUrlCreatedAction().call(urlResource);

    manager.metricPublisher = Mockito.mock(MetricPublisher.class);
    manager.traitsPublisher = Mockito.mock(TraitsPublisher.class);

    manager.scheduleWork();

    PingDestination expectedDest = PingerTestUtils.createTestPingDestination();

    Map<TraitHeader, String> expectedTraitsItems =
        new ImmutableMap.Builder<TraitHeader, String>()
            .put(TraitHeader.SERVER, "GitHub.com")
            .build();

    ArgumentCaptor<PingStatus> metricsRestStatusCaptor = ArgumentCaptor.forClass(PingStatus.class);
    Mockito.verify(manager.metricPublisher).sendToMetricsViaRest(metricsRestStatusCaptor.capture());
    assertStatus(expectedDest, expectedTraitsItems, metricsRestStatusCaptor.getValue());

    ArgumentCaptor<PingStatus> metricsStatusCaptor = ArgumentCaptor.forClass(PingStatus.class);
    Mockito.verify(manager.metricPublisher).publishToTopic(metricsStatusCaptor.capture());
    assertStatus(expectedDest, expectedTraitsItems, metricsStatusCaptor.getValue());

    ArgumentCaptor<PingStatus> traitsStatusCaptor = ArgumentCaptor.forClass(PingStatus.class);
    Mockito.verify(manager.traitsPublisher).publish(traitsStatusCaptor.capture());
    assertStatus(expectedDest, expectedTraitsItems, traitsStatusCaptor.getValue());
  }
  @Before
  public void setUp() {
    view = mock(ILookupView.class);
    model = mock(ILookupModel.class);

    new LookupPresenter(view, model);

    ArgumentCaptor<IListener> submissionListenerArgument = ArgumentCaptor.forClass(IListener.class);
    verify(view).addSubmissionListener(submissionListenerArgument.capture());
    submissionListener = submissionListenerArgument.getValue();

    ArgumentCaptor<IListener> resultsReturnedListenerArgument =
        ArgumentCaptor.forClass(IListener.class);
    verify(model).addResultsReturnedListener(resultsReturnedListenerArgument.capture());
    resultsReturnedListener = resultsReturnedListenerArgument.getValue();

    ArgumentCaptor<IListener> failureListenerArgument = ArgumentCaptor.forClass(IListener.class);
    verify(model).addFailureListener(failureListenerArgument.capture());
    failureListener = failureListenerArgument.getValue();

    ArgumentCaptor<IListener> noResultsReturnedListenerArgument =
        ArgumentCaptor.forClass(IListener.class);
    verify(model).addNoResultsReturnedListener(noResultsReturnedListenerArgument.capture());
    noResultsReturnedListener = noResultsReturnedListenerArgument.getValue();
  }
예제 #20
0
  @Test
  public void shouldRegisterChannel() {
    String triggerEvent =
        "{ displayName: 'displayName', subject: 'subject', eventParameters: [{ displayName: 'displayName', eventKey: 'eventKey' }] }";
    String channel =
        String.format(
            "{displayName: %s, triggerTaskEvents: [%s]}", BUNDLE_SYMBOLIC_NAME, triggerEvent);
    InputStream stream = new ByteArrayInputStream(channel.getBytes(Charset.forName("UTF-8")));

    channelService.registerChannel(stream, BUNDLE_SYMBOLIC_NAME, VERSION);

    ArgumentCaptor<TransactionCallback> transactionCaptor =
        ArgumentCaptor.forClass(TransactionCallback.class);
    verify(channelsDataService).doInTransaction(transactionCaptor.capture());
    transactionCaptor.getValue().doInTransaction(null);

    ArgumentCaptor<Channel> captor = ArgumentCaptor.forClass(Channel.class);
    verify(channelsDataService).create(captor.capture());

    Channel c = captor.getValue();

    assertEquals(BUNDLE_SYMBOLIC_NAME, c.getDisplayName());
    assertEquals(BUNDLE_SYMBOLIC_NAME, c.getModuleName());
    assertEquals(VERSION, c.getModuleVersion());
    assertEquals(1, c.getTriggerTaskEvents().size());
    assertEquals(
        new TriggerEvent(
            "displayName",
            "subject",
            null,
            asList(new EventParameter("displayName", "eventKey")),
            ""),
        c.getTriggerTaskEvents().get(0));
  }
예제 #21
0
  /**
   * Pass the VoltMessage to CI's handleRead() and inspect if the expected parameters are passed to
   * the initiator's createTranction() method. This is a convenient method if the caller expects the
   * result of handling this message is to create a new transaction.
   *
   * @param msg
   * @param procName
   * @param partitionParam null if it's a multi-part txn
   * @param isAdmin
   * @param isReadonly
   * @param isSinglePart
   * @param isEverySite
   * @return StoredProcedureInvocation object passed to createTransaction()
   * @throws IOException
   */
  private StoredProcedureInvocation readAndCheck(
      ByteBuffer msg,
      String procName,
      Object partitionParam,
      boolean isAdmin,
      boolean isReadonly,
      boolean isSinglePart,
      boolean isEverySite)
      throws IOException {
    ClientResponseImpl resp = m_ci.handleRead(msg, m_handler, m_cxn);
    assertNull(resp);

    ArgumentCaptor<Long> destinationCaptor = ArgumentCaptor.forClass(Long.class);
    ArgumentCaptor<Iv2InitiateTaskMessage> messageCaptor =
        ArgumentCaptor.forClass(Iv2InitiateTaskMessage.class);
    verify(m_messenger).send(destinationCaptor.capture(), messageCaptor.capture());

    Iv2InitiateTaskMessage message = messageCaptor.getValue();
    // assertEquals(isAdmin, message.); // is admin
    assertEquals(isReadonly, message.isReadOnly()); // readonly
    assertEquals(isSinglePart, message.isSinglePartition()); // single-part
    // assertEquals(isEverySite, message.g); // every site
    assertEquals(procName, message.getStoredProcedureName());
    if (isSinglePart) {
      int expected = TheHashinator.hashToPartition(partitionParam);
      assertEquals(
          new Long(m_cartographer.getHSIdForMaster(expected)), destinationCaptor.getValue());
    } else {
      assertEquals(
          new Long(m_cartographer.getHSIdForMultiPartitionInitiator()),
          destinationCaptor.getValue());
    }
    return message.getStoredProcedureInvocation();
  }
예제 #22
0
  @Test
  public void testUpdateDataUsage() throws PersistenceException {
    ArgumentCaptor<String> keyArg1 = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> keyArg2 = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> cqlArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<PersistentItem> itemArg = ArgumentCaptor.forClass(PersistentItem.class);

    attributesList = new ArrayList<>();
    Map<String, Object> attributes = new HashMap<>();
    attributes.put(DATA_USAGE_LONG, LONG_1);
    attributes.put(DATA_LIMIT_LONG, LONG_1);
    attributesList.add(attributes);
    when(persistentStore.get(anyString(), anyString())).thenReturn(attributesList);

    attributesStore.updateUserDataUsage(USER, LONG_5);

    verify(persistentStore, atLeast(2)).get(keyArg1.capture(), cqlArg.capture());
    verify(persistentStore).add(keyArg2.capture(), itemArg.capture());

    assertThat(keyArg1.getValue(), is(PersistentStore.USER_ATTRIBUTE_TYPE));
    assertThat(keyArg2.getValue(), is(PersistentStore.USER_ATTRIBUTE_TYPE));

    assertThat(itemArg.getValue().getLongProperty(AttributesStore.DATA_USAGE_KEY), is(600L));

    assertThat(cqlArg.getValue(), is(CQL));
  }
  @Test
  public void testOnSeekBarMovedChangesCOlor() {
    presenter.mBtService = service;
    presenter.onSeekBarMove(50, 100, 255);

    verify(service, times(1)).changeColor(colorCaptor.capture(), handlerCaptor.capture());
    assertPlutoColorEqual(50, 100, 255, colorCaptor.getValue());
  }
 protected void verifySent(long hsId, RejoinMessage expected) {
   ArgumentCaptor<Long> hsIdCaptor = ArgumentCaptor.forClass(Long.class);
   ArgumentCaptor<VoltMessage> msgCaptor = ArgumentCaptor.forClass(VoltMessage.class);
   verify(m_coordinator).send(hsIdCaptor.capture(), msgCaptor.capture());
   assertEquals(hsId, hsIdCaptor.getValue().longValue());
   RejoinMessage msg = (RejoinMessage) msgCaptor.getValue();
   assertEquals(expected.getType(), msg.getType());
   assertEquals(expected.m_sourceHSId, msg.m_sourceHSId);
 }
  @Test
  public void testOnSeekBarMovedOnSuccess() {
    presenter.mBtService = service;
    presenter.onSeekBarMove(50, 100, 255);
    verify(service, times(1)).changeColor(any(PlutoColor.class), handlerCaptor.capture());
    handlerCaptor.getValue().onSuccess();

    verify(view, times(1)).setBackgroundColor(colorCaptor.capture());
    assertPlutoColorEqual(50, 100, 255, colorCaptor.getValue());
  }
예제 #26
0
 /**
  * Run the following test case.
  *
  * <ol>
  *   <li>Run a multiple actions, with multiple actions
  *   <li>Have one of them fail. The rest is successful
  *   <li>Check to make sure the failure event is never fired
  * </ol>
  */
 @SuppressWarnings("unchecked")
 @Test
 public void testrunMultipleActionsMultipleSuccess_oneFailure() {
   // Don't immediately call process until both queries are in the queue.
   fakeScheduler.setThreshold(2);
   ArrayList<VdcActionParametersBase> parameters = new ArrayList<VdcActionParametersBase>();
   parameters.add(new VdcActionParametersBase());
   parameters.add(new VdcActionParametersBase());
   parameters.get(0).setCommandId(Guid.Empty);
   Object testState = new Object();
   frontend.runMultipleAction(
       VdcActionType.AddLocalStorageDomain,
       parameters,
       false,
       mockMultipleActionCallback,
       testState);
   verify(mockService)
       .runMultipleActions(
           eq(VdcActionType.AddLocalStorageDomain),
           eq(parameters),
           eq(false),
           eq(false),
           callbackMultipleActions.capture());
   ArrayList<VdcReturnValueBase> returnValues = new ArrayList<VdcReturnValueBase>();
   returnValues.add(new VdcReturnValueBase());
   returnValues.add(new VdcReturnValueBase());
   returnValues.get(0).setCanDoAction(true);
   returnValues.get(1).setCanDoAction(false);
   callbackMultipleActions.getValue().onSuccess(returnValues);
   verify(mockFrontendFailureEvent, never())
       .raise(eq(Frontend.class), (FrontendFailureEventArgs) any());
   @SuppressWarnings("rawtypes")
   ArgumentCaptor<ArrayList> failedCaptor = ArgumentCaptor.forClass(ArrayList.class);
   verify(mockEventsHandler)
       .runMultipleActionFailed(eq(VdcActionType.AddLocalStorageDomain), failedCaptor.capture());
   assertEquals("There is one failure", 1, failedCaptor.getValue().size()); // $NON-NLS-1$
   assertEquals(
       "Failures should match",
       returnValues.get(1),
       failedCaptor.getValue().get(0)); // $NON-NLS-1$
   verify(mockMultipleActionCallback).executed(callbackMultipleParam.capture());
   assertEquals(
       "Parameters should match",
       parameters, //$NON-NLS-1$
       callbackMultipleParam.getValue().getParameters());
   assertEquals(
       "Result should match",
       returnValues, //$NON-NLS-1$
       callbackMultipleParam.getValue().getReturnValue());
   assertEquals(
       "States should match",
       testState,
       callbackMultipleParam.getValue().getState()); // $NON-NLS-1$
 }
예제 #27
0
  /** Fake an adhoc compiler result and return it to the CI, see if CI initiates the txn. */
  @Test
  public void testFinishedMPAdHocPlanning() throws Exception {
    // Need a batch and a statement
    AdHocPlannedStmtBatch plannedStmtBatch =
        new AdHocPlannedStmtBatch(
            "select * from a",
            null,
            0,
            0,
            "localhost",
            false,
            ProcedureInvocationType.ORIGINAL,
            0,
            0,
            null);
    AdHocPlannedStatement s =
        new AdHocPlannedStatement(
            "select * from a".getBytes(Constants.UTF8ENCODING),
            new CorePlan(
                new byte[0],
                new byte[0],
                new byte[20],
                new byte[20],
                false,
                false,
                true,
                new VoltType[0],
                0),
            ParameterSet.emptyParameterSet(),
            null,
            null,
            null);
    plannedStmtBatch.addStatement(s);
    m_ci.processFinishedCompilerWork(plannedStmtBatch).run();

    ArgumentCaptor<Long> destinationCaptor = ArgumentCaptor.forClass(Long.class);
    ArgumentCaptor<Iv2InitiateTaskMessage> messageCaptor =
        ArgumentCaptor.forClass(Iv2InitiateTaskMessage.class);
    verify(m_messenger).send(destinationCaptor.capture(), messageCaptor.capture());
    Iv2InitiateTaskMessage message = messageCaptor.getValue();

    // assertFalse(boolValues.get(0)); // is admin
    assertTrue(message.isReadOnly()); // readonly
    assertFalse(message.isSinglePartition()); // single-part
    // assertFalse(boolValues.get(3)); // every site
    assertEquals("@AdHoc_RO_MP", message.getStoredProcedureName());

    byte[] serializedData = (byte[]) message.getStoredProcedureInvocation().getParameterAtIndex(0);
    AdHocPlannedStatement[] statements =
        AdHocPlannedStmtBatch.planArrayFromBuffer(ByteBuffer.wrap(serializedData));
    assertEquals(1, statements.length);
    String sql = new String(statements[0].sql, Constants.UTF8ENCODING);
    assertEquals("select * from a", sql);
  }
예제 #28
0
  @Test
  public void testSetNoDataLimit() throws PersistenceException {
    final long DATA_LIMIT = -1;
    ArgumentCaptor<String> keyArg = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<PersistentItem> itemArg = ArgumentCaptor.forClass(PersistentItem.class);
    attributesStore.setDataLimit(USER, DATA_LIMIT);
    verify(persistentStore).add(keyArg.capture(), itemArg.capture());
    assertThat(keyArg.getValue(), is(PersistentStore.USER_ATTRIBUTE_TYPE));

    assertThat(
        itemArg.getValue().getLongProperty(AttributesStore.DATA_USAGE_LIMIT_KEY), is(DATA_LIMIT));
  }
  protected void verifyLastEthernetIcon(boolean visible, int icon) {
    ArgumentCaptor<Boolean> visibleArg = ArgumentCaptor.forClass(Boolean.class);
    ArgumentCaptor<Integer> iconArg = ArgumentCaptor.forClass(Integer.class);

    Mockito.verify(mSignalCluster, Mockito.atLeastOnce())
        .setEthernetIndicators(
            visibleArg.capture(),
            iconArg.capture(),
            ArgumentCaptor.forClass(String.class).capture());
    assertEquals("Ethernet visible, in status bar", visible, (boolean) visibleArg.getValue());
    assertEquals("Ethernet icon, in status bar", icon, (int) iconArg.getValue());
  }
 /**
  * Verify that reportedDatastores/reportedImageDatastores/reportedNetworks don't get reset when
  * datastores/imageDatastores/networks are null.
  */
 @Test
 public void testSetHostStateEmpty() throws Throwable {
   service.setHostState("host-id", AgentState.ACTIVE, null, null, null);
   ArgumentCaptor<String> arg1 = ArgumentCaptor.forClass(String.class);
   ArgumentCaptor<ServiceDocument> arg2 = ArgumentCaptor.forClass(ServiceDocument.class);
   verify(dcpRestClient).patch(arg1.capture(), arg2.capture());
   HostService.State patch = (HostService.State) arg2.getValue();
   assertThat(patch.agentState, is(AgentState.ACTIVE));
   assertThat(patch.reportedDatastores, is(nullValue()));
   assertThat(patch.reportedImageDatastores, is(nullValue()));
   assertThat(patch.reportedNetworks, is(nullValue()));
   verifyNoMoreInteractions(dcpRestClient);
 }