Search in sources :

Example 91 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project sonarqube by SonarSource.

the class SvnBlameCommandTest method testParsingOfOutputWithMergeHistory.

@Test
public void testParsingOfOutputWithMergeHistory() throws Exception {
    File repoDir = unzip("repo-svn-with-merge.zip");
    String scmUrl = "file:///" + unixPath(new File(repoDir, "repo-svn"));
    File baseDir = new File(checkout(scmUrl), "dummy-svn/trunk");
    when(fs.baseDir()).thenReturn(baseDir);
    DefaultInputFile inputFile = new TestInputFileBuilder("foo", DUMMY_JAVA).setLines(27).setModuleBaseDir(baseDir.toPath()).build();
    BlameOutput blameResult = mock(BlameOutput.class);
    when(input.filesToBlame()).thenReturn(singletonList(inputFile));
    newSvnBlameCommand().blame(input, blameResult);
    ArgumentCaptor<List> captor = ArgumentCaptor.forClass(List.class);
    verify(blameResult).blameResult(eq(inputFile), captor.capture());
    List<BlameLine> result = captor.getValue();
    assertThat(result).hasSize(27);
    Date commitDate = new Date(1342691097393L);
    Date revision6Date = new Date(1415262184300L);
    BlameLine[] expected = IntStream.rangeClosed(1, 27).mapToObj(i -> {
        if (i == 2 || i == 24) {
            return new BlameLine().date(revision6Date).revision("6").author("henryju");
        } else {
            return new BlameLine().date(commitDate).revision("2").author("dgageot");
        }
    }).toArray(BlameLine[]::new);
    assertThat(result).containsExactly(expected);
}
Also used : TestInputFileBuilder(org.sonar.api.batch.fs.internal.TestInputFileBuilder) BlameLine(org.sonar.api.batch.scm.BlameLine) Arrays(java.util.Arrays) Enumeration(java.util.Enumeration) Date(java.util.Date) SVNStatus(org.tmatesoft.svn.core.wc.SVNStatus) URISyntaxException(java.net.URISyntaxException) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BlameInput(org.sonar.api.batch.scm.BlameCommand.BlameInput) SVNClientManager(org.tmatesoft.svn.core.wc.SVNClientManager) Collections.singletonList(java.util.Collections.singletonList) Mockito.verifyNoInteractions(org.mockito.Mockito.verifyNoInteractions) Mockito.doThrow(org.mockito.Mockito.doThrow) Mockito.anyBoolean(org.mockito.Mockito.anyBoolean) ZipFile(java.util.zip.ZipFile) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) Parameterized(org.junit.runners.Parameterized) StandardOpenOption(java.nio.file.StandardOpenOption) FileSystem(org.sonar.api.batch.fs.FileSystem) TestInputFileBuilder(org.sonar.api.batch.fs.internal.TestInputFileBuilder) BlameLine(org.sonar.api.batch.scm.BlameLine) List(java.util.List) SVNStatusClient(org.tmatesoft.svn.core.wc.SVNStatusClient) Mockito.any(org.mockito.Mockito.any) LoggerLevel(org.sonar.api.utils.log.LoggerLevel) Mockito.eq(org.mockito.Mockito.eq) Mockito.mock(org.mockito.Mockito.mock) IntStream(java.util.stream.IntStream) InputFile(org.sonar.api.batch.fs.InputFile) SVNWCUtil(org.tmatesoft.svn.core.wc.SVNWCUtil) DefaultInputFile(org.sonar.api.batch.fs.internal.DefaultInputFile) SVNDepth(org.tmatesoft.svn.core.SVNDepth) Assert.assertThrows(org.junit.Assert.assertThrows) RunWith(org.junit.runner.RunWith) Parameters(org.junit.runners.Parameterized.Parameters) SvnCodec(org.tmatesoft.svn.core.internal.wc2.compat.SvnCodec) SVNLogClient(org.tmatesoft.svn.core.wc.SVNLogClient) ArgumentCaptor(org.mockito.ArgumentCaptor) Before(org.junit.Before) ISVNOptions(org.tmatesoft.svn.core.wc.ISVNOptions) Files(java.nio.file.Files) SVNStatusType(org.tmatesoft.svn.core.wc.SVNStatusType) SvnCheckout(org.tmatesoft.svn.core.wc2.SvnCheckout) IOException(java.io.IOException) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) File(java.io.File) SVNAuthenticationException(org.tmatesoft.svn.core.SVNAuthenticationException) Mockito.verify(org.mockito.Mockito.verify) ISVNAuthenticationManager(org.tmatesoft.svn.core.auth.ISVNAuthenticationManager) Rule(org.junit.Rule) LogTester(org.sonar.api.utils.log.LogTester) SVNRevision(org.tmatesoft.svn.core.wc.SVNRevision) Paths(java.nio.file.Paths) SVNURL(org.tmatesoft.svn.core.SVNURL) SVNUpdateClient(org.tmatesoft.svn.core.wc.SVNUpdateClient) BlameOutput(org.sonar.api.batch.scm.BlameCommand.BlameOutput) SvnTarget(org.tmatesoft.svn.core.wc2.SvnTarget) TemporaryFolder(org.junit.rules.TemporaryFolder) DefaultInputFile(org.sonar.api.batch.fs.internal.DefaultInputFile) Collections.singletonList(java.util.Collections.singletonList) List(java.util.List) BlameOutput(org.sonar.api.batch.scm.BlameCommand.BlameOutput) ZipFile(java.util.zip.ZipFile) InputFile(org.sonar.api.batch.fs.InputFile) DefaultInputFile(org.sonar.api.batch.fs.internal.DefaultInputFile) File(java.io.File) Date(java.util.Date) Test(org.junit.Test)

Example 92 with ArgumentCaptor

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

the class DecisionTableGridTest method testSetDisplayNameMultipleOutputClauseWithNonEmptyValue.

@Test
@SuppressWarnings("unchecked")
public void testSetDisplayNameMultipleOutputClauseWithNonEmptyValue() {
    setupGrid(makeHasNameForDecision(), 0);
    final String defaultName = "default-name";
    final Consumer<ValueAndDataTypeHeaderMetaData> test = (md) -> md.setValue(new Name(NAME_NEW));
    addOutputClause(3);
    final ArgumentCaptor<CompositeCommand> compositeCommandCaptor1 = ArgumentCaptor.forClass(CompositeCommand.class);
    hasExpression.getName().setValue(defaultName);
    expression.get().getOutput().get(0).setName(defaultName);
    assertHeaderMetaDataTest(0, 2, test, compositeCommandCaptor1, SetHasValueCommand.class, UpdateElementPropertyCommand.class);
    compositeCommandCaptor1.getValue().execute(canvasHandler);
    assertThat(hasExpression.getName().getValue()).isEqualTo(NAME_NEW);
    assertThat(expression.get().getOutput().get(0).getName()).isEqualTo(defaultName);
    final ArgumentCaptor<CompositeCommand> compositeCommandCaptor2 = ArgumentCaptor.forClass(CompositeCommand.class);
    hasExpression.getName().setValue(defaultName);
    expression.get().getOutput().get(0).setName(defaultName);
    assertHeaderMetaDataTest(1, 2, test, compositeCommandCaptor2, SetHasValueCommand.class);
    compositeCommandCaptor2.getValue().execute(canvasHandler);
    assertThat(hasExpression.getName().getValue()).isEqualTo(defaultName);
    assertThat(expression.get().getOutput().get(0).getName()).isEqualTo(NAME_NEW);
    final ArgumentCaptor<CompositeCommand> compositeCommandCaptor3 = ArgumentCaptor.forClass(CompositeCommand.class);
    hasExpression.getName().setValue(defaultName);
    expression.get().getOutput().get(1).setName(defaultName);
    assertHeaderMetaDataTest(0, 3, test, compositeCommandCaptor3, SetHasValueCommand.class, UpdateElementPropertyCommand.class);
    compositeCommandCaptor3.getValue().execute(canvasHandler);
    assertThat(hasExpression.getName().getValue()).isEqualTo(NAME_NEW);
    assertThat(expression.get().getOutput().get(1).getName()).isEqualTo(defaultName);
    final ArgumentCaptor<CompositeCommand> compositeCommandCaptor4 = ArgumentCaptor.forClass(CompositeCommand.class);
    hasExpression.getName().setValue(defaultName);
    expression.get().getOutput().get(1).setName(defaultName);
    assertHeaderMetaDataTest(1, 3, test, compositeCommandCaptor4, SetHasValueCommand.class);
    compositeCommandCaptor4.getValue().execute(canvasHandler);
    assertThat(hasExpression.getName().getValue()).isEqualTo(defaultName);
    assertThat(expression.get().getOutput().get(0).getName()).isEqualTo(NAME_NEW);
}
Also used : TextAreaSingletonDOMElementFactory(org.kie.workbench.common.dmn.client.widgets.grid.columns.factory.TextAreaSingletonDOMElementFactory) UpdateElementPropertyCommand(org.kie.workbench.common.stunner.core.client.canvas.command.UpdateElementPropertyCommand) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ManagedInstance(org.jboss.errai.ioc.client.api.ManagedInstance) ListSelectorView(org.kie.workbench.common.dmn.client.widgets.grid.controls.list.ListSelectorView) DMNGridLayer(org.kie.workbench.common.dmn.client.widgets.layer.DMNGridLayer) GridColumn(org.uberfire.ext.wires.core.grids.client.model.GridColumn) SetTypeRefCommand(org.kie.workbench.common.dmn.client.commands.general.SetTypeRefCommand) InformationItemPrimary(org.kie.workbench.common.dmn.api.definition.model.InformationItemPrimary) GridLayerRedrawManager(org.uberfire.ext.wires.core.grids.client.widget.layer.impl.GridLayerRedrawManager) GridFactoryCommandUtils(org.kie.workbench.common.dmn.client.editors.expressions.types.GridFactoryCommandUtils) DeleteDecisionRuleCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.DeleteDecisionRuleCommand) Mockito.doAnswer(org.mockito.Mockito.doAnswer) DeleteOutputClauseCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.DeleteOutputClauseCommand) Diagram(org.kie.workbench.common.stunner.core.diagram.Diagram) SetCellValueCommand(org.kie.workbench.common.dmn.client.commands.general.SetCellValueCommand) Index(org.kie.workbench.common.stunner.core.graph.processing.index.Index) NOPDomainObject(org.kie.workbench.common.dmn.api.definition.NOPDomainObject) HitPolicy(org.kie.workbench.common.dmn.api.definition.model.HitPolicy) OutputClause(org.kie.workbench.common.dmn.api.definition.model.OutputClause) DeleteCellValueCommand(org.kie.workbench.common.dmn.client.commands.general.DeleteCellValueCommand) HasName(org.kie.workbench.common.dmn.api.definition.HasName) QName(org.kie.workbench.common.dmn.api.property.dmn.QName) AddInputClauseCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.AddInputClauseCommand) SetHitPolicyCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.SetHitPolicyCommand) GridBodyCellEditContext(org.uberfire.ext.wires.core.grids.client.widget.context.GridBodyCellEditContext) DMNDiagramUtils(org.kie.workbench.common.dmn.api.graph.DMNDiagramUtils) GraphCommandExecutionContext(org.kie.workbench.common.stunner.core.graph.command.GraphCommandExecutionContext) ValueAndDataTypePopoverView(org.kie.workbench.common.dmn.client.editors.types.ValueAndDataTypePopoverView) Mockito.mock(org.mockito.Mockito.mock) SetHasValueCommand(org.kie.workbench.common.dmn.client.commands.general.SetHasValueCommand) ValueAndDataTypeHeaderMetaData(org.kie.workbench.common.dmn.client.widgets.grid.columns.ValueAndDataTypeHeaderMetaData) Mock(org.mockito.Mock) HitPolicyPopoverView(org.kie.workbench.common.dmn.client.editors.expressions.types.dtable.hitpolicy.HitPolicyPopoverView) RunWith(org.junit.runner.RunWith) AbsolutePanel(com.google.gwt.user.client.ui.AbsolutePanel) Mockito.spy(org.mockito.Mockito.spy) DMNSession(org.kie.workbench.common.dmn.client.session.DMNSession) Name(org.kie.workbench.common.dmn.api.property.dmn.Name) DMNGridColumn(org.kie.workbench.common.dmn.client.widgets.grid.model.DMNGridColumn) GridCellTuple(org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellTuple) Context(org.kie.workbench.common.dmn.api.definition.model.Context) Command(org.uberfire.mvp.Command) Before(org.junit.Before) TranslationService(org.jboss.errai.ui.client.local.spi.TranslationService) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) GridData(org.uberfire.ext.wires.core.grids.client.model.GridData) SessionCommandManager(org.kie.workbench.common.stunner.core.client.command.SessionCommandManager) DeleteInputClauseCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.DeleteInputClauseCommand) Graph(org.kie.workbench.common.stunner.core.graph.Graph) Mockito.never(org.mockito.Mockito.never) DomainObjectSelectionEvent(org.kie.workbench.common.stunner.core.client.canvas.event.selection.DomainObjectSelectionEvent) Assert.assertNull(org.junit.Assert.assertNull) GridCellValueTuple(org.kie.workbench.common.dmn.client.widgets.grid.model.GridCellValueTuple) Mockito.reset(org.mockito.Mockito.reset) Assert.assertEquals(org.junit.Assert.assertEquals) DMNGraphUtils(org.kie.workbench.common.dmn.client.graph.DMNGraphUtils) CellEditorControlsView(org.kie.workbench.common.dmn.client.widgets.grid.controls.container.CellEditorControlsView) DefinitionUtils(org.kie.workbench.common.stunner.core.util.DefinitionUtils) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) BaseExpressionGrid(org.kie.workbench.common.dmn.client.widgets.grid.BaseExpressionGrid) AddDecisionRuleCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.AddDecisionRuleCommand) ItemDefinitionUtils(org.kie.workbench.common.dmn.client.editors.types.common.ItemDefinitionUtils) Mockito.atLeast(org.mockito.Mockito.atLeast) AddOutputClauseCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.AddOutputClauseCommand) ContextEntry(org.kie.workbench.common.dmn.api.definition.model.ContextEntry) DecisionRule(org.kie.workbench.common.dmn.api.definition.model.DecisionRule) AbstractCanvasHandler(org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler) AbstractCanvasGraphCommand(org.kie.workbench.common.stunner.core.client.canvas.command.AbstractCanvasGraphCommand) DomainObject(org.kie.workbench.common.stunner.core.domainobject.DomainObject) GridWidget(org.uberfire.ext.wires.core.grids.client.widget.grid.GridWidget) CanvasCommand(org.kie.workbench.common.stunner.core.client.command.CanvasCommand) List(java.util.List) DMNDiagramsSession(org.kie.workbench.common.dmn.client.docks.navigator.drds.DMNDiagramsSession) HasValueAndTypeRef(org.kie.workbench.common.dmn.client.editors.types.HasValueAndTypeRef) BaseGridCellValue(org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridCellValue) DefaultCanvasCommandFactory(org.kie.workbench.common.dmn.client.commands.factory.DefaultCanvasCommandFactory) InformationItem(org.kie.workbench.common.dmn.api.definition.model.InformationItem) BuiltInType(org.kie.workbench.common.dmn.api.property.dmn.types.BuiltInType) Optional(java.util.Optional) EventSourceMock(org.uberfire.mocks.EventSourceMock) SetBuiltinAggregatorCommand(org.kie.workbench.common.dmn.client.commands.expressions.types.dtable.SetBuiltinAggregatorCommand) DecisionTable(org.kie.workbench.common.dmn.api.definition.model.DecisionTable) DeleteHasValueCommand(org.kie.workbench.common.dmn.client.commands.general.DeleteHasValueCommand) Node(org.kie.workbench.common.stunner.core.graph.Node) IntStream(java.util.stream.IntStream) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Viewport(com.ait.lienzo.client.core.shape.Viewport) HasListSelectorControl(org.kie.workbench.common.dmn.client.widgets.grid.controls.list.HasListSelectorControl) CanvasCommandResultBuilder(org.kie.workbench.common.stunner.core.client.command.CanvasCommandResultBuilder) BuiltinAggregator(org.kie.workbench.common.dmn.api.definition.model.BuiltinAggregator) Function(java.util.function.Function) Captor(org.mockito.Captor) ExpressionEditorChanged(org.kie.workbench.common.dmn.client.widgets.grid.model.ExpressionEditorChanged) RefreshFormPropertiesEvent(org.kie.workbench.common.stunner.forms.client.event.RefreshFormPropertiesEvent) BaseBounds(org.uberfire.ext.wires.core.grids.client.model.impl.BaseBounds) Transform(com.ait.lienzo.client.core.types.Transform) LienzoMockitoTestRunner(com.ait.lienzo.test.LienzoMockitoTestRunner) ArgumentCaptor(org.mockito.ArgumentCaptor) ReadOnlyProvider(org.kie.workbench.common.stunner.core.client.ReadOnlyProvider) Element(org.kie.workbench.common.stunner.core.graph.Element) SessionManager(org.kie.workbench.common.stunner.core.client.api.SessionManager) ArgumentMatchers.anyInt(org.mockito.ArgumentMatchers.anyInt) DMNEditorConstants(org.kie.workbench.common.dmn.client.resources.i18n.DMNEditorConstants) DMNGridPanel(org.kie.workbench.common.dmn.client.widgets.panel.DMNGridPanel) InputClauseLiteralExpression(org.kie.workbench.common.dmn.api.definition.model.InputClauseLiteralExpression) CanvasViolation(org.kie.workbench.common.stunner.core.client.command.CanvasViolation) Iterator(java.util.Iterator) Mockito.when(org.mockito.Mockito.when) Definition(org.kie.workbench.common.stunner.core.graph.content.definition.Definition) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) BaseGridData(org.uberfire.ext.wires.core.grids.client.model.impl.BaseGridData) Text(org.kie.workbench.common.dmn.api.property.dmn.Text) Decision(org.kie.workbench.common.dmn.api.definition.model.Decision) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) Collections(java.util.Collections) ValueAndDataTypeHeaderMetaData(org.kie.workbench.common.dmn.client.widgets.grid.columns.ValueAndDataTypeHeaderMetaData) HasName(org.kie.workbench.common.dmn.api.definition.HasName) QName(org.kie.workbench.common.dmn.api.property.dmn.QName) Name(org.kie.workbench.common.dmn.api.property.dmn.Name) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) Test(org.junit.Test)

Example 93 with ArgumentCaptor

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

the class PasteSelectionSessionCommandTest method executeWithMultiSelection.

@Test
@SuppressWarnings("unchecked")
public void executeWithMultiSelection() {
    pasteSelectionSessionCommand.bind(session);
    pasteSelectionSessionCommand.setTestEdgeFoundInCanvas(true);
    pasteSelectionSessionCommand.setTestEdgeFoundInClipboard(false);
    // Mock the callback of CloneNodeCommand
    ArgumentCaptor<Consumer> consumerNode = ArgumentCaptor.forClass(Consumer.class);
    ArgumentCaptor<Consumer> consumerNode2 = ArgumentCaptor.forClass(Consumer.class);
    when(cloneNodeCommand.getCandidate()).thenReturn(node);
    when(cloneNodeCommand2.getCandidate()).thenReturn(node2);
    when(canvasCommandFactory.cloneNode(eq(node), any(), any(), consumerNode.capture())).thenReturn(cloneNodeCommand);
    when(canvasCommandFactory.cloneNode(eq(node2), any(), any(), consumerNode2.capture())).thenReturn(cloneNodeCommand2);
    Map<Node, ArgumentCaptor<Consumer>> consumerMap = new HashMap() {

        {
            put(node, consumerNode);
            put(node2, consumerNode2);
        }
    };
    // Mock the callback of CloneConnectorCommand
    ArgumentCaptor<Consumer> consumerEdge = ArgumentCaptor.forClass(Consumer.class);
    when(canvasCommandFactory.cloneConnector(any(), Mockito.<String>any(), Mockito.<String>any(), Mockito.<String>any(), consumerEdge.capture())).thenReturn(cloneConnectorCommand);
    // apply callbacks mocks
    when(sessionCommandManager.execute(eq(canvasHandler), any())).thenAnswer(param -> {
        CompositeCommand argument = param.getArgument(1, CompositeCommand.class);
        // callback to nodes
        argument.getCommands().stream().filter(c -> c instanceof CloneNodeCommand).forEach(c -> {
            CloneNodeCommand cloneNodeCommand = (CloneNodeCommand) c;
            Node candidate = cloneNodeCommand.getCandidate();
            consumerMap.get(candidate).getValue().accept(cloneMap.get(candidate));
        });
        // callback to connectors
        argument.getCommands().stream().filter(c -> c instanceof CloneConnectorCommand).forEach(c -> consumerEdge.getValue().accept(cloneEdge));
        return commandResult;
    });
    // Executing the command
    clipboardControl.set(graphInstance.startNode, graphInstance.edge1, graphInstance.intermNode);
    when(selectionControl.getSelectedItems()).thenReturn(Arrays.asList(graphInstance.startNode.getUUID(), graphInstance.edge1.getUUID(), graphInstance.intermNode.getUUID()));
    CopySelectionSessionCommand.getInstance(sessionManager).bind(session);
    pasteSelectionSessionCommand.execute(callback);
    verify(canvasCommandFactory, times(1)).cloneNode(eq(graphInstance.startNode), eq(graphInstance.parentNode.getUUID()), eq(new Point2D(X, DEFAULT_PADDING + Y + NODE_SIZE)), any());
    verify(canvasCommandFactory, times(1)).cloneConnector(eq(graphInstance.edge1), Mockito.<String>any(), Mockito.<String>any(), Mockito.<String>any(), any());
    // check command registry update after execution to allow a single undo/redo
    verify(commandRegistry, times(2)).pop();
    ArgumentCaptor<Command> commandArgumentCaptor = ArgumentCaptor.forClass(Command.class);
    verify(commandRegistry, times(1)).register(commandArgumentCaptor.capture());
    assertTrue(commandArgumentCaptor.getValue() instanceof CompositeCommand);
    assertEquals(2, ((CompositeCommand) commandArgumentCaptor.getValue()).size());
}
Also used : Arrays(java.util.Arrays) DefinitionUtils(org.kie.workbench.common.stunner.core.util.DefinitionUtils) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ManagedInstance(org.jboss.errai.ioc.client.api.ManagedInstance) Edge(org.kie.workbench.common.stunner.core.graph.Edge) AbstractCanvas(org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas) UUID(org.kie.workbench.common.stunner.core.util.UUID) DEFAULT_PADDING(org.kie.workbench.common.stunner.core.client.session.command.impl.PasteSelectionSessionCommand.DEFAULT_PADDING) CloneNodeCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneNodeCommand) CanvasSelectionEvent(org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasSelectionEvent) Map(java.util.Map) Diagram(org.kie.workbench.common.stunner.core.diagram.Diagram) Registry(org.appformer.client.stateControl.registry.Registry) Point2D(org.kie.workbench.common.stunner.core.graph.content.view.Point2D) CanvasCommandFactory(org.kie.workbench.common.stunner.core.client.command.CanvasCommandFactory) AbstractCanvasHandler(org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler) ClientSession(org.kie.workbench.common.stunner.core.client.session.ClientSession) Metadata(org.kie.workbench.common.stunner.core.diagram.Metadata) Objects(java.util.Objects) EdgeClipboard(org.kie.workbench.common.stunner.core.client.canvas.controls.EdgeClipboard) Annotation(java.lang.annotation.Annotation) Bounds(org.kie.workbench.common.stunner.core.graph.content.Bounds) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Node(org.kie.workbench.common.stunner.core.graph.Node) Mockito.mock(org.mockito.Mockito.mock) LocalClipboardControl(org.kie.workbench.common.stunner.core.client.canvas.controls.clipboard.LocalClipboardControl) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Connection(org.kie.workbench.common.stunner.core.graph.content.view.Connection) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) View(org.kie.workbench.common.stunner.core.graph.content.view.View) ArgumentCaptor(org.mockito.ArgumentCaptor) ClientSessionCommand(org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand) Element(org.kie.workbench.common.stunner.core.graph.Element) KeyboardEvent(org.kie.workbench.common.stunner.core.client.event.keyboard.KeyboardEvent) Command(org.kie.workbench.common.stunner.core.command.Command) SessionManager(org.kie.workbench.common.stunner.core.client.api.SessionManager) CommandResult(org.kie.workbench.common.stunner.core.command.CommandResult) Before(org.junit.Before) Event(javax.enterprise.event.Event) CloneConnectorCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneConnectorCommand) TestingGraphInstanceBuilder(org.kie.workbench.common.stunner.core.TestingGraphInstanceBuilder) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) ClipboardControl(org.kie.workbench.common.stunner.core.client.canvas.controls.ClipboardControl) SessionCommandManager(org.kie.workbench.common.stunner.core.client.command.SessionCommandManager) ViewConnector(org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) Collections(java.util.Collections) Mockito.reset(org.mockito.Mockito.reset) Assert.assertEquals(org.junit.Assert.assertEquals) TestingGraphMockHandler(org.kie.workbench.common.stunner.core.TestingGraphMockHandler) ArgumentCaptor(org.mockito.ArgumentCaptor) HashMap(java.util.HashMap) Node(org.kie.workbench.common.stunner.core.graph.Node) CloneNodeCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneNodeCommand) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) CloneConnectorCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneConnectorCommand) Consumer(java.util.function.Consumer) Point2D(org.kie.workbench.common.stunner.core.graph.content.view.Point2D) CloneNodeCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneNodeCommand) ClientSessionCommand(org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand) Command(org.kie.workbench.common.stunner.core.command.Command) CloneConnectorCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneConnectorCommand) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) Test(org.junit.Test)

Example 94 with ArgumentCaptor

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

the class PasteSelectionSessionCommandTest method executeWithMultiSelectionWithEdgesClipboard.

@Test
@SuppressWarnings("unchecked")
public void executeWithMultiSelectionWithEdgesClipboard() {
    final Connection sourceConnection = (Connection) ((ViewConnector) graphInstance.edge1.getContent()).getSourceConnection().orElse(null);
    final Connection targetConnection = (Connection) ((ViewConnector) graphInstance.edge1.getContent()).getTargetConnection().orElse(null);
    final EdgeClipboard clipboard = clipboardControl.buildNewEdgeClipboard(graphInstance.startNode.getUUID(), sourceConnection, graphInstance.intermNode.getUUID(), targetConnection);
    clipboardControl.set(graphInstance.startNode, graphInstance.edge1, graphInstance.intermNode);
    final Map<String, EdgeClipboard> map = new HashMap<>();
    map.put(graphInstance.edge1.getUUID(), clipboard);
    when(clipboardControl.getEdgeMap()).thenReturn(map);
    assertEquals(1, clipboardControl.getEdgeMap().size());
    pasteSelectionSessionCommand.bind(session);
    pasteSelectionSessionCommand.setTestEdgeFoundInCanvas(false);
    pasteSelectionSessionCommand.setTestEdgeFoundInClipboard(true);
    assertEquals(false, pasteSelectionSessionCommand.isEdgeFoundInCanvas(graphInstance.edge1));
    assertEquals(true, pasteSelectionSessionCommand.isEdgeFoundInClipboard(graphInstance.edge1));
    // Mock the callback of CloneNodeCommand
    ArgumentCaptor<Consumer> consumerNode = ArgumentCaptor.forClass(Consumer.class);
    ArgumentCaptor<Consumer> consumerNode2 = ArgumentCaptor.forClass(Consumer.class);
    when(cloneNodeCommand.getCandidate()).thenReturn(node);
    when(cloneNodeCommand2.getCandidate()).thenReturn(node2);
    when(canvasCommandFactory.cloneNode(eq(node), any(), any(), consumerNode.capture())).thenReturn(cloneNodeCommand);
    when(canvasCommandFactory.cloneNode(eq(node2), any(), any(), consumerNode2.capture())).thenReturn(cloneNodeCommand2);
    Map<Node, ArgumentCaptor<Consumer>> consumerMap = new HashMap() {

        {
            put(node, consumerNode);
            put(node2, consumerNode2);
        }
    };
    // Mock the callback of CloneConnectorCommand
    ArgumentCaptor<Consumer> consumerEdge = ArgumentCaptor.forClass(Consumer.class);
    when(canvasCommandFactory.cloneConnector(any(), Mockito.<String>any(), Mockito.<String>any(), Mockito.<String>any(), consumerEdge.capture())).thenReturn(cloneConnectorCommand);
    // apply callbacks mocks
    when(sessionCommandManager.execute(eq(canvasHandler), any())).thenAnswer(param -> {
        CompositeCommand argument = param.getArgument(1, CompositeCommand.class);
        // callback to nodes
        argument.getCommands().stream().filter(c -> c instanceof CloneNodeCommand).forEach(c -> {
            CloneNodeCommand cloneNodeCommand = (CloneNodeCommand) c;
            Node candidate = cloneNodeCommand.getCandidate();
            consumerMap.get(candidate).getValue().accept(cloneMap.get(candidate));
        });
        // callback to connectors
        argument.getCommands().stream().filter(c -> c instanceof CloneConnectorCommand).forEach(c -> consumerEdge.getValue().accept(cloneEdge));
        return commandResult;
    });
    // Executing the command
    clipboardControl.set(graphInstance.startNode, graphInstance.edge1, graphInstance.intermNode);
    when(selectionControl.getSelectedItems()).thenReturn(Arrays.asList(graphInstance.startNode.getUUID(), graphInstance.edge1.getUUID(), graphInstance.intermNode.getUUID()));
    CopySelectionSessionCommand.getInstance(sessionManager).bind(session);
    pasteSelectionSessionCommand.execute(callback);
    verify(canvasCommandFactory, times(1)).cloneNode(eq(graphInstance.startNode), eq(graphInstance.parentNode.getUUID()), eq(new Point2D(X, DEFAULT_PADDING + Y + NODE_SIZE)), any());
    verify(canvasCommandFactory, times(1)).cloneConnector(eq(graphInstance.edge1), Mockito.<String>any(), Mockito.<String>any(), Mockito.<String>any(), any());
    // check command registry update after execution to allow a single undo/redo
    verify(commandRegistry, times(2)).pop();
    ArgumentCaptor<Command> commandArgumentCaptor = ArgumentCaptor.forClass(Command.class);
    verify(commandRegistry, times(1)).register(commandArgumentCaptor.capture());
    assertTrue(commandArgumentCaptor.getValue() instanceof CompositeCommand);
    assertEquals(2, ((CompositeCommand) commandArgumentCaptor.getValue()).size());
}
Also used : Arrays(java.util.Arrays) DefinitionUtils(org.kie.workbench.common.stunner.core.util.DefinitionUtils) ArgumentMatchers.eq(org.mockito.ArgumentMatchers.eq) ManagedInstance(org.jboss.errai.ioc.client.api.ManagedInstance) Edge(org.kie.workbench.common.stunner.core.graph.Edge) AbstractCanvas(org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvas) UUID(org.kie.workbench.common.stunner.core.util.UUID) DEFAULT_PADDING(org.kie.workbench.common.stunner.core.client.session.command.impl.PasteSelectionSessionCommand.DEFAULT_PADDING) CloneNodeCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneNodeCommand) CanvasSelectionEvent(org.kie.workbench.common.stunner.core.client.canvas.event.selection.CanvasSelectionEvent) Map(java.util.Map) Diagram(org.kie.workbench.common.stunner.core.diagram.Diagram) Registry(org.appformer.client.stateControl.registry.Registry) Point2D(org.kie.workbench.common.stunner.core.graph.content.view.Point2D) CanvasCommandFactory(org.kie.workbench.common.stunner.core.client.command.CanvasCommandFactory) AbstractCanvasHandler(org.kie.workbench.common.stunner.core.client.canvas.AbstractCanvasHandler) ClientSession(org.kie.workbench.common.stunner.core.client.session.ClientSession) Metadata(org.kie.workbench.common.stunner.core.diagram.Metadata) Objects(java.util.Objects) EdgeClipboard(org.kie.workbench.common.stunner.core.client.canvas.controls.EdgeClipboard) Annotation(java.lang.annotation.Annotation) Bounds(org.kie.workbench.common.stunner.core.graph.content.Bounds) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) Node(org.kie.workbench.common.stunner.core.graph.Node) Mockito.mock(org.mockito.Mockito.mock) LocalClipboardControl(org.kie.workbench.common.stunner.core.client.canvas.controls.clipboard.LocalClipboardControl) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Connection(org.kie.workbench.common.stunner.core.graph.content.view.Connection) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) Mockito.spy(org.mockito.Mockito.spy) View(org.kie.workbench.common.stunner.core.graph.content.view.View) ArgumentCaptor(org.mockito.ArgumentCaptor) ClientSessionCommand(org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand) Element(org.kie.workbench.common.stunner.core.graph.Element) KeyboardEvent(org.kie.workbench.common.stunner.core.client.event.keyboard.KeyboardEvent) Command(org.kie.workbench.common.stunner.core.command.Command) SessionManager(org.kie.workbench.common.stunner.core.client.api.SessionManager) CommandResult(org.kie.workbench.common.stunner.core.command.CommandResult) Before(org.junit.Before) Event(javax.enterprise.event.Event) CloneConnectorCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneConnectorCommand) TestingGraphInstanceBuilder(org.kie.workbench.common.stunner.core.TestingGraphInstanceBuilder) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) ClipboardControl(org.kie.workbench.common.stunner.core.client.canvas.controls.ClipboardControl) SessionCommandManager(org.kie.workbench.common.stunner.core.client.command.SessionCommandManager) ViewConnector(org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector) Mockito.verify(org.mockito.Mockito.verify) Consumer(java.util.function.Consumer) Mockito(org.mockito.Mockito) Mockito.never(org.mockito.Mockito.never) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) Collections(java.util.Collections) Mockito.reset(org.mockito.Mockito.reset) Assert.assertEquals(org.junit.Assert.assertEquals) TestingGraphMockHandler(org.kie.workbench.common.stunner.core.TestingGraphMockHandler) ViewConnector(org.kie.workbench.common.stunner.core.graph.content.view.ViewConnector) ArgumentCaptor(org.mockito.ArgumentCaptor) HashMap(java.util.HashMap) Node(org.kie.workbench.common.stunner.core.graph.Node) Connection(org.kie.workbench.common.stunner.core.graph.content.view.Connection) CloneNodeCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneNodeCommand) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) CloneConnectorCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneConnectorCommand) Consumer(java.util.function.Consumer) Point2D(org.kie.workbench.common.stunner.core.graph.content.view.Point2D) CloneNodeCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneNodeCommand) ClientSessionCommand(org.kie.workbench.common.stunner.core.client.session.command.ClientSessionCommand) Command(org.kie.workbench.common.stunner.core.command.Command) CloneConnectorCommand(org.kie.workbench.common.stunner.core.client.canvas.command.CloneConnectorCommand) CompositeCommand(org.kie.workbench.common.stunner.core.command.impl.CompositeCommand) EdgeClipboard(org.kie.workbench.common.stunner.core.client.canvas.controls.EdgeClipboard) Test(org.junit.Test)

Example 95 with ArgumentCaptor

use of org.mockito.ArgumentCaptor in project wikidata-query-rdf by wikimedia.

the class KafkaPollerUnitTest method storedOffsetsFromBoth.

@Test
public void storedOffsetsFromBoth() throws RetryableException {
    // Scenario where all offsets are loaded from both storage and timestamp
    Collection<String> topics = ImmutableList.of("topictest", "othertopic", "thirdtopic");
    KafkaOffsetsRepository offsetsRepository = mock(KafkaOffsetsRepository.class);
    createTopicPartitions(1);
    // capture args for assign
    ArgumentCaptor<Collection<TopicPartition>> assignArgs = ArgumentCaptor.forClass((Class) Collection.class);
    doNothing().when(consumer).assign(assignArgs.capture());
    // capture args for seek
    ArgumentCaptor<TopicPartition> seekTopics = ArgumentCaptor.forClass(TopicPartition.class);
    ArgumentCaptor<Long> seekOffsets = ArgumentCaptor.forClass(Long.class);
    doNothing().when(consumer).seek(seekTopics.capture(), seekOffsets.capture());
    // Stored offsets
    Map<TopicPartition, OffsetAndTimestamp> offsetMap = ImmutableMap.of(new TopicPartition("topictest", 0), new OffsetAndTimestamp(1, START_TIME.toEpochMilli()), new TopicPartition("othertopic", 0), new OffsetAndTimestamp(3, START_TIME.toEpochMilli()));
    when(offsetsRepository.load(any())).thenReturn(offsetMap);
    // Timestamp-driven offsets
    when(consumer.offsetsForTimes(any())).thenAnswer(i -> {
        Map<TopicPartition, Long> map = i.getArgumentAt(0, Map.class);
        // Check that timestamps are OK
        map.forEach((k, v) -> assertThat(v).isEqualTo(START_TIME.toEpochMilli()));
        // All offsets are 500
        return map.entrySet().stream().collect(Collectors.toMap(Entry::getKey, l -> new OffsetAndTimestamp(500L, l.getValue())));
    });
    when(consumer.poll(anyLong())).thenReturn(EMPTY_CHANGES);
    KafkaPoller poller = new KafkaPoller(consumer, uris, START_TIME, BATCH_SIZE, topics, offsetsRepository, false, new MetricRegistry());
    Batch batch = poller.firstBatch();
    // should not call offsetsForTimes, since all offsets are in store
    verify(consumer, times(1)).offsetsForTimes(any());
    // We assign to 3 topics
    verify(consumer, times(1)).assign(any());
    assertThat(assignArgs.getValue()).hasSize(topics.size());
    assertThat(seekOffsets.getAllValues()).hasSize(topics.size()).contains(// This offset is from timestamp
    500L);
}
Also used : Arrays(java.util.Arrays) ChangeEvent(org.wikidata.query.rdf.tool.change.events.ChangeEvent) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) URISyntaxException(java.net.URISyntaxException) ConsumerRecords(org.apache.kafka.clients.consumer.ConsumerRecords) Collections.singletonList(java.util.Collections.singletonList) Collections.singleton(java.util.Collections.singleton) Matchers.eq(org.mockito.Matchers.eq) Duration(java.time.Duration) Map(java.util.Map) URI(java.net.URI) TimestampType(org.apache.kafka.common.record.TimestampType) Uris(org.wikidata.query.rdf.tool.wikibase.WikibaseRepository.Uris) TopicPartition(org.apache.kafka.common.TopicPartition) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Mockito.doNothing(org.mockito.Mockito.doNothing) PartitionInfo(org.apache.kafka.common.PartitionInfo) OffsetAndTimestamp(org.apache.kafka.clients.consumer.OffsetAndTimestamp) Collectors(java.util.stream.Collectors) Matchers.any(org.mockito.Matchers.any) START_TIME(org.wikidata.query.rdf.tool.change.events.ChangeEventFixtures.START_TIME) List(java.util.List) ConsumerRecord(org.apache.kafka.clients.consumer.ConsumerRecord) Entry(java.util.Map.Entry) OffsetAndMetadata(org.apache.kafka.clients.consumer.OffsetAndMetadata) Mockito.mock(org.mockito.Mockito.mock) KafkaConsumer(org.apache.kafka.clients.consumer.KafkaConsumer) Mock(org.mockito.Mock) RunWith(org.junit.runner.RunWith) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) Matchers.anyLong(org.mockito.Matchers.anyLong) RetryableException(org.wikidata.query.rdf.tool.exception.RetryableException) DOMAIN(org.wikidata.query.rdf.tool.change.events.ChangeEventFixtures.DOMAIN) ChangeEventFixtures.makeDeleteEvent(org.wikidata.query.rdf.tool.change.events.ChangeEventFixtures.makeDeleteEvent) Before(org.junit.Before) MetricRegistry(com.codahale.metrics.MetricRegistry) Mockito.times(org.mockito.Mockito.times) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) Maps(com.google.common.collect.Maps) Mockito.verify(org.mockito.Mockito.verify) Collectors.toList(java.util.stream.Collectors.toList) ChangeEventFixtures.makeRCEvent(org.wikidata.query.rdf.tool.change.events.ChangeEventFixtures.makeRCEvent) MockitoJUnitRunner(org.mockito.runners.MockitoJUnitRunner) Batch(org.wikidata.query.rdf.tool.change.KafkaPoller.Batch) Collections(java.util.Collections) MetricRegistry(com.codahale.metrics.MetricRegistry) Batch(org.wikidata.query.rdf.tool.change.KafkaPoller.Batch) TopicPartition(org.apache.kafka.common.TopicPartition) Matchers.anyLong(org.mockito.Matchers.anyLong) Collection(java.util.Collection) OffsetAndTimestamp(org.apache.kafka.clients.consumer.OffsetAndTimestamp) Test(org.junit.Test)

Aggregations

ArgumentCaptor (org.mockito.ArgumentCaptor)231 Mockito.verify (org.mockito.Mockito.verify)156 List (java.util.List)128 Test (org.junit.Test)116 Mockito.mock (org.mockito.Mockito.mock)113 Mockito.when (org.mockito.Mockito.when)100 Test (org.junit.jupiter.api.Test)86 ArgumentMatchers.any (org.mockito.ArgumentMatchers.any)85 Mockito (org.mockito.Mockito)85 Map (java.util.Map)76 BeforeEach (org.junit.jupiter.api.BeforeEach)72 Arrays (java.util.Arrays)69 Collectors (java.util.stream.Collectors)69 Collections (java.util.Collections)68 Before (org.junit.Before)65 ArgumentMatchers.eq (org.mockito.ArgumentMatchers.eq)64 Mockito.times (org.mockito.Mockito.times)64 ArrayList (java.util.ArrayList)60 ExtendWith (org.junit.jupiter.api.extension.ExtendWith)60 Mockito.never (org.mockito.Mockito.never)58