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

The following examples show how to use org.easymock.Capture#getValues() . 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: TestPremiumNotificationStrategy.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleTriggersOfSameTypeOnlyIssueOneNotification() {
   Capture<CallTreeContext> contextCapture = EasyMock.newCapture(CaptureType.ALL);
   callTreeExecutor.notifyParallel(EasyMock.capture(contextCapture));
   EasyMock.expectLastCall();

   setupCallTree(1, callTreeEntry(UUID.randomUUID(), true));
   Trigger t = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 1);
   Trigger t2 = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 0);

   replay();

   AlarmIncident incident = incidentBuilder()
         .withAlert(AlertType.CO)
         .build();

   strategy.execute(incident.getAddress(), incident.getPlaceId(), ImmutableList.of(t, t2));
   List<CallTreeContext> contexts = contextCapture.getValues();
   assertEquals(1, contexts.size());
   assertCallTreeContext(contexts.get(0), NotificationConstants.CO_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL);
   verify();
}
 
Example 2
Source File: TestBasicNotificationStrategy.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleAlerts() {
   Capture<CallTreeContext> contextCapture = EasyMock.newCapture(CaptureType.ALL);
   callTreeExecutor.notifyOwner(EasyMock.capture(contextCapture));
   EasyMock.expectLastCall().times(2);

   setupCallTree(1, callTreeEntry(UUID.randomUUID(), true));
   Trigger t = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 1);
   Trigger t2 = setupTrigger(UUID.randomUUID(), AlertType.SECURITY, "Some Device", "Some Dev Type Hint", 1);

   replay();

   AlarmIncident incident = incidentBuilder()
         .withAlert(AlertType.CO)
         .addAdditionalAlert(AlertType.SECURITY)
         .build();

   strategy.execute(incident.getAddress(), incident.getPlaceId(), ImmutableList.of(t, t2));
   List<CallTreeContext> contexts = contextCapture.getValues();
   assertEquals(2, contexts.size());
   assertCallTreeContext(contexts.get(0), NotificationConstants.CO_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL);
   assertCallTreeContext(contexts.get(1), NotificationConstants.SECURITY_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL);
   verify();
}
 
Example 3
Source File: TestBasicNotificationStrategy.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultipleTriggersOfSameTypeOnlyIssueOneNotification() {
   Capture<CallTreeContext> contextCapture = EasyMock.newCapture(CaptureType.ALL);
   callTreeExecutor.notifyOwner(EasyMock.capture(contextCapture));
   EasyMock.expectLastCall();

   setupCallTree(1, callTreeEntry(UUID.randomUUID(), true));
   Trigger t = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 1);
   Trigger t2 = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 0);

   replay();

   AlarmIncident incident = incidentBuilder()
         .withAlert(AlertType.CO)
         .build();

   strategy.execute(incident.getAddress(), incident.getPlaceId(), ImmutableList.of(t, t2));
   List<CallTreeContext> contexts = contextCapture.getValues();
   assertEquals(1, contexts.size());
   assertCallTreeContext(contexts.get(0), NotificationConstants.CO_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL);
   verify();
}
 
Example 4
Source File: MongoDbOutputTest.java    From pentaho-mongodb-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if mongo output configuration contains excessive fields in step input against mongo output fields, we
 * generate a mockLog record about the fields will not be used in mongo output.
 *
 * @throws Exception
 */
@Test public void testStepLogSkippedFields() throws Exception {
  MongoDbOutput output = prepareMongoDbOutputMock();

  final String[] metaNames = new String[] { "a1", "a2", "a3" };
  String[] mongoNames = new String[] { "a1", "a2" };
  Capture<String> loggerCapture = new Capture<String>( CaptureType.ALL );
  output.logBasic( EasyMock.capture( loggerCapture ) );
  EasyMock.replay( output );
  RowMetaInterface rmi = getStubRowMetaInterface( metaNames );
  List<MongoDbOutputMeta.MongoField> mongoFields = getMongoFields( mongoNames );

  output.checkInputFieldsMatch( rmi, mongoFields );
  List<String> logRecords = loggerCapture.getValues();

  Assert.assertEquals( "We have one mockLog record generated", 1, logRecords.size() );
  Assert.assertTrue( "We have a mockLog record mentions that 'a3' field will not be used.",
    logRecords.get( 0 ).contains( "a3" ) );
}
 
Example 5
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testEventBusLogForFallbackDisabled() throws ExecutionException, InterruptedException {
  Capture<AbstractBuckEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(3);
  EasyMock.replay(eventBus);

  testRemoteActionExceptionFallbackDisabledForBuildError();

  List<AbstractBuckEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof ConsoleEvent);
  Assert.assertTrue(events.get(2) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(2);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
}
 
Example 6
Source File: TestBasicNotificationStrategy.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleAlertsSecondLater() {
   Capture<CallTreeContext> contextCapture = EasyMock.newCapture(CaptureType.ALL);
   callTreeExecutor.notifyOwner(EasyMock.capture(contextCapture));
   EasyMock.expectLastCall().times(2);

   setupCallTree(2, callTreeEntry(UUID.randomUUID(), true));
   Trigger t = setupTrigger(UUID.randomUUID(), AlertType.CO, "Some Device", "Some Dev Type Hint", 1);
   Trigger t2 = setupTrigger(UUID.randomUUID(), AlertType.SECURITY, "Some Device", "Some Dev Type Hint", 1);

   replay();

   AlarmIncident incident = incidentBuilder()
         .withAlert(AlertType.CO)
         .build();

   strategy.execute(incident.getAddress(), incident.getPlaceId(), ImmutableList.of(t));

   // simulate a second alert occurring after the first one has already been notified
   incident = AlarmIncident.builder(incident)
         .addAdditionalAlert(AlertType.SECURITY)
         .build();

   strategy.execute(incident.getAddress(), incident.getPlaceId(), ImmutableList.of(t, t2));

   List<CallTreeContext> contexts = contextCapture.getValues();
   assertEquals(2, contexts.size());
   assertCallTreeContext(contexts.get(0), NotificationConstants.CO_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL);
   assertCallTreeContext(contexts.get(1), NotificationConstants.SECURITY_KEY, NotificationCapability.NotifyRequest.PRIORITY_CRITICAL);
   verify();
}
 
Example 7
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testRemoteGrpcException() throws ExecutionException, InterruptedException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(6);
  EasyMock.replay(eventBus);

  EasyMock.expect(strategyBuildResult.getBuildResult())
      .andReturn(Futures.immediateFailedFuture(Status.DEADLINE_EXCEEDED.asRuntimeException()))
      .times(2);
  BuildResult localResult = successBuildResult("//local/did:though");
  EasyMock.expect(buildStrategyContext.runWithDefaultBehavior())
      .andReturn(Futures.immediateFuture(Optional.of(localResult)))
      .once();
  EasyMock.expect(buildStrategyContext.getExecutorService()).andReturn(directExecutor).once();
  EasyMock.expect(strategyBuildResult.getRuleContext()).andReturn(ruleContext);

  EasyMock.replay(strategyBuildResult, buildStrategyContext);
  ruleContext.enterState(State.UPLOADING_ACTION, Optional.empty());
  ruleContext.enterState(State.EXECUTING, Optional.empty());
  FallbackStrategyBuildResult fallbackStrategyBuildResult =
      new FallbackStrategyBuildResult(
          RULE_NAME, strategyBuildResult, buildStrategyContext, eventBus, true, false, true);
  Assert.assertEquals(
      localResult.getStatus(),
      fallbackStrategyBuildResult.getBuildResult().get().get().getStatus());
  EasyMock.verify(strategyBuildResult, buildStrategyContext);

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertEquals(6, events.size());
  Assert.assertTrue(events.get(4) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(5) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(5);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.DEADLINE_EXCEEDED);
  Assert.assertEquals(finishedEvent.getLastNonTerminalState(), State.EXECUTING);
  Assert.assertEquals(finishedEvent.getExitCode(), OptionalInt.empty());
}
 
Example 8
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testEventsAreSent() throws ExecutionException, InterruptedException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(2);
  EasyMock.replay(eventBus);

  testRemoteActionError();

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(1);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
}
 
Example 9
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test
public void testInterruptedState() throws ExecutionException, InterruptedException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(2);
  EasyMock.replay(eventBus);

  testRemoteInterruptedException();

  List<LocalFallbackEvent> events = eventCapture.getValues();
  LocalFallbackEvent.Finished event = (LocalFallbackEvent.Finished) events.get(1);
  Assert.assertEquals(LocalFallbackEvent.Result.INTERRUPTED, event.getRemoteResult());
  Assert.assertEquals(LocalFallbackEvent.Result.SUCCESS, event.getLocalResult());
}
 
Example 10
Source File: LinkDiscoveryManagerTest.java    From floodlight_with_topoguard with Apache License 2.0 4 votes vote down vote up
@Test
public void testSwitchAdded() throws Exception {
    LinkDiscoveryManager linkDiscovery = getLinkDiscoveryManager();
    Capture<OFMessage> wc;
    Capture<FloodlightContext> fc;
    Set<Short> qPorts;
    OFPhysicalPort ofpp = new OFPhysicalPort();
    ofpp.setName("eth4242");
    ofpp.setPortNumber((short)4242);
    ofpp.setHardwareAddress(HexString.fromHexString("5c:16:c7:00:00:01"));
    ofpp.setCurrentFeatures(0);
    ImmutablePort p1 = ImmutablePort.fromOFPhysicalPort(ofpp);
    IOFSwitch sw1 = createMockSwitch(1L);

    // Set switch map in floodlightProvider.
    Map<Long, IOFSwitch> switches = new HashMap<Long, IOFSwitch>();
    switches.put(1L, sw1);
    getMockFloodlightProvider().setSwitches(switches);

    // Create the set of ports
    List<Short> ports = new ArrayList<Short>();
    for(short p=1; p<=20; ++p) {
        ports.add(p);
    }

    // Set the captures.
    wc = new Capture<OFMessage>(CaptureType.ALL);
    fc = new Capture<FloodlightContext>(CaptureType.ALL);

    // Expect switch to return those ports.
    expect(sw1.getEnabledPortNumbers()).andReturn(ports).anyTimes();
    expect(sw1.getPort(EasyMock.anyShort())).andReturn(p1).anyTimes();
    sw1.write(capture(wc), capture(fc));
    expectLastCall().anyTimes();
    replay(sw1);

    linkDiscovery.switchActivated(sw1.getId());
    verify(sw1);

    qPorts = linkDiscovery.getQuarantinedPorts(sw1.getId());
    assertNotNull(qPorts);
    assertFalse(qPorts.isEmpty());

    Thread.sleep(100);
    qPorts = linkDiscovery.getQuarantinedPorts(sw1.getId());
    assertNotNull(qPorts);
    assertFalse(qPorts.isEmpty());

    Thread.sleep(200);
    qPorts = linkDiscovery.getQuarantinedPorts(sw1.getId());
    assertNotNull(qPorts);
    assertTrue(qPorts.isEmpty());

    // Ensure that through every switch port, an LLDP and BDDP
    // packet was sent out.  Total # of packets = # of ports * 2.
    assertTrue(wc.hasCaptured());
    List<OFMessage> msgList = wc.getValues();
    assertTrue(msgList.size() == ports.size() * 2);
}
 
Example 11
Source File: DhcpRelayManagerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Ignores specific vlans from specific devices if config.
 *
 * @throws Exception the exception from this test
 */
@Test
public void testIgnoreVlan() throws Exception {
    ObjectMapper om = new ObjectMapper();
    JsonNode json = om.readTree(Resources.getResource(CONFIG_FILE_PATH));
    IgnoreDhcpConfig config = new IgnoreDhcpConfig();
    json = json.path("apps").path(DHCP_RELAY_APP).path(IgnoreDhcpConfig.KEY);
    config.init(APP_ID, IgnoreDhcpConfig.KEY, json, om, null);

    Capture<Objective> capturedFromDev1 = newCapture(CaptureType.ALL);
    flowObjectiveService.apply(eq(DEV_1_ID), capture(capturedFromDev1));
    expectLastCall().times(DHCP_SELECTORS.size());
    Capture<Objective> capturedFromDev2 = newCapture(CaptureType.ALL);
    flowObjectiveService.apply(eq(DEV_2_ID), capture(capturedFromDev2));
    expectLastCall().times(DHCP_SELECTORS.size());
    replay(flowObjectiveService);
    manager.updateConfig(config);
    verify(flowObjectiveService);

    List<Objective> objectivesFromDev1 = capturedFromDev1.getValues();
    List<Objective> objectivesFromDev2 = capturedFromDev2.getValues();

    assertTrue(objectivesFromDev1.containsAll(objectivesFromDev2));
    assertTrue(objectivesFromDev2.containsAll(objectivesFromDev1));

    for (int index = 0; index < objectivesFromDev1.size(); index++) {
        TrafficSelector selector =
                DefaultTrafficSelector.builder(DHCP_SELECTORS.get(index))
                .matchVlanId(IGNORED_VLAN)
                .build();
        ForwardingObjective fwd = (ForwardingObjective) objectivesFromDev1.get(index);
        assertEquals(selector, fwd.selector());
        assertEquals(DefaultTrafficTreatment.emptyTreatment(), fwd.treatment());
        assertEquals(IGNORE_CONTROL_PRIORITY, fwd.priority());
        assertEquals(ForwardingObjective.Flag.VERSATILE, fwd.flag());
        assertEquals(Objective.Operation.ADD, fwd.op());
        fwd.context().ifPresent(ctx -> {
            ctx.onSuccess(fwd);
        });
    }
    objectivesFromDev2.forEach(obj -> obj.context().ifPresent(ctx -> ctx.onSuccess(obj)));
    assertEquals(2, v4Handler.ignoredVlans.size());
    assertEquals(2, v6Handler.ignoredVlans.size());
}
 
Example 12
Source File: DhcpRelayManagerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * "IgnoreVlan" policy should be removed when the config removed.
 */
@Test
public void testRemoveIgnoreVlan() {
    v4Handler.ignoredVlans.put(DEV_1_ID, IGNORED_VLAN);
    v4Handler.ignoredVlans.put(DEV_2_ID, IGNORED_VLAN);
    v6Handler.ignoredVlans.put(DEV_1_ID, IGNORED_VLAN);
    v6Handler.ignoredVlans.put(DEV_2_ID, IGNORED_VLAN);
    IgnoreDhcpConfig config = new IgnoreDhcpConfig();

    Capture<Objective> capturedFromDev1 = newCapture(CaptureType.ALL);
    flowObjectiveService.apply(eq(DEV_1_ID), capture(capturedFromDev1));
    expectLastCall().times(DHCP_SELECTORS.size());
    Capture<Objective> capturedFromDev2 = newCapture(CaptureType.ALL);
    flowObjectiveService.apply(eq(DEV_2_ID), capture(capturedFromDev2));
    expectLastCall().times(DHCP_SELECTORS.size());
    replay(flowObjectiveService);
    manager.removeConfig(config);
    verify(flowObjectiveService);

    List<Objective> objectivesFromDev1 = capturedFromDev1.getValues();
    List<Objective> objectivesFromDev2 = capturedFromDev2.getValues();

    assertTrue(objectivesFromDev1.containsAll(objectivesFromDev2));
    assertTrue(objectivesFromDev2.containsAll(objectivesFromDev1));

    for (int index = 0; index < objectivesFromDev1.size(); index++) {
        TrafficSelector selector =
                DefaultTrafficSelector.builder(DHCP_SELECTORS.get(index))
                .matchVlanId(IGNORED_VLAN)
                .build();
        ForwardingObjective fwd = (ForwardingObjective) objectivesFromDev1.get(index);
        assertEquals(selector, fwd.selector());
        assertEquals(DefaultTrafficTreatment.emptyTreatment(), fwd.treatment());
        assertEquals(IGNORE_CONTROL_PRIORITY, fwd.priority());
        assertEquals(ForwardingObjective.Flag.VERSATILE, fwd.flag());
        assertEquals(Objective.Operation.REMOVE, fwd.op());
        fwd.context().ifPresent(ctx -> {
            ctx.onSuccess(fwd);
        });
    }
    objectivesFromDev2.forEach(obj -> obj.context().ifPresent(ctx -> ctx.onSuccess(obj)));
    assertEquals(0, v4Handler.ignoredVlans.size());
    assertEquals(0, v6Handler.ignoredVlans.size());
}
 
Example 13
Source File: LocalFallbackStrategyTest.java    From buck with Apache License 2.0 4 votes vote down vote up
@Test
public void testExitCodeAndFallback()
    throws ExecutionException, InterruptedException, IOException {
  Capture<LocalFallbackEvent> eventCapture = Capture.newInstance(CaptureType.ALL);
  eventBus.post(EasyMock.capture(eventCapture));
  EasyMock.expectLastCall().times(2);
  EasyMock.replay(eventBus);
  String mockWorker = "mock_worker";
  RemoteExecutionMetadata remoteExecutionMetadata =
      RemoteExecutionMetadata.newBuilder()
          .setWorkerInfo(WorkerInfo.newBuilder().setHostname(mockWorker).build())
          .setExecutedActionInfo(
              ExecutedActionInfo.newBuilder()
                  .setIsFallbackEnabledForCompletedAction(
                      BoolValue.newBuilder().setValue(true).build())
                  .build())
          .build();

  StepFailedException exc =
      StepFailedException.createForFailingStepWithExitCode(
          new AbstractExecutionStep("remote_execution") {
            @Override
            public StepExecutionResult execute(ExecutionContext context) {
              throw new RuntimeException();
            }
          },
          executionContext,
          StepExecutionResult.builder().setExitCode(1).setStderr("").build(),
          remoteExecutionMetadata);

  // Just here to test if this is serializable by jackson, as we do Log.warn this.
  new ObjectMapper().writeValueAsString(exc);

  EasyMock.expect(strategyBuildResult.getBuildResult())
      .andReturn(Futures.immediateFailedFuture(exc))
      .times(2);
  BuildResult localResult = successBuildResult("//local/did:though");
  EasyMock.expect(buildStrategyContext.runWithDefaultBehavior())
      .andReturn(Futures.immediateFuture(Optional.of(localResult)))
      .once();
  EasyMock.expect(buildStrategyContext.getExecutorService()).andReturn(directExecutor).once();
  EasyMock.expect(strategyBuildResult.getRuleContext()).andReturn(ruleContext);

  EasyMock.replay(strategyBuildResult, buildStrategyContext);
  FallbackStrategyBuildResult fallbackStrategyBuildResult =
      new FallbackStrategyBuildResult(
          RULE_NAME, strategyBuildResult, buildStrategyContext, eventBus, true, false, false);
  Assert.assertEquals(
      localResult.getStatus(),
      fallbackStrategyBuildResult.getBuildResult().get().get().getStatus());
  EasyMock.verify(strategyBuildResult, buildStrategyContext);

  List<LocalFallbackEvent> events = eventCapture.getValues();
  Assert.assertTrue(events.get(0) instanceof LocalFallbackEvent.Started);
  Assert.assertTrue(events.get(1) instanceof LocalFallbackEvent.Finished);
  LocalFallbackEvent.Finished finishedEvent = (LocalFallbackEvent.Finished) events.get(1);
  Assert.assertEquals(finishedEvent.getRemoteGrpcStatus(), Status.OK);
  Assert.assertEquals(finishedEvent.getExitCode(), OptionalInt.of(1));
  Assert.assertEquals(
      finishedEvent.getRemoteExecutionMetadata().get().getWorkerInfo().getHostname(), mockWorker);
}