/** Tests that Har resources are sorted properly by request time. */
 @Test
 public void sortHarResources() throws Exception {
   HarResource a = EasyMock.createMock(HarResource.class);
   HarResource b = EasyMock.createMock(HarResource.class);
   HarResource c = EasyMock.createMock(HarResource.class);
   HarResource d = EasyMock.createMock(HarResource.class);
   EasyMock.expect(a.getRequestTime()).andReturn(new BigDecimal(1.328670831670000E9)).anyTimes();
   EasyMock.expect(b.getRequestTime()).andReturn(new BigDecimal(1.328670831660000E9)).anyTimes();
   EasyMock.expect(c.getRequestTime()).andReturn(new BigDecimal(1.328670831650000E9)).anyTimes();
   EasyMock.expect(d.getRequestTime()).andReturn(null).anyTimes();
   EasyMock.replay(a, b, c, d);
   HashMap<String, HarResource> map = Maps.newHashMap();
   map.put("1.1", a);
   map.put("2.2", b);
   map.put("3.3", c);
   map.put("4.4", d);
   HarObject har = new HarObject();
   List<Map.Entry<String, HarResource>> list = Lists.newArrayList(map.entrySet());
   har.sortHarResources(list);
   String[] sortedRequestIds = {"4.4", "3.3", "2.2", "1.1"};
   int i = 0;
   for (Map.Entry<String, HarResource> resource : list) {
     assertTrue(resource.getKey().equals(sortedRequestIds[i++]));
   }
   EasyMock.verify(a, b, c, d);
 }
Exemple #2
0
 protected void setUp() {
   mock = EasyMock.createMock(Collaborator.class); // 1
   mock1 = EasyMock.createMock(Collaborator.class); // 1
   classUnderTest = new ClassUnderTest();
   classUnderTest.addListener(mock);
   // classUnderTest.addListener(mock1);
 }
  /** Verify that when adding a second player to a full game, an exception is thrown */
  @Test(expected = SnowmanFullException.class)
  public void addPlayerFullTest() {
    // setup dummy entityfactory
    EntityFactory dummyEntityFactory = EasyMock.createMock(EntityFactory.class);
    SnowmanFlag dummyFlag = EasyMock.createNiceMock(SnowmanFlag.class);
    EasyMock.expect(dummyFlag.getID()).andStubReturn(new Integer(0));
    EasyMock.replay(dummyFlag);
    EasyMock.expect(
            dummyEntityFactory.createSnowmanFlag(
                EasyMock.isA(SnowmanGame.class),
                EasyMock.isA(ETeamColor.class),
                EasyMock.isA(Coordinate.class),
                EasyMock.isA(Coordinate.class)))
        .andStubReturn(dummyFlag);
    EasyMock.replay(dummyEntityFactory);

    // create the players
    SnowmanPlayer dummyPlayer = EasyMock.createMock(SnowmanPlayer.class);
    SnowmanPlayer dummyPlayer2 = EasyMock.createMock(SnowmanPlayer.class);
    SnowmanPlayer dummyPlayer3 = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color = ETeamColor.Red;

    // create the game
    SnowmanGame game = new SnowmanGameImpl(gameName, 4, dummyEntityFactory);

    // add the players
    game.addPlayer(dummyPlayer, color);
    game.addPlayer(dummyPlayer2, color);
    game.addPlayer(dummyPlayer3, color);
  }
  public static EdmEntityType mockTargetEdmEntityType() {
    EdmEntityType entityType = EasyMock.createMock(EdmEntityType.class);
    EdmMapping mapping = EasyMock.createMock(EdmMapping.class);

    List<String> propertyNames = new ArrayList<String>();
    propertyNames.add("price");
    try {
      EasyMock.expect(mapping.getInternalName()).andStubReturn("SalesOrderLineItem");
      EasyMock.replay(mapping);
      EasyMock.expect(entityType.getName()).andStubReturn("SalesOrderLineItem");
      EasyMock.expect(entityType.getMapping()).andStubReturn(mapping);
      EdmProperty property = mockEdmPropertyOfTarget();
      EasyMock.expect(entityType.getProperty("price")).andStubReturn(property);
      EasyMock.expect(entityType.getPropertyNames()).andStubReturn(propertyNames);

      List<EdmProperty> keyProperties = new ArrayList<EdmProperty>();
      keyProperties.add(property);
      EasyMock.expect(entityType.getKeyProperties()).andStubReturn(keyProperties);

    } catch (EdmException e) {
      fail(
          ODataJPATestConstants.EXCEPTION_MSG_PART_1
              + e.getMessage()
              + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
    }
    EasyMock.replay(entityType);
    return entityType;
  }
  /** {@inheritDoc} */
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    mMockFlasher = EasyMock.createMock(IDeviceFlasher.class);
    mMockDevice = EasyMock.createMock(ITestDevice.class);
    EasyMock.expect(mMockDevice.getSerialNumber()).andReturn("foo").anyTimes();
    mMockBuildInfo = new DeviceBuildInfo("0", "", "");
    mMockBuildInfo.setBuildFlavor("flavor");
    mDeviceFlashPreparer =
        new DeviceFlashPreparer() {
          @Override
          protected IDeviceFlasher createFlasher(ITestDevice device) {
            return mMockFlasher;
          }

          @Override
          int getDeviceBootPollTimeMs() {
            return 100;
          }
        };
    mDeviceFlashPreparer.setDeviceBootTime(100);
    // expect this call
    mMockFlasher.setUserDataFlashOption(UserDataFlashOption.FLASH);
    mTmpDir = FileUtil.createTempDir("tmp");
  }
 @Before
 public void setUp() {
   peekIterator = EasyMock.createMock(PeekingIterator.class);
   comparator = EasyMock.createMock(Comparator.class);
   binaryFn = EasyMock.createMock(BinaryFn.class);
   testingIterator = CombiningIterator.create(peekIterator, comparator, binaryFn);
 }
 public static EdmEntityType mockSourceEdmEntityType() {
   EdmEntityType entityType = EasyMock.createMock(EdmEntityType.class);
   EdmMapping mapping = EasyMock.createMock(EdmMapping.class);
   List<String> navigationPropertyNames = new ArrayList<String>();
   List<String> propertyNames = new ArrayList<String>();
   propertyNames.add("id");
   propertyNames.add("description");
   navigationPropertyNames.add("SalesOrderLineItemDetails");
   try {
     EasyMock.expect(mapping.getInternalName()).andStubReturn("SalesOrderHeader");
     EasyMock.replay(mapping);
     EasyMock.expect(entityType.getName()).andStubReturn("SalesOrderHeader");
     EasyMock.expect(entityType.getMapping()).andStubReturn(mapping);
     EasyMock.expect(entityType.getNavigationPropertyNames())
         .andStubReturn(navigationPropertyNames);
     EasyMock.expect(entityType.getProperty("SalesOrderLineItemDetails"))
         .andStubReturn(mockNavigationProperty());
     EdmProperty property1 = mockEdmPropertyOfSource1();
     EasyMock.expect(entityType.getProperty("id")).andStubReturn(property1);
     EasyMock.expect(entityType.getProperty("description"))
         .andStubReturn(mockEdmPropertyOfSource2());
     EasyMock.expect(entityType.getPropertyNames()).andStubReturn(propertyNames);
     List<EdmProperty> keyProperties = new ArrayList<EdmProperty>();
     keyProperties.add(property1);
     EasyMock.expect(entityType.getKeyProperties()).andStubReturn(keyProperties);
   } catch (EdmException e) {
     fail(
         ODataJPATestConstants.EXCEPTION_MSG_PART_1
             + e.getMessage()
             + ODataJPATestConstants.EXCEPTION_MSG_PART_2);
   }
   EasyMock.replay(entityType);
   return entityType;
 }
  protected void testListenerAddGetRemove(
      Class<?> cls, Class<?> eventClass, Class<?> listenerClass, Object c) throws Exception {

    Object mockListener1 = EasyMock.createMock(listenerClass);
    Object mockListener2 = EasyMock.createMock(listenerClass);

    // Verify we start from no listeners
    verifyListeners(c, eventClass);

    // Add one listener and verify
    addListener(c, mockListener1, listenerClass);
    verifyListeners(c, eventClass, mockListener1);

    // Add another listener and verify
    addListener(c, mockListener2, listenerClass);
    verifyListeners(c, eventClass, mockListener1, mockListener2);

    // Ensure we can fetch using parent class also
    if (eventClass.getSuperclass() != null) {
      verifyListeners(c, eventClass.getSuperclass(), mockListener1, mockListener2);
    }

    // Remove the first and verify
    removeListener(c, mockListener1, listenerClass);
    verifyListeners(c, eventClass, mockListener2);

    // Remove the remaining and verify
    removeListener(c, mockListener2, listenerClass);
    verifyListeners(c, eventClass);
  }
  @BeforeMethod(groups = "unit")
  public void init() {
    support = new EventSupportImpl();

    eventDispatcher = EasyMock.createMock(EventDispatcher.class);
    messageSource = EasyMock.createMock(MessageSource.class);

    collection.add(eventDispatcher);
    collection.add(messageSource);

    support.setEventDispatcher(eventDispatcher);
    support.setMessageSource(messageSource);
    event = null;
    eventDispatcher.fireEvent(
        EasyMockUtils.record(
            new EasyMockUtils.Recorder<EventBase>() {
              public void record(final EventBase object) {
                event = object;
              }
            }));

    EasyMock.expect(messageSource.getMessage("code", null)).andStubReturn("message");

    collection.replay();
    final User user = new User();
    user.setCagridId(userId);

    template = new EventBaseImpl();
    template.setJobId(jobId);
    template.setUserId(userId);
    template.setJobName(jobName);
    template.setWorkflowId(workflowId);
  }
  @Test(expectedExceptions = CitrusRuntimeException.class)
  public void testFailingAction() {

    final Conditional conditionalAction = new Conditional();
    conditionalAction.setExpression("1 = 1");

    final TestAction action1 = EasyMock.createMock(TestAction.class);
    final TestAction action2 = EasyMock.createMock(TestAction.class);
    final TestAction action3 = EasyMock.createMock(TestAction.class);

    reset(action1, action2, action3);

    action1.execute(this.context);
    expectLastCall().once();

    replay(action1, action2, action3);

    final List<TestAction> actionList = new ArrayList<TestAction>();
    actionList.add(action1);
    actionList.add(new FailAction());
    actionList.add(action2);
    actionList.add(action3);

    conditionalAction.setActions(actionList);

    conditionalAction.execute(this.context);

    verify(action1, action2, action3);
  }
  @Test
  public void testMultipleActions() {

    final Conditional conditionalAction = new Conditional();
    conditionalAction.setExpression("1 = 1");

    final TestAction action1 = EasyMock.createMock(TestAction.class);
    final TestAction action2 = EasyMock.createMock(TestAction.class);
    final TestAction action3 = EasyMock.createMock(TestAction.class);

    reset(action1, action2, action3);

    action1.execute(this.context);
    expectLastCall().once();
    action2.execute(this.context);
    expectLastCall().once();
    action3.execute(this.context);
    expectLastCall().once();

    replay(action1, action2, action3);

    final List<TestAction> actionList = new ArrayList<TestAction>();
    actionList.add(action1);
    actionList.add(action2);
    actionList.add(action3);

    conditionalAction.setActions(actionList);

    conditionalAction.execute(this.context);

    verify(action1, action2, action3);
  }
Exemple #12
0
 /** Tests channelDisconnected() method. */
 @Test
 public void testChannelDisconnected() throws Exception {
   channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class);
   channelStateEvent = EasyMock.createMock(ChannelStateEvent.class);
   ospfInterfaceChannelHandler.channelDisconnected(channelHandlerContext, channelStateEvent);
   assertThat(ospfInterfaceChannelHandler, is(notNullValue()));
 }
Exemple #13
0
 /** Tests exceptionCaught() method. */
 @Test(expected = Exception.class)
 public void testExceptionCaught() throws Exception {
   channelHandlerContext = EasyMock.createMock(ChannelHandlerContext.class);
   ExceptionEvent exception = EasyMock.createMock(ExceptionEvent.class);
   ospfInterfaceChannelHandler.exceptionCaught(channelHandlerContext, exception);
   assertThat(ospfInterfaceChannelHandler, is(notNullValue()));
 }
  protected void setUp() throws Exception {
    super.setUp();

    ReflectionFactory reflectionFactory = EasyMock.createNiceMock(ReflectionFactory.class);
    LifecycleInvoker invoker = EasyMock.createMock(LifecycleInvoker.class);
    EasyMock.expect(reflectionFactory.createLifecycleInvoker(EasyMock.isA(Method.class)))
        .andReturn(invoker);

    ClassLoaderRegistry classLoaderRegistry = EasyMock.createMock(ClassLoaderRegistry.class);
    EasyMock.expect(classLoaderRegistry.getClassLoader(EasyMock.anyObject()))
        .andReturn(getClass().getClassLoader())
        .anyTimes();
    EasyMock.replay(reflectionFactory, classLoaderRegistry);

    builder = new ImplementationManagerFactoryBuilderImpl(reflectionFactory, classLoaderRegistry);
    Constructor<Foo> constructor = Foo.class.getConstructor(String.class, Long.class);

    definition = new ImplementationManagerDefinition();
    definition.setImplementationClass(Foo.class);
    definition.setConstructor(constructor);
    definition.setInitMethod(Foo.class.getMethod("init"));
    definition.setDestroyMethod(Foo.class.getMethod("destroy"));
    Map<InjectionSite, Injectable> construction = definition.getConstruction();
    construction.put(
        new ConstructorInjectionSite(constructor, 0), new Injectable(InjectableType.PROPERTY, "a"));
    construction.put(
        new ConstructorInjectionSite(constructor, 1),
        new Injectable(InjectableType.REFERENCE, "b"));
  }
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testMonitorAndContinueWithoutTimeout() {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    CoutingEventHandler handler = new CoutingEventHandler();
    EventBus eventBus = new EventBus();
    eventBus.register(handler);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.CONTINUE), eventBus);

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(null);
    assertNotNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.run();
    assertEquals(handler.numCompletes, 0);
    assertEquals(handler.numFailures, 0);
    assertEquals(handler.numTimeouts, 0);

    verify(mockFuture);
    verify(schedulerMock);
  }
 @SuppressWarnings("unchecked")
 @Before
 public void setUp() throws Exception {
   EntityManagerFactory factory = EasyMock.createMock(EntityManagerFactory.class);
   init = new ConstantInitializer<EntityManagerFactory>(factory);
   observer = EasyMock.createMock(CommandObserver.class);
 }
  @SuppressWarnings({"rawtypes", "unchecked"})
  public void testStartMonitoringWithTimeout() {
    ScheduledFuture mockFuture = EasyMock.createMock(ScheduledFuture.class);
    ScheduledExecutorService schedulerMock = EasyMock.createMock(ScheduledExecutorService.class);
    expect(
            schedulerMock.scheduleWithFixedDelay(
                anyObject(Runnable.class), anyLong(), anyLong(), anyObject(TimeUnit.class)))
        .andReturn(mockFuture);

    replay(mockFuture);
    replay(schedulerMock);

    AsyncMonitor<Object> monitor =
        mockMonitor(schedulerMock, new Object(), mockFunction(MonitorStatus.DONE), new EventBus());

    assertNull(monitor.getFuture());
    assertNull(monitor.getTimeout());

    monitor.startMonitoring(100L);

    assertNotNull(monitor.getFuture());
    assertNotNull(monitor.getTimeout());
    assertTrue(monitor.getTimeout() > 100L);

    verify(mockFuture);
    verify(schedulerMock);
  }
  public void testExceptionIfNot5xx() {
    FalseOn5xx function = new FalseOn5xx();
    HttpResponse response = EasyMock.createMock(HttpResponse.class);
    HttpResponseException exception = EasyMock.createMock(HttpResponseException.class);

    // Status code is called twice
    expect(response.getStatusCode()).andReturn(600);
    expect(response.getStatusCode()).andReturn(600);
    // Get response gets called twice
    expect(exception.getResponse()).andReturn(response);
    expect(exception.getResponse()).andReturn(response);
    // Get cause is called to determine the root cause
    expect(exception.getCause()).andReturn(null);

    replay(response);
    replay(exception);

    try {
      function.createOrPropagate(exception);
    } catch (Exception ex) {
      assertEquals(ex, exception);
    }

    verify(response);
    verify(exception);
  }
  /**
   * Verify that when adding a second player to a game, the correct information for that player is
   * set and it does not conflict with the first player
   */
  @Test
  public void addSecondPlayerTest() {
    // setup dummy entityfactory
    EntityFactory dummyEntityFactory = EasyMock.createMock(EntityFactory.class);
    SnowmanFlag dummyFlag = EasyMock.createNiceMock(SnowmanFlag.class);
    EasyMock.expect(dummyFlag.getID()).andStubReturn(new Integer(0));
    EasyMock.replay(dummyFlag);
    EasyMock.expect(
            dummyEntityFactory.createSnowmanFlag(
                EasyMock.isA(SnowmanGame.class),
                EasyMock.isA(ETeamColor.class),
                EasyMock.isA(Coordinate.class),
                EasyMock.isA(Coordinate.class)))
        .andStubReturn(dummyFlag);
    EasyMock.replay(dummyEntityFactory);

    // create the player
    ClientSession session = EasyMock.createNiceMock(ClientSession.class);
    SnowmanPlayer dummyPlayer = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color = ETeamColor.Red;

    // create the second player
    ClientSession session2 = EasyMock.createNiceMock(ClientSession.class);
    SnowmanPlayer dummyPlayer2 = EasyMock.createMock(SnowmanPlayer.class);
    ETeamColor color2 = ETeamColor.Blue;

    // create the game
    SnowmanGame game = new SnowmanGameImpl(gameName, 4, dummyEntityFactory);

    // record information that should be set on the player1
    dummyPlayer.setID(1);
    dummyPlayer.setLocation(EasyMock.anyFloat(), EasyMock.anyFloat());
    dummyPlayer.setTeamColor(color);
    dummyPlayer.setGame(game);
    EasyMock.expect(dummyPlayer.getSession()).andStubReturn(session);
    EasyMock.replay(dummyPlayer);

    // record information that should be set on the player2
    dummyPlayer2.setID(2);
    dummyPlayer2.setLocation(EasyMock.anyFloat(), EasyMock.anyFloat());
    dummyPlayer2.setTeamColor(color2);
    dummyPlayer2.setGame(game);
    EasyMock.expect(dummyPlayer2.getSession()).andStubReturn(session2);
    EasyMock.replay(dummyPlayer2);

    // record that the players should be added to the channel
    EasyMock.resetToDefault(gameChannel);
    EasyMock.expect(gameChannel.join(session)).andReturn(gameChannel);
    EasyMock.expect(gameChannel.join(session2)).andReturn(gameChannel);
    EasyMock.replay(gameChannel);

    // add the player
    game.addPlayer(dummyPlayer, color);
    game.addPlayer(dummyPlayer2, color2);

    // verify the calls
    EasyMock.verify(dummyPlayer);
    EasyMock.verify(dummyPlayer2);
    EasyMock.verify(gameChannel);
  }
  @BeforeMethod(groups = "unit")
  public void init() {
    factory = new RawExtractJobFactoryImpl();
    stagingDirectoryFactory = EasyMock.createMock(CredentialedStagingDirectoryFactory.class);
    stagingDirectory = EasyMock.createMock(StagingDirectory.class);
    EasyMock.expect(stagingDirectory.getAbsolutePath()).andStubReturn(PATH);

    EasyMock.expect(stagingDirectory.getSep()).andStubReturn("/");
    final Supplier<DisposableResourceTracker> trackerSupplier = EasyMockUtils.createMockSupplier();
    tracker = createMock(DisposableResourceTracker.class);
    expect(trackerSupplier.get()).andReturn(tracker);
    replay(trackerSupplier);
    rawPopulator = EasyMock.createMock(InputContext.class);

    converter = EasyMock.createMock(DTAToMzXMLConverter.class);
    options = new DTAToMzXMLOptions();

    factory.setDtaToMzXMLConverter(converter);
    factory.setDtaToMxXMLOptions(options);
    factory.setDisposableResourceTrackerSupplier(trackerSupplier);
    factory.setCredentialedStagingDirectoryFactory(stagingDirectoryFactory);
    mockObjects =
        MockObjectCollection.fromObjects(
            stagingDirectoryFactory, stagingDirectory, tracker, rawPopulator, converter);
  }
  @Test
  public void getRichTextImageHasCorrectUrl() throws RepositoryException, RichTextException {
    final RichTextImage image =
        new RichTextImage("/content/gallery/image.png/image.png", "image.png");
    image.setSelectedResourceDefinition("hippogallery:original");

    final IRichTextImageFactory mockImageFactory = EasyMock.createMock(IRichTextImageFactory.class);
    expect(mockImageFactory.loadImageItem(eq("image.png/{_document}/hippogallery:original")))
        .andReturn(image);

    final IRichTextLinkFactory mockLinkFactory = EasyMock.createMock(IRichTextLinkFactory.class);
    expect(mockLinkFactory.getLinkUuids())
        .andReturn(Collections.singleton("0e8a928c-b83f-4bb9-9e52-1a22b7e9ee21"));

    final Node documentNode = MockNode.root();
    final Node imageFacetNode = documentNode.addNode("image.png", HippoNodeType.NT_FACETSELECT);
    imageFacetNode.setProperty(HippoNodeType.HIPPO_DOCBASE, "0e8a928c-b83f-4bb9-9e52-1a22b7e9ee21");

    final IModel<Node> mockNodeModel = EasyMock.createMock(IModel.class);
    expect(mockNodeModel.getObject()).andReturn(documentNode).anyTimes();

    final RichTextImageURLProvider urlProvider =
        new RichTextImageURLProvider(mockImageFactory, mockLinkFactory, mockNodeModel);

    replay(mockImageFactory, mockLinkFactory, mockNodeModel);

    model = new RichTextImageMetaDataModel(delegate, urlProvider);
    delegate.setObject("<img src=\"image.png/{_document}/hippogallery:original\"/>");

    assertEquals(
        "<img src=\"binaries/content/gallery/image.png/image.png/hippogallery:original\" data-facetselect=\"image.png/{_document}/hippogallery:original\" data-type=\"hippogallery:original\"/>",
        model.getObject());
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testRpcException() {
    Logger logger = EasyMock.createMock(Logger.class);
    RpcContext.getContext().setRemoteAddress("127.0.0.1", 1234);
    RpcException exception = new RpcException("TestRpcException");
    logger.error(
        EasyMock.eq(
            "Got unchecked and undeclared exception which called by 127.0.0.1. service: "
                + DemoService.class.getName()
                + ", method: sayHello, exception: "
                + RpcException.class.getName()
                + ": TestRpcException"),
        EasyMock.eq(exception));
    ExceptionFilter exceptionFilter = new ExceptionFilter(logger);
    RpcInvocation invocation =
        new RpcInvocation("sayHello", new Class<?>[] {String.class}, new Object[] {"world"});
    Invoker<DemoService> invoker = EasyMock.createMock(Invoker.class);
    EasyMock.expect(invoker.getInterface()).andReturn(DemoService.class);
    EasyMock.expect(invoker.invoke(EasyMock.eq(invocation))).andThrow(exception);

    EasyMock.replay(logger, invoker);

    try {
      exceptionFilter.invoke(invoker, invocation);
    } catch (RpcException e) {
      assertEquals("TestRpcException", e.getMessage());
    }
    EasyMock.verify(logger, invoker);
    RpcContext.removeContext();
  }
  @Test
  public void testConfigurationEventDeletedNonScope() throws Exception {
    String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "abc.def";

    ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    EasyMock.replay(cm);

    SecuredCommandConfigTransformer scct = new SecuredCommandConfigTransformer();
    scct.setConfigAdmin(cm);
    scct.init();

    @SuppressWarnings("unchecked")
    ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmRef);
    ConfigurationEvent event =
        new ConfigurationEvent(cmRef, ConfigurationEvent.CM_DELETED, null, testPid);

    EasyMock.reset(cm);
    // Do not expect any further calls to cm...
    EasyMock.replay(cm);

    scct.configurationEvent(event);
    EasyMock.verify(cm);
  }
  @Test
  public void testConfigurationEventAdded() throws Exception {
    String testPid = SecuredCommandConfigTransformer.PROXY_COMMAND_ACL_PID_PREFIX + "test123";
    Configuration conf = EasyMock.createMock(Configuration.class);
    EasyMock.expect(conf.getPid()).andReturn(testPid).anyTimes();
    EasyMock.replay(conf);

    ConfigurationAdmin cm = EasyMock.createMock(ConfigurationAdmin.class);
    EasyMock.expect(cm.listConfigurations(EasyMock.isA(String.class))).andReturn(null).anyTimes();
    EasyMock.expect(cm.getConfiguration(testPid)).andReturn(conf).anyTimes();
    EasyMock.replay(cm);

    final List<String> generateCalled = new ArrayList<String>();
    SecuredCommandConfigTransformer scct =
        new SecuredCommandConfigTransformer() {
          @Override
          void generateServiceGuardConfig(Configuration config) throws IOException {
            generateCalled.add(config.getPid());
          }
        };
    scct.setConfigAdmin(cm);
    scct.init();

    @SuppressWarnings("unchecked")
    ServiceReference<ConfigurationAdmin> cmRef = EasyMock.createMock(ServiceReference.class);
    EasyMock.replay(cmRef);

    ConfigurationEvent event =
        new ConfigurationEvent(cmRef, ConfigurationEvent.CM_UPDATED, null, testPid);

    assertEquals("Precondition", 0, generateCalled.size());
    scct.configurationEvent(event);
    assertEquals(1, generateCalled.size());
    assertEquals(testPid, generateCalled.iterator().next());
  }
Exemple #25
0
  @Test
  public void testIgnorePaths() throws IOException {
    ProjectFilesystem filesystem = EasyMock.createMock(ProjectFilesystem.class);
    EasyMock.expect(filesystem.getPathRelativizer())
        .andReturn(Functions.<String>identity())
        .times(2);
    BuildTargetParser parser = EasyMock.createMock(BuildTargetParser.class);
    EasyMock.replay(filesystem, parser);

    Reader reader =
        new StringReader(
            Joiner.on('\n').join("[project]", "ignore = .git, foo, bar/, baz//, a/b/c"));
    BuckConfig config = BuckConfig.createFromReader(reader, filesystem, parser, Platform.detect());

    ImmutableSet<String> ignorePaths = config.getIgnorePaths();
    assertEquals(
        "Should ignore paths, sans trailing slashes",
        ignorePaths,
        ImmutableSet.of(
            BuckConstant.BUCK_OUTPUT_DIRECTORY,
            ".idea",
            System.getProperty(BuckConfig.BUCK_BUCKD_DIR_KEY, ".buckd"),
            config.getCacheDir(),
            ".git",
            "foo",
            "bar",
            "baz",
            "a/b/c"));

    EasyMock.verify(filesystem, parser);
  }
  @Test
  public void testAmendBuilder() throws NoSuchBuildTargetException {
    Map<BuildTarget, BuildRule> buildRuleIndex = Maps.newHashMap();
    BuildRuleResolver ruleResolver = new BuildRuleResolver(buildRuleIndex);

    // Set up mocks.
    ProjectFilesystem projectFilesystem = EasyMock.createMock(ProjectFilesystem.class);
    EasyMock.expect(projectFilesystem.getAbsolutifier())
        .andReturn(IdentityPathAbsolutifier.getIdentityAbsolutifier());
    BuildTargetParser buildTargetParser =
        new BuildTargetParser(projectFilesystem) {
          @Override
          public BuildTarget parse(String buildTargetName, ParseContext parseContext)
              throws NoSuchBuildTargetException {
            return BuildTargetFactory.newInstance(buildTargetName);
          }
        };
    Map<String, ?> instance =
        ImmutableMap.of(
            "vm_args", ImmutableList.of("-Dbuck.robolectric_dir=javatests/com/facebook/base"),
            "source_under_test", ImmutableList.of("//java/com/facebook/base:base"));
    BuildTarget buildTarget = BuildTargetFactory.newInstance("//javatests/com/facebook/base:base");
    BuildFileTree buildFileTree = EasyMock.createMock(BuildFileTree.class);
    EasyMock.replay(projectFilesystem, buildFileTree);
    BuildRuleFactoryParams params =
        new BuildRuleFactoryParams(
            instance,
            projectFilesystem,
            buildFileTree,
            buildTargetParser,
            buildTarget,
            new FakeRuleKeyBuilderFactory());

    // Create a builder using the factory.
    RobolectricTestBuildRuleFactory factory = new RobolectricTestBuildRuleFactory();
    RobolectricTestRule.Builder builder =
        factory.newBuilder(new FakeAbstractBuildRuleBuilderParams()).setBuildTarget(buildTarget);

    // Invoke the method under test.
    factory.amendBuilder(builder, params);

    // Create a build rule using the builder.
    BuildRule base =
        new FakeJavaLibraryRule(
            BuildRuleType.ANDROID_LIBRARY,
            buildTarget,
            ImmutableSortedSet.<BuildRule>of(),
            ImmutableSet.<BuildTargetPattern>of());
    buildRuleIndex.put(BuildTargetFactory.newInstance("//java/com/facebook/base:base"), base);
    RobolectricTestRule robolectricRule =
        (RobolectricTestRule) ruleResolver.buildAndAddToIndex(builder);

    // Verify the build rule built from the builder.
    assertEquals(
        ImmutableList.of("-Dbuck.robolectric_dir=javatests/com/facebook/base"),
        robolectricRule.getVmArgs());
    assertEquals(ImmutableSet.of(base), robolectricRule.getSourceUnderTest());
    EasyMock.verify(projectFilesystem, buildFileTree);
  }
  public void testConstruction() {
    ProtocolProviderServiceIrcImpl provider =
        EasyMock.createMock(ProtocolProviderServiceIrcImpl.class);
    IrcConnection connection = EasyMock.createMock(IrcConnection.class);
    EasyMock.replay(provider, connection);

    new CommandFactory(provider, connection);
  }
  public PartitionsResourceTest() throws RestConfigException {
    mdObserver = EasyMock.createMock(MetadataObserver.class);
    producerPool = EasyMock.createMock(ProducerPool.class);
    ctx = new Context(config, mdObserver, producerPool, null, null);

    addResource(new TopicsResource(ctx));
    addResource(new PartitionsResource(ctx));
  }
 public static Object[] prepareConfiguration(String pages, boolean turnOff) {
   Configuration conf = EasyMock.createMock(Configuration.class);
   EasyMock.expect(conf.getString("generatePdfMaxRange")).andReturn(pages).anyTimes();
   EasyMock.expect(conf.getBoolean("turnOffPdfCheck")).andReturn(turnOff).anyTimes();
   KConfiguration kConfiguration = EasyMock.createMock(KConfiguration.class);
   EasyMock.expect(kConfiguration.getConfiguration()).andReturn(conf).anyTimes();
   return new Object[] {conf, kConfiguration};
 }
 @Before
 public void setUp() {
   error = new BoxServerError();
   error.setStatus(HttpStatus.SC_FORBIDDEN);
   boxResponse = EasyMock.createMock(DefaultBoxResponse.class);
   response = EasyMock.createMock(BasicHttpResponse.class);
   entity = EasyMock.createMock(StringEntity.class);
   statusLine = EasyMock.createMock(StatusLine.class);
 }