@Test
  public void testConnectionShutdown() throws Exception {
    final InputStream instream = Mockito.mock(InputStream.class);
    final OutputStream outstream = Mockito.mock(OutputStream.class);
    Mockito.when(socket.getInputStream()).thenReturn(instream);
    Mockito.when(socket.getOutputStream()).thenReturn(outstream);

    conn.bind(socket);
    conn.ensureOpen();
    conn.getSessionOutputBuffer().write(0);

    Assert.assertTrue(conn.isOpen());

    conn.shutdown();

    Assert.assertFalse(conn.isOpen());

    Mockito.verify(outstream, Mockito.never())
        .write(Mockito.<byte[]>any(), Mockito.anyInt(), Mockito.anyInt());
    Mockito.verify(socket, Mockito.never()).shutdownInput();
    Mockito.verify(socket, Mockito.never()).shutdownOutput();
    Mockito.verify(socket, Mockito.times(1)).close();

    conn.close();
    Mockito.verify(socket, Mockito.times(1)).close();

    conn.shutdown();
    Mockito.verify(socket, Mockito.times(2)).close();
  }
 public void testJobDispatcher() {
   final MultipleNodeExecutorFactory factory = Mockito.mock(MultipleNodeExecutorFactory.class);
   final MultipleNodeExecutorTuner tuner = new MultipleNodeExecutorTuner(factory);
   final JobDispatcher dispatcher = Mockito.mock(JobDispatcher.class);
   final Map<String, Collection<Capability>> capabilities =
       new HashMap<String, Collection<Capability>>();
   Mockito.when(dispatcher.getAllCapabilities()).thenReturn(capabilities);
   tuner.setJobDispatcher(dispatcher);
   tuner.run();
   Mockito.verifyZeroInteractions(factory);
   capabilities.put("A", Arrays.asList(Capability.instanceOf("Foo")));
   capabilities.put("B", Arrays.asList(Capability.instanceOf("Bar")));
   tuner.run();
   Mockito.verifyZeroInteractions(factory);
   capabilities.put(
       "A",
       Arrays.asList(
           Capability.instanceOf("Foo"),
           Capability.parameterInstanceOf(PlatformCapabilities.NODE_COUNT, 10d)));
   capabilities.put(
       "B",
       Arrays.asList(
           Capability.instanceOf("Bar"),
           Capability.parameterInstanceOf(PlatformCapabilities.NODE_COUNT, 4d)));
   tuner.run();
   Mockito.verify(factory, Mockito.times(1)).setMaximumConcurrency(7);
   Mockito.verify(factory, Mockito.times(1)).invalidateCache();
   Mockito.when(factory.getMaximumConcurrency()).thenReturn(7);
   tuner.run();
   Mockito.verify(factory, Mockito.times(1)).setMaximumConcurrency(7);
   Mockito.verify(factory, Mockito.times(1)).invalidateCache();
 }
  @Test
  public void testRenderComponent() throws Exception {
    given(productReferencesComponentModel.getMaximumNumberProducts())
        .willReturn(Integer.valueOf(1));
    given(productReferencesComponentModel.getTitle()).willReturn(TITLE_VALUE);
    given(productReferencesComponentModel.getProductReferenceTypes())
        .willReturn(Arrays.asList(ProductReferenceTypeEnum.ACCESSORIES));
    given(productReferencesComponentModel.getItemtype()).willReturn(TEST_TYPE_CODE);

    requestContextData.setProduct(new ProductModel());
    given(
            productFacade.getProductReferencesForCode(
                Mockito.anyString(),
                Mockito.anyList(),
                Mockito.any(List.class),
                Mockito.<Integer>any()))
        .willReturn(productReferenceDataList);

    final String viewName =
        productReferencesComponentController.handleComponent(
            request, response, model, productReferencesComponentModel);
    verify(model, Mockito.times(1)).addAttribute(TITLE, TITLE_VALUE);
    verify(model, Mockito.times(1)).addAttribute(PRODUCT_REFERENCES, productReferenceDataList);
    Assert.assertEquals(TEST_TYPE_VIEW, viewName);
  }
  @Test
  public void playerNoOpSetLvl() {
    Player player = Mockito.mock(Player.class);

    cmd.onCommand(player, "setlvl");
    Mockito.verify(player)
        .sendMessage("§6[EC] §eSyntax: /level setLevel <Module> <Value> [Player]");

    cmd.onCommand(player, "setlvl", "t");
    Mockito.verify(player, Mockito.times(2))
        .sendMessage("§6[EC] §eSyntax: /level setLevel <Module> <Value> [Player]");

    cmd.onCommand(player, "setlevel", "t", "5");
    Mockito.verify(player).sendMessage("§6[EC] §cYou cannot execute that command.");

    player = Mockito.mock(Player.class);
    cmd.onCommand(player, "setlevel", "t", "asd");
    Mockito.verify(player)
        .sendMessage("§6[EC] §eSyntax: /level setLevel <Module> <Value> [Player]");
    Mockito.verify(player).sendMessage("§6[EC] §e<Value> has to be a natural number");

    cmd.onCommand(player, "setlvl", "t", "5", "cryxli");
    Mockito.verify(player).sendMessage("§6[EC] §cYou cannot execute that command.");

    Mockito.when(server.getPlayer(player.getName())).thenReturn(player);
    cmd.onCommand(player, "setlvl", "t", "5", "cryxli");
    Mockito.verify(player, Mockito.times(2))
        .sendMessage("§6[EC] §cYou cannot execute that command.");

    cmd.onCommand(player, "setlvl", "d", "15", "cryxli");
    Mockito.verify(player, Mockito.times(3))
        .sendMessage("§6[EC] §cYou cannot execute that command.");
  }
  @Test
  public void testListProjectsActionByNormalUser() throws Exception {
    String actionString = Action.ListProjects.toString();

    when(mockHttpServletRequest.getParameter(ServletUtil.ACTION)).thenReturn(actionString);

    // set AuthenticateOneTimeUser false
    prepareEnterAuthenticateOneTimeUser(false);
    User user = stubbingCheckUser();

    String xmi = constructProjectsObjectsXmi();
    doThrow(
            new org.talend.gwtadministrator.server.remoteconnection.ConnectionUtil
                .ResponseException(xmi))
        .when(ConnectionUtil.class);
    ConnectionUtil.listAuthorizedProjects(user);

    // RUN...
    defaultConnectionStrategy.execute(mockHttpServletRequest, mockHttpServletResponse);

    verifyNecessaryChecks(actionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkUser(loginString, password, false);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.listAuthorizedProjects(user);

    PrintWriter writer = mockHttpServletResponse.getWriter();
    writer.flush();
    System.out.println(outStringWriter.toString());
    // ASSERT...
    assertThat(outStringWriter.toString(), is("RESPONSE:" + xmi));
  }
  @SuppressWarnings("unchecked")
  @Test
  public void testAuthenticateTMForInstance_SSO() throws Throwable {
    // given
    Map<String, String> settings = getProxySettingsForMode("SAML_SP");
    createServiceInstance(
        ProvisioningStatus.COMPLETED, InstanceParameter.BSS_USER, InstanceParameter.BSS_USER_PWD);
    VOUserDetails manager = createVOUserDetails(10000, "user", "tp123");
    manager.setUserRoles(Collections.singleton(UserRoleType.TECHNOLOGY_MANAGER));
    Mockito.doReturn(manager)
        .when(besDAO)
        .getUserDetails(
            Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString());
    Mockito.doReturn(new PasswordAuthentication("nobody", ""))
        .when(configService)
        .getWebServiceAuthentication(Matchers.any(ServiceInstance.class), Matchers.anyMap());
    Mockito.doReturn(settings).when(configService).getAllProxyConfigurationSettings();

    // when
    authenticateTMForInstance(CTRL_ID, "appInstanceId", manager.getUserId(), "pass");

    // then
    Mockito.verify(besDAO, Mockito.times(0))
        .getUser(Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class));
    Mockito.verify(besDAO, Mockito.times(2))
        .getUserDetails(
            Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString());
  }
  @Test
  public void testAuthenticateTMForController_SSO() throws Throwable {

    // given
    Map<String, String> proxySettings = getProxySettingsForMode("SAML_SP");
    Map<String, Setting> controlleSettings = getControllerSettingsForOrg("tp123");

    VOUserDetails manager = createVOUserDetails(10001, "user", "tp123");
    manager.setUserRoles(Collections.singleton(UserRoleType.TECHNOLOGY_MANAGER));

    Mockito.doReturn(proxySettings).when(configService).getAllProxyConfigurationSettings();
    Mockito.doReturn(controlleSettings)
        .when(configService)
        .getControllerConfigurationSettings(Matchers.anyString());
    Mockito.doReturn(manager)
        .when(besDAO)
        .getUserDetails(
            Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString());

    // when
    authenticateTMForController(CTRL_ID, manager.getUserId(), "pass");

    // then
    Mockito.verify(besDAO, Mockito.times(0))
        .getUser(Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class));
    Mockito.verify(besDAO, Mockito.times(1))
        .getUserDetails(
            Matchers.any(ServiceInstance.class), Matchers.any(VOUser.class), Matchers.anyString());
  }
  @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
  @Test
  public void validateRetieveItemWithLastAccessUpdateTimeDelay() throws Exception {
    // need to ensure we wait 100 ms
    int wait = 100;

    ((DefaultAttributesHandler) repository.getAttributesHandler()).setLastRequestedResolution(wait);
    Thread.sleep(wait);

    AttributeStorage attributeStorageSpy =
        Mockito.spy(repository.getAttributesHandler().getAttributeStorage());
    repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy);

    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.greaterThan(originalLastAccessTime));

    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any());
    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .getAttributes(Mockito.<RepositoryItemUid>any());
  }
  @Test
  public final void testSequenceNumberValidator() {

    IKinesisProxy proxy = Mockito.mock(IKinesisProxy.class);

    SequenceNumberValidator validator =
        new SequenceNumberValidator(proxy, shardId, validateWithGetIterator);

    String goodSequence = "456";
    String iterator = "happyiterator";
    String badSequence = "789";
    Mockito.doReturn(iterator)
        .when(proxy)
        .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), goodSequence);
    Mockito.doThrow(new InvalidArgumentException(""))
        .when(proxy)
        .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), badSequence);

    validator.validateSequenceNumber(goodSequence);
    Mockito.verify(proxy, Mockito.times(1))
        .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), goodSequence);

    try {
      validator.validateSequenceNumber(badSequence);
      fail("Bad sequence number did not cause the validator to throw an exception");
    } catch (IllegalArgumentException e) {
      Mockito.verify(proxy, Mockito.times(1))
          .getIterator(shardId, ShardIteratorType.AFTER_SEQUENCE_NUMBER.toString(), badSequence);
    }

    nonNumericValueValidationTest(validator, proxy, validateWithGetIterator);
  }
  @Test
  public void eventCollected_is_not_called() {

    // given:

    Predicate<Integer> filter = Mockito.mock(UberClasses.cast(Predicate.class));
    EventHandler<Integer> filterEH = Mockito.mock(UberClasses.cast(EventHandler.class));

    Mockito.when(filter.test(Matchers.any())).thenReturn(false);
    Mockito.when(filterEH.test(Matchers.any())).thenReturn(true);

    EventCollector<Listener, Integer> collector = createCollector(filter, filterEH);
    Listener target = collector.getTarget();

    // when:

    target.event(100);
    target.event(200);

    // then:

    Mockito.verify(filter, Mockito.times(2)).test(Matchers.any());
    Mockito.verify(filterEH, Mockito.times(2)).test(Matchers.any());

    // and:

    Mockito.verifyNoMoreInteractions(filterEH);
  }
  @BenchmarkOptions(benchmarkRounds = 10, warmupRounds = 1)
  @Test
  public void validateRetieveItemWithOutLastAccessUpdateTimeDelay()
      throws LocalStorageException, ItemNotFoundException, IOException {
    // do the test, but make sure the _iterations_ will not get out of the "resolution" span!
    // Note: this test is just broken as is, what guarantees it will finish the cycles in given X
    // millis?
    // Meaning, the assertions + rounds is wrong.
    ((DefaultAttributesHandler) repository.getAttributesHandler())
        .setLastRequestedResolution(30000L);
    AttributeStorage attributeStorageSpy =
        Mockito.spy(repository.getAttributesHandler().getAttributeStorage());
    repository.getAttributesHandler().setAttributeStorage(attributeStorageSpy);

    ResourceStoreRequest resourceRequest = new ResourceStoreRequest(testFilePath);
    resourceRequest.getRequestContext().put(AccessManager.REQUEST_REMOTE_ADDRESS, "127.0.0.1");

    AbstractStorageItem storageItem =
        localRepositoryStorageUnderTest.retrieveItem(repository, resourceRequest);

    MatcherAssert.assertThat(storageItem, Matchers.notNullValue());
    MatcherAssert.assertThat(
        storageItem.getLastRequested(), Matchers.equalTo(originalLastAccessTime));

    Mockito.verify(attributeStorageSpy, Mockito.times(0))
        .putAttributes(Mockito.<RepositoryItemUid>any(), Mockito.<Attributes>any());
    Mockito.verify(attributeStorageSpy, Mockito.times(1))
        .getAttributes(Mockito.<RepositoryItemUid>any());
  }
  @Test
  public void ChainHandler_eventCollected_is_NOT_called() {

    // given:

    Predicate<Integer> filter = Mockito.mock(UberClasses.cast(Predicate.class));
    EventHandler<Integer> handler = Mockito.mock(UberClasses.cast(EventHandler.class));

    Mockito.when(filter.test(Matchers.any())).thenReturn(true);
    Mockito.when(handler.test(Matchers.any())).thenReturn(false);

    EventCollector<Listener, Integer> collector =
        EventCollector.create(
            Listener.class, Listener::event, EventHandlers.chain(filter, handler));

    Listener target = collector.getTarget();

    // when

    target.event(100);

    // then

    InOrder order = Mockito.inOrder(filter, handler);
    order.verify(filter, Mockito.times(1)).test(100);
    order.verify(handler, Mockito.times(1)).test(100);
    order.verifyNoMoreInteractions();
  }
  @Test
  public void events_are_collected() {

    // given:

    Predicate<Integer> filter = Mockito.mock(UberClasses.cast(Predicate.class));
    EventHandler<Integer> filterEH = Mockito.mock(UberClasses.cast(EventHandler.class));

    Mockito.when(filter.test(Matchers.any())).thenReturn(true);
    Mockito.when(filterEH.test(Matchers.any())).thenReturn(true);

    Mockito.when(filter.test(200)).thenReturn(false);

    EventCollector<Listener, Integer> collector = createCollector(filter, filterEH);
    Listener target = collector.getTarget();

    // when:

    target.event(100);
    target.event(200);
    target.event(300);

    // then:

    Mockito.verify(filter, Mockito.times(3)).test(Matchers.any());
    Mockito.verify(filterEH, Mockito.times(3)).test(Matchers.any());

    // and:

    List<Integer> events = collector.getEvents();
    Assert.assertThat(events, contains(100, 300));
    Assert.assertThat(collector.getLastEvent(), equalTo(300));
  }
  @Test
  public void canChangeWalletNameAndPasswordIfWalletIsAlreadyOpen() {
    // Arrange:
    final WalletNamePasswordPair pair2 = createPair("n2", "p2");
    final WalletDescriptor descriptor2 = createDescriptor("n2");
    final TestContext context = new TestContext();
    Mockito.when(context.descriptorFactory.createNew(pair2, FILE_EXTENSION))
        .thenReturn(descriptor2);

    // Act:
    context.walletServices.open(context.pair);
    context.walletServices.move(context.pair, pair2);

    // Assert:
    // - the original is opened and the target is created
    Mockito.verify(context.descriptorFactory, Mockito.times(2))
        .openExisting(context.pair, FILE_EXTENSION);
    Mockito.verify(context.descriptorFactory, Mockito.times(1)).createNew(pair2, FILE_EXTENSION);

    // - the original is loaded
    Mockito.verify(context.repository, Mockito.times(2)).load(context.descriptor);

    // - the target is saved
    final Wallet updatedWallet = context.walletServices.get(new WalletName("n2"));
    Assert.assertThat(updatedWallet.getName(), IsEqual.equalTo(new WalletName("n2")));
    // TODO BR: Fix this
    // Mockito.verify(context.repository, Mockito.times(1)).save(descriptor2, updatedWallet);
    Mockito.verify(context.repository, Mockito.times(1)).save(Mockito.any(), Mockito.any());

    // - the original wallet is deleted
    Mockito.verify(context.descriptor, Mockito.times(1)).delete();
  }
  @SuppressWarnings("resource")
  @Test
  public void updateEntityWithListeners() {
    @SuppressWarnings("unchecked")
    Repository<Entity> decoratedRepository = Mockito.mock(Repository.class);
    Mockito.when(decoratedRepository.getName()).thenReturn("entityFullName");
    EntityListenerRepositoryDecorator entityListenerRepositoryDecorator =
        new EntityListenerRepositoryDecorator(decoratedRepository, entityListenersService);
    EntityListener entityListener0 =
        Mockito.when(Mockito.mock(EntityListener.class).getEntityId())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    EntityListener entityListener1 =
        Mockito.when(Mockito.mock(EntityListener.class).getEntityId())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    entityListenersService.addEntityListener("entityFullName", entityListener0);
    entityListenersService.addEntityListener("entityFullName", entityListener1);

    Entity entity =
        Mockito.when(Mockito.mock(Entity.class).getIdValue())
            .thenReturn(Integer.valueOf(1))
            .getMock();
    entityListenerRepositoryDecorator.update(entity);

    Mockito.verify(decoratedRepository).update(entity);
    Mockito.verify(entityListener0, Mockito.times(1)).postUpdate(entity);
    Mockito.verify(entityListener1, Mockito.times(1)).postUpdate(entity);
  }
  @Test
  public void testValidateConnectionStale() throws Exception {
    final HttpConnection conn = Mockito.mock(HttpConnection.class);
    Mockito.when(conn.isOpen()).thenReturn(true);
    Mockito.when(conn.isStale()).thenReturn(false);

    final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class);
    Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn);

    final LocalConnPool pool = new LocalConnPool(connFactory, 2, 10);
    pool.setValidateAfterInactivity(5);

    final Future<LocalPoolEntry> future1 = pool.lease("somehost", null);
    final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(entry1);

    pool.release(entry1, true);

    Thread.sleep(10);

    Mockito.verify(connFactory, Mockito.times(1)).create("somehost");
    Mockito.when(conn.isStale()).thenReturn(true);

    final Future<LocalPoolEntry> future2 = pool.lease("somehost", null);
    final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(entry2);
    Assert.assertNotSame(entry1, entry2);

    Mockito.verify(conn, Mockito.times(1)).isStale();
    Mockito.verify(conn, Mockito.times(1)).close();
    Mockito.verify(connFactory, Mockito.times(2)).create("somehost");
  }
  @Test
  public void testCreateNewIfExpired() throws Exception {
    final LocalConnFactory connFactory = Mockito.mock(LocalConnFactory.class);

    final HttpConnection conn1 = Mockito.mock(HttpConnection.class);
    Mockito.when(conn1.isOpen()).thenReturn(true);
    Mockito.when(connFactory.create(Mockito.eq("somehost"))).thenReturn(conn1);

    final LocalConnPool pool = new LocalConnPool(connFactory, 2, 2);

    final Future<LocalPoolEntry> future1 = pool.lease("somehost", null);
    final LocalPoolEntry entry1 = future1.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(entry1);

    Mockito.verify(connFactory, Mockito.times(1)).create(Mockito.eq("somehost"));

    entry1.updateExpiry(1, TimeUnit.MILLISECONDS);
    pool.release(entry1, true);

    Thread.sleep(200L);

    final Future<LocalPoolEntry> future2 = pool.lease("somehost", null);
    final LocalPoolEntry entry2 = future2.get(1, TimeUnit.SECONDS);
    Assert.assertNotNull(entry2);

    Mockito.verify(connFactory, Mockito.times(2)).create(Mockito.eq("somehost"));

    final PoolStats totals = pool.getTotalStats();
    Assert.assertEquals(0, totals.getAvailable());
    Assert.assertEquals(1, totals.getLeased());
    Assert.assertEquals(Collections.singleton("somehost"), pool.getRoutes());
    final PoolStats stats = pool.getStats("somehost");
    Assert.assertEquals(0, stats.getAvailable());
    Assert.assertEquals(1, stats.getLeased());
  }
  public void testParams() {
    Map<String, Object> params = Maps.newHashMap();
    ActionDef def = Mockito.mock(ActionDef.class);
    Action test = new MyAction(null, def, params);
    LoggingContext.KeyValueLogger logger = Mockito.mock(LoggingContext.KeyValueLogger.class);

    assertSame("params should be initialized", params, test.getParams());

    params.put("a", "b");
    test.logParams(logger);
    // logable values of null should avoid calls to the logger.
    Mockito.verifyNoMoreInteractions(logger);

    Mockito.when(def.getLoggableParams()).thenReturn(Lists.newArrayList("a", "b"));
    test.logParams(logger);
    Mockito.verify(logger, Mockito.times(1)).log("a", "b");
    Mockito.verify(logger, Mockito.times(1)).log("b", "null");
    Mockito.verifyNoMoreInteractions(logger);

    test = new MyAction(null, def, null);
    assertEquals("params can be initialized to null", null, test.getParams());
    test.logParams(logger);
    // params of null should avoid calls to the logger.
    Mockito.verifyNoMoreInteractions(logger);
  }
  @Test
  public void noMinionsSpawnBefore90Seconds() throws Exception {
    int tickPerSecond = 10;
    Engine engine = new Engine();
    Nexus nexus = new Nexus(engine);
    SummonerRiftNexusBehavior behavior = new SummonerRiftNexusBehavior(engine, nexus);
    nexus.setBehavior(behavior);
    engine.addActor(nexus);

    Actor spectator = Mockito.mock(Actor.class);
    engine.addActor(spectator);
    engine.start();

    engine.enqueue(new TickEvent(LocalTime.parse("00:00:10"), tickPerSecond));
    Mockito.verify(spectator, Mockito.times(0)).onEvent(Matchers.isA(MinionWaveSpawnEvent.class));

    engine.enqueue(new TickEvent(LocalTime.parse("00:00:20"), tickPerSecond));
    Mockito.verify(spectator, Mockito.times(0)).onEvent(Matchers.isA(MinionWaveSpawnEvent.class));

    engine.enqueue(new TickEvent(LocalTime.parse("00:00:30"), tickPerSecond));
    Mockito.verify(spectator, Mockito.times(0)).onEvent(Matchers.isA(MinionWaveSpawnEvent.class));

    engine.enqueue(new TickEvent(LocalTime.parse("00:01:30"), tickPerSecond));
    Mockito.verify(spectator, Mockito.times(1)).onEvent(Matchers.isA(MinionWaveSpawnEvent.class));
  }
  @Test
  public void navigate() {
    NavigateAllListener beforeListener = Mockito.mock(NavigateAllListener.class);
    NavigateAllListener afterListener = Mockito.mock(NavigateAllListener.class);

    events().beforeNavigate(beforeListener);
    events().afterNavigate(afterListener);
    goTo(DEFAULT_URL);

    Mockito.verify(beforeListener, Mockito.times(1))
        .on(
            Mockito.eq(DEFAULT_URL),
            Mockito.<WebDriver>anyObject(),
            Mockito.<NavigateAllListener.Direction>anyObject());
    Mockito.verify(afterListener, Mockito.times(1))
        .on(
            Mockito.eq(DEFAULT_URL),
            Mockito.<WebDriver>anyObject(),
            Mockito.<NavigateAllListener.Direction>anyObject());

    getDriver().navigate().refresh();

    Mockito.verify(beforeListener, Mockito.times(1))
        .on(
            (String) Mockito.isNull(),
            Mockito.<WebDriver>anyObject(),
            Mockito.eq(NavigateAllListener.Direction.REFRESH));
    Mockito.verify(afterListener, Mockito.times(1))
        .on(
            (String) Mockito.isNull(),
            Mockito.<WebDriver>anyObject(),
            Mockito.eq(NavigateAllListener.Direction.REFRESH));
  }
Exemple #21
0
  @Test
  public void testCategoryRemovedEventListenersCalled() {
    CategoryRemovedEventListener categoryRemovedEventListenerMock1 =
        Mockito.mock(CategoryRemovedEventListener.class);
    CategoryRemovedEventListener categoryRemovedEventListenerMock2 =
        Mockito.mock(CategoryRemovedEventListener.class);

    pinBoard.addCategoryRemovedEventListener(categoryRemovedEventListenerMock1);
    pinBoard.addCategoryRemovedEventListener(categoryRemovedEventListenerMock2);

    Category cat1 = new Category("cat1", false, NoteColor.DEFAULT_COLOR);
    Category cat2 = new Category("cat2", false, NoteColor.DEFAULT_COLOR);
    Category cat3 = new Category("cat3", false, NoteColor.DEFAULT_COLOR);
    pinBoard.addCategory(cat1);
    pinBoard.addCategory(cat2);
    pinBoard.addCategory(cat3);

    pinBoard.removeCategory(cat1);
    pinBoard.removeCategory(cat2);
    pinBoard.removeCategory(cat3);

    Mockito.verify(categoryRemovedEventListenerMock1, Mockito.times(3))
        .categoryRemoved(Mockito.any(CategoryRemovedEvent.class));
    Mockito.verify(categoryRemovedEventListenerMock2, Mockito.times(3))
        .categoryRemoved(Mockito.any(CategoryRemovedEvent.class));
  }
  @Test
  public void testFlexOffer() {
    try {
      FlexOffer flexOffer = buildFlexOffer();
      controller.action(flexOffer, null);

      Mockito.verify(corePlanboardValidatorService, Mockito.times(1))
          .validateTimezone(Matchers.eq(flexOffer.getTimeZone()));
      Mockito.verify(corePlanboardValidatorService, Mockito.times(1))
          .validateCurrency(Matchers.eq(flexOffer.getCurrency()));
      Mockito.verify(corePlanboardValidatorService, Mockito.times(1))
          .validatePTUDuration(Matchers.eq(flexOffer.getPTUDuration()));

      Mockito.verify(corePlanboardBusinessService, Mockito.times(1))
          .storeFlexOffer(
              Matchers.eq(flexOffer.getMessageMetadata().getSenderDomain()), Matchers.eq(flexOffer),
              Matchers.eq(DocumentStatus.ACCEPTED),
                  Matchers.eq(flexOffer.getMessageMetadata().getSenderDomain()));

      Mockito.verify(jmsService, Mockito.times(1))
          .sendMessageToOutQueue(Matchers.contains("Accepted"));
    } catch (BusinessException e) {
      fail(e.getMessage());
    }
  }
  @Test
  public void testHandleEvent_withContext_withRule_strictMaximum() throws Exception {

    Mockito.when(
            this.preferencesMngr.get(
                IPreferencesMngr.AUTONOMIC_MAX_VM_NUMBER, "" + Integer.MAX_VALUE))
        .thenReturn("4");
    Mockito.when(this.preferencesMngr.get(IPreferencesMngr.AUTONOMIC_STRICT_MAX_VM_NUMBER, "true"))
        .thenReturn("true");

    ManagedApplication ma = factorizeConfiguration();
    this.autonomicMngr.handleEvent(ma, new MsgNotifAutonomic("app", "/root", "event", null));

    Mockito.verify(this.preferencesMngr, Mockito.times(1))
        .get(IPreferencesMngr.AUTONOMIC_MAX_VM_NUMBER, "" + Integer.MAX_VALUE);
    Mockito.verify(this.preferencesMngr, Mockito.times(1))
        .get(IPreferencesMngr.AUTONOMIC_STRICT_MAX_VM_NUMBER, "true");

    ArgumentCaptor<CommandExecutionContext> execCtx =
        ArgumentCaptor.forClass(CommandExecutionContext.class);
    Mockito.verify(this.commandsMngr, Mockito.times(3))
        .execute(Mockito.any(Application.class), Mockito.anyString(), execCtx.capture());

    for (CommandExecutionContext c : execCtx.getAllValues()) {
      Assert.assertEquals(4, c.getMaxVm());
      Assert.assertTrue(c.isStrictMaxVm());
    }
  }
 @Test
 public void usingUnsupportedBuildAreaWithLiftDistance() throws Exception {
   AbstractPrintFileProcessor processor = createNewPrintFileProcessor();
   Graphics2D graphics = Mockito.mock(Graphics2D.class);
   PrintJob printJob = createTestPrintJob(processor);
   Mockito.when(
           printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode())
       .thenReturn("G99 ${1 + UnknownVariable * 2} ;dependent on buildArea");
   Double whenBuilAreaMMCalled =
       printJob.getPrintFileProcessor().getBuildAreaMM(Mockito.any(PrintJob.class));
   Mockito.when(whenBuilAreaMMCalled).thenReturn(null);
   DataAid aid = processor.initializeJobCacheWithDataAid(printJob);
   try {
     aid.customizer.setNextStep(PrinterStep.PerformExposure);
     processor.printImageAndPerformPostProcessing(aid, image);
     Assert.fail("Must throw InappropriateDeviceException");
   } catch (InappropriateDeviceException e) {
     Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(2))
         .getBuildAreaMM(Mockito.any(PrintJob.class));
   }
   Mockito.when(
           printJob.getPrinter().getConfiguration().getSlicingProfile().getZLiftDistanceGCode())
       .thenReturn("G99 ${1 + buildAreaMM * 2} ;dependent on buildArea");
   try {
     aid.customizer.setNextStep(PrinterStep.PerformExposure);
     processor.printImageAndPerformPostProcessing(aid, image);
     Mockito.verify(printJob.getPrintFileProcessor(), Mockito.times(5))
         .getBuildAreaMM(Mockito.any(PrintJob.class));
   } catch (InappropriateDeviceException e) {
     Assert.fail("Should not throw InappropriateDeviceException");
   }
 }
  @Test
  public void testSwapSHS4DHS_NotInEngine() {
    // Setup
    items.add(shs);
    items.add(shs);
    items.add(shs);
    items.add(shs);
    items.add(shs); // 3 in engine, 2 outside.

    newType = dhs;
    oldType = shs;

    engineHsSlots = 0;
    equippedHs = items.size();
    maxEquippableNewType = 2;
    maxGloballyEquippableNewType = 10;

    makeDefaultCut();

    Mockito.when(component.getSlotsFree()).thenReturn(0);

    // Execute
    OpSetHeatSinkType cut = new OpSetHeatSinkType(null, loadout, dhsUpgrade);
    cut.apply();

    // Verify
    Mockito.verify(component, Mockito.times(items.size())).removeItem(shs);
    Mockito.verify(component, Mockito.times(maxEquippableNewType)).addItem(dhs);
  }
  @Test
  public void reuseRetainingPresenter() {
    Mockito.when(callback.getPresenter()).thenReturn(presenter);
    delegate.onAttachedToWindow();

    Mockito.verify(callback, Mockito.never()).createPresenter();
    Mockito.verify(callback, Mockito.times(1)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(1)).attachView(view);
  }
  @Test
  public void twoMessages() throws Exception {
    ByteBuffer buf = new VertxByteBuffer().append(dummyMsgID);
    handler.newMessage(DataFormat.Binary, buf, false);
    handler.continueMessage(new VertxByteBuffer(), true);
    handler.newMessage(DataFormat.Binary, buf, true);

    verify(msgdecoder, Mockito.times(2)).decode(anyObject(), anyObject(), anyObject());
    verify(session, Mockito.times(2)).processMessage(dummyMessage);
  }
  @Test
  public void startViewGroup() {
    Mockito.when(callback.createPresenter()).thenReturn(presenter);

    delegate.onAttachedToWindow();

    Mockito.verify(callback, Mockito.times(1)).createPresenter();
    Mockito.verify(callback, Mockito.times(1)).setPresenter(presenter);
    Mockito.verify(presenter, Mockito.times(1)).attachView(view);
  }
  private void verifyNecessaryChecks(String actionString) throws Exception {
    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkParameter(actionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkParameter(versionString);

    verifyStatic(org.mockito.Mockito.times(1));
    ConnectionUtil.checkVersion(versionString);
  }
 @Test
 public void testShutdownHook() {
   ArgumentCaptor<Thread> shutdownHookCaptor = ArgumentCaptor.forClass(Thread.class);
   DataCollectorMain main = new TMain();
   Assert.assertEquals(0, main.doMain());
   Mockito.verify(runtime, Mockito.times(1)).addShutdownHook(shutdownHookCaptor.capture());
   Mockito.reset(task);
   shutdownHookCaptor.getValue().run();
   Mockito.verify(task, Mockito.times(1)).stop();
 }