Search in sources :

Example 81 with Mock

use of org.mockito.Mock in project pravega by pravega.

the class StreamMetadataTasksTest method setup.

@Before
public void setup() throws Exception {
    zkServer = new TestingServerStarter().start();
    zkServer.start();
    zkClient = CuratorFrameworkFactory.newClient(zkServer.getConnectString(), new ExponentialBackoffRetry(200, 10, 5000));
    zkClient.start();
    StreamMetrics.initialize();
    TransactionMetrics.initialize();
    StreamMetadataStore streamStore = getStore();
    // create a partial mock.
    streamStorePartialMock = spy(streamStore);
    ImmutableMap<BucketStore.ServiceType, Integer> map = ImmutableMap.of(BucketStore.ServiceType.RetentionService, 1, BucketStore.ServiceType.WatermarkingService, 1);
    bucketStore = StreamStoreFactory.createInMemoryBucketStore(map);
    kvtStore = spy(getKvtStore());
    TaskMetadataStore taskMetadataStore = TaskStoreFactory.createZKStore(zkClient, executor);
    SegmentHelper segmentHelperMock = SegmentHelperMock.getSegmentHelperMock();
    connectionFactory = new SocketConnectionFactoryImpl(ClientConfig.builder().build());
    EventHelper helper = EventHelperMock.getEventHelperMock(executor, "host", ((AbstractStreamMetadataStore) streamStore).getHostTaskIndex());
    streamMetadataTasks = spy(new StreamMetadataTasks(streamStorePartialMock, bucketStore, taskMetadataStore, segmentHelperMock, executor, "host", new GrpcAuthHelper(authEnabled, "key", 300), helper));
    EventHelper helperMock = EventHelperMock.getEventHelperMock(executor, "host", ((AbstractStreamMetadataStore) streamStore).getHostTaskIndex());
    kvtMetadataTasks = spy(new TableMetadataTasks(kvtStore, segmentHelperMock, executor, executor, "host", GrpcAuthHelper.getDisabledAuthHelper(), helperMock));
    streamTransactionMetadataTasks = new StreamTransactionMetadataTasks(streamStorePartialMock, segmentHelperMock, executor, "host", new GrpcAuthHelper(authEnabled, "key", 300));
    this.streamRequestHandler = new StreamRequestHandler(new AutoScaleTask(streamMetadataTasks, streamStorePartialMock, executor), new ScaleOperationTask(streamMetadataTasks, streamStorePartialMock, executor), new UpdateStreamTask(streamMetadataTasks, streamStorePartialMock, bucketStore, executor), new SealStreamTask(streamMetadataTasks, streamTransactionMetadataTasks, streamStorePartialMock, executor), new DeleteStreamTask(streamMetadataTasks, streamStorePartialMock, bucketStore, executor), new TruncateStreamTask(streamMetadataTasks, streamStorePartialMock, executor), new CreateReaderGroupTask(streamMetadataTasks, streamStorePartialMock, executor), new DeleteReaderGroupTask(streamMetadataTasks, streamStorePartialMock, executor), new UpdateReaderGroupTask(streamMetadataTasks, streamStore, executor), streamStorePartialMock, new DeleteScopeTask(streamMetadataTasks, streamStore, kvtStore, kvtMetadataTasks, executor), executor);
    consumer = new ControllerService(kvtStore, kvtMetadataTasks, streamStorePartialMock, bucketStore, streamMetadataTasks, streamTransactionMetadataTasks, segmentHelperMock, executor, null, requestTracker);
    commitWriter = new EventStreamWriterMock<>();
    abortWriter = new EventStreamWriterMock<>();
    streamTransactionMetadataTasks.initializeStreamWriters(commitWriter, abortWriter);
    final ScalingPolicy policy1 = ScalingPolicy.fixed(2);
    final StreamConfiguration configuration1 = StreamConfiguration.builder().scalingPolicy(policy1).build();
    streamStorePartialMock.createScope(SCOPE, null, executor).join();
    // stream1
    long start = System.currentTimeMillis();
    streamStorePartialMock.createStream(SCOPE, stream1, configuration1, start, null, executor).get();
    streamStorePartialMock.setState(SCOPE, stream1, State.ACTIVE, null, executor).get();
    AbstractMap.SimpleEntry<Double, Double> segment1 = new AbstractMap.SimpleEntry<>(0.5, 0.75);
    AbstractMap.SimpleEntry<Double, Double> segment2 = new AbstractMap.SimpleEntry<>(0.75, 1.0);
    List<Long> sealedSegments = Collections.singletonList(1L);
    VersionedMetadata<EpochTransitionRecord> response = streamStorePartialMock.submitScale(SCOPE, stream1, sealedSegments, Arrays.asList(segment1, segment2), start + 20, null, null, executor).get();
    VersionedMetadata<State> state = streamStorePartialMock.getVersionedState(SCOPE, stream1, null, executor).join();
    state = streamStorePartialMock.updateVersionedState(SCOPE, stream1, State.SCALING, state, null, executor).join();
    streamStorePartialMock.startScale(SCOPE, stream1, false, response, state, null, executor).join();
    streamStorePartialMock.scaleCreateNewEpochs(SCOPE, stream1, response, null, executor).get();
    streamStorePartialMock.scaleSegmentsSealed(SCOPE, stream1, sealedSegments.stream().collect(Collectors.toMap(x -> x, x -> 0L)), response, null, executor).get();
    streamStorePartialMock.completeScale(SCOPE, stream1, response, null, executor).join();
    streamStorePartialMock.updateVersionedState(SCOPE, stream1, State.ACTIVE, state, null, executor).get();
    // stream2
    streamStorePartialMock.createStream(SCOPE, stream2, configuration1, System.currentTimeMillis(), null, executor).get();
    streamStorePartialMock.setState(SCOPE, stream1, State.ACTIVE, null, executor).get();
    streamStorePartialMock.createStream(SCOPE, stream3, configuration1, System.currentTimeMillis(), null, executor).get();
    streamStorePartialMock.setState(SCOPE, stream1, State.ACTIVE, null, executor).get();
}
Also used : DeleteScopeTask(io.pravega.controller.server.eventProcessor.requesthandlers.DeleteScopeTask) UpdateStreamEvent(io.pravega.shared.controller.event.UpdateStreamEvent) Arrays(java.util.Arrays) StreamCut(io.pravega.client.stream.StreamCut) EventStreamWriter(io.pravega.client.stream.EventStreamWriter) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) Cleanup(lombok.Cleanup) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) AbstractStreamMetadataStore(io.pravega.controller.store.stream.AbstractStreamMetadataStore) StoreException(io.pravega.controller.store.stream.StoreException) AutoScaleTask(io.pravega.controller.server.eventProcessor.requesthandlers.AutoScaleTask) TaskMetadataStore(io.pravega.controller.store.task.TaskMetadataStore) Duration(java.time.Duration) Map(java.util.Map) Mockito.doAnswer(org.mockito.Mockito.doAnswer) RGStreamCutRecord(io.pravega.shared.controller.event.RGStreamCutRecord) LockFailedException(io.pravega.controller.store.task.LockFailedException) Mockito.doReturn(org.mockito.Mockito.doReturn) ReaderGroupConfig(io.pravega.client.stream.ReaderGroupConfig) ControllerEventStreamWriterMock(io.pravega.controller.mocks.ControllerEventStreamWriterMock) StreamTruncationRecord(io.pravega.controller.store.stream.records.StreamTruncationRecord) StreamMetadataStoreTestHelper(io.pravega.controller.store.stream.StreamMetadataStoreTestHelper) DeleteStreamEvent(io.pravega.shared.controller.event.DeleteStreamEvent) RequestTracker(io.pravega.common.tracing.RequestTracker) ActiveTxnRecord(io.pravega.controller.store.stream.records.ActiveTxnRecord) ControllerEvent(io.pravega.shared.controller.event.ControllerEvent) KVTableMetadataStore(io.pravega.controller.store.kvtable.KVTableMetadataStore) Assert.assertFalse(org.junit.Assert.assertFalse) CreateReaderGroupTask(io.pravega.controller.server.eventProcessor.requesthandlers.CreateReaderGroupTask) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) EventStreamWriterMock(io.pravega.controller.mocks.EventStreamWriterMock) Futures(io.pravega.common.concurrent.Futures) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) Mockito.mock(org.mockito.Mockito.mock) CuratorFrameworkFactory(org.apache.curator.framework.CuratorFrameworkFactory) Mockito.doCallRealMethod(org.mockito.Mockito.doCallRealMethod) StreamMetrics(io.pravega.controller.metrics.StreamMetrics) StreamStoreFactory(io.pravega.controller.store.stream.StreamStoreFactory) TransactionMetrics(io.pravega.controller.metrics.TransactionMetrics) NameUtils.computeSegmentId(io.pravega.shared.NameUtils.computeSegmentId) ConnectionFactory(io.pravega.client.connection.impl.ConnectionFactory) Mock(org.mockito.Mock) RetentionPolicy(io.pravega.client.stream.RetentionPolicy) Exceptions(io.pravega.common.Exceptions) TruncateStreamEvent(io.pravega.shared.controller.event.TruncateStreamEvent) Mockito.spy(org.mockito.Mockito.spy) Supplier(java.util.function.Supplier) UpdateSubscriberStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateSubscriberStatus) ArrayList(java.util.ArrayList) Lists(com.google.common.collect.Lists) TestingServerStarter(io.pravega.test.common.TestingServerStarter) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) TestingServer(org.apache.curator.test.TestingServer) EventHelper(io.pravega.controller.task.EventHelper) UpdateReaderGroupTask(io.pravega.controller.server.eventProcessor.requesthandlers.UpdateReaderGroupTask) CreateReaderGroupEvent(io.pravega.shared.controller.event.CreateReaderGroupEvent) Before(org.junit.Before) SegmentHelperMock(io.pravega.controller.mocks.SegmentHelperMock) EventHelperMock(io.pravega.controller.mocks.EventHelperMock) Assert.assertTrue(org.junit.Assert.assertTrue) CreateStreamResponse(io.pravega.controller.store.stream.CreateStreamResponse) Test(org.junit.Test) TableMetadataTasks(io.pravega.controller.task.KeyValueTable.TableMetadataTasks) Assert.assertNotEquals(org.junit.Assert.assertNotEquals) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) StreamConfigurationRecord(io.pravega.controller.store.stream.records.StreamConfigurationRecord) TaskStoreFactory(io.pravega.controller.store.task.TaskStoreFactory) Assert.assertNull(org.junit.Assert.assertNull) DeleteStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.DeleteStreamTask) StreamRequestHandler(io.pravega.controller.server.eventProcessor.requesthandlers.StreamRequestHandler) DeleteReaderGroupStatus(io.pravega.controller.stream.api.grpc.v1.Controller.DeleteReaderGroupStatus) Mockito.reset(org.mockito.Mockito.reset) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Assert.assertEquals(org.junit.Assert.assertEquals) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) CommitEvent(io.pravega.shared.controller.event.CommitEvent) AssertExtensions(io.pravega.test.common.AssertExtensions) DeleteReaderGroupEvent(io.pravega.shared.controller.event.DeleteReaderGroupEvent) TimeoutException(java.util.concurrent.TimeoutException) SealStreamEvent(io.pravega.shared.controller.event.SealStreamEvent) VersionedMetadata(io.pravega.controller.store.VersionedMetadata) Stream(io.pravega.client.stream.Stream) After(org.junit.After) SubscribersResponse(io.pravega.controller.stream.api.grpc.v1.Controller.SubscribersResponse) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) TaskExceptions(io.pravega.controller.server.eventProcessor.requesthandlers.TaskExceptions) EpochTransitionRecord(io.pravega.controller.store.stream.records.EpochTransitionRecord) ImmutableSet(com.google.common.collect.ImmutableSet) SealStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.SealStreamTask) ImmutableMap(com.google.common.collect.ImmutableMap) AssertExtensions.assertFutureThrows(io.pravega.test.common.AssertExtensions.assertFutureThrows) DeleteScopeEvent(io.pravega.shared.controller.event.DeleteScopeEvent) CompletionException(java.util.concurrent.CompletionException) ScaleStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleResponse.ScaleStreamStatus) UUID(java.util.UUID) ScaleOperationTask(io.pravega.controller.server.eventProcessor.requesthandlers.ScaleOperationTask) LinkedBlockingQueue(java.util.concurrent.LinkedBlockingQueue) Collectors(java.util.stream.Collectors) AbstractClientFactoryImpl(io.pravega.client.stream.impl.AbstractClientFactoryImpl) List(java.util.List) CuratorFramework(org.apache.curator.framework.CuratorFramework) Config(io.pravega.controller.util.Config) UpdateStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.UpdateStreamTask) TxnStatus(io.pravega.controller.store.stream.TxnStatus) VersionedTransactionData(io.pravega.controller.store.stream.VersionedTransactionData) Optional(java.util.Optional) DeleteScopeTask(io.pravega.controller.server.eventProcessor.requesthandlers.DeleteScopeTask) TruncateStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.TruncateStreamTask) NotImplementedException(org.apache.commons.lang3.NotImplementedException) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) OperationContext(io.pravega.controller.store.stream.OperationContext) Segment(io.pravega.client.segment.impl.Segment) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) Getter(lombok.Getter) SegmentHelper(io.pravega.controller.server.SegmentHelper) ModelHelper(io.pravega.client.control.impl.ModelHelper) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) BucketStore(io.pravega.controller.store.stream.BucketStore) AbortEvent(io.pravega.shared.controller.event.AbortEvent) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) StreamCutImpl(io.pravega.client.stream.impl.StreamCutImpl) LinkedList(java.util.LinkedList) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) ScaleResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ScaleResponse) EventWriterConfig(io.pravega.client.stream.EventWriterConfig) ControllerService(io.pravega.controller.server.ControllerService) NameUtils(io.pravega.shared.NameUtils) Assert.assertNotNull(org.junit.Assert.assertNotNull) StreamCutRecord(io.pravega.controller.store.stream.records.StreamCutRecord) AbstractMap(java.util.AbstractMap) EpochRecord(io.pravega.controller.store.stream.records.EpochRecord) UpdateStreamStatus(io.pravega.controller.stream.api.grpc.v1.Controller.UpdateStreamStatus) Data(lombok.Data) State(io.pravega.controller.store.stream.State) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) UpdateReaderGroupEvent(io.pravega.shared.controller.event.UpdateReaderGroupEvent) DeleteReaderGroupTask(io.pravega.controller.server.eventProcessor.requesthandlers.DeleteReaderGroupTask) ReaderGroupConfigResponse(io.pravega.controller.stream.api.grpc.v1.Controller.ReaderGroupConfigResponse) ScaleOpEvent(io.pravega.shared.controller.event.ScaleOpEvent) Collections(java.util.Collections) ClientConfig(io.pravega.client.ClientConfig) ExponentialBackoffRetry(org.apache.curator.retry.ExponentialBackoffRetry) CreateReaderGroupTask(io.pravega.controller.server.eventProcessor.requesthandlers.CreateReaderGroupTask) AbstractStreamMetadataStore(io.pravega.controller.store.stream.AbstractStreamMetadataStore) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) ControllerService(io.pravega.controller.server.ControllerService) AbstractMap(java.util.AbstractMap) AutoScaleTask(io.pravega.controller.server.eventProcessor.requesthandlers.AutoScaleTask) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) TableMetadataTasks(io.pravega.controller.task.KeyValueTable.TableMetadataTasks) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) SealStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.SealStreamTask) TestingServerStarter(io.pravega.test.common.TestingServerStarter) EpochTransitionRecord(io.pravega.controller.store.stream.records.EpochTransitionRecord) TaskMetadataStore(io.pravega.controller.store.task.TaskMetadataStore) UpdateStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.UpdateStreamTask) DeleteReaderGroupTask(io.pravega.controller.server.eventProcessor.requesthandlers.DeleteReaderGroupTask) SegmentHelper(io.pravega.controller.server.SegmentHelper) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) ScaleOperationTask(io.pravega.controller.server.eventProcessor.requesthandlers.ScaleOperationTask) StreamRequestHandler(io.pravega.controller.server.eventProcessor.requesthandlers.StreamRequestHandler) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) State(io.pravega.controller.store.stream.State) DeleteStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.DeleteStreamTask) UpdateReaderGroupTask(io.pravega.controller.server.eventProcessor.requesthandlers.UpdateReaderGroupTask) AtomicLong(java.util.concurrent.atomic.AtomicLong) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) EventHelper(io.pravega.controller.task.EventHelper) TruncateStreamTask(io.pravega.controller.server.eventProcessor.requesthandlers.TruncateStreamTask) Before(org.junit.Before)

Example 82 with Mock

use of org.mockito.Mock in project pravega by pravega.

the class IntermittentCnxnFailureTest method createStreamTest.

@Test(timeout = 30000)
public void createStreamTest() throws Exception {
    final ScalingPolicy policy1 = ScalingPolicy.fixed(2);
    final StreamConfiguration configuration1 = StreamConfiguration.builder().scalingPolicy(policy1).build();
    // start stream creation in background/asynchronously.
    // the connection to server will fail and should be retried
    controllerService.createStream(SCOPE, stream1, configuration1, System.currentTimeMillis(), 0L);
    // we should get illegalStateException
    try {
        Retry.withExpBackoff(10, 10, 4).retryingOn(StoreException.DataNotFoundException.class).throwingOn(IllegalStateException.class).run(() -> {
            Futures.getAndHandleExceptions(streamStore.getConfiguration(SCOPE, stream1, null, executor), CompletionException::new);
            return null;
        });
    } catch (CompletionException ex) {
        Assert.assertEquals(Exceptions.unwrap(ex).getMessage(), "stream state unknown");
        assertEquals(Exceptions.unwrap(ex).getClass(), IllegalStateException.class);
    }
    // Mock createSegment to return success.
    doReturn(CompletableFuture.completedFuture(true)).when(segmentHelperMock).createSegment(anyString(), anyString(), anyInt(), any(), any(), anyLong(), anyLong());
    AtomicBoolean result = new AtomicBoolean(false);
    Retry.withExpBackoff(10, 10, 4).retryingOn(IllegalStateException.class).throwingOn(RuntimeException.class).run(() -> {
        Futures.getAndHandleExceptions(streamStore.getConfiguration(SCOPE, stream1, null, executor).thenAccept(configuration -> result.set(configuration.equals(configuration1))), CompletionException::new);
        return null;
    });
    assertTrue(result.get());
}
Also used : Retry(io.pravega.common.util.Retry) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) StoreException(io.pravega.controller.store.stream.StoreException) MetricsNames(io.pravega.shared.MetricsNames) TaskMetadataStore(io.pravega.controller.store.task.TaskMetadataStore) Duration(java.time.Duration) After(org.junit.After) Controller(io.pravega.controller.stream.api.grpc.v1.Controller) ClassRule(org.junit.ClassRule) PravegaZkCuratorResource(io.pravega.controller.PravegaZkCuratorResource) CompletionException(java.util.concurrent.CompletionException) RequestTracker(io.pravega.common.tracing.RequestTracker) KVTableMetadataStore(io.pravega.controller.store.kvtable.KVTableMetadataStore) MetricsProvider(io.pravega.shared.metrics.MetricsProvider) Config(io.pravega.controller.util.Config) MetricRegistryUtils(io.pravega.shared.metrics.MetricRegistryUtils) StreamMetadataStore(io.pravega.controller.store.stream.StreamMetadataStore) Futures(io.pravega.common.concurrent.Futures) GrpcAuthHelper(io.pravega.controller.server.security.auth.GrpcAuthHelper) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) StreamMetrics(io.pravega.controller.metrics.StreamMetrics) StreamStoreFactory(io.pravega.controller.store.stream.StreamStoreFactory) ArgumentMatchers.anyLong(org.mockito.ArgumentMatchers.anyLong) SegmentHelper(io.pravega.controller.server.SegmentHelper) Mock(org.mockito.Mock) Exceptions(io.pravega.common.Exceptions) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ConnectionPoolImpl(io.pravega.client.connection.impl.ConnectionPoolImpl) BucketStore(io.pravega.controller.store.stream.BucketStore) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) HostMonitorConfigImpl(io.pravega.controller.store.host.impl.HostMonitorConfigImpl) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) SocketConnectionFactoryImpl(io.pravega.client.connection.impl.SocketConnectionFactoryImpl) Before(org.junit.Before) ControllerService(io.pravega.controller.server.ControllerService) ConnectionPool(io.pravega.client.connection.impl.ConnectionPool) SerializedClassRunner(io.pravega.test.common.SerializedClassRunner) Assert.assertTrue(org.junit.Assert.assertTrue) StatsProvider(io.pravega.shared.metrics.StatsProvider) Test(org.junit.Test) TableMetadataTasks(io.pravega.controller.task.KeyValueTable.TableMetadataTasks) HostStoreFactory(io.pravega.controller.store.host.HostStoreFactory) ExecutionException(java.util.concurrent.ExecutionException) Mockito(org.mockito.Mockito) TaskStoreFactory(io.pravega.controller.store.task.TaskStoreFactory) HostControllerStore(io.pravega.controller.store.host.HostControllerStore) MetricsConfig(io.pravega.shared.metrics.MetricsConfig) ExecutorServiceHelpers(io.pravega.common.concurrent.ExecutorServiceHelpers) Assert(org.junit.Assert) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) Assert.assertEquals(org.junit.Assert.assertEquals) ClientConfig(io.pravega.client.ClientConfig) ArgumentMatchers.anyString(org.mockito.ArgumentMatchers.anyString) ScalingPolicy(io.pravega.client.stream.ScalingPolicy) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletionException(java.util.concurrent.CompletionException) StreamConfiguration(io.pravega.client.stream.StreamConfiguration) StoreException(io.pravega.controller.store.stream.StoreException) Test(org.junit.Test)

Example 83 with Mock

use of org.mockito.Mock in project kie-wb-common by kiegroup.

the class CommandUtilsTest method testUpdateParentInformation_WithMultipleColumns.

@Test
@SuppressWarnings("unchecked")
public void testUpdateParentInformation_WithMultipleColumns() {
    setupUiModel(Pair.newPair(new ExpressionEditorColumn(gridLayer, new BaseHeaderMetaData("column"), ExpressionEditorColumn.DEFAULT_WIDTH, gridWidget), (rowIndex) -> {
        final BaseExpressionGrid grid = mock(BaseExpressionGrid.class);
        final GridCellTuple gct = new GridCellTuple(rowIndex, 0, mock(GridWidget.class));
        when(grid.getParentInformation()).thenReturn(gct);
        return new ExpressionCellValue(Optional.of(grid));
    }), Pair.newPair(new RowNumberColumn(), (rowIndex) -> new BaseGridCellValue<>(rowIndex + 1)));
    assertParentInformationValues(0);
    gridData.moveColumnTo(0, gridData.getColumns().get(1));
    CommandUtils.updateParentInformation(gridData);
    assertParentInformationValues(1);
}
Also used : IntStream(java.util.stream.IntStream) CellEditorControlsView(org.kie.workbench.common.dmn.client.widgets.grid.controls.container.CellEditorControlsView) DMNGridData(org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridData) Arrays(java.util.Arrays) BaseGrid(org.kie.workbench.common.dmn.client.widgets.grid.BaseGrid) BaseGridRow(org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridRow) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) BaseExpressionGrid(org.kie.workbench.common.dmn.client.widgets.grid.BaseExpressionGrid) DMNGridLayer(org.kie.workbench.common.dmn.client.widgets.layer.DMNGridLayer) GridColumn(org.uberfire.ext.wires.core.grids.client.model.GridColumn) GridRenderer(org.uberfire.ext.wires.core.grids.client.widget.grid.renderers.grids.GridRenderer) Function(java.util.function.Function) BaseHeaderMetaData(org.uberfire.ext.wires.core.grids.client.model.impl.BaseHeaderMetaData) ArrayList(java.util.ArrayList) Id(org.kie.workbench.common.dmn.api.property.dmn.Id) RefreshFormPropertiesEvent(org.kie.workbench.common.stunner.forms.client.event.RefreshFormPropertiesEvent) LienzoMockitoTestRunner(com.ait.lienzo.test.LienzoMockitoTestRunner) RowNumberColumn(org.uberfire.ext.wires.core.grids.client.widget.grid.columns.RowNumberColumn) GridCellTuple(org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple) Assertions(org.assertj.core.api.Assertions) Assert.fail(org.junit.Assert.fail) SessionManager(org.kie.workbench.common.stunner.core.client.api.SessionManager) Pair(org.uberfire.commons.data.Pair) Mockito.doReturn(org.mockito.Mockito.doReturn) Before(org.junit.Before) TranslationService(org.jboss.errai.ui.client.local.spi.TranslationService) GridCell(org.uberfire.ext.wires.core.grids.client.model.GridCell) DecisionRule(org.kie.workbench.common.dmn.api.definition.model.DecisionRule) Test(org.junit.Test) AbstractCanvasHandler(org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler) Mockito.when(org.mockito.Mockito.when) GridData(org.uberfire.ext.wires.core.grids.client.model.GridData) SessionCommandManager(org.kie.workbench.common.stunner.core.client.command.SessionCommandManager) GridWidget(org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget) List(java.util.List) DomainObjectSelectionEvent(org.kie.workbench.common.stunner.core.client.canvas.event.selection.DomainObjectSelectionEvent) BaseGridCellValue(org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue) DefaultCanvasCommandFactory(org.kie.workbench.common.dmn.client.commands.factory.DefaultCanvasCommandFactory) GridCellValue(org.uberfire.ext.wires.core.grids.client.model.GridCellValue) ExpressionCellValue(org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionCellValue) Optional(java.util.Optional) ExpressionEditorColumn(org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionEditorColumn) EventSourceMock(org.uberfire.mocks.EventSourceMock) Expression(org.kie.workbench.common.dmn.api.definition.model.Expression) Collections(java.util.Collections) Assert.assertEquals(org.junit.Assert.assertEquals) Mockito.mock(org.mockito.Mockito.mock) RowNumberColumn(org.uberfire.ext.wires.core.grids.client.widget.grid.columns.RowNumberColumn) ExpressionEditorColumn(org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionEditorColumn) GridCellTuple(org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple) BaseExpressionGrid(org.kie.workbench.common.dmn.client.widgets.grid.BaseExpressionGrid) BaseHeaderMetaData(org.uberfire.ext.wires.core.grids.client.model.impl.BaseHeaderMetaData) ExpressionCellValue(org.kie.workbench.common.dmn.client.editors.expressions.types.context.ExpressionCellValue) BaseGridCellValue(org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue) Test(org.junit.Test)

Example 84 with Mock

use of org.mockito.Mock in project kie-wb-common by kiegroup.

the class DataTypeConstraintTest method testOpenModal.

@Test
public void testOpenModal() {
    final DataTypeListItem listItem = mock(DataTypeListItem.class);
    final String constraint = "1,2,3";
    final String type = "string";
    final BiConsumer<String, ConstraintType> onShowConsumer = (s, c) -> {
    /* Nothing. */
    };
    doReturn(listItem).when(dataTypeConstraint).getListItem();
    doReturn(constraint).when(dataTypeConstraint).getValue();
    doReturn(onShowConsumer).when(dataTypeConstraint).getOnShowConsumer();
    when(listItem.getType()).thenReturn(type);
    dataTypeConstraint.openModal();
    constraintModal.load(type, constraint, ENUMERATION);
    constraintModal.show(onShowConsumer);
}
Also used : DataTypeListItem(org.kie.workbench.common.dmn.client.editors.types.listview.DataTypeListItem) GwtMockitoTestRunner(com.google.gwtmockito.GwtMockitoTestRunner) ENUMERATION(org.kie.workbench.common.dmn.api.definition.model.ConstraintType.ENUMERATION) Mock(org.mockito.Mock) Assert.assertNotNull(org.junit.Assert.assertNotNull) ManagedInstance(org.jboss.errai.ioc.client.api.ManagedInstance) DataType(org.kie.workbench.common.dmn.client.editors.types.common.DataType) RunWith(org.junit.runner.RunWith) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.spy(org.mockito.Mockito.spy) DataTypeListItem(org.kie.workbench.common.dmn.client.editors.types.listview.DataTypeListItem) Mockito.verify(org.mockito.Mockito.verify) Assert.assertSame(org.junit.Assert.assertSame) Assert.assertNull(org.junit.Assert.assertNull) HTMLElement(elemental2.dom.HTMLElement) Assert.assertFalse(org.junit.Assert.assertFalse) BiConsumer(java.util.function.BiConsumer) ConstraintType(org.kie.workbench.common.dmn.api.definition.model.ConstraintType) Mockito.doReturn(org.mockito.Mockito.doReturn) Assert.assertEquals(org.junit.Assert.assertEquals) Before(org.junit.Before) Mockito.mock(org.mockito.Mockito.mock) ConstraintType(org.kie.workbench.common.dmn.api.definition.model.ConstraintType) Test(org.junit.Test)

Example 85 with Mock

use of org.mockito.Mock in project kie-wb-common by kiegroup.

the class TimePickerTest method testOnDateChanged.

@Test
public void testOnDateChanged() {
    final Consumer<Moment> consumer = mock(Consumer.class);
    picker.setOnDateChanged(consumer);
    final String expected = "14:55:01";
    final Moment moment = mock(Moment.class);
    when(moment.format("HH:mm:ss")).thenReturn(expected);
    picker.onDateChanged(moment);
    assertEquals(expected, input.value);
    verify(consumer).accept(argThat(argument -> Objects.equals(argument, moment)));
}
Also used : GwtMockitoTestRunner(com.google.gwtmockito.GwtMockitoTestRunner) HTMLInputElement(elemental2.dom.HTMLInputElement) ArgumentMatchers.argThat(org.mockito.ArgumentMatchers.argThat) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Mockito.spy(org.mockito.Mockito.spy) Captor(org.mockito.Captor) Moment(org.uberfire.client.views.pfly.widgets.Moment) Mockito.verify(org.mockito.Mockito.verify) Objects(java.util.Objects) Consumer(java.util.function.Consumer) ArgumentCaptor(org.mockito.ArgumentCaptor) Assert.assertFalse(org.junit.Assert.assertFalse) Mockito.doReturn(org.mockito.Mockito.doReturn) Assert.assertEquals(org.junit.Assert.assertEquals) Before(org.junit.Before) Mockito.mock(org.mockito.Mockito.mock) Moment(org.uberfire.client.views.pfly.widgets.Moment) Test(org.junit.Test)

Aggregations

Mock (org.mockito.Mock)135 Mockito.mock (org.mockito.Mockito.mock)109 Test (org.junit.Test)104 Before (org.junit.Before)96 Mockito.verify (org.mockito.Mockito.verify)89 Mockito.when (org.mockito.Mockito.when)82 List (java.util.List)81 RunWith (org.junit.runner.RunWith)76 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)65 Collections (java.util.Collections)56 ArrayList (java.util.ArrayList)55 ArgumentCaptor (org.mockito.ArgumentCaptor)52 Mockito.spy (org.mockito.Mockito.spy)48 Arrays (java.util.Arrays)44 Assert.assertEquals (org.junit.Assert.assertEquals)41 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)41 Mockito.doReturn (org.mockito.Mockito.doReturn)41 Map (java.util.Map)40 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)38 Mockito.never (org.mockito.Mockito.never)37