org.mockito.Answers Java Examples

The following examples show how to use org.mockito.Answers. 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: SessionTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void test_discard_all_discards_all_portals_and_prepared_statements() throws Exception {
    SQLExecutor sqlExecutor = SQLExecutor.builder(clusterService).build();
    DependencyCarrier executor = mock(DependencyCarrier.class, Answers.RETURNS_MOCKS);
    Session session = new Session(
        sqlExecutor.analyzer,
        sqlExecutor.planner,
        new JobsLogs(() -> false),
        false,
        executor,
        AccessControl.DISABLED,
        SessionContext.systemSessionContext());

    session.parse("S_1", "SELECT 1", List.of());
    session.bind("P_1", "S_1", List.of(), null);

    assertThat(session.portals.size(), is(1));
    assertThat(session.preparedStatements.size(), is(1));

    session.parse("stmt", "DISCARD ALL", Collections.emptyList());
    session.bind("", "stmt", Collections.emptyList(), null);
    session.execute("", 0, new BaseResultReceiver());

    assertThat(session.portals.entrySet(), Matchers.empty());
    assertThat(session.preparedStatements.entrySet(), Matchers.empty());
}
 
Example #2
Source File: OffHeapDiskStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testProvidingOffHeapDiskStoreConfiguration() throws Exception {
  OffHeapDiskStore.Provider provider = new OffHeapDiskStore.Provider();
  ServiceLocator serviceLocator = dependencySet().with(diskResourceService).with(provider)
    .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS)).build();
  serviceLocator.startAllServices();

  CacheConfiguration<?, ?> cacheConfiguration = MockitoUtil.mock(CacheConfiguration.class);
  when(cacheConfiguration.getResourcePools()).thenReturn(newResourcePoolsBuilder().disk(1, MemoryUnit.MB, false).build());
  PersistenceSpaceIdentifier<?> space = diskResourceService.getPersistenceSpaceIdentifier("cache", cacheConfiguration);

  @SuppressWarnings("unchecked")
  Store.Configuration<Long, Object[]> storeConfig1 = MockitoUtil.mock(Store.Configuration.class);
  when(storeConfig1.getKeyType()).thenReturn(Long.class);
  when(storeConfig1.getValueType()).thenReturn(Object[].class);
  when(storeConfig1.getResourcePools()).thenReturn(ResourcePoolsBuilder.newResourcePoolsBuilder()
    .disk(10, MB)
    .build());
  when(storeConfig1.getDispatcherConcurrency()).thenReturn(1);

  OffHeapDiskStore<Long, Object[]> offHeapDiskStore1 = provider.createStore(
          storeConfig1, space, new OffHeapDiskStoreConfiguration("pool", 2, 4));
  assertThat(offHeapDiskStore1.getThreadPoolAlias(), is("pool"));
  assertThat(offHeapDiskStore1.getWriterConcurrency(), is(2));
  assertThat(offHeapDiskStore1.getDiskSegments(), is(4));
}
 
Example #3
Source File: XAStoreTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testRank() throws Exception {
  XAStore.Provider provider = new XAStore.Provider();
  XAStoreConfiguration configuration = new XAStoreConfiguration("testXAResourceId");
  ServiceLocator serviceLocator = dependencySet()
    .with(provider)
    .with(Store.Provider.class)
    .with(mock(DiskResourceService.class))
    .with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS))
    .with(mock(TransactionManagerProvider.class)).build();

  serviceLocator.startAllServices();

  Set<ServiceConfiguration<?, ?>> xaStoreConfigs = Collections.singleton(configuration);
  assertThat(provider.wrapperStoreRank(xaStoreConfigs), is(1));

  Set<ServiceConfiguration<?, ?>> emptyConfigs = emptySet();
  assertThat(provider.wrapperStoreRank(emptyConfigs), is(0));

}
 
Example #4
Source File: ServiceProviderTest.java    From ehcache3 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSupportsMultipleAuthoritativeTierProviders() throws Exception {

  ServiceLocator.DependencySet dependencySet = dependencySet();

  OnHeapStore.Provider cachingTierProvider = new OnHeapStore.Provider();
  OffHeapStore.Provider authoritativeTierProvider = new OffHeapStore.Provider();
  OffHeapDiskStore.Provider diskStoreProvider = new OffHeapDiskStore.Provider();

  dependencySet.with(cachingTierProvider);
  dependencySet.with(authoritativeTierProvider);
  dependencySet.with(diskStoreProvider);
  dependencySet.with(mock(DiskResourceService.class));
  dependencySet.with(mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS));

  ServiceLocator serviceLocator = dependencySet.build();
  serviceLocator.startAllServices();

  assertThat(serviceLocator.getServicesOfType(CachingTier.Provider.class),
    IsCollectionContaining.<CachingTier.Provider>hasItem(IsSame.<CachingTier.Provider>sameInstance(cachingTierProvider)));
  assertThat(serviceLocator.getServicesOfType(AuthoritativeTier.Provider.class),
    IsCollectionContaining.<AuthoritativeTier.Provider>hasItem(IsSame.<AuthoritativeTier.Provider>sameInstance(authoritativeTierProvider)));
  assertThat(serviceLocator.getServicesOfType(OffHeapDiskStore.Provider.class),
    IsCollectionContaining.<OffHeapDiskStore.Provider>hasItem(IsSame.<OffHeapDiskStore.Provider>sameInstance(diskStoreProvider)));
}
 
Example #5
Source File: AbstractConnectorImplRepositoryStoreTest.java    From bonita-studio with GNU General Public License v2.0 6 votes vote down vote up
/**
 * @throws java.lang.Exception
 */
@SuppressWarnings("unchecked")
@Before
public void setUp() throws Exception {
    implRepositoryStore = mock(AbstractConnectorImplRepositoryStore.class);
    doAnswer(Answers.CALLS_REAL_METHODS.get()).when(implRepositoryStore)
            .cleanJarDependency(any(IRepositoryFileStore.class), any(IRepositoryStore.class), any(IRepositoryStore.class));

    connectorImpl = ConnectorImplementationFactory.eINSTANCE.createConnectorImplementation();
    connectorImpl.setDefinitionId("def");
    connectorImpl.setDefinitionVersion("1.0");
    connectorImpl.setImplementationClassname("org.bonita.MyImpl");
    connectorImpl.setImplementationId("impl");
    connectorImpl.setImplementationVersion("1.0");
    JarDependencies deps = ConnectorImplementationFactory.eINSTANCE.createJarDependencies();
    String jarName = NamingUtils.toConnectorImplementationFilename(connectorImpl.getImplementationId(), connectorImpl.getImplementationVersion(), false)
            + ".jar";
    deps.getJarDependency().add(
            jarName);
    connectorImpl.setJarDependencies(deps);

    doReturn(connectorImpl).when(fStore).getContent();

    doReturn(depFileStore).when(dependencyRepositoryStore).getChild(jarName, true);
}
 
Example #6
Source File: LeaseLockTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void updateWithValidLeaderElectionRecordShouldSendPutRequest() throws Exception {
  // Given
  final Resource<Lease, ?> leaseResource = leases.withName("name");
  final Replaceable<Lease, Lease> replaceable = mock(Replaceable.class, Answers.RETURNS_DEEP_STUBS);
  when(leaseResource.lockResourceVersion(any())).thenReturn(replaceable);
  final Lease leaseInTheCluster = new Lease();
  leaseInTheCluster.setSpec(new LeaseSpec());
  when(leaseResource.get()).thenReturn(leaseInTheCluster);
  final LeaderElectionRecord record = new LeaderElectionRecord(
    "1337", Duration.ofSeconds(1), ZonedDateTime.now(), ZonedDateTime.now(), 0);
  record.setVersion("313373");
  final LeaseLock lock = new LeaseLock("namespace", "name", "1337");
  // When
  lock.update(kc, record);
  // Then
  verify(replaceable, times(1)).replace(eq(leaseInTheCluster));
  assertEquals("1337", leaseInTheCluster.getSpec().getHolderIdentity());
}
 
Example #7
Source File: ResultSetReceiverTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void testChannelIsPeriodicallyFlushedToAvoidConsumingTooMuchMemory() {
    Channel channel = mock(Channel.class, Answers.RETURNS_DEEP_STUBS);
    ResultSetReceiver resultSetReceiver = new ResultSetReceiver(
        "select * from t",
        channel,
        RuntimeException::new,
        Collections.singletonList(PGTypes.get(DataTypes.INTEGER)),
        null
    );
    Row1 row1 = new Row1(1);
    for (int i = 0; i < 1500; i++) {
        resultSetReceiver.setNextRow(row1);
    }
    verify(channel, times(1)).flush();
}
 
Example #8
Source File: ConfigMapLockTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
void updateWithValidLeaderElectionRecordShouldSendPutRequest() throws Exception {
  // Given
  final Resource<ConfigMap, ?> configMapResource = configMaps.withName("name");
  final Replaceable<ConfigMap, ConfigMap> replaceable = mock(Replaceable.class, Answers.RETURNS_DEEP_STUBS);
  when(configMapResource.lockResourceVersion(any())).thenReturn(replaceable);
  final ConfigMap configMapInTheCluster = new ConfigMap();
  configMapInTheCluster.setMetadata(new ObjectMetaBuilder().withAnnotations(new HashMap<>()).build());
  when(configMapResource.get()).thenReturn(configMapInTheCluster);
  final LeaderElectionRecord record = new LeaderElectionRecord(
    "1337", Duration.ofSeconds(1), ZonedDateTime.now(), ZonedDateTime.now(), 0);
  record.setVersion("313373");
  final ConfigMapLock lock = new ConfigMapLock("namespace", "name", "1337");
  // When
  lock.update(kc, record);
  // Then
  verify(replaceable, times(1)).replace(eq(configMapInTheCluster));
}
 
Example #9
Source File: ProjectingRowConsumerTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare() {
    functions = getFunctions();
    memoryManager = new OnHeapMemoryManager(usedBytes -> {});
    projectorFactory = new ProjectionToProjectorVisitor(
        clusterService,
        new NodeJobsCounter(),
        functions,
        THREAD_POOL,
        Settings.EMPTY,
        mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS),
        new InputFactory(functions),
        new EvaluatingNormalizer(
            functions,
            RowGranularity.SHARD,
            r -> Literal.ofUnchecked(r.valueType(), r.valueType().value("1")),
            null),
        t -> null,
        t -> null,
        Version.CURRENT,
        new ShardId("dummy", UUID.randomUUID().toString(), 0)
    );
}
 
Example #10
Source File: FilerUtilsTest.java    From FreeBuilder with Apache License 2.0 6 votes vote down vote up
@Test
public void testConstructor_avoidsEclipseWriterBug() throws IOException {
  // Due to a bug in Eclipse, we *must* call close on the object returned from openWriter().
  // Eclipse proxies a Writer but does not implement the fluent API correctly.
  // Here, we implement the fluent Writer API with the same bug:
  Writer mockWriter = Mockito.mock(Writer.class, (Answer<?>) invocation -> {
    if (Writer.class.isAssignableFrom(invocation.getMethod().getReturnType())) {
      // Erroneously return the delegate writer (matching the Eclipse bug!)
      return source;
    } else {
      return Answers.RETURNS_SMART_NULLS.get().answer(invocation);
    }
  });
  when(sourceFile.openWriter()).thenReturn(mockWriter);

  FilerUtils.writeCompilationUnit(filer, unit, originatingElement);
  verify(mockWriter).close();
}
 
Example #11
Source File: ProjectionToProjectorVisitorTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare() {
    MockitoAnnotations.initMocks(this);
    functions = getFunctions();
    visitor = new ProjectionToProjectorVisitor(
        clusterService,
        new NodeJobsCounter(),
        functions,
        THREAD_POOL,
        Settings.EMPTY,
        mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS),
        new InputFactory(functions),
        EvaluatingNormalizer.functionOnlyNormalizer(functions),
        t -> null,
        t -> null
    );
    memoryManager = new OnHeapMemoryManager(usedBytes -> {});

    avgSignature = Signature.aggregate(
        "avg",
        DataTypes.INTEGER.getTypeSignature(),
        DataTypes.DOUBLE.getTypeSignature()
    );
}
 
Example #12
Source File: ProjectorsTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Before
public void prepare() throws Exception {
    Functions functions = getFunctions();
    memoryManager = new OnHeapMemoryManager(bytes -> {});
    projectorFactory = new ProjectionToProjectorVisitor(
        clusterService,
        new NodeJobsCounter(),
        functions,
        THREAD_POOL,
        Settings.EMPTY,
        mock(TransportActionProvider.class, Answers.RETURNS_DEEP_STUBS),
        new InputFactory(functions),
        new EvaluatingNormalizer(
            functions,
            RowGranularity.SHARD,
            r -> Literal.ofUnchecked(r.valueType(), r.valueType().value("1")),
            null),
        t -> null,
        t -> null,
        Version.CURRENT,
        new ShardId("dummy", UUID.randomUUID().toString(), 0)
    );
}
 
Example #13
Source File: SessionTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Test
public void test_closing_a_statement_closes_related_portals() {
    SQLExecutor sqlExecutor = SQLExecutor.builder(clusterService).build();
    DependencyCarrier executor = mock(DependencyCarrier.class, Answers.RETURNS_MOCKS);
    Session session = new Session(
        sqlExecutor.analyzer,
        sqlExecutor.planner,
        new JobsLogs(() -> false),
        false,
        executor,
        AccessControl.DISABLED,
        SessionContext.systemSessionContext());

    session.parse("S_1", "SELECT 1", List.of());
    session.bind("P_1", "S_1", List.of(), null);

    assertThat(session.portals.size(), is(1));
    assertThat(session.preparedStatements.size(), is(1));

    session.close((byte) 'S', "S_1");
    assertThat(session.portals.entrySet(), Matchers.empty());
    assertThat(session.preparedStatements.entrySet(), Matchers.empty());
}
 
Example #14
Source File: DecommissioningServiceTest.java    From crate with Apache License 2.0 6 votes vote down vote up
@Before
public void init() throws Exception {
    executorService = mock(ScheduledExecutorService.class, Answers.RETURNS_MOCKS);
    jobsLogs = new JobsLogs(() -> true);
    sqlOperations = mock(SQLOperations.class, Answers.RETURNS_MOCKS);
    decommissioningService = new TestableDecommissioningService(
        Settings.EMPTY,
        clusterService,
        jobsLogs,
        executorService,
        sqlOperations,
        () -> exited.set(true),
        mock(TransportClusterHealthAction.class),
        mock(TransportClusterUpdateSettingsAction.class)
    );
}
 
Example #15
Source File: SmtpSessionTest.java    From NioSmtpClient with Apache License 2.0 6 votes vote down vote up
private SslHandler getSslHandler() throws Exception {
  // get SslHandler if it was added to the pipeline
  ArgumentCaptor<ChannelHandler> captor = ArgumentCaptor.forClass(ChannelHandler.class);
  verify(pipeline).addFirst(captor.capture());
  SslHandler sslHandler = (SslHandler) captor.getValue();

  // mock and store the context so we can get the handshake future
  ChannelHandlerContext context = mock(ChannelHandlerContext.class);
  when(context.executor()).thenReturn(ImmediateEventExecutor.INSTANCE);
  when(context.channel()).thenReturn(mock(Channel.class, Answers.RETURNS_MOCKS.get()));

  // add the handler but prevent the handshake from running automatically
  when(channel.isActive()).thenReturn(false);
  sslHandler.handlerAdded(context);

  return sslHandler;
}
 
Example #16
Source File: CharacteristicSubscriptionTest.java    From neatle with MIT License 6 votes vote down vote up
@Test
public void testStopWhileStillStarting() {
    final BluetoothGatt bluetoothGatt = Mockito.mock(BluetoothGatt.class, Answers.RETURNS_DEEP_STUBS);

    when(device.isConnected()).thenReturn(true);
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocationOnMock) {
            BluetoothGattCallback callback = invocationOnMock.getArgument(0);
            callback.onServicesDiscovered(bluetoothGatt, BluetoothGatt.GATT_SUCCESS);

            return null;
        }
    }).when(device).execute(Mockito.<BluetoothGattCallback>any());

    subscription.start();

    Robolectric.getForegroundThreadScheduler().pause();

    subscription.stop();
    subscription.start();

    Robolectric.getForegroundThreadScheduler().unPause();

    assertTrue(subscription.isStarted());
}
 
Example #17
Source File: MockFactory.java    From rheem with Apache License 2.0 6 votes vote down vote up
public static ExecutionOperator createExecutionOperator(String name, int numInputs, int numOutputs, Platform platform) {
    final ExecutionOperator mockedExecutionOperator = mock(ExecutionOperator.class, Answers.CALLS_REAL_METHODS);
    when(mockedExecutionOperator.toString()).thenReturn("ExecutionOperator[" + name + "]");
    when(mockedExecutionOperator.getPlatform()).thenReturn(platform);

    // Mock input slots.
    final InputSlot[] inputSlots = new InputSlot[numInputs];
    for (int inputIndex = 0; inputIndex < numInputs; inputIndex++) {
        inputSlots[inputIndex] = new InputSlot("input-" + inputIndex, mockedExecutionOperator, mock(DataSetType.class));
    }
    when(mockedExecutionOperator.getAllInputs()).thenReturn(inputSlots);
    when(mockedExecutionOperator.getNumInputs()).thenCallRealMethod();

    // Mock output slots.
    final OutputSlot[] outputSlots = new OutputSlot[numOutputs];
    for (int outputIndex = 0; outputIndex < numOutputs; outputIndex++) {
        outputSlots[outputIndex] = new OutputSlot("output" + outputIndex, mockedExecutionOperator, mock(DataSetType.class));
    }
    when(mockedExecutionOperator.getAllOutputs()).thenReturn(outputSlots);
    when(mockedExecutionOperator.getNumOutputs()).thenCallRealMethod();
    return mockedExecutionOperator;
}
 
Example #18
Source File: SysNodeChecksTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationLowDiskWatermarkCheck() {
    DiskWatermarkNodesSysCheck low = new LowDiskWatermarkNodesSysCheck(
        clusterService,
        Settings.EMPTY,
        mock(NodeService.class, Answers.RETURNS_MOCKS)
    );

    assertThat(low.id(), is(6));
    assertThat(low.severity(), is(SysCheck.Severity.HIGH));

    // default threshold is: 85% used
    assertThat(low.isValid(15, 100), is(true));
    assertThat(low.isValid(14, 100), is(false));
}
 
Example #19
Source File: TieredStoreFlushWhileShutdownTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
private ServiceLocator getServiceLocator(File location) throws Exception {
  DefaultPersistenceConfiguration persistenceConfiguration = new DefaultPersistenceConfiguration(location);
  DefaultLocalPersistenceService fileService = new DefaultLocalPersistenceService(persistenceConfiguration);
  DefaultDiskResourceService diskResourceService = new DefaultDiskResourceService();
  ServiceLocator.DependencySet dependencySet = dependencySet();
  dependencySet.with(fileService);
  dependencySet.with(diskResourceService);
  dependencySet.with(new OnHeapStore.Provider());
  dependencySet.with(new OffHeapDiskStore.Provider());
  dependencySet.with(Mockito.mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS));
  return dependencySet.build();
}
 
Example #20
Source File: SysNodeChecksTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationFloodStageDiskWatermarkCheck() {
    DiskWatermarkNodesSysCheck floodStage = new FloodStageDiskWatermarkNodesSysCheck(
        clusterService,
        Settings.EMPTY,
        mock(NodeService.class, Answers.RETURNS_MOCKS)
    );

    assertThat(floodStage.id(), is(7));
    assertThat(floodStage.severity(), is(SysCheck.Severity.HIGH));

    // default threshold is: 95% used
    assertThat(floodStage.isValid(5, 100), is(true));
    assertThat(floodStage.isValid(4, 100), is(false));
}
 
Example #21
Source File: ClusteredStoreProviderTest.java    From ehcache3 with Apache License 2.0 5 votes vote down vote up
@Test
public void testRankTiered() throws Exception {
  TieredStore.Provider provider = new TieredStore.Provider();
  ServiceLocator serviceLocator = dependencySet()
    .with(provider)
    .with(new ClusteredStore.Provider())
    .with(new OnHeapStore.Provider())
    .with(new OffHeapStore.Provider())
    .with(new OffHeapDiskStore.Provider())
    .with(mock(DiskResourceService.class))
    .with(Mockito.mock(CacheManagerProviderService.class, Answers.RETURNS_DEEP_STUBS))
    .with(mock(ClusteringService.class)).build();
  serviceLocator.startAllServices();

  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK);
  assertRank(provider, 2, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 3, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);

  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK);
  assertRank(provider, 2, ClusteredResourceType.Types.SHARED, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 3, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);

  // Multiple clustered resources not currently supported
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
  assertRank(provider, 0, ClusteredResourceType.Types.DEDICATED, ClusteredResourceType.Types.SHARED, ResourceType.Core.DISK, ResourceType.Core.OFFHEAP, ResourceType.Core.HEAP);
}
 
Example #22
Source File: CompiledJavaccFileTest.java    From javaccPlugin with MIT License 5 votes vote down vote up
@Test(expected = CompiledJavaccFileOperationException.class)
public void copyCustomAstClassToTargetDirectoryFails() throws Exception {
    PowerMockito.mockStatic(FileUtils.class, Answers.CALLS_REAL_METHODS.get());
    doThrow(new IOException()).when(FileUtils.class);
    FileUtils.copyFile(any(File.class), any(File.class));
    
    File file = new File(outputDirectory, "FileWithCorrespondingCustomAstClass.java");
    CompiledJavaccFile compiledJavaccFile = new CompiledJavaccFile(file, outputDirectory, customAstClassesDirectory, targetDirectory, logger);
    
    compiledJavaccFile.copyCustomAstClassToTargetDirectory(customAstClassesDirectory);
}
 
Example #23
Source File: JavaToJavaccDependencyActionTest.java    From javaccPlugin with MIT License 5 votes vote down vote up
@Test
public void noInteractionsWithProjectIfJavaPluginNotApplied() {
    project = Mockito.mock(Project.class, Answers.RETURNS_MOCKS.get());
    JavaToJavaccDependencyAction action = new JavaToJavaccDependencyAction();

    action.execute(project);

    Mockito.verify(project).getPlugins();
    Mockito.verifyNoMoreInteractions(project);
}
 
Example #24
Source File: SysNodeChecksTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testValidationHighDiskWatermarkCheck() {
    DiskWatermarkNodesSysCheck high = new HighDiskWatermarkNodesSysCheck(
        clusterService,
        Settings.EMPTY,
        mock(NodeService.class, Answers.RETURNS_MOCKS)
    );

    assertThat(high.id(), is(5));
    assertThat(high.severity(), is(SysCheck.Severity.HIGH));

    // default threshold is: 90% used
    assertThat(high.isValid(10, 100), is(true));
    assertThat(high.isValid(9, 100), is(false));
}
 
Example #25
Source File: SysNodeChecksTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testLowDiskWatermarkSucceedsIfThresholdCheckIsDisabled() {
    LowDiskWatermarkNodesSysCheck check = new LowDiskWatermarkNodesSysCheck(
        clusterService,
        Settings.builder().put("cluster.routing.allocation.disk.threshold_enabled", false).build(),
        mock(NodeService.class, Answers.RETURNS_MOCKS)
    );
    assertThat(check.isValid(), is(true));
}
 
Example #26
Source File: SysNodeChecksTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoveryAfterNodesCheckWithCorrectSetting() {
    ClusterService clusterService = mock(ClusterService.class, Answers.RETURNS_DEEP_STUBS);

    RecoveryAfterNodesSysCheck recoveryAfterNodesCheck =
        new RecoveryAfterNodesSysCheck(clusterService, Settings.EMPTY);

    when(clusterService.localNode().getId()).thenReturn("node");
    when(clusterService.state().nodes().getSize()).thenReturn(8);

    assertThat(recoveryAfterNodesCheck.id(), is(2));
    assertThat(recoveryAfterNodesCheck.severity(), is(SysCheck.Severity.HIGH));
    assertThat(recoveryAfterNodesCheck.validate(8, 8), is(true));
}
 
Example #27
Source File: SysNodeChecksTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoveryAfterNodesCheckWithLessThanQuorum() {
    ClusterService clusterService = mock(ClusterService.class, Answers.RETURNS_DEEP_STUBS);

    RecoveryAfterNodesSysCheck recoveryAfterNodesCheck =
        new RecoveryAfterNodesSysCheck(clusterService, Settings.EMPTY);

    when(clusterService.localNode().getId()).thenReturn("node");
    when(clusterService.state().nodes().getSize()).thenReturn(8);

    assertThat(recoveryAfterNodesCheck.id(), is(2));
    assertThat(recoveryAfterNodesCheck.severity(), is(SysCheck.Severity.HIGH));
    assertThat(recoveryAfterNodesCheck.validate(4, 8), is(false));
}
 
Example #28
Source File: TransportKillAllNodeActionTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testKillIsCalledOnTasks() throws Exception {
    TasksService tasksService = mock(TasksService.class, Answers.RETURNS_MOCKS);

    TransportKillAllNodeAction transportKillAllNodeAction = new TransportKillAllNodeAction(
        tasksService,
        clusterService,
        MockTransportService.createNewService(
            Settings.EMPTY, Version.CURRENT, THREAD_POOL, clusterService.getClusterSettings())
    );

    transportKillAllNodeAction.nodeOperation(new KillAllRequest()).get(5, TimeUnit.SECONDS);
    verify(tasksService, times(1)).killAll();
}
 
Example #29
Source File: TransportKillJobsNodeActionTest.java    From crate with Apache License 2.0 5 votes vote down vote up
@Test
public void testKillIsCalledOnJobContextService() throws Exception {
    TasksService tasksService = mock(TasksService.class, Answers.RETURNS_MOCKS);
    TransportKillJobsNodeAction transportKillJobsNodeAction = new TransportKillJobsNodeAction(
        tasksService,
        clusterService,
        MockTransportService.createNewService(
            Settings.EMPTY, Version.CURRENT, THREAD_POOL, clusterService.getClusterSettings())
    );

    List<UUID> toKill = ImmutableList.of(UUID.randomUUID(), UUID.randomUUID());

    transportKillJobsNodeAction.nodeOperation(new KillJobsRequest(toKill, null)).get(5, TimeUnit.SECONDS);
    verify(tasksService, times(1)).killJobs(toKill, null);
}
 
Example #30
Source File: ZookeeperStatusHandlerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
@Test
public void testMntrBugZk36Solr14463() {
  assumeWorkingMockito();
  ZookeeperStatusHandler zkStatusHandler = mock(ZookeeperStatusHandler.class);
  when(zkStatusHandler.getZkRawResponse("zoo1:2181", "ruok")).thenReturn(Arrays.asList("imok"));
  when(zkStatusHandler.getZkRawResponse("zoo1:2181", "mntr")).thenReturn(
      Arrays.asList("zk_version\t3.5.5-390fe37ea45dee01bf87dc1c042b5e3dcce88653, built on 05/03/2019 12:07 GMT",
          "zk_avg_latency\t1",
          "zk_server_state\tleader",
          "zk_synced_followers\t2"));
  when(zkStatusHandler.getZkRawResponse("zoo1:2181", "conf")).thenReturn(
      Arrays.asList("clientPort=2181"));
  when(zkStatusHandler.getZkStatus(anyString(), any())).thenCallRealMethod();
  when(zkStatusHandler.monitorZookeeper(anyString())).thenCallRealMethod();
  when(zkStatusHandler.validateZkRawResponse(ArgumentMatchers.any(), any(), any())).thenAnswer(Answers.CALLS_REAL_METHODS);

  Map<String, Object> mockStatus = zkStatusHandler.getZkStatus("zoo1:2181", ZkDynamicConfig.fromZkConnectString("zoo1:2181"));
  String expected = "{\n" +
      "  \"mode\":\"ensemble\",\n" +
      "  \"dynamicReconfig\":true,\n" +
      "  \"ensembleSize\":1,\n" +
      "  \"details\":[{\n" +
      "      \"zk_synced_followers\":\"2\",\n" +
      "      \"zk_version\":\"3.5.5-390fe37ea45dee01bf87dc1c042b5e3dcce88653, built on 05/03/2019 12:07 GMT\",\n" +
      "      \"zk_avg_latency\":\"1\",\n" +
      "      \"host\":\"zoo1:2181\",\n" +
      "      \"clientPort\":\"2181\",\n" +
      "      \"ok\":true,\n" +
      "      \"zk_server_state\":\"leader\"}],\n" +
      "  \"zkHost\":\"zoo1:2181\",\n" +
      "  \"errors\":[\"Leader reports 2 followers, but we only found 0. Please check zkHost configuration\"],\n" +
      "  \"status\":\"red\"}";
  assertEquals(expected, JSONUtil.toJSON(mockStatus));
}