Java Code Examples for org.easymock.Capture#getValue()

The following examples show how to use org.easymock.Capture#getValue() . 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: AlarmSubsystemFixture.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
/**
 * Compares triggers ignoring timestamps.
 * @param capture
 * @param trigger
 */
public static void assertTriggersMatch(Capture<List<IncidentTrigger>> capture, IncidentTrigger... expected) {
	List<IncidentTrigger> actual = capture.getValue();
	
	for(int i=0; i<expected.length; i++) {
		IncidentTrigger expectedTrigger = expected[i];
		if(actual.size() <= i) {
			String message = String.format("Expected [%s] but was missing for index %d", expectedTrigger, i);
			fail(message);
		}
		else {
			IncidentTrigger actualTrigger = actual.get(i);
			assertEquals(String.format("Expected [%s] but was [%s] for index %d", expectedTrigger.getEvent(), actualTrigger.getEvent(), i), expectedTrigger.getEvent(), actualTrigger.getEvent());
			assertEquals(String.format("Expected [%s] but was [%s] for index %d", expectedTrigger.getSource(), actualTrigger.getSource(), i), expectedTrigger.getSource(), actualTrigger.getSource());
		}
	}
	
	assertEquals(expected.length, actual.size());
}
 
Example 2
Source File: TestPlatformAlarmIncidentService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAlertCreatesNewIncident() {
   expectCurrentAndReturnNull();
   List<IncidentTrigger> triggers = ImmutableList.of(IncidentFixtures.createIncidentTrigger(AlertType.WATER, IncidentTrigger.EVENT_LEAK));
   Capture<AlarmIncident> incidentCapture = expectUpdate();
   replay();
   
   service.addAlert(context, WaterAlarm.NAME, triggers);
   
   AlarmIncident incident = incidentCapture.getValue();
   assertFalse(incident.isMonitored());   //water is not monitored
   assertIncidentTrackers(incident, TrackerState.ALERT);
   assertIncidentAlert(incident, AlertType.WATER);
   
   assertBroadcastAdded(incident);
   assertAddAlarm(incident, AlertType.WATER, ImmutableList.of(AlertType.WATER), triggers);
   assertBroadcastAlert(AlertType.WATER, triggers);
   assertNoMessages();
   
   verify();
}
 
Example 3
Source File: TestPhoenixTransactSQL.java    From ambari-metrics with Apache License 2.0 6 votes vote down vote up
@Test
public void testPrepareGetAggregatePrecisionHours() throws SQLException {
  Condition condition = new DefaultCondition(
    new ArrayList<>(Arrays.asList("cpu_user", "mem_free")), Collections.singletonList("h1"),
    "a1", "i1", 1407959718L, 1407959918L, Precision.HOURS, null, false);
  Connection connection = createNiceMock(Connection.class);
  PreparedStatement preparedStatement = createNiceMock(PreparedStatement.class);
  Capture<String> stmtCapture = new Capture<String>();
  expect(connection.prepareStatement(EasyMock.and(EasyMock.anyString(), EasyMock.capture(stmtCapture))))
      .andReturn(preparedStatement);

  replay(connection, preparedStatement);
  PhoenixTransactSQL.prepareGetAggregateSqlStmt(connection, condition);
  String stmt = stmtCapture.getValue();
  Assert.assertTrue(stmt.contains("FROM METRIC_AGGREGATE_HOURLY_UUID"));
  Assert.assertNull(condition.getLimit());
  verify(connection, preparedStatement);
}
 
Example 4
Source File: TestSetPreferencesHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void test(Map<String, Object> foundPrefs, Map<String, Object> requestPrefs,
   Map<String, Object> expectedPrefsToEmit)
{
   expect(mockSession.getActivePlace()).andReturn(ACTIVE_PLACE_ID.toString()).anyTimes();

   expect(mockPreferencesDao.findById(PRINCIPAL_ID, ACTIVE_PLACE_ID)).andReturn(foundPrefs);

   mockPreferencesDao.merge(PRINCIPAL_ID, ACTIVE_PLACE_ID, requestPrefs);
   expectLastCall();

   Capture<PlatformMessage> messageCapture = newCapture();
   expect(mockPlatformMessageBus.send(capture(messageCapture))).andReturn(null);

   replay();

   MessageBody requestBody = SetPreferencesRequest.builder().withPrefs(requestPrefs).build();
   ClientMessage request = ClientMessage.builder().withPayload(requestBody).create();

   componentUnderTest.handle(request, mockSession);

   PlatformMessage message = messageCapture.getValue();
   assertThat(PreferencesChangedEvent.getPrefs(message.getValue()), equalTo(expectedPrefsToEmit));
}
 
Example 5
Source File: CommandInvocationHandlerTest.java    From chrome-devtools-java-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testInvokeStringMethodWithParamsAndReturnsAnnotation() throws Throwable {
  Capture<MethodInvocation> methodInvocationCapture = Capture.newInstance();
  expect(
          chromeDevToolsService.invoke(
              eq("ReturnsValue"), eq(String.class), eq(null), capture(methodInvocationCapture)))
      .andReturn(null);

  replayAll();

  assertNull(
      invocationHandler.invoke(
          this,
          getMethodByName("stringMethodWithParamsAndAnnotation"),
          new Object[] {"Test", 1}));

  verifyAll();

  MethodInvocation methodInvocation = methodInvocationCapture.getValue();

  assertNotNull(methodInvocation.getId());
  assertEquals(
      "CommandInvocationHandlerTest.stringMethodWithParamsAndAnnotation",
      methodInvocation.getMethod());
  assertFalse(methodInvocation.getParams().isEmpty());

  assertEquals("Test", methodInvocation.getParams().get("paramTest"));
  assertEquals(1, (int) methodInvocation.getParams().get("paramTest1"));
}
 
Example 6
Source File: AbstractReplyCallbackTest.java    From mongodb-async-driver with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link AbstractReplyCallback#asError(Reply)} .
 */
@SuppressWarnings("unchecked")
@Test
public void testAsErrorWithErrorMsg() {
    final List<Document> docs = Collections.singletonList(BuilderFactory
            .start().addString("errmsg", "This is an error.").build());
    final Query q = new Query("db", "c", BuilderFactory.start().build(),
            null, 0, 0, 0, false, ReadPreference.PRIMARY, false, false,
            false, false);
    final Reply reply = new Reply(0, 0, 0, docs, false, false, false, true);

    final Callback<MongoIterator<Document>> mockCallback = createMock(Callback.class);
    final Capture<Throwable> capture = new Capture<Throwable>();

    mockCallback.exception(capture(capture));
    expectLastCall();

    replay(mockCallback);

    final CursorCallback callback = new CursorCallback(null, q, false,
            mockCallback);
    callback.callback(reply);

    verify(mockCallback);

    final Throwable thrown = capture.getValue();
    assertThat(thrown, instanceOf(ShardConfigStaleException.class));
    assertTrue(thrown.getMessage().contains("This is an error."));
}
 
Example 7
Source File: TaxonomyResourceProviderTest.java    From incubator-atlas with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateResource() throws Exception {
    AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class);
    QueryFactory queryFactory = createStrictMock(QueryFactory.class);
    AtlasQuery query = createStrictMock(AtlasQuery.class);
    Capture<ResourceDefinition> resourceDefinitionCapture = newCapture();
    Capture<Request> requestCapture = newCapture();

    // empty response indicates that resource doesn't already exist
    Collection<Map<String, Object>> queryResult = new ArrayList<>();

    // mock expectations
    expect(queryFactory.createTaxonomyQuery(capture(requestCapture))).andReturn(query);
    expect(query.execute()).andReturn(queryResult);
    expect(typeSystem.createEntity(capture(resourceDefinitionCapture), capture(requestCapture))).andReturn("testGuid");
    replay(typeSystem, queryFactory, query);

    Map<String, Object> requestProperties = new HashMap<>();
    requestProperties.put("name", "taxonomyName");
    Request userRequest = new InstanceRequest(requestProperties);

    TaxonomyResourceProvider provider = new TestTaxonomyResourceProvider(typeSystem);
    provider.setQueryFactory(queryFactory);

    provider.createResource(userRequest);

    assertEquals(new TaxonomyResourceDefinition().getTypeName(),
            resourceDefinitionCapture.getValue().getTypeName());

    Request request = requestCapture.getValue();
    assertNull(request.getQueryString());
    assertEquals(requestProperties, request.getQueryProperties());

    verify(typeSystem, queryFactory, query);
}
 
Example 8
Source File: JmxSupportTest.java    From mongodb-async-driver with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for
 * {@link JmxSupport#register(AbstractMetrics, String, String)}.
 *
 * @throws JMException
 *             On a test failure.
 */
@Test
public void testRegisterOnJMException() throws JMException {
    final AbstractMetrics mockMetrics = createMock(AbstractMetrics.class);
    final MBeanServer mockServer = createMock(MBeanServer.class);

    final Capture<Object> captureObject = new Capture<Object>();
    final Capture<ObjectName> captureName = new Capture<ObjectName>();

    expect(
            mockServer.registerMBean(capture(captureObject),
                    capture(captureName))).andThrow(
            new InstanceAlreadyExistsException());

    replay(mockMetrics, mockServer);

    final JmxSupport support = new JmxSupport(mockServer);

    support.register(mockMetrics, "subType", "foo");

    verify(mockMetrics, mockServer);

    final ObjectName name = captureName.getValue();
    assertThat(name, notNullValue());
    assertThat(name.getDomain(), is(JmxSupport.DOMAIN_NAME));
    assertThat(name.getKeyProperty("type"), is("metrics"));
    assertThat(name.getKeyProperty("subType"), is("subType"));
    assertThat(name.getKeyProperty("name"), is("foo"));
    assertThat(name.getKeyProperty("index"), nullValue());

    final Object bean = captureObject.getValue();
    assertThat(bean, instanceOf(MetricsMXBeanProxy.class));
}
 
Example 9
Source File: PaymentChannelServerTest.java    From green_android with GNU General Public License v3.0 5 votes vote down vote up
private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) {
    final TwoWayChannelMessage response = initiateCapture.getValue();
    final MessageType type = response.getType();
    assertEquals("Wrong type " + type, MessageType.INITIATE, type);
    final long actualExpire = response.getInitiate().getExpireTimeSecs();
    assertTrue("Expire time too small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire);
    assertTrue("Expire time too large  " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire);
}
 
Example 10
Source File: PaymentChannelServerTest.java    From bcm-android with GNU General Public License v3.0 5 votes vote down vote up
private void assertExpireTime(long expectedExpire, Capture<TwoWayChannelMessage> initiateCapture) {
    final TwoWayChannelMessage response = initiateCapture.getValue();
    final MessageType type = response.getType();
    assertEquals("Wrong type " + type, MessageType.INITIATE, type);
    final long actualExpire = response.getInitiate().getExpireTimeSecs();
    assertTrue("Expire time too small " + expectedExpire + " > " + actualExpire, expectedExpire <= actualExpire);
    assertTrue("Expire time too large  " + expectedExpire + "<" + actualExpire, expectedExpire >= actualExpire);
}
 
Example 11
Source File: JmxSupportTest.java    From mongodb-async-driver with Apache License 2.0 5 votes vote down vote up
/**
 * Test method for {@link JmxSupport#unregister(String, String, int)}.
 *
 * @throws JMException
 *             On a test failure.
 */
@Test
public void testUnregisterServer() throws JMException {
    final MBeanServer mockServer = createMock(MBeanServer.class);

    final Capture<ObjectName> captureName = new Capture<ObjectName>();
    final Capture<ObjectName> captureName2 = new Capture<ObjectName>();

    expect(mockServer.isRegistered(capture(captureName))).andReturn(true);
    mockServer.unregisterMBean(capture(captureName2));
    expectLastCall();

    replay(mockServer);

    final JmxSupport support = new JmxSupport(mockServer);

    support.unregister("subType", "foo", 1234);

    verify(mockServer);

    final ObjectName name = captureName.getValue();
    assertThat(name, notNullValue());
    assertThat(name.getDomain(), is(JmxSupport.DOMAIN_NAME));
    assertThat(name.getKeyProperty("type"), is("metrics"));
    assertThat(name.getKeyProperty("subType"), is("subType"));
    assertThat(name.getKeyProperty("serverName"), is("foo"));
    assertThat(name.getKeyProperty("index"), is("1234"));

    assertThat(captureName2.getValue(), sameInstance(name));
}
 
Example 12
Source File: TestHubAlarmIncidentService.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
/**
 * The initial CO trigger is sent to both addAlert & updateIncident, but only relayed by addAlert
 */
@Test
public void testAddAlertThenUpdateAlertDoesNotDuplicateTriggers() {
   expectGetActiveAndReturnNull(incidentId);
   List<IncidentTrigger> triggers = ImmutableList.of(IncidentFixtures.createIncidentTrigger(AlertType.CO, IncidentTrigger.EVENT_CO));
   Capture<AlarmIncident> incidentCapture = expectUpdate();
   replay();
   
   // initial alert
   AlarmModel.setAlertState(CarbonMonoxideAlarm.NAME, context.model(), AlarmCapability.ALERTSTATE_ALERT);
   service.addAlert(context, CarbonMonoxideAlarm.NAME, triggers);
   
   AlarmIncident incident = incidentCapture.getValue();
   assertIncidentMonitored(incident);
   assertIncidentTrackers(incident, TrackerState.ALERT);
   assertIncidentAlert(incident, AlertType.CO);
   
   assertBroadcastAdded(incident);
   assertAddAlarm(incident, AlertType.CO, ImmutableList.of(AlertType.CO), triggers);
   assertBroadcastAlert(AlertType.CO, triggers);
   assertNoMessages();
   
   reset();
   expectGetActiveAndReturn(incident);
   expectTriggersAdded(incident, triggers);
   replay();
   
   // update incident, nothing new
   service.updateIncident(context, triggers);
   assertNoMessages();
   
   verify();
}
 
Example 13
Source File: TrackDataHubTest.java    From mytracks with Apache License 2.0 4 votes vote down vote up
/**
 * Tests tracks point able change. Register a listener after a track change.
 */
public void testTrackPointsTableUpdate_reRegisterAfterTrackChange() {

  // Register one listener
  Capture<ContentObserver> observerCapture = new Capture<ContentObserver>();
  dataSource.registerContentObserver(
      eq(TrackPointsColumns.CONTENT_URI), capture(observerCapture));

  FixedSizeLocationIterator locationIterator = new FixedSizeLocationIterator(1, 10, 5);
  expect(myTracksProviderUtils.getTrackPointLocationIterator(
      eq(TRACK_ID), eq(0L), eq(false), isA(LocationFactory.class))).andReturn(locationIterator);
  expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID)).andReturn(10L);
  trackDataListener1.clearTrackPoints();
  locationIterator.expectLocationsDelivered(trackDataListener1);
  trackDataListener1.onNewTrackPointsDone();
  replay();

  trackDataHub.start();
  trackDataHub.loadTrack(TRACK_ID);
  trackDataHub.registerTrackDataListener(
      trackDataListener1, EnumSet.of(TrackDataType.SAMPLED_IN_TRACK_POINTS_TABLE));
  verifyAndReset();

  // Unregister the listener
  ContentObserver observer = observerCapture.getValue();
  dataSource.unregisterContentObserver(observer);
  replay();

  trackDataHub.unregisterTrackDataListener(trackDataListener1);
  verifyAndReset();

  // Register the listener after a new track
  dataSource.registerContentObserver(
      eq(TrackPointsColumns.CONTENT_URI), capture(observerCapture));
  locationIterator = new FixedSizeLocationIterator(1, 10);
  expect(myTracksProviderUtils.getTrackPointLocationIterator(
      eq(TRACK_ID + 1), eq(0L), eq(false), isA(LocationFactory.class)))
      .andReturn(locationIterator);
  expect(myTracksProviderUtils.getLastTrackPointId(TRACK_ID + 1)).andReturn(10L);
  trackDataListener1.clearTrackPoints();
  locationIterator.expectLocationsDelivered(trackDataListener1);
  trackDataListener1.onNewTrackPointsDone();
  replay();

  trackDataHub.loadTrack(TRACK_ID + 1);
  trackDataHub.registerTrackDataListener(
      trackDataListener1, EnumSet.of(TrackDataType.SAMPLED_IN_TRACK_POINTS_TABLE));
  verifyAndReset();
}
 
Example 14
Source File: AbstractTransportConnectionTestCases.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for {@link TransportConnection#send} .
 *
 * @throws IOException
 *             On a failure connecting to the Mock MongoDB server.
 */
@Test
public void testConnectionLost() throws IOException {

    final MongoClientConfiguration config = new MongoClientConfiguration();
    config.setReadTimeout(100);
    connect(config);

    assertTrue("Should have connected to the server.",
            ourServer.waitForClient(TimeUnit.SECONDS.toMillis(10)));

    final DocumentBuilder builder = BuilderFactory.start();
    builder.addInteger("getlasterror", 1);

    final GetLastError error = new GetLastError("fo", false, false, 0, 0);
    myTestConnection.send(error, null);
    assertTrue("Should receive the request after flush.",
            ourServer.waitForRequest(1, TimeUnit.SECONDS.toMillis(10)));

    assertTrue(myTestConnection.isIdle());
    assertTrue(myTestConnection.isOpen());
    assertEquals(0, myTestConnection.getPendingCount());

    // Break the connection.
    final PropertyChangeListener mockListener = EasyMock
            .createMock(PropertyChangeListener.class);
    makeThreadSafe(mockListener, true);
    final Capture<PropertyChangeEvent> capture = new Capture<PropertyChangeEvent>();

    mockListener.propertyChange(capture(capture));
    expectLastCall();

    replay(mockListener);

    myTestConnection.addPropertyChangeListener(mockListener);
    ourServer.disconnectClient();
    ourServer.waitForDisconnect(TimeUnit.SECONDS.toMillis(10));
    myTestConnection.waitForClosed(10, TimeUnit.SECONDS);

    // Pause for a beat for the event to get pushed out.
    waitFor(capture);

    verify(mockListener);

    final PropertyChangeEvent evt = capture.getValue();
    assertEquals(Connection.OPEN_PROP_NAME, evt.getPropertyName());
    assertEquals(Boolean.FALSE, evt.getNewValue());
    assertEquals(Boolean.TRUE, evt.getOldValue());

    myTestConnection.removePropertyChangeListener(mockListener);

    assertTrue(myTestConnection.isIdle());
    assertFalse(myTestConnection.isOpen());
}
 
Example 15
Source File: MongoDbAuthenticatorTest.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for
 * {@link MongoDbAuthenticator#startAuthentication(Credential, Connection)}
 * .
 */
@Test
public void testAuthenticationNonceReplyMissingNonce() {
    final Credential credential = Credential
            .builder()
            .userName("allanbank")
            .password(
                    new char[] { 's', 'u', 'p', 'e', 'r', 's', 'e', 'c',
                            'r', 'e', 't' }).build();

    final Capture<Message> getNonceCapture = new Capture<Message>();
    final Capture<ReplyCallback> getNonceReplyCapture = new Capture<ReplyCallback>();

    final Connection mockConnection = createMock(Connection.class);

    mockConnection.send(capture(getNonceCapture),
            capture(getNonceReplyCapture));
    expectLastCall();

    replay(mockConnection);

    final MongoDbAuthenticator authenticator = new MongoDbAuthenticator();

    // Start the process with a getnonce command.
    authenticator.startAuthentication(credential, mockConnection);

    // Should have sent the getnonce command.
    assertThat(getNonceCapture.hasCaptured(), is(true));
    assertThat(getNonceCapture.getValue(), instanceOf(Command.class));

    final Command nonceCommand = (Command) getNonceCapture.getValue();
    assertThat(nonceCommand.getCommand(),
            is(BuilderFactory.start().add("getnonce", 1).build()));

    assertThat(getNonceReplyCapture.hasCaptured(), is(true));

    // Trigger the next stage of processing.
    final Document reply = BuilderFactory.start().build();
    getNonceReplyCapture.getValue().callback(
            new Reply(1, 0, 0, Collections.singletonList(reply), true,
                    false, false, false));

    try {
        authenticator.result();
        fail("Should have thrown a MongoDbAuthenticationException");
    }
    catch (final MongoDbAuthenticationException error) {
        // Good.
    }

    verify(mockConnection);
}
 
Example 16
Source File: TestHubAlarmIncidentService.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
/**
 * The initial SECURITY alerts have already been passed along during PREALERT
 * Then SECURITY alerts
 * Then an additional trigger is sent
 */
@Test
public void testAddAlertThenUpdateAlertIncludesNewTriggers() {
   expectGetActiveAndReturnNull(incidentId);
   List<IncidentTrigger> initialTriggers = ImmutableList.of(IncidentFixtures.createIncidentTrigger(AlertType.SECURITY, IncidentTrigger.EVENT_MOTION), IncidentFixtures.createIncidentTrigger(AlertType.SECURITY, IncidentTrigger.EVENT_MOTION));
   Date preAlertEndTime = new Date(initialTriggers.get(0).getTime().getTime() + 1000);
   IncidentTrigger postAlertTrigger = IncidentFixtures.createIncidentTrigger(AlertType.SECURITY, IncidentTrigger.EVENT_MOTION);
   postAlertTrigger.setTime(new Date(preAlertEndTime.getTime() + 1000));
   List<IncidentTrigger> secondaryTriggers = ImmutableList.of(postAlertTrigger);
   Capture<AlarmIncident> incidentCapture = expectUpdate();
   replay();

   // pre-alert
   AlarmModel.setAlertState(SecurityAlarm.NAME, context.model(), AlarmCapability.ALERTSTATE_PREALERT);
   service.addPreAlert(context, SecurityAlarm.NAME, preAlertEndTime, initialTriggers);

   AlarmIncident incident = incidentCapture.getValue();
   assertIncidentMonitored(incident);
   assertIncidentTrackers(incident, TrackerState.PREALERT);
   assertIncidentPreAlert(incident, preAlertEndTime);
   
   assertBroadcastAdded(incident);
   assertNoMessages();
   
   reset();
   EasyMock.expect(mockPopulationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL).anyTimes();
   expectGetActiveAndReturn(incident);
   incidentCapture = expectUpdate();
   replay();
   
   // entrance delay expires
   AlarmModel.setAlertState(SecurityAlarm.NAME, context.model(), AlarmCapability.ALERTSTATE_ALERT);
   service.addAlert(context, SecurityAlarm.NAME, initialTriggers);
   
   incident = incidentCapture.getValue();
   assertIncidentMonitored(incident);
   assertIncidentTrackers(incident, TrackerState.PREALERT, TrackerState.ALERT);
   assertIncidentAlert(incident, AlertType.SECURITY);
   
   assertBroadcastChanged(incident);
   assertAddAlarm(incident, AlertType.SECURITY, ImmutableList.of(AlertType.SECURITY), initialTriggers);
   assertBroadcastAlert(AlertType.SECURITY, initialTriggers);
   assertNoMessages();
   
   reset();
   EasyMock.expect(mockPopulationCacheMgr.getPopulationByPlaceId(EasyMock.anyObject(UUID.class))).andReturn(Population.NAME_GENERAL).anyTimes();
   expectGetActiveAndReturn(incident);
   expectTriggersAdded(incident, secondaryTriggers);
   replay();
   
   // update incident, nothing new
   service.updateIncident(context, secondaryTriggers);
   assertAddAlarm(incident, AlertType.SECURITY, ImmutableList.of(AlertType.SECURITY), secondaryTriggers);
   assertNoMessages();
   
   verify();
}
 
Example 17
Source File: BatchedWriteCallbackTest.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for
 * {@link BatchedWriteCallback#BatchedWriteCallback(String, String,Callback, BatchedWrite, Client, List)}
 * . This constructor is used for a set of write operations that do use the
 * write commands. e.g., the server is on or after MongoDB 2.6.
 */
@SuppressWarnings("unchecked")
@Test
public void testBatchedWriteUsingWriteCommandsDurabilityFailure() {
    final Document doc = d().build();

    final String databaseName = "db";
    final Callback<Long> mockResults = createMock(Callback.class);
    final BatchedWrite write = BatchedWrite.builder().insert(doc)
            .update(doc, doc).delete(doc).build();
    final Client mockClient = createMock(Client.class);
    final List<BatchedWrite.Bundle> bundles = write.toBundles("foo",
            Client.MAX_DOCUMENT_SIZE, 1000);

    final DocumentBuilder replyErrorDoc = BuilderFactory.start()
            .add("ok", 1).add("n", 0);
    replyErrorDoc.push("writeConcernError").add("code", 1234)
            .add("errmsg", "Durabilty Error");
    final Reply replyError = new Reply(0, 0, 0,
            Collections.singletonList(replyErrorDoc.build()), false, false,
            false, false);

    final Document replyDoc = BuilderFactory.start().add("ok", 1)
            .add("n", 1).build();
    final Reply reply = new Reply(0, 0, 0,
            Collections.singletonList(replyDoc), false, false, false, false);

    replay(mockResults, mockClient);
    final BatchedWriteCallback cb = new BatchedWriteCallback(databaseName,
            "foo", mockResults, write, mockClient, bundles);
    assertThat(cb.getForwardCallback(), sameInstance(mockResults));
    verify(mockResults, mockClient);

    final Capture<ReplyCallback> capture1 = new Capture<ReplyCallback>();
    final Capture<ReplyCallback> capture2 = new Capture<ReplyCallback>();
    final Capture<ReplyCallback> capture3 = new Capture<ReplyCallback>();

    // Send the requests.
    reset(mockResults, mockClient);
    mockClient.send(anyObject(Message.class), capture(capture1));
    expectLastCall();
    mockClient.send(anyObject(Message.class), capture(capture2));
    expectLastCall();
    mockClient.send(anyObject(Message.class), capture(capture3));
    expectLastCall();
    replay(mockResults, mockClient);
    cb.send();
    verify(mockResults, mockClient);

    // Now the results.
    reset(mockResults, mockClient);
    replay(mockResults, mockClient);
    capture1.getValue().callback(reply);
    verify(mockResults, mockClient);

    // Now the results.
    reset(mockResults, mockClient);
    replay(mockResults, mockClient);
    capture2.getValue().callback(replyError);
    verify(mockResults, mockClient);

    // Now the results.
    final Capture<Throwable> caughtError = new Capture<Throwable>();
    reset(mockResults, mockClient);
    mockResults.exception(capture(caughtError));
    expectLastCall();
    replay(mockResults, mockClient);
    capture3.getValue().callback(reply);
    verify(mockResults, mockClient);

    final Throwable caught = caughtError.getValue();
    assertThat(caught, instanceOf(BatchedWriteException.class));
    final BatchedWriteException batchError = (BatchedWriteException) caught;
    assertThat(batchError.getErrors().size(), is(1));
    assertThat(batchError.getErrors().keySet().iterator().next(), is(write
            .getWrites().get(1)));
    final Throwable t = batchError.getErrors().values().iterator().next();
    assertThat(t.getMessage(), is("Durabilty Error"));
    assertThat(batchError.getN(), is(2L));
    assertThat(batchError.getSkipped().isEmpty(), is(true));
    assertThat(batchError.getWrite(), sameInstance(write));

}
 
Example 18
Source File: CursorCallbackTest.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for {@link CursorCallback#getAddress()} and
 * {@link CursorCallback#setAddress}.
 */
@SuppressWarnings("unchecked")
@Test
public void testGetAddress() {
    final Query q = new Query("db", "c", BuilderFactory.start().build(),
            null, 0, 0, 0, false, ReadPreference.PRIMARY, false, false,
            false, false);
    final Reply reply = reply();

    final Callback<MongoIterator<Document>> mockCallback = createMock(Callback.class);

    replay(mockCallback);

    CursorCallback callback = new CursorCallback(null, q, false,
            mockCallback);
    assertNull(callback.getAddress());
    callback.setAddress("server");
    assertEquals("server", callback.getAddress());

    verify(mockCallback);

    reset(mockCallback);

    replay(mockCallback);

    callback = new CursorCallback(null, q, false, mockCallback);
    callback.callback(reply);
    verify(mockCallback);

    reset(mockCallback);

    final Capture<MongoIterator<Document>> capture2 = new Capture<MongoIterator<Document>>();
    mockCallback.callback(capture(capture2));
    EasyMock.expectLastCall();

    replay(mockCallback);

    assertNull(callback.getAddress());
    callback.setAddress("server");
    assertEquals("server", callback.getAddress());

    final MongoIterator<Document> iter = capture2.getValue();
    assertThat(iter, instanceOf(MongoIteratorImpl.class));
    final MongoIteratorImpl mIter = (MongoIteratorImpl) iter;
    assertEquals("server", mIter.getReadPerference().getServer());

    verify(mockCallback);
}
 
Example 19
Source File: TaxonomyResourceProviderTest.java    From incubator-atlas with Apache License 2.0 4 votes vote down vote up
@Test
public void testGetResourceById_notInitialized_taxonomyAlreadyExists() throws Exception {
    AtlasTypeSystem typeSystem = createStrictMock(AtlasTypeSystem.class);
    QueryFactory queryFactory = createStrictMock(QueryFactory.class);
    AtlasQuery query = createStrictMock(AtlasQuery.class);
    Capture<Request> checkForAnyTaxonomiesCapture = newCapture();
    Capture<Request> requestCapture = newCapture();

    Collection<Map<String, Object>> queryResult = new ArrayList<>();
    Map<String, Object> queryResultRow = new HashMap<>();
    queryResult.add(queryResultRow);
    queryResultRow.put("name", "taxonomyName");
    queryResultRow.put("description", "test taxonomy description");
    queryResultRow.put("creation_time", "04/20/2016");

    // mock expectations
    expect(queryFactory.createTaxonomyQuery(capture(checkForAnyTaxonomiesCapture))).andReturn(query);
    expect(query.execute()).andReturn(queryResult);
    expect(queryFactory.createTaxonomyQuery(capture(requestCapture))).andReturn(query);
    expect(query.execute()).andReturn(queryResult);
    replay(typeSystem, queryFactory, query);

    TestTaxonomyResourceProvider provider = new TestTaxonomyResourceProvider(typeSystem);
    provider.setInitialized(false);
    provider.setQueryFactory(queryFactory);

    Map<String, Object> requestProperties = new HashMap<>();
    requestProperties.put("name", "taxonomyName");
    Request userRequest = new InstanceRequest(requestProperties);

    Result result = provider.getResourceById(userRequest);

    assertEquals(1, result.getPropertyMaps().size());
    assertEquals(queryResultRow, result.getPropertyMaps().iterator().next());

    Request request = requestCapture.getValue();
    assertNull(request.getQueryString());
    assertEquals(0, request.getAdditionalSelectProperties().size());
    assertEquals(requestProperties, request.getQueryProperties());

    verify(typeSystem, queryFactory, query);
}
 
Example 20
Source File: MongoDbAuthenticatorTest.java    From mongodb-async-driver with Apache License 2.0 4 votes vote down vote up
/**
 * Test method for
 * {@link MongoDbAuthenticator#startAuthentication(Credential, Connection)}
 * .
 */
@Test
public void testAuthenticationFails() {
    final Credential credential = Credential
            .builder()
            .userName("allanbank")
            .password(
                    new char[] { 's', 'u', 'p', 'e', 'r', 's', 'e', 'c',
                            'r', 'e', 't' }).build();

    final Capture<Message> getNonceCapture = new Capture<Message>();
    final Capture<ReplyCallback> getNonceReplyCapture = new Capture<ReplyCallback>();
    final Capture<Message> authCapture = new Capture<Message>();
    final Capture<ReplyCallback> authReplyCapture = new Capture<ReplyCallback>();

    final Connection mockConnection = createMock(Connection.class);

    mockConnection.send(capture(getNonceCapture),
            capture(getNonceReplyCapture));
    expectLastCall();
    mockConnection.send(capture(authCapture), capture(authReplyCapture));
    expectLastCall();

    replay(mockConnection);

    final MongoDbAuthenticator authenticator = new MongoDbAuthenticator();

    // Start the process with a getnonce command.
    authenticator.startAuthentication(credential, mockConnection);

    // Should have sent the getnonce command.
    assertThat(getNonceCapture.hasCaptured(), is(true));
    assertThat(getNonceCapture.getValue(), instanceOf(Command.class));

    final Command nonceCommand = (Command) getNonceCapture.getValue();
    assertThat(nonceCommand.getCommand(),
            is(BuilderFactory.start().add("getnonce", 1).build()));

    assertThat(getNonceReplyCapture.hasCaptured(), is(true));

    // Trigger the next stage of processing.
    Document reply = BuilderFactory.start()
            .add("nonce", "0123456789abcdef").build();
    getNonceReplyCapture.getValue().callback(
            new Reply(1, 0, 0, Collections.singletonList(reply), true,
                    false, false, false));

    // And the auth command is sent.
    assertThat(authCapture.hasCaptured(), is(true));
    assertThat(authCapture.getValue(), instanceOf(Command.class));

    final Command authCommand = (Command) authCapture.getValue();
    assertThat(
            authCommand.getCommand(),
            is(BuilderFactory.start().addInteger("authenticate", 1)
                    .add(reply.get("nonce"))
                    .addString("user", credential.getUserName())
                    .addString("key", "54d8cd8954719ec33c7166807c164969")
                    .build()));

    assertThat(authReplyCapture.hasCaptured(), is(true));

    // and trigger the auth failure.
    reply = BuilderFactory.start().build();
    authReplyCapture.getValue().callback(
            new Reply(1, 0, 0, Collections.singletonList(reply), true,
                    false, false, false));

    assertThat(authenticator.result(), is(false));

    verify(mockConnection);
}