@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 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");
  }
예제 #4
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();
  }
예제 #6
0
  @Test
  public void testUpdateArray() throws Exception {
    String sql =
        "update LdapModel.People set userid = 1, vals = ('a','b') where dn = 'x'"; //$NON-NLS-1$

    QueryMetadataInterface metadata = exampleLdap();

    Update query = (Update) getCommand(sql, metadata);

    LDAPExecutionFactory config = new LDAPExecutionFactory();

    LdapContext context = Mockito.mock(LdapContext.class);

    Mockito.stub(context.lookup("")).toReturn(context);

    LDAPUpdateExecution lue = new LDAPUpdateExecution(query, context);

    lue.execute();
    ArgumentCaptor<ModificationItem[]> captor = ArgumentCaptor.forClass(ModificationItem[].class);
    Mockito.verify(context)
        .modifyAttributes(ArgumentCaptor.forClass(String.class).capture(), captor.capture());
    ModificationItem[] modifications = captor.getValue();
    assertEquals(2, modifications.length);
    assertEquals("uid: 1", modifications[0].getAttribute().toString());
    assertEquals("vals: a, b", modifications[1].getAttribute().toString());
  }
예제 #7
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());
  }
예제 #8
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()));
  }
예제 #9
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));
  }
예제 #10
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));
  }
예제 #11
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));
  }
예제 #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));
  }
  @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());
  }
예제 #14
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());
  }
예제 #15
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();
  }
  public void testOrderedIncoming() throws Exception {
    TransactionBatchContext batch1 = transactionBatch(0, 1, 2);
    TransactionBatchContext batch2 = transactionBatch(1, 2, 3);

    sequencer.goToActiveMode();
    sequencer.addResentServerTransactionIDs(batch2.getTransactionIDs());
    sequencer.addResentServerTransactionIDs(batch1.getTransactionIDs());
    sequencer.transactionManagerStarted(clientIDs(0, 1));

    // Add a batch that isn't resent, should be processed last
    TransactionBatchContext batch3 = transactionBatch(0, 4, 5);
    TransactionBatchContext batch4 = transactionBatch(1, 4, 5);
    sequencer.addTransactions(batch3);
    sequencer.addTransactions(batch4);

    sequencer.addTransactions(batch2);
    sequencer.addTransactions(batch1);

    ArgumentCaptor<Map> c = ArgumentCaptor.<Map>forClass(Map.class);
    ArgumentCaptor<NodeID> n = ArgumentCaptor.<NodeID>forClass(NodeID.class);

    InOrder inOrder = inOrder(replicatedObjectManager, transactionManager);
    inOrder.verify(transactionManager).incomingTransactions(n.capture(), c.capture());
    inOrder.verify(replicatedObjectManager).relayTransactions(batch1);
    inOrder.verify(transactionManager).incomingTransactions(n.capture(), c.capture());
    inOrder.verify(replicatedObjectManager).relayTransactions(batch2);

    inOrder.verify(transactionManager).incomingTransactions(n.capture(), c.capture());
    inOrder.verify(replicatedObjectManager).relayTransactions(batch3);
    inOrder.verify(transactionManager).incomingTransactions(n.capture(), c.capture());
    inOrder.verify(replicatedObjectManager).relayTransactions(batch4);

    verifyBatches(true, c, batch1, batch2, batch3, batch4);
  }
 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);
 }
예제 #18
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);
  }
  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());
  }
예제 #20
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));
  }
 /**
  * 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);
 }
예제 #22
0
  @Test
  public void testFinishedSPAdHocPlanning() throws Exception {
    // Need a batch and a statement
    AdHocPlannedStmtBatch plannedStmtBatch =
        new AdHocPlannedStmtBatch(
            "select * from a where i = 3",
            3,
            0,
            0,
            "localhost",
            false,
            ProcedureInvocationType.ORIGINAL,
            0,
            0,
            null);
    AdHocPlannedStatement s =
        new AdHocPlannedStatement(
            "select * from a where i = 3".getBytes(Constants.UTF8ENCODING),
            new CorePlan(
                new byte[0], null, new byte[20], null, false, false, true, new VoltType[0], 0),
            ParameterSet.fromArrayNoCopy(new Object[0]),
            null,
            null,
            3);
    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();

    assertTrue(message.isReadOnly()); // readonly
    assertTrue(message.isSinglePartition()); // single-part
    assertEquals("@AdHoc_RO_SP", message.getStoredProcedureName());

    // SP AdHoc should have partitioning parameter serialized in the parameter set
    Object partitionParam = message.getStoredProcedureInvocation().getParameterAtIndex(0);
    assertTrue(partitionParam instanceof byte[]);
    VoltType type =
        VoltType.get((Byte) message.getStoredProcedureInvocation().getParameterAtIndex(1));
    assertTrue(type.isInteger());
    byte[] serializedData = (byte[]) message.getStoredProcedureInvocation().getParameterAtIndex(2);
    AdHocPlannedStatement[] statements =
        AdHocPlannedStmtBatch.planArrayFromBuffer(ByteBuffer.wrap(serializedData));
    assertTrue(Arrays.equals(TheHashinator.valueToBytes(3), (byte[]) partitionParam));
    assertEquals(1, statements.length);
    String sql = new String(statements[0].sql, Constants.UTF8ENCODING);
    assertEquals("select * from a where i = 3", sql);
  }
  @Test
  public void testInputParsed() {
    final Integer messageNumber = 21;

    final ArgumentCaptor<Instant> dateCaptor = ArgumentCaptor.forClass(Instant.class);
    final ArgumentCaptor<Integer> messageNumberCaptor = ArgumentCaptor.forClass(Integer.class);

    trackerService.inputParsed(messageNumber);

    verify(trackerDAO).saveInputParse(dateCaptor.capture(), messageNumberCaptor.capture());
    assertEquals(messageNumber, messageNumberCaptor.getValue());
    assertEquals(
        LocalDate.now(), dateCaptor.getValue().atZone(ZoneId.systemDefault()).toLocalDate());
  }
  @Test
  public void find_with_paging() {
    GroupMembershipQuery query =
        GroupMembershipQuery.builder().login("arthur").pageIndex(3).pageSize(10).build();
    finder.find(query);

    ArgumentCaptor<Integer> argumentOffset = ArgumentCaptor.forClass(Integer.class);
    ArgumentCaptor<Integer> argumentLimit = ArgumentCaptor.forClass(Integer.class);
    verify(groupMembershipDao)
        .selectGroups(eq(query), anyLong(), argumentOffset.capture(), argumentLimit.capture());

    assertThat(argumentOffset.getValue()).isEqualTo(20);
    assertThat(argumentLimit.getValue()).isEqualTo(11);
  }
  @Test
  public void visibilityRunnable_run_withNonVisibleView_shouldCallOnNonVisibleCallback()
      throws Exception {
    when(view.getVisibility()).thenReturn(View.INVISIBLE);
    subject.addView(view, MIN_PERCENTAGE_VIEWED);

    subject.new VisibilityRunnable().run();

    ArgumentCaptor<List> visibleCaptor = ArgumentCaptor.forClass(List.class);
    ArgumentCaptor<List> invisibleCaptor = ArgumentCaptor.forClass(List.class);
    verify(visibilityTrackerListener)
        .onVisibilityChanged(visibleCaptor.capture(), invisibleCaptor.capture());
    assertThat(visibleCaptor.getValue().size()).isEqualTo(0);
    assertThat(invisibleCaptor.getValue().size()).isEqualTo(1);
  }
  @Test
  public void testAddStatefulProcess() {
    @Stateful
    final class Process implements DiscreteEventProcess {
      @Override
      public void dispatchEvent(Event e) {}

      @Override
      public void offer(Event event) {}

      @Override
      public Event peek(long currentSimtime) {
        return null;
      }

      @Override
      public void remove(Event event) {}
    }

    Process dummy = new Process();
    builder.add(dummy);

    verify(service).register(dummy);

    // source
    ArgumentCaptor<EventSource> sourceArgument = ArgumentCaptor.forClass(EventSource.class);
    verify(process).addEventSource(sourceArgument.capture());

    EventSource addedSource = sourceArgument.getValue();
    assertNotNull(addedSource);
    assertTrue(addedSource instanceof TimewarpEventSourceAdapter);
    verify(service).register(addedSource);

    // sink
    ArgumentCaptor<EventSink> sinkArgument = ArgumentCaptor.forClass(EventSink.class);
    verify(process).addEventSink(sinkArgument.capture());

    EventSink addedSink = sinkArgument.getValue();
    assertNotNull(addedSink);
    assertTrue(addedSink instanceof TimewarpEventSinkAdapter);
    verify(service).register(addedSink);

    // dispatcher
    verify(process).addEventDispatcher(dummy);

    verifyNoMoreInteractions(process);
    verifyNoMoreInteractions(service);
  }
 @Test
 public void clientRequestMultipleEmptyDataFrames() throws Exception {
   final String text = "";
   final ByteBuf content = Unpooled.copiedBuffer(text.getBytes());
   final FullHttpRequest request =
       new DefaultFullHttpRequest(
           HttpVersion.HTTP_1_1, HttpMethod.GET, "/some/path/resource2", content, true);
   try {
     HttpHeaders httpHeaders = request.headers();
     httpHeaders.set(HttpUtil.ExtensionHeaderNames.STREAM_ID.text(), 3);
     httpHeaders.set(HttpHeaders.Names.CONTENT_LENGTH, text.length());
     final Http2Headers http2Headers =
         new DefaultHttp2Headers().method(as("GET")).path(as("/some/path/resource2"));
     runInChannel(
         clientChannel,
         new Http2Runnable() {
           @Override
           public void run() {
             frameWriter.writeHeaders(ctxClient(), 3, http2Headers, 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, false, newPromiseClient());
             frameWriter.writeData(ctxClient(), 3, content.retain(), 0, true, newPromiseClient());
             ctxClient().flush();
           }
         });
     awaitRequests();
     ArgumentCaptor<FullHttpMessage> requestCaptor =
         ArgumentCaptor.forClass(FullHttpMessage.class);
     verify(serverListener).messageReceived(requestCaptor.capture());
     capturedRequests = requestCaptor.getAllValues();
     assertEquals(request, capturedRequests.get(0));
   } finally {
     request.release();
   }
 }
  @Test
  public void shouldQueryResourceSetToken() throws Exception {

    // Given
    Map<String, Object> queryParameters = new HashMap<String, Object>();
    queryParameters.put(ResourceSetTokenField.CLIENT_ID, "CLIENT_ID");
    ResourceSetDescription resourceSet1 =
        new ResourceSetDescription(
            "123", "CLIENT_ID", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());
    ResourceSetDescription resourceSet2 =
        new ResourceSetDescription(
            "456", "CLIENT_ID", "RESOURCE_OWNER_ID", Collections.<String, Object>emptyMap());

    given(dataStore.query(Matchers.<QueryFilter<String>>anyObject()))
        .willReturn(asSet(resourceSet1, resourceSet2));
    resourceSet1.setRealm("REALM");
    resourceSet2.setRealm("REALM");

    // When
    QueryFilter<String> query = QueryFilter.alwaysTrue();
    Set<ResourceSetDescription> resourceSetDescriptions = store.query(query);

    // Then
    assertThat(resourceSetDescriptions).contains(resourceSet1, resourceSet2);
    ArgumentCaptor<QueryFilter> tokenFilterCaptor = ArgumentCaptor.forClass(QueryFilter.class);
    verify(dataStore).query(tokenFilterCaptor.capture());
    assertThat(tokenFilterCaptor.getValue())
        .isEqualTo(
            QueryFilter.and(query, QueryFilter.equalTo(ResourceSetTokenField.REALM, "REALM")));
  }
  @Test
  public void testServerReturnsAnHttp401() throws Exception {
    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);

    when(myHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 401, "Unauthorized"));
    when(myHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_TEXT));
    when(myHttpResponse.getEntity().getContent())
        .thenAnswer(
            new Answer<InputStream>() {
              @Override
              public InputStream answer(InvocationOnMock theInvocation) throws Throwable {
                return new ReaderInputStream(
                    new StringReader("Unauthorized"), Charset.forName("UTF-8"));
              }
            });
    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    IGenericClient client = myCtx.newRestfulGenericClient("http://foo");
    try {
      client.read().resource(Patient.class).withId("123").execute();
      fail();
    } catch (AuthenticationException e) {
      // good
    }
  }
  @Test
  public void testServerReturnsWrongVersionForDstu2() throws Exception {
    Conformance conf = new Conformance();
    conf.setFhirVersion("0.80");
    String msg = myCtx.newXmlParser().encodeResourceToString(conf);

    ArgumentCaptor<HttpUriRequest> capt = ArgumentCaptor.forClass(HttpUriRequest.class);

    when(myHttpResponse.getStatusLine())
        .thenReturn(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    when(myHttpResponse.getEntity().getContentType())
        .thenReturn(new BasicHeader("content-type", Constants.CT_FHIR_XML + "; charset=UTF-8"));
    when(myHttpResponse.getEntity().getContent())
        .thenReturn(new ReaderInputStream(new StringReader(msg), Charset.forName("UTF-8")));

    when(myHttpClient.execute(capt.capture())).thenReturn(myHttpResponse);

    myCtx.getRestfulClientFactory().setServerValidationMode(ServerValidationModeEnum.ONCE);
    try {
      myCtx.newRestfulGenericClient("http://foo").read(new UriDt("http://foo/Patient/123"));
      fail();
    } catch (FhirClientInappropriateForServerException e) {
      String out = e.toString();
      String want =
          "The server at base URL \"http://foo/metadata\" returned a conformance statement indicating that it supports FHIR version \"0.80\" which corresponds to DSTU1, but this client is configured to use DSTU2 (via the FhirContext)";
      ourLog.info(out);
      ourLog.info(want);
      assertThat(out, containsString(want));
    }
  }