org.easymock.CaptureType Java Examples

The following examples show how to use org.easymock.CaptureType. 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: TestCallTree.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private static void initEasyMockVariableSupport(final SubsystemContext<? extends SubsystemModel> context){
   // basically this is implementing variable support
   final Capture<String> nameRef = EasyMock.newCapture(CaptureType.LAST);
   final Capture<Object> valueRef = EasyMock.newCapture(CaptureType.LAST);
   EasyMock
      .expect(context.getVariable(EasyMock.capture(nameRef)))
      .andAnswer(new IAnswer<LooselyTypedReference>() {
         @Override
         public LooselyTypedReference answer() throws Throwable {
            String json = context.model().getAttribute(TypeMarker.string(), "_subvars:" + nameRef.getValue(), "null");
            return JSON.fromJson(json, LooselyTypedReference.class);
         }
      })
      .anyTimes();
   context.setVariable(EasyMock.capture(nameRef), EasyMock.capture(valueRef));
   EasyMock
      .expectLastCall()
      .andAnswer(new IAnswer<Object>() {
         @Override
         public Object answer() throws Throwable {
            context.model().setAttribute("_subvars:" + nameRef.getValue(), JSON.toJson(valueRef.getValue()));
            return null;
         }
      })
      .anyTimes();
}
 
Example #2
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 #3
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 #4
Source File: TestCallTree.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void setupHappyPath(boolean callReplay){

      setupCallTree();

      EasyMock.expect(context.model()).andReturn(model).anyTimes();
      EasyMock.expect(context.logger()).andReturn(LOGGER).anyTimes();
      EasyMock.expect(context.getAccountId()).andReturn((UUID) accountModel.getAddress().getId()).anyTimes();
      EasyMock.expect(context.getPlaceId()).andReturn((UUID) placeModel.getAddress().getId()).anyTimes();
      
      store = new SimpleModelStore();
      EasyMock.expect(context.models()).andReturn(store).anyTimes();
      store.addModel(owner.toMap());
      
      
      messgaesSent = EasyMock.newCapture(CaptureType.ALL);
      context.send(EasyMock.anyObject(Address.class), EasyMock.capture(messgaesSent));
      EasyMock.expectLastCall().anyTimes();
      
      wakeUpTimeout = EasyMock.newCapture(CaptureType.ALL);
      EasyMock.expect(context.wakeUpAt(EasyMock.capture(wakeUpTimeout))).andReturn(null).anyTimes();
      
      if(callReplay){
         EasyMock.replay(context);
      }
   }
 
Example #5
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 #6
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 #7
Source File: MetricsManagerTest.java    From ambari-logsearch with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
  manager = new MetricsManager();

  mockClient = strictMock(LogFeederAMSClient.class);
  Field f = MetricsManager.class.getDeclaredField("amsClient");
  f.setAccessible(true);
  f.set(manager, mockClient);

  EasyMock.expect(mockClient.getCollectorUri(null)).andReturn("null://null:null/null").anyTimes();
  capture = EasyMock.newCapture(CaptureType.FIRST);
  mockClient.emitMetrics(EasyMock.capture(capture));
  EasyMock.expectLastCall().andReturn(true).once();

  replay(mockClient);
  manager.setAmsClient(mockClient);
  manager.init();
}
 
Example #8
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 #9
Source File: TestPlaceServiceLevelDowngradeListener.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoOnMessageServiceLevelBasic() {
	PlatformMessage message = createListenerAndMessage(ServiceLevel.BASIC);
	//setup mocks
	EasyMock.expect(mockCache.isServiceLevelChange(message)).andReturn(true);
	EasyMock.expect(mockVideoDao.countByTag(curPlaceId, VideoConstants.TAG_FAVORITE)).andReturn(5l);
	Capture<Date> deleteTimeCapture = EasyMock.newCapture(CaptureType.LAST);
	
	mockVideoDao.addToPurgePinnedRecording(EasyMock.eq(curPlaceId), EasyMock.capture(deleteTimeCapture));
	EasyMock.expectLastCall();
	replay();
	
	long now = System.currentTimeMillis();
	theListener.onMessage(message);
	Date deleteTime = deleteTimeCapture.getValue();
	int deleteDelay = (int) TimeUnit.MILLISECONDS.toDays(deleteTime.getTime() - now);
	
	assertEquals(theListener.getPurgePinnedVideosAfterDays(), deleteDelay);
	verify();
}
 
Example #10
Source File: TestVerifyEmailRESTHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
private void mockSetup(UUID personId, String token) {
	EasyMock.expect(client.getPrincipalId()).andReturn(personId).anyTimes();
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(personId, generateRequest(token)).getBytes()));
   EasyMock.expect(ctx.channel()).andReturn(channel).anyTimes();

   EasyMock.expect(clientFactory.get(channel)).andReturn(client).anyTimes();
   platformMsgCapture = EasyMock.newCapture(CaptureType.ALL);     
   EasyMock.expect(platformBus.send(EasyMock.capture(platformMsgCapture))).andAnswer(
      () -> {
         return Futures.immediateFuture(null);
      }
   ).anyTimes();
   
   
   //logout always needs to be called
   client.logout();
	EasyMock.expectLastCall();   	  	
	EasyMock.expect(authenticator.expireCookie()).andReturn(new DefaultCookie("test", "test"));
}
 
Example #11
Source File: FilterJSONTest.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public void init(FilterJsonDescriptorImpl filterJsonDescriptor) throws Exception {
  mockOutputManager = EasyMock.strictMock(OutputManager.class);
  capture = EasyMock.newCapture(CaptureType.LAST);

  filterJson = new FilterJSON();
  filterJson.loadConfig(filterJsonDescriptor);
  filterJson.setOutputManager(mockOutputManager);
  filterJson.init(new LogFeederProps());
}
 
Example #12
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 #13
Source File: EasyMockCaptureAgrumentExample.java    From journaldev with MIT License 5 votes vote down vote up
@Test
public void test_multiple_calls_args_catcher() {
	ArrayList<Integer> mockList = mock(ArrayList.class);
	Capture<Integer> captureArguments = newCapture(CaptureType.ALL);
	expect(mockList.add(captureInt(captureArguments))).andReturn(true).times(2);
	replay(mockList);

	assertTrue(mockList.add(10));
	assertTrue(mockList.add(20));
	
	System.out.println(captureArguments.getValues());
	
	verify(mockList);
}
 
Example #14
Source File: EasyMockCaptureAgrumentExample.java    From journaldev with MIT License 5 votes vote down vote up
@Test
public void test_multiple_args_catcher() {
	MathUtils mock = mock(MathUtils.class);
	Capture<Integer> captureArguments = newCapture(CaptureType.ALL);

	expect(mock.add(captureInt(captureArguments), captureInt(captureArguments))).andReturn(10).times(2);
	replay(mock);

	assertEquals(mock.add(0,10), 10);
	assertEquals(mock.add(1, 9), 10);
	
	System.out.println(captureArguments.getValues());

	verify(mock);
}
 
Example #15
Source File: HubTest.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Test
public void testFloodNoBufferId() throws Exception {
    // build our expected flooded packetOut
    OFPacketOut po = ((OFPacketOut) mockFloodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT))
        .setActions(Arrays.asList(new OFAction[] {new OFActionOutput().setPort(OFPort.OFPP_FLOOD.getValue())}))
        .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH)
        .setBufferId(-1)
        .setInPort((short) 1)
        .setPacketData(this.testPacketSerialized);
    po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLengthU()
            + this.testPacketSerialized.length);

    // Mock up our expected behavior
    IOFSwitch mockSwitch = createMock(IOFSwitch.class);
    
    Capture<OFMessage> wc1 = new Capture<OFMessage>(CaptureType.ALL);
    Capture<FloodlightContext> bc1 = new Capture<FloodlightContext>(CaptureType.ALL);
    
    mockSwitch.write(capture(wc1), capture(bc1));

    // Start recording the replay on the mocks
    replay(mockSwitch);
    // Get the listener and trigger the packet in
    IOFMessageListener listener = mockFloodlightProvider.getListeners().get(
            OFType.PACKET_IN).get(0);
    listener.receive(mockSwitch, this.packetIn,
                     parseAndAnnotate(this.packetIn));

    // Verify the replay matched our expectations
    verify(mockSwitch);
    
    assertTrue(wc1.hasCaptured());
    OFMessage m = wc1.getValue();
    assertEquals(po, m);
}
 
Example #16
Source File: HubTest.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Test
public void testFloodBufferId() throws Exception {
    MockFloodlightProvider mockFloodlightProvider = getMockFloodlightProvider();
    this.packetIn.setBufferId(10);

    // build our expected flooded packetOut
    OFPacketOut po = ((OFPacketOut) mockFloodlightProvider.getOFMessageFactory().getMessage(OFType.PACKET_OUT))
        .setActions(Arrays.asList(new OFAction[] {new OFActionOutput().setPort(OFPort.OFPP_FLOOD.getValue())}))
        .setActionsLength((short) OFActionOutput.MINIMUM_LENGTH)
        .setBufferId(10)
        .setInPort((short) 1);
    po.setLengthU(OFPacketOut.MINIMUM_LENGTH + po.getActionsLengthU());

    // Mock up our expected behavior
    IOFSwitch mockSwitch = createMock(IOFSwitch.class);
    Capture<OFMessage> wc1 = new Capture<OFMessage>(CaptureType.ALL);
    Capture<FloodlightContext> bc1 = new Capture<FloodlightContext>(CaptureType.ALL);
    
    mockSwitch.write(capture(wc1), capture(bc1));

    // Start recording the replay on the mocks
    replay(mockSwitch);
    // Get the listener and trigger the packet in
    IOFMessageListener listener = mockFloodlightProvider.getListeners().get(
            OFType.PACKET_IN).get(0);
    listener.receive(mockSwitch, this.packetIn,
                     parseAndAnnotate(this.packetIn));

    // Verify the replay matched our expectations
    verify(mockSwitch);
    
    assertTrue(wc1.hasCaptured());
    OFMessage m = wc1.getValue();
    assertEquals(po, m);
}
 
Example #17
Source File: StaticFlowTests.java    From floodlight_with_topoguard with Apache License 2.0 5 votes vote down vote up
@Override
public void setUp() throws Exception {
    super.setUp();
    staticFlowEntryPusher = new StaticFlowEntryPusher();
    storage = createStorageWithFlowEntries();
    dpid = HexString.toLong(TestSwitch1DPID);

    mockSwitch = createNiceMock(IOFSwitch.class);
    writeCapture = new Capture<OFMessage>(CaptureType.ALL);
    contextCapture = new Capture<FloodlightContext>(CaptureType.ALL);
    writeCaptureList = new Capture<List<OFMessage>>(CaptureType.ALL);

    //OFMessageSafeOutStream mockOutStream = createNiceMock(OFMessageSafeOutStream.class);
    mockSwitch.write(capture(writeCapture), capture(contextCapture));
    expectLastCall().anyTimes();
    mockSwitch.write(capture(writeCaptureList), capture(contextCapture));
    expectLastCall().anyTimes();
    mockSwitch.flush();
    expectLastCall().anyTimes();


    FloodlightModuleContext fmc = new FloodlightModuleContext();
    fmc.addService(IStorageSourceService.class, storage);

    MockFloodlightProvider mockFloodlightProvider = getMockFloodlightProvider();
    Map<Long, IOFSwitch> switchMap = new HashMap<Long, IOFSwitch>();
    switchMap.put(dpid, mockSwitch);
    // NO ! expect(mockFloodlightProvider.getSwitches()).andReturn(switchMap).anyTimes();
    mockFloodlightProvider.setSwitches(switchMap);
    fmc.addService(IFloodlightProviderService.class, mockFloodlightProvider);
    RestApiServer restApi = new RestApiServer();
    fmc.addService(IRestApiService.class, restApi);
    restApi.init(fmc);
    staticFlowEntryPusher.init(fmc);
    staticFlowEntryPusher.startUp(fmc);    // again, to hack unittest
}
 
Example #18
Source File: DhcpRelayManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Should ignore ignore rules installation when device not available.
 */
@Test
public void testIgnoreUnknownDevice() throws IOException {
    reset(manager.deviceService);
    Device device = createNiceMock(Device.class);
    expect(device.is(Pipeliner.class)).andReturn(true).anyTimes();

    expect(manager.deviceService.getDevice(DEV_1_ID)).andReturn(device).anyTimes();
    expect(manager.deviceService.getDevice(DEV_2_ID)).andReturn(null).anyTimes();

    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());
    replay(flowObjectiveService, manager.deviceService, device);

    manager.updateConfig(config);
    capturedFromDev1.getValues().forEach(obj -> obj.context().ifPresent(ctx -> ctx.onSuccess(obj)));

    assertEquals(1, v4Handler.ignoredVlans.size());
    assertEquals(1, v6Handler.ignoredVlans.size());
}
 
Example #19
Source File: DhcpRelayManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Should try install ignore rules when device comes up.
 */
@Test
public void testInstallIgnoreRuleWhenDeviceComesUp() throws IOException {
    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);

    reset(manager.cfgService, flowObjectiveService, manager.deviceService);
    expect(manager.cfgService.getConfig(APP_ID, IgnoreDhcpConfig.class))
            .andReturn(config).anyTimes();

    Device device = createNiceMock(Device.class);
    expect(device.is(Pipeliner.class)).andReturn(true).anyTimes();
    expect(device.id()).andReturn(DEV_1_ID).anyTimes();
    expect(manager.deviceService.getDevice(DEV_1_ID)).andReturn(device).anyTimes();
    DeviceEvent event = new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, device);
    Capture<Objective> capturedFromDev1 = newCapture(CaptureType.ALL);
    flowObjectiveService.apply(eq(DEV_1_ID), capture(capturedFromDev1));
    expectLastCall().times(DHCP_SELECTORS.size());
    replay(manager.cfgService, flowObjectiveService, manager.deviceService, device);

    manager.deviceListener.event(event);

    // Wait until all flow objective events are captured before triggering onSuccess
    int expectFlowObjCount = Dhcp4HandlerImpl.DHCP_SELECTORS.size() + Dhcp6HandlerImpl.DHCP_SELECTORS.size();
    assertAfter(EVENT_PROCESSING_MS, () -> assertEquals(expectFlowObjCount, capturedFromDev1.getValues().size()));
    capturedFromDev1.getValues().forEach(obj -> obj.context().ifPresent(ctx -> ctx.onSuccess(obj)));

    assertAfter(EVENT_PROCESSING_MS, () -> assertEquals(1, v4Handler.ignoredVlans.size()));
    assertAfter(EVENT_PROCESSING_MS, () -> assertEquals(1, v6Handler.ignoredVlans.size()));
}
 
Example #20
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 #21
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 #22
Source File: FilterKeyValueTest.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public void init(FilterKeyValueDescriptor filterKeyValueDescriptor) throws Exception {
  mockOutputManager = EasyMock.strictMock(OutputManager.class);
  capture = EasyMock.newCapture(CaptureType.LAST);

  filterKeyValue = new FilterKeyValue();
  filterKeyValue.loadConfig(filterKeyValueDescriptor);
  filterKeyValue.setOutputManager(mockOutputManager);
  filterKeyValue.init(new LogFeederProps());
}
 
Example #23
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 #24
Source File: TestPlatformSubsystemContext.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void preparePlatformBus() {
   messages = Capture.newInstance(CaptureType.ALL);
   EasyMock
      .expect(platformBus.send(EasyMock.capture(messages)))
      .andReturn(Futures.immediateFuture(null))
      .anyTimes();
}
 
Example #25
Source File: TestPlaceSetAttributesHandler_Location.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void captureSaves() {
   savedPlaces = Capture.newInstance(CaptureType.ALL);
   EasyMock
      .expect(placeDao.save(EasyMock.capture(savedPlaces)))
      .andAnswer(() -> {
         Place p = savedPlaces.getValue().copy();
         p.setModified(new Date());
         return p;
      })
      .anyTimes();
}
 
Example #26
Source File: TestPlaceSetAttributesHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void captureSaves() {
   savedPlaces = Capture.newInstance(CaptureType.ALL);
   EasyMock
      .expect(placeDao.save(EasyMock.capture(savedPlaces)))
      .andAnswer(() -> {
         Place p = savedPlaces.getValue().copy();
         p.setModified(new Date());
         return p;
      })
      .anyTimes();
   replay();
}
 
Example #27
Source File: TestRequestEmailVerificationRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
private Capture<Person> mockSetup(Person curPerson, boolean personExist, boolean principalMatch, String source, int times) {
	EasyMock.expect(client.getPrincipalId()).andReturn(curPerson.getId()).times(times);
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(curPerson.getId(), generateRequest(source)).getBytes())).times(times);
   EasyMock.expect(ctx.channel()).andReturn(channel).times(times);

   EasyMock.expect(clientFactory.get(channel)).andReturn(client).times(times);
   platformMsgCapture = EasyMock.newCapture(CaptureType.ALL);     
   EasyMock.expect(platformBus.send(EasyMock.capture(platformMsgCapture))).andAnswer(
      () -> {
         return Futures.immediateFuture(null);
      }
   ).anyTimes();
   
   
   //logout always needs to be called
   client.logout();
	EasyMock.expectLastCall().times(times);   	  	
	EasyMock.expect(authenticator.expireCookie()).andReturn(new DefaultCookie("test", "test")).times(times);
	
	if(principalMatch) {
		EasyMock.expect(client.getPrincipalName()).andReturn(curPerson.getEmail()).times(times);   	
	}else{
		EasyMock.expect(client.getPrincipalName()).andReturn("[email protected]").times(times); 
	}
	if(personExist) {
		EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(curPerson).times(times);
	}else{
		EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(null).times(times);
	}
	Capture<Person> personUpdatedCapture = EasyMock.newCapture(CaptureType.ALL);
	EasyMock.expect(personDao.update(EasyMock.capture(personUpdatedCapture))).andReturn(curPerson).times(times);
	
	EasyMock.expect(mockPersonPlaceAssocDAO.findPlaceIdsByPerson(curPerson.getId())).andReturn(ImmutableSet.<UUID>of(curPerson.getCurrPlace())).anyTimes();
	
	return personUpdatedCapture;
}
 
Example #28
Source File: TestVerifyEmailRESTHandler.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Test
public void testRequestEmailVerification_Success() throws Exception {
	Person curPerson = createPerson();
	String token = "t123545";
   curPerson.setEmailVerificationToken(token);
   
   mockSetup(curPerson.getId(), token);		
	
	EasyMock.expect(personDao.findById(curPerson.getId())).andReturn(curPerson);
	Capture<Person> personUpdatedCapture = EasyMock.newCapture(CaptureType.LAST);
	EasyMock.expect(personDao.update(EasyMock.capture(personUpdatedCapture))).andReturn(curPerson);
	
	Set<UUID> placeIds = ImmutableSet.<UUID>of(curPerson.getCurrPlace(), UUID.randomUUID());
	EasyMock.expect(personPlaceAssocDao.findPlaceIdsByPerson(curPerson.getId())).andReturn(placeIds);
	
   replay();      
   
   FullHttpResponse response = handler.respond(request, ctx);   
        
   //Should send a value change for each place this person belongs to
	List<PlatformMessage> msgs = platformMsgCapture.getValues();
	Iterator<UUID> placeIdsIt = placeIds.iterator();
	msgs.forEach((cur) -> {
		assertValueChangeSent(cur, placeIdsIt.next());
	});
	
	Person personUpdated = personUpdatedCapture.getValue();
	assertNotNull(personUpdated.getEmailVerificationToken());
	assertNotNull(personUpdated.getEmailVerified());
   
   MessageBody mb = toClientRequest(response);
   assertEquals(MessageConstants.MSG_EMPTY_MESSAGE, mb.getMessageType());
   
}
 
Example #29
Source File: FilterGrokTest.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
public void init(FilterGrokDescriptor filterGrokDescriptor) throws Exception {
  mockOutputManager = EasyMock.strictMock(OutputManager.class);
  capture = EasyMock.newCapture(CaptureType.LAST);

  filterGrok = new FilterGrok();
  filterGrok.loadConfig(filterGrokDescriptor);
  filterGrok.setOutputManager(mockOutputManager);
  filterGrok.setInput(EasyMock.mock(Input.class));
  filterGrok.init(new LogFeederProps());
}
 
Example #30
Source File: TestLockDeviceRESTHandler.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
private FullHttpResponse callLockDeviceRequest(String curDeviceId, String curReason, boolean curSuccess, boolean curPersonMatch) throws Exception {
   EasyMock.expect(client.getPrincipalId()).andReturn(curLoggedPerson.getId()).anyTimes();
   EasyMock.expect(request.content()).andReturn(Unpooled.copiedBuffer(generateClientMessage(generateRequest(curDeviceId, curReason)).getBytes()));
   EasyMock.expect(ctx.channel()).andReturn(channel).anyTimes();

   EasyMock.expect(clientFactory.get(channel)).andReturn(client).anyTimes();
   Capture<PlatformMessage> platformMsgCapture = EasyMock.newCapture(CaptureType.ALL);
  
   EasyMock.expect(platformBus.send(EasyMock.capture(platformMsgCapture))).andAnswer(
      () -> {
         return Futures.immediateFuture(null);
      }
   ).anyTimes();
   
   MobileDevice mobileDevice = new MobileDevice();
   mobileDevice.setDeviceIdentifier(curDeviceId);
   if(curPersonMatch) {
   	mobileDevice.setPersonId(curLoggedPerson.getId());
   	mobileDeviceDao.delete(mobileDevice);
   	EasyMock.expectLastCall();
   	EasyMock.expect(personDao.findById(curLoggedPerson.getId())).andReturn(curLoggedPerson);
   }else{
   	mobileDevice.setPersonId(UUID.randomUUID());
   }
   EasyMock.expect(mobileDeviceDao.findWithToken(curDeviceId)).andReturn(mobileDevice);
   
   
   //logout always needs to be called
   client.logout();
	EasyMock.expectLastCall();   	  	
	EasyMock.expect(authenticator.expireCookie()).andReturn(new DefaultCookie("test", "test"));		
	
   replay();      
   
   FullHttpResponse response = handler.respond(request, ctx);   
   
   if(curSuccess) {
   	//notification needs to be sent
   	PlatformMessage msg = platformMsgCapture.getValue();
   	assertNotificationSent(msg);         	      	
   }
   return response;
   
}