method2testcases
stringlengths
118
3.08k
### Question: AddOutputClauseCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler context) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler context) { if (!uiModelColumn.isPresent()) { uiModelColumn = Optional.of(uiModelColumnSupplier.get()); } uiModel.insertColumn(uiColumnIndex, uiModelColumn.get()); for (int rowIndex = 0; rowIndex < dtable.getRule().size(); rowIndex++) { uiModelMapper.fromDMNModel(rowIndex, uiColumnIndex); } updateParentInformation(); executeCanvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler context) { uiModelColumn.ifPresent(uiModel::deleteColumn); updateParentInformation(); undoCanvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } AddOutputClauseCommand(final DecisionTable dtable, final OutputClause outputClause, final GridData uiModel, final Supplier<OutputClauseColumn> uiModelColumnSupplier, final int uiColumnIndex, final DecisionTableUIModelMapper uiModelMapper, final org.uberfire.mvp.Command executeCanvasOperation, final org.uberfire.mvp.Command undoCanvasOperation); void updateParentInformation(); }### Answer: @Test public void testCanvasCommandAllow() throws Exception { makeCommand(DecisionTableUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT); final Command<AbstractCanvasHandler, CanvasViolation> canvasCommand = command.newCanvasCommand(canvasHandler); assertEquals(CanvasCommandResultBuilder.SUCCESS, canvasCommand.allow(canvasHandler)); }
### Question: SetBuiltinAggregatorCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } SetBuiltinAggregatorCommand(final DecisionTable dtable, final BuiltinAggregator aggregator, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { makeCommand(OLD_AGGREGATOR); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { makeCommand(OLD_AGGREGATOR); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verifyZeroInteractions(handler, gce, ruleManager); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { makeCommand(OLD_AGGREGATOR); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); reset(canvasOperation); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verifyZeroInteractions(handler, gce, ruleManager); verify(canvasOperation).execute(); }
### Question: DMNValidationServiceImpl implements DMNValidationService { @Override public boolean isValidVariableName(final String source) { return FEELParser.isVariableNameValid(source); } @Override boolean isValidVariableName(final String source); }### Answer: @Test public void testIsValidVariableNameWhenSourceIsValid() { assertTrue(service.isValidVariableName("drools")); } @Test public void testIsValidVariableNameWhenSourceIsNotValid() { assertFalse(service.isValidVariableName("9drools")); }
### Question: DeleteDecisionRuleCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { uiModel.deleteRow(uiRowIndex); updateRowNumbers(); updateParentInformation(); canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { uiModel.insertRow(uiRowIndex, oldUiModelRow); updateRowNumbers(); updateParentInformation(); canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } DeleteDecisionRuleCommand(final DecisionTable dtable, final GridData uiModel, final int uiRowIndex, final org.uberfire.mvp.Command canvasOperation); void updateRowNumbers(); void updateParentInformation(); }### Answer: @Test public void testCanvasCommandAllow() throws Exception { makeCommand(0); final Command<AbstractCanvasHandler, CanvasViolation> canvasCommand = command.newCanvasCommand(canvasHandler); assertEquals(CanvasCommandResultBuilder.SUCCESS, canvasCommand.allow(canvasHandler)); }
### Question: SetHitPolicyCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } SetHitPolicyCommand(final DecisionTable dtable, final HitPolicy hitPolicy, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { makeCommand(OLD_HIT_POLICY); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { makeCommand(OLD_HIT_POLICY); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verifyZeroInteractions(handler, gce, ruleManager); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { makeCommand(OLD_HIT_POLICY); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); reset(canvasOperation); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verifyZeroInteractions(handler, gce, ruleManager); verify(canvasOperation).execute(); }
### Question: AddInputClauseCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler context) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler context) { if (!uiModelColumn.isPresent()) { uiModelColumn = Optional.of(uiModelColumnSupplier.get()); } uiModel.insertColumn(uiColumnIndex, uiModelColumn.get()); for (int rowIndex = 0; rowIndex < dtable.getRule().size(); rowIndex++) { uiModelMapper.fromDMNModel(rowIndex, uiColumnIndex); } updateParentInformation(); executeCanvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler context) { uiModelColumn.ifPresent(uiModel::deleteColumn); updateParentInformation(); undoCanvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } AddInputClauseCommand(final DecisionTable dtable, final InputClause inputClause, final GridData uiModel, final Supplier<InputClauseColumn> uiModelColumnSupplier, final int uiColumnIndex, final DecisionTableUIModelMapper uiModelMapper, final org.uberfire.mvp.Command executeCanvasOperation, final org.uberfire.mvp.Command undoCanvasOperation); void updateParentInformation(); }### Answer: @Test public void testCanvasCommandAllow() throws Exception { makeCommand(DecisionTableUIModelMapperHelper.ROW_INDEX_COLUMN_COUNT); final Command<AbstractCanvasHandler, CanvasViolation> canvasCommand = command.newCanvasCommand(canvasHandler); assertEquals(CanvasCommandResultBuilder.SUCCESS, canvasCommand.allow(canvasHandler)); }
### Question: SetParametersCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } SetParametersCommand(final FunctionDefinition function, final List<InformationItem> parameters, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { setupCommand(); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { setupCommand(); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { setupCommand(); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verify(canvasOperation).execute(); }
### Question: MoveRowsCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler ach) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext gcec) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext gcec) { moveRows(index); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext gcec) { moveRows(oldIndex); return GraphCommandResultBuilder.SUCCESS; } private void moveRows(final int index) { final List<ContextEntry> rowsToMove = rows .stream() .map(r -> uiModel.getRows().indexOf(r)) .map(i -> context.getContextEntry().get(i)) .collect(Collectors.toList()); final List<ContextEntry> rows = context.getContextEntry(); CommandUtils.moveRows(rows, rowsToMove, index); } }; } MoveRowsCommand(final Context context, final DMNGridData uiModel, final int index, final List<GridRow> rows, final org.uberfire.mvp.Command canvasOperation); void updateRowNumbers(); void updateParentInformation(); }### Answer: @Test public void testGraphCommandAllow() { setupCommand(0, uiModel.getRow(0)); final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.allow(gce)); } @Test public void testGraphCommandExecuteMoveUp() { setupCommand(0, uiModel.getRow(1)); assertEquals(GraphCommandResultBuilder.SUCCESS, command.newGraphCommand(handler).execute(gce)); assertRelationDefinition(1, 0); } @Test public void testGraphCommandExecuteMoveDown() { setupCommand(1, uiModel.getRow(0)); assertEquals(GraphCommandResultBuilder.SUCCESS, command.newGraphCommand(handler).execute(gce)); assertRelationDefinition(1, 0); }
### Question: MoveRowsCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler ach) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> allow(AbstractCanvasHandler context) { if (index == uiModel.getRowCount() - 1) { return CanvasCommandResultBuilder.failed(); } return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler ach) { uiModel.moveRowsTo(index, rows); updateRowNumbers(); updateParentInformation(); canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler ach) { uiModel.moveRowsTo(oldIndex, rows); updateRowNumbers(); updateParentInformation(); canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } MoveRowsCommand(final Context context, final DMNGridData uiModel, final int index, final List<GridRow> rows, final org.uberfire.mvp.Command canvasOperation); void updateRowNumbers(); void updateParentInformation(); }### Answer: @Test public void testCanvasCommandAllow() { setupCommand(0, uiModel.getRow(0)); final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); }
### Question: DMNContentServiceImpl extends KieService<String> implements DMNContentService { @Override public List<Path> getPMMLModelsPaths(final WorkspaceProject workspaceProject) { return pathsHelper.getPMMLModelsPaths(workspaceProject); } @Inject DMNContentServiceImpl(final CommentedOptionFactory commentedOptionFactory, final DMNIOHelper dmnIOHelper, final DMNPathsHelper pathsHelper, final PMMLIncludedDocumentFactory pmmlIncludedDocumentFactory); @Override String getContent(final Path path); @Override DMNContentResource getProjectContent(final Path path, final String defSetId); @Override void saveContent(final Path path, final String content, final Metadata metadata, final String comment); @Override List<Path> getModelsPaths(final WorkspaceProject workspaceProject); @Override List<Path> getDMNModelsPaths(final WorkspaceProject workspaceProject); @Override List<Path> getPMMLModelsPaths(final WorkspaceProject workspaceProject); @Override PMMLDocumentMetadata loadPMMLDocumentMetadata(final Path path); @Override String getSource(final Path path); }### Answer: @Test public void testGetPMMLModelsPaths() { final Path path1 = mock(Path.class); final Path path2 = mock(Path.class); final List<Path> expectedPaths = asList(path1, path2); when(pathsHelper.getPMMLModelsPaths(workspaceProject)).thenReturn(expectedPaths); final List<Path> actualPaths = service.getPMMLModelsPaths(workspaceProject); assertEquals(expectedPaths, actualPaths); }
### Question: AddParameterCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } AddParameterCommand(final FunctionDefinition function, final InformationItem parameter, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verify(canvasOperation).execute(); }
### Question: UpdateParameterNameCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler handler) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext gce) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext gce) { parameter.getName().setValue(name); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext gce) { parameter.getName().setValue(oldName); return GraphCommandResultBuilder.SUCCESS; } }; } UpdateParameterNameCommand(final InformationItem parameter, final String name, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testGraphCommandAllow() { final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.allow(gce)); } @Test public void testGraphCommandExecute() { final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.execute(gce)); assertEquals(NEW_PARAMETER_NAME, parameter.getName().getValue()); } @Test public void testGraphCommandUndo() { final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.execute(gce)); assertEquals(GraphCommandResultBuilder.SUCCESS, c.undo(gce)); assertEquals(OLD_PARAMETER_NAME, parameter.getName().getValue()); }
### Question: UpdateParameterNameCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } UpdateParameterNameCommand(final InformationItem parameter, final String name, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verify(canvasOperation).execute(); }
### Question: RemoveParameterCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } RemoveParameterCommand(final FunctionDefinition function, final InformationItem parameter, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verify(canvasOperation).execute(); }
### Question: UpdateParameterTypeRefCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler handler) { return new AbstractGraphCommand() { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext gce) { return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext gce) { parameter.setTypeRef(typeRef); return GraphCommandResultBuilder.SUCCESS; } @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext gce) { parameter.setTypeRef(oldTypeRef); return GraphCommandResultBuilder.SUCCESS; } }; } UpdateParameterTypeRefCommand(final InformationItem parameter, final QName typeRef, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testGraphCommandAllow() { final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.allow(gce)); } @Test public void testGraphCommandExecute() { final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.execute(gce)); assertEquals(NEW_PARAMETER_TYPE_REF, parameter.getTypeRef()); } @Test public void testGraphCommandUndo() { final Command<GraphCommandExecutionContext, RuleViolation> c = command.newGraphCommand(handler); assertEquals(GraphCommandResultBuilder.SUCCESS, c.execute(gce)); assertEquals(GraphCommandResultBuilder.SUCCESS, c.undo(gce)); assertEquals(OLD_PARAMETER_TYPE_REF, parameter.getTypeRef()); }
### Question: UpdateParameterTypeRefCommand extends AbstractCanvasGraphCommand implements VetoExecutionCommand, VetoUndoCommand { @Override protected Command<AbstractCanvasHandler, CanvasViolation> newCanvasCommand(final AbstractCanvasHandler handler) { return new AbstractCanvasCommand() { @Override public CommandResult<CanvasViolation> execute(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } @Override public CommandResult<CanvasViolation> undo(final AbstractCanvasHandler handler) { canvasOperation.execute(); return CanvasCommandResultBuilder.SUCCESS; } }; } UpdateParameterTypeRefCommand(final InformationItem parameter, final QName typeRef, final org.uberfire.mvp.Command canvasOperation); }### Answer: @Test public void testCanvasCommandAllow() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.allow(handler)); } @Test public void testCanvasCommandExecute() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.execute(handler)); verify(canvasOperation).execute(); } @Test public void testCanvasCommandUndo() { final Command<AbstractCanvasHandler, CanvasViolation> c = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, c.undo(handler)); verify(canvasOperation).execute(); }
### Question: SetChildrenCommand extends org.kie.workbench.common.stunner.core.graph.command.impl.SetChildrenCommand { @Override protected void execute(final GraphCommandExecutionContext context, final Node<?, Edge> parent, final Node<?, Edge> candidate) { super.execute(context, parent, candidate); if (parent.getContent() instanceof View) { final DMNModelInstrumentedBase parentDMNModel = (DMNModelInstrumentedBase) ((View) parent.getContent()).getDefinition(); if (candidate.getContent() instanceof View) { final DMNModelInstrumentedBase childDMNModel = (DMNModelInstrumentedBase) ((View) candidate.getContent()).getDefinition(); childDMNModel.setParent(parentDMNModel); DefaultValueUtilities.updateNewNodeName(getGraph(context), childDMNModel); } } } SetChildrenCommand(final @MapsTo("parentUUID") String parentUUID, final @MapsTo("candidateUUIDs") String[] candidateUUIDs); SetChildrenCommand(final Node<?, Edge> parent, final Node<?, Edge> candidate); }### Answer: @Test @SuppressWarnings("unchecked") public void testExecute() { super.testExecute(); verify(candidateDefinition).setParent(eq(parentDefinition)); verify(candidateDefinitionName).setValue(candidateDefinitionNameCaptor.capture()); final String name = candidateDefinitionNameCaptor.getValue(); assertThat(name).startsWith(Decision.class.getSimpleName()); assertThat(name).endsWith("-1"); }
### Question: DMNDeleteElementsGraphCommand extends DeleteElementsCommand { @Override protected DMNSafeDeleteNodeCommand createSafeDeleteNodeCommand(final Node<?, Edge> node, final SafeDeleteNodeCommand.Options options, final DeleteCallback callback) { return new DMNSafeDeleteNodeCommand(node, callback.onDeleteNode(node, options), options, getGraphsProvider()); } DMNDeleteElementsGraphCommand(final Supplier<Collection<Element>> elements, final DeleteCallback callback, final GraphsProvider graphsProvider); GraphsProvider getGraphsProvider(); }### Answer: @Test public void testCreateSafeDeleteNodeCommand() { final GraphsProvider selectedDiagramProvider = mock(GraphsProvider.class); final Node<?, Edge> node = mock(Node.class); final SafeDeleteNodeCommand.Options options = SafeDeleteNodeCommand.Options.defaults(); final DeleteElementsCommand.DeleteCallback callback = mock(DeleteElementsCommand.DeleteCallback.class); final DMNDeleteElementsGraphCommand command = mock(DMNDeleteElementsGraphCommand.class); when(command.getGraphsProvider()).thenReturn(selectedDiagramProvider); when(node.getUUID()).thenReturn("uuid"); when(command.createSafeDeleteNodeCommand(node, options, callback)).thenCallRealMethod(); final SafeDeleteNodeCommand actual = command.createSafeDeleteNodeCommand(node, options, callback); assertTrue(actual instanceof DMNSafeDeleteNodeCommand); final DMNSafeDeleteNodeCommand dmnCommand = (DMNSafeDeleteNodeCommand) actual; assertEquals(dmnCommand.getNode(), node); assertEquals(dmnCommand.getOptions(), options); assertEquals(dmnCommand.getGraphsProvider(), selectedDiagramProvider); }
### Question: DMNDeleteElementsCommand extends DeleteElementsCommand { @Override protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) { return new DMNDeleteElementsGraphCommand(() -> elements, new CanvasMultipleDeleteProcessor(), getGraphsProvider()); } DMNDeleteElementsCommand(final Collection<Element> elements, final GraphsProvider graphsProvider); GraphsProvider getGraphsProvider(); }### Answer: @Test public void testNewGraphCommand() { final GraphsProvider selectedDiagramProvider = mock(GraphsProvider.class); final ArrayList<Element> elements = new ArrayList<>(); final Element element = mock(Element.class); when(element.getUUID()).thenReturn("uuid"); elements.add(element); final DMNDeleteElementsCommand cmd = new DMNDeleteElementsCommand(elements, selectedDiagramProvider); final Command<GraphCommandExecutionContext, RuleViolation> actual = cmd.newGraphCommand(null); assertTrue(actual instanceof DMNDeleteElementsGraphCommand); assertEquals(cmd.getGraphsProvider(), ((DMNDeleteElementsGraphCommand) actual).getGraphsProvider()); }
### Question: DMNDeleteNodeCommand extends DeleteNodeCommand { @Override protected Command<GraphCommandExecutionContext, RuleViolation> newGraphCommand(final AbstractCanvasHandler context) { return new DMNSafeDeleteNodeCommand(candidate, deleteProcessor, options, getGraphsProvider()); } DMNDeleteNodeCommand(final Node candidate, final GraphsProvider graphsProvider); GraphsProvider getGraphsProvider(); }### Answer: @Test public void testNewGraphCommand() { final GraphsProvider selectedDiagramProvider = mock(GraphsProvider.class); final Node candidate = mock(Node.class); when(candidate.getUUID()).thenReturn("uuid"); final DMNDeleteNodeCommand cmd = new DMNDeleteNodeCommand(candidate, selectedDiagramProvider); final Command<GraphCommandExecutionContext, RuleViolation> actual = cmd.newGraphCommand(null); assertTrue(actual instanceof DMNSafeDeleteNodeCommand); final DMNSafeDeleteNodeCommand safeCmd = (DMNSafeDeleteNodeCommand) actual; assertEquals(cmd.getCandidate(), safeCmd.getNode()); assertEquals(cmd.getDeleteProcessor(), safeCmd.getSafeDeleteCallback().get()); assertEquals(cmd.getOptions(), safeCmd.getOptions()); assertEquals(cmd.getGraphsProvider(), safeCmd.getGraphsProvider()); }
### Question: DMNSafeDeleteNodeCommand extends SafeDeleteNodeCommand { @Override public boolean shouldKeepChildren(final Node<Definition<?>, Edge> candidate) { return DefinitionUtils.getElementDefinition(candidate) instanceof DecisionService; } DMNSafeDeleteNodeCommand(final Node<?, Edge> node, final SafeDeleteNodeCommandCallback safeDeleteCallback, final Options options, final GraphsProvider graphsProvider); @Override boolean shouldKeepChildren(final Node<Definition<?>, Edge> candidate); @Override GraphsProvider getGraphsProvider(); }### Answer: @Test public void testShouldKeepChildren() { final DecisionService decisionService = mock(DecisionService.class); final Node<Definition<?>, Edge> candidate = mock(Node.class); final DMNSafeDeleteNodeCommand cmd = createMock(decisionService, candidate); final boolean actual = cmd.shouldKeepChildren(candidate); assertTrue(actual); } @Test public void testShouldKeepChildrenWhenIsNotDecisionService() { final Object decisionService = mock(Object.class); final Node<Definition<?>, Edge> candidate = mock(Node.class); final DMNSafeDeleteNodeCommand cmd = createMock(decisionService, candidate); final boolean actual = cmd.shouldKeepChildren(candidate); assertFalse(actual); }
### Question: NoOperationGraphCommand extends AbstractGraphCommand { @Override protected CommandResult<RuleViolation> check(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context); @Override CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context); }### Answer: @Test public void testCheck() { assertThat(command.check(context)).isEqualTo(GraphCommandResultBuilder.SUCCESS); }
### Question: NoOperationGraphCommand extends AbstractGraphCommand { @Override public CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context); @Override CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context); }### Answer: @Test public void testExecute() { assertThat(command.execute(context)).isEqualTo(GraphCommandResultBuilder.SUCCESS); }
### Question: NoOperationGraphCommand extends AbstractGraphCommand { @Override public CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context) { return GraphCommandResultBuilder.SUCCESS; } @Override CommandResult<RuleViolation> execute(final GraphCommandExecutionContext context); @Override CommandResult<RuleViolation> undo(final GraphCommandExecutionContext context); }### Answer: @Test public void testUndo() { assertThat(command.undo(context)).isEqualTo(GraphCommandResultBuilder.SUCCESS); }
### Question: DMNServiceClient { public <T> ServiceCallback<List<T>> callback(final Consumer<List<T>> consumer) { return new ServiceCallback<List<T>>() { @Override public void onSuccess(final List<T> item) { consumer.accept(item); } @Override public void onError(final ClientRuntimeError error) { getClientServicesProxy().logWarning(error); consumer.accept(new ArrayList<>()); } }; } DMNServiceClient(final DMNClientServicesProxy clientServicesProxy); ServiceCallback<List<T>> callback(final Consumer<List<T>> consumer); }### Answer: @Test public void testCallback() { final Consumer consumer = mock(Consumer.class); final ServiceCallback service = client.callback(consumer); final List item = mock(List.class); service.onSuccess(item); verify(consumer, atLeastOnce()).accept(item); final ClientRuntimeError error = mock(ClientRuntimeError.class); service.onError(error); verify(proxy).logWarning(error); verify(consumer, atLeastOnce()).accept(any(ArrayList.class)); }
### Question: DMNIncludeModelsClient extends DMNServiceClient { public void loadModels(final Path path, final Consumer<List<IncludedModel>> listConsumer) { clientServicesProxy.loadModels(path, callback(listConsumer)); } @Inject DMNIncludeModelsClient(final DMNClientServicesProxy clientServicesProxy); void loadModels(final Path path, final Consumer<List<IncludedModel>> listConsumer); void loadNodesFromImports(final List<DMNIncludedModel> includeModels, final Consumer<List<DMNIncludedNode>> consumer); void loadItemDefinitionsByNamespace(final String modelName, final String namespace, final Consumer<List<ItemDefinition>> consumer); }### Answer: @Test @SuppressWarnings("unchecked") public void testLoadModels() { client.loadModels(path, listConsumerDMNModels); verify(service).loadModels(eq(path), any(ServiceCallback.class)); }
### Question: DMNIncludeModelsClient extends DMNServiceClient { public void loadNodesFromImports(final List<DMNIncludedModel> includeModels, final Consumer<List<DMNIncludedNode>> consumer) { clientServicesProxy.loadNodesFromImports(includeModels, callback(consumer)); } @Inject DMNIncludeModelsClient(final DMNClientServicesProxy clientServicesProxy); void loadModels(final Path path, final Consumer<List<IncludedModel>> listConsumer); void loadNodesFromImports(final List<DMNIncludedModel> includeModels, final Consumer<List<DMNIncludedNode>> consumer); void loadItemDefinitionsByNamespace(final String modelName, final String namespace, final Consumer<List<ItemDefinition>> consumer); }### Answer: @Test @SuppressWarnings("unchecked") public void testLoadNodesFromImports() { final DMNIncludedModel includedModel1 = mock(DMNIncludedModel.class); final DMNIncludedModel includedModel2 = mock(DMNIncludedModel.class); final List<DMNIncludedModel> imports = asList(includedModel1, includedModel2); client.loadNodesFromImports(imports, listConsumerDMNNodes); verify(service).loadNodesFromImports(eq(imports), any(ServiceCallback.class)); }
### Question: DMNIncludeModelsClient extends DMNServiceClient { public void loadItemDefinitionsByNamespace(final String modelName, final String namespace, final Consumer<List<ItemDefinition>> consumer) { clientServicesProxy.loadItemDefinitionsByNamespace(modelName, namespace, callback(consumer)); } @Inject DMNIncludeModelsClient(final DMNClientServicesProxy clientServicesProxy); void loadModels(final Path path, final Consumer<List<IncludedModel>> listConsumer); void loadNodesFromImports(final List<DMNIncludedModel> includeModels, final Consumer<List<DMNIncludedNode>> consumer); void loadItemDefinitionsByNamespace(final String modelName, final String namespace, final Consumer<List<ItemDefinition>> consumer); }### Answer: @Test @SuppressWarnings("unchecked") public void testLoadItemDefinitionsByNamespace() { final String modelName = "model1"; final String namespace = ": client.loadItemDefinitionsByNamespace(modelName, namespace, listConsumerDMNItemDefinitions); verify(service).loadItemDefinitionsByNamespace(eq(modelName), eq(namespace), any(ServiceCallback.class)); }
### Question: ReadOnlyProviderImpl implements ReadOnlyProvider { @Override public boolean isReadOnlyDiagram() { return contextProvider.isReadOnly(); } @Inject ReadOnlyProviderImpl(final EditorContextProvider contextProvider); @Override boolean isReadOnlyDiagram(); }### Answer: @Test public void testIsReadOnlyDiagramWhenIsGithub() { when(contextProvider.getChannel()).thenReturn(GITHUB); assertFalse(readOnlyProvider.isReadOnlyDiagram()); } @Test public void testIsReadOnlyDiagramWhenIsDefault() { when(contextProvider.getChannel()).thenReturn(DEFAULT); assertFalse(readOnlyProvider.isReadOnlyDiagram()); } @Test public void testIsReadOnlyDiagramWhenIsVsCode() { when(contextProvider.getChannel()).thenReturn(VSCODE); assertFalse(readOnlyProvider.isReadOnlyDiagram()); } @Test public void testIsReadOnlyDiagramWhenIsOnline() { when(contextProvider.getChannel()).thenReturn(ONLINE); assertFalse(readOnlyProvider.isReadOnlyDiagram()); } @Test public void testIsReadOnlyDiagramWhenIsDesktop() { when(contextProvider.getChannel()).thenReturn(DESKTOP); assertFalse(readOnlyProvider.isReadOnlyDiagram()); } @Test public void testIsReadOnlyDiagramWhenIsEmbedded() { when(contextProvider.getChannel()).thenReturn(EMBEDDED); assertFalse(readOnlyProvider.isReadOnlyDiagram()); }
### Question: DMNDataObjectsClient extends DMNServiceClient { public void loadDataObjects(final Consumer<List<DataObject>> listConsumer) { clientServicesProxy.loadDataObjects( callback(listConsumer)); } @Inject DMNDataObjectsClient(final DMNClientServicesProxy clientServicesProxy); void loadDataObjects(final Consumer<List<DataObject>> listConsumer); }### Answer: @Test public void testLoadDataObjects() { final Consumer<List<DataObject>> consumer = mock(Consumer.class); final ServiceCallback serviceCallback = mock(ServiceCallback.class); doReturn(serviceCallback).when(client).callback(consumer); client.loadDataObjects(consumer); verify(proxy).loadDataObjects(serviceCallback); }
### Question: BoxedExpressionHelper { public Optional<HasExpression> getOptionalHasExpression(final Node<View, Edge> node) { final Object definition = DefinitionUtils.getElementDefinition(node); final HasExpression expression; if (definition instanceof BusinessKnowledgeModel) { expression = ((BusinessKnowledgeModel) definition).asHasExpression(); } else if (definition instanceof Decision) { expression = (Decision) definition; } else { expression = null; } return Optional.ofNullable(expression); } Optional<HasExpression> getOptionalHasExpression(final Node<View, Edge> node); Optional<Expression> getOptionalExpression(final Node<View, Edge> node); Expression getExpression(final Node<View, Edge> node); HasExpression getHasExpression(final Node<View, Edge> node); }### Answer: @Test public void testGetOptionalHasExpressionWhenNodeIsDecision() { final View content = mock(View.class); final Decision expectedHasExpression = mock(Decision.class); when(node.getContent()).thenReturn(content); when(content.getDefinition()).thenReturn(expectedHasExpression); final Optional<HasExpression> actualHasExpression = helper.getOptionalHasExpression(node); assertTrue(actualHasExpression.isPresent()); assertEquals(expectedHasExpression, actualHasExpression.get()); } @Test public void testGetOptionalHasExpressionWhenNodeIsOtherDRGElement() { final View content = mock(View.class); final InputData expectedHasExpression = mock(InputData.class); when(node.getContent()).thenReturn(content); when(content.getDefinition()).thenReturn(expectedHasExpression); final Optional<HasExpression> actualHasExpression = helper.getOptionalHasExpression(node); assertFalse(actualHasExpression.isPresent()); }
### Question: BoxedExpressionHelper { public Expression getExpression(final Node<View, Edge> node) { return getHasExpression(node).getExpression(); } Optional<HasExpression> getOptionalHasExpression(final Node<View, Edge> node); Optional<Expression> getOptionalExpression(final Node<View, Edge> node); Expression getExpression(final Node<View, Edge> node); HasExpression getHasExpression(final Node<View, Edge> node); }### Answer: @Test public void testGetExpression() { final View content = mock(View.class); final Decision decision = mock(Decision.class); final Expression expectedExpression = mock(Expression.class); when(node.getContent()).thenReturn(content); when(content.getDefinition()).thenReturn(decision); when(decision.getExpression()).thenReturn(expectedExpression); final Expression actualExpression = helper.getExpression(node); assertEquals(expectedExpression, actualExpression); }
### Question: BoxedExpressionHelper { public HasExpression getHasExpression(final Node<View, Edge> node) { return getOptionalHasExpression(node).orElseThrow(UnsupportedOperationException::new); } Optional<HasExpression> getOptionalHasExpression(final Node<View, Edge> node); Optional<Expression> getOptionalExpression(final Node<View, Edge> node); Expression getExpression(final Node<View, Edge> node); HasExpression getHasExpression(final Node<View, Edge> node); }### Answer: @Test public void testGetHasExpression() { final View content = mock(View.class); final Decision expected = mock(Decision.class); when(node.getContent()).thenReturn(content); when(content.getDefinition()).thenReturn(expected); final HasExpression actual = helper.getHasExpression(node); assertEquals(expected, actual); } @Test(expected = UnsupportedOperationException.class) public void testGetHasExpressionWhenNodeDoesNotHaveExpression() { final View content = mock(View.class); when(node.getContent()).thenReturn(content); when(content.getDefinition()).thenReturn(new InputData()); helper.getHasExpression(node); }
### Question: DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>, HasEnabled { @EventHandler("add-button") @SuppressWarnings("unused") public void onClickTypeButton(final ClickEvent clickEvent) { cellEditor.show(nameAndUrlPopover, clickEvent.getClientX(), clickEvent.getClientY()); } @Inject DocumentationLinksWidget(final ManagedInstance<DocumentationLinkItem> listItems, final TranslationService translationService, final HTMLDivElement linksContainer, final HTMLDivElement noneContainer, final HTMLAnchorElement addButton, final NameAndUrlPopoverView.Presenter nameAndUrlPopover, final CellEditorControlsView cellEditor, @Named("span") final HTMLElement addLink, @Named("span") final HTMLElement noLink, final Event<LockRequiredEvent> locker, final @DMNEditor ReadOnlyProvider readOnlyProvider); @PostConstruct void init(); @Override DocumentationLinks getValue(); @Override void setValue(final DocumentationLinks documentationLinks); @Override void setValue(final DocumentationLinks documentationLinks, final boolean fireEvents); @EventHandler("add-button") @SuppressWarnings("unused") void onClickTypeButton(final ClickEvent clickEvent); @Override HandlerRegistration addValueChangeHandler(final ValueChangeHandler<DocumentationLinks> handler); @Override boolean isEnabled(); @Override void setEnabled(final boolean enabled); void setDMNModel(final DRGElement model); }### Answer: @Test public void testOnClickTypeButton() { final int x = 111; final int y = 222; final ClickEvent clickEvent = mock(ClickEvent.class); when(clickEvent.getClientX()).thenReturn(x); when(clickEvent.getClientY()).thenReturn(y); widget.onClickTypeButton(clickEvent); verify(cellEditor).show(nameAndUrlPopover, x, y); }
### Question: DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>, HasEnabled { public void setDMNModel(final DRGElement model) { setValue(model.getLinksHolder().getValue()); refresh(); } @Inject DocumentationLinksWidget(final ManagedInstance<DocumentationLinkItem> listItems, final TranslationService translationService, final HTMLDivElement linksContainer, final HTMLDivElement noneContainer, final HTMLAnchorElement addButton, final NameAndUrlPopoverView.Presenter nameAndUrlPopover, final CellEditorControlsView cellEditor, @Named("span") final HTMLElement addLink, @Named("span") final HTMLElement noLink, final Event<LockRequiredEvent> locker, final @DMNEditor ReadOnlyProvider readOnlyProvider); @PostConstruct void init(); @Override DocumentationLinks getValue(); @Override void setValue(final DocumentationLinks documentationLinks); @Override void setValue(final DocumentationLinks documentationLinks, final boolean fireEvents); @EventHandler("add-button") @SuppressWarnings("unused") void onClickTypeButton(final ClickEvent clickEvent); @Override HandlerRegistration addValueChangeHandler(final ValueChangeHandler<DocumentationLinks> handler); @Override boolean isEnabled(); @Override void setEnabled(final boolean enabled); void setDMNModel(final DRGElement model); }### Answer: @Test public void testSetDMNModel() { final DocumentationLinksHolder holder = mock(DocumentationLinksHolder.class); final DocumentationLinks value = mock(DocumentationLinks.class); when(holder.getValue()).thenReturn(value); final DRGElement model = mock(DRGElement.class); when(model.getLinksHolder()).thenReturn(holder); widget.setDMNModel(model); verify(widget).setValue(value); verify(widget).refresh(); }
### Question: DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>, HasEnabled { void onExternalLinkDeleted(final DMNExternalLink externalLink) { locker.fire(new LockRequiredEvent()); getValue().getLinks().remove(externalLink); refresh(); } @Inject DocumentationLinksWidget(final ManagedInstance<DocumentationLinkItem> listItems, final TranslationService translationService, final HTMLDivElement linksContainer, final HTMLDivElement noneContainer, final HTMLAnchorElement addButton, final NameAndUrlPopoverView.Presenter nameAndUrlPopover, final CellEditorControlsView cellEditor, @Named("span") final HTMLElement addLink, @Named("span") final HTMLElement noLink, final Event<LockRequiredEvent> locker, final @DMNEditor ReadOnlyProvider readOnlyProvider); @PostConstruct void init(); @Override DocumentationLinks getValue(); @Override void setValue(final DocumentationLinks documentationLinks); @Override void setValue(final DocumentationLinks documentationLinks, final boolean fireEvents); @EventHandler("add-button") @SuppressWarnings("unused") void onClickTypeButton(final ClickEvent clickEvent); @Override HandlerRegistration addValueChangeHandler(final ValueChangeHandler<DocumentationLinks> handler); @Override boolean isEnabled(); @Override void setEnabled(final boolean enabled); void setDMNModel(final DRGElement model); }### Answer: @Test public void testOnExternalLinkDeleted() { final DocumentationLinks value = mock(DocumentationLinks.class); final DMNExternalLink externalLink = mock(DMNExternalLink.class); final List<DMNExternalLink> links = new ArrayList<>(); links.add(externalLink); when(value.getLinks()).thenReturn(links); widget.setValue(value); widget.onExternalLinkDeleted(externalLink); assertFalse(links.contains(externalLink)); verify(widget).refresh(); verify(locker).fire(any()); }
### Question: DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>, HasEnabled { void onDMNExternalLinkCreated(final DMNExternalLink externalLink) { locker.fire(new LockRequiredEvent()); getValue().addLink(externalLink); refresh(); } @Inject DocumentationLinksWidget(final ManagedInstance<DocumentationLinkItem> listItems, final TranslationService translationService, final HTMLDivElement linksContainer, final HTMLDivElement noneContainer, final HTMLAnchorElement addButton, final NameAndUrlPopoverView.Presenter nameAndUrlPopover, final CellEditorControlsView cellEditor, @Named("span") final HTMLElement addLink, @Named("span") final HTMLElement noLink, final Event<LockRequiredEvent> locker, final @DMNEditor ReadOnlyProvider readOnlyProvider); @PostConstruct void init(); @Override DocumentationLinks getValue(); @Override void setValue(final DocumentationLinks documentationLinks); @Override void setValue(final DocumentationLinks documentationLinks, final boolean fireEvents); @EventHandler("add-button") @SuppressWarnings("unused") void onClickTypeButton(final ClickEvent clickEvent); @Override HandlerRegistration addValueChangeHandler(final ValueChangeHandler<DocumentationLinks> handler); @Override boolean isEnabled(); @Override void setEnabled(final boolean enabled); void setDMNModel(final DRGElement model); }### Answer: @Test public void testOnDMNExternalLinkCreated() { final DMNExternalLink createdLink = mock(DMNExternalLink.class); final DocumentationLinks value = mock(DocumentationLinks.class); widget.setValue(value); widget.onDMNExternalLinkCreated(createdLink); verify(value).addLink(createdLink); verify(locker).fire(any()); verify(widget).refresh(); }
### Question: DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>, HasEnabled { @PostConstruct public void init() { nameAndUrlPopover.setOnExternalLinkCreated(this::onDMNExternalLinkCreated); addLink.textContent = translationService.getTranslation(DMNDocumentationI18n_Add); noLink.textContent = translationService.getTranslation(DMNDocumentationI18n_None); setupAddButtonReadOnlyStatus(); } @Inject DocumentationLinksWidget(final ManagedInstance<DocumentationLinkItem> listItems, final TranslationService translationService, final HTMLDivElement linksContainer, final HTMLDivElement noneContainer, final HTMLAnchorElement addButton, final NameAndUrlPopoverView.Presenter nameAndUrlPopover, final CellEditorControlsView cellEditor, @Named("span") final HTMLElement addLink, @Named("span") final HTMLElement noLink, final Event<LockRequiredEvent> locker, final @DMNEditor ReadOnlyProvider readOnlyProvider); @PostConstruct void init(); @Override DocumentationLinks getValue(); @Override void setValue(final DocumentationLinks documentationLinks); @Override void setValue(final DocumentationLinks documentationLinks, final boolean fireEvents); @EventHandler("add-button") @SuppressWarnings("unused") void onClickTypeButton(final ClickEvent clickEvent); @Override HandlerRegistration addValueChangeHandler(final ValueChangeHandler<DocumentationLinks> handler); @Override boolean isEnabled(); @Override void setEnabled(final boolean enabled); void setDMNModel(final DRGElement model); }### Answer: @Test public void testInit() { final String addText = "add"; final String noLinkText = "no link text"; when(translationService.getTranslation(DMNDocumentationI18n_Add)).thenReturn(addText); when(translationService.getTranslation(DMNDocumentationI18n_None)).thenReturn(noLinkText); widget.init(); assertEquals(addLink.textContent, addText); assertEquals(noLink.textContent, noLinkText); verify(widget).setupAddButtonReadOnlyStatus(); }
### Question: DocumentationLinkItem implements UberElemental<DMNExternalLink> { @Override public void init(final DMNExternalLink externalLink) { this.externalLink = externalLink; link.href = externalLink.getUrl(); link.textContent = externalLink.getDescription(); } @Inject DocumentationLinkItem(final HTMLDivElement item, final HTMLAnchorElement link, final HTMLAnchorElement deleteLink); @Override HTMLElement getElement(); @Override void init(final DMNExternalLink externalLink); @SuppressWarnings("unused") @EventHandler("deleteLink") void onDeleteLinkClick(final ClickEvent clickEvent); Consumer<DMNExternalLink> getOnDeleted(); void setOnDeleted(final Consumer<DMNExternalLink> onDeleted); }### Answer: @Test public void testInit() { final String url = "http: final String description = "My nice description."; final DMNExternalLink externalLink = new DMNExternalLink(); externalLink.setDescription(description); externalLink.setUrl(url); documentationLinkItem.init(externalLink); assertEquals(description, link.textContent); assertEquals(url, link.href); }
### Question: DocumentationLinkItem implements UberElemental<DMNExternalLink> { @SuppressWarnings("unused") @EventHandler("deleteLink") public void onDeleteLinkClick(final ClickEvent clickEvent) { if (!Objects.isNull(getOnDeleted())) { getOnDeleted().accept(externalLink); } } @Inject DocumentationLinkItem(final HTMLDivElement item, final HTMLAnchorElement link, final HTMLAnchorElement deleteLink); @Override HTMLElement getElement(); @Override void init(final DMNExternalLink externalLink); @SuppressWarnings("unused") @EventHandler("deleteLink") void onDeleteLinkClick(final ClickEvent clickEvent); Consumer<DMNExternalLink> getOnDeleted(); void setOnDeleted(final Consumer<DMNExternalLink> onDeleted); }### Answer: @Test public void testOnDeleteLinkClick() { final Consumer<DMNExternalLink> onDelete = mock(Consumer.class); documentationLinkItem.setOnDeleted(onDelete); final DMNExternalLink externalLink = mock(DMNExternalLink.class); documentationLinkItem.init(externalLink); documentationLinkItem.onDeleteLinkClick(null); verify(onDelete).accept(externalLink); }
### Question: DMNDocumentationExternalLink { @JsOverlay public static DMNDocumentationExternalLink create(final String description, final String url) { final DMNDocumentationExternalLink link = new DMNDocumentationExternalLink(); link.description = description; link.url = url; return link; } private DMNDocumentationExternalLink(); @JsOverlay static DMNDocumentationExternalLink create(final String description, final String url); @JsOverlay final String getDescription(); @JsOverlay final String getUrl(); }### Answer: @Test public void testCreate() { final String url = "url"; final String description = "description"; final DMNDocumentationExternalLink created = DMNDocumentationExternalLink.create(description, url); assertEquals(url, created.getUrl()); assertEquals(description, created.getDescription()); }
### Question: DMNDocumentationDRDsFactory { void setExpressionContainerGrid(final Diagram diagram, final String uuid) { final Node<View, Edge> node = getNode(diagram, uuid); final Object definition = DefinitionUtils.getElementDefinition(node); final HasExpression hasExpression = expressionHelper.getHasExpression(node); final Optional<HasName> hasName = Optional.of((HasName) definition); final ExpressionContainerGrid grid = getExpressionContainerGrid(); grid.setExpression(node.getUUID(), hasExpression, hasName, false); clearSelections(grid); } @Inject DMNDocumentationDRDsFactory(final SessionManager sessionManager, final BoxedExpressionHelper expressionHelper); List<DMNDocumentationDRD> create(final Diagram diagram); }### Answer: @Test public void testSetExpressionContainerGrid() { final String uuid = "0000-1111-2222-3333"; final String name = "Decision-1"; final Node<View, Edge> node = new NodeImpl<>(uuid); final Decision drgElement = new Decision(); final HasExpression hasExpression = mock(HasExpression.class); final View view = mock(View.class); node.setContent(view); drgElement.setName(new Name(name)); when(graph.nodes()).thenReturn(singletonList(node)); when(view.getDefinition()).thenReturn(drgElement); when(expressionHelper.getHasExpression(node)).thenReturn(hasExpression); factory.setExpressionContainerGrid(diagram, uuid); verify(expressionContainerGrid).setExpression(uuid, hasExpression, Optional.of(drgElement), false); verify(factory).clearSelections(expressionContainerGrid); }
### Question: DMNDocumentationDRDsFactory { void clearSelections(final ExpressionContainerGrid grid) { grid.getBaseExpressionGrid().ifPresent(expressionGrid -> { expressionGrid.getModel().clearSelections(); expressionGrid.draw(); }); } @Inject DMNDocumentationDRDsFactory(final SessionManager sessionManager, final BoxedExpressionHelper expressionHelper); List<DMNDocumentationDRD> create(final Diagram diagram); }### Answer: @Test public void testClearSelections() { factory.clearSelections(expressionContainerGrid); verify(expressionGrid.getModel()).clearSelections(); verify(expressionGrid).draw(); }
### Question: DMNDocumentationServiceImpl implements DMNDocumentationService { @Override public DMNDocumentation processDocumentation(final Diagram diagram) { return dmnDocumentationFactory.create(diagram); } @Inject DMNDocumentationServiceImpl(final ClientMustacheTemplateRenderer mustacheTemplateRenderer, final DMNDocumentationFactory dmnDocumentationFactory); @Override DMNDocumentation processDocumentation(final Diagram diagram); @Override HTMLDocumentationTemplate getDocumentationTemplate(); @Override DocumentationOutput buildDocumentation(final HTMLDocumentationTemplate template, final DMNDocumentation diagramDocumentation); @Override DocumentationOutput generate(final Diagram diagram); }### Answer: @Test public void testProcessDocumentation() { final DMNDocumentation expectedDocumentation = mock(DMNDocumentation.class); when(dmnDocumentationFactory.create(diagram)).thenReturn(expectedDocumentation); final DMNDocumentation actualDocumentation = service.processDocumentation(diagram); assertEquals(expectedDocumentation, actualDocumentation); }
### Question: DMNDocumentationServiceImpl implements DMNDocumentationService { @Override public HTMLDocumentationTemplate getDocumentationTemplate() { final DMNDocumentationTemplateSource source = GWT.create(DMNDocumentationTemplateSource.class); return new HTMLDocumentationTemplate(source.documentationTemplate().getText()); } @Inject DMNDocumentationServiceImpl(final ClientMustacheTemplateRenderer mustacheTemplateRenderer, final DMNDocumentationFactory dmnDocumentationFactory); @Override DMNDocumentation processDocumentation(final Diagram diagram); @Override HTMLDocumentationTemplate getDocumentationTemplate(); @Override DocumentationOutput buildDocumentation(final HTMLDocumentationTemplate template, final DMNDocumentation diagramDocumentation); @Override DocumentationOutput generate(final Diagram diagram); }### Answer: @Test public void testGetDocumentationTemplate() { final HTMLDocumentationTemplate documentationTemplate = service.getDocumentationTemplate(); final String expectedTemplate = "documentationTemplate"; final String actualTemplate = documentationTemplate.getTemplate(); assertEquals(expectedTemplate, actualTemplate); }
### Question: DMNDocumentationServiceImpl implements DMNDocumentationService { @Override public DocumentationOutput buildDocumentation(final HTMLDocumentationTemplate template, final DMNDocumentation diagramDocumentation) { final String rendered = mustacheTemplateRenderer.render(template.getTemplate(), diagramDocumentation); return new DocumentationOutput(rendered); } @Inject DMNDocumentationServiceImpl(final ClientMustacheTemplateRenderer mustacheTemplateRenderer, final DMNDocumentationFactory dmnDocumentationFactory); @Override DMNDocumentation processDocumentation(final Diagram diagram); @Override HTMLDocumentationTemplate getDocumentationTemplate(); @Override DocumentationOutput buildDocumentation(final HTMLDocumentationTemplate template, final DMNDocumentation diagramDocumentation); @Override DocumentationOutput generate(final Diagram diagram); }### Answer: @Test public void testBuildDocumentation() { final HTMLDocumentationTemplate template = mock(HTMLDocumentationTemplate.class); final DMNDocumentation documentation = mock(DMNDocumentation.class); final String documentationTemplate = "documentationTemplate"; final String rendered = "<template rendered='true' />"; final DocumentationOutput expectedOutput = new DocumentationOutput(rendered); when(template.getTemplate()).thenReturn(documentationTemplate); when(mustacheTemplateRenderer.render(documentationTemplate, documentation)).thenReturn(rendered); final DocumentationOutput actualOutput = service.buildDocumentation(template, documentation); assertEquals(expectedOutput.getValue(), actualOutput.getValue()); }
### Question: DMNDocumentationServiceImpl implements DMNDocumentationService { @Override public DocumentationOutput generate(final Diagram diagram) { return Optional.ofNullable(diagram) .map(this::processDocumentation) .map(dmnDocumentation -> buildDocumentation(getDocumentationTemplate(), dmnDocumentation)) .orElse(EMPTY); } @Inject DMNDocumentationServiceImpl(final ClientMustacheTemplateRenderer mustacheTemplateRenderer, final DMNDocumentationFactory dmnDocumentationFactory); @Override DMNDocumentation processDocumentation(final Diagram diagram); @Override HTMLDocumentationTemplate getDocumentationTemplate(); @Override DocumentationOutput buildDocumentation(final HTMLDocumentationTemplate template, final DMNDocumentation diagramDocumentation); @Override DocumentationOutput generate(final Diagram diagram); }### Answer: @Test public void testGenerateWhenDiagramIsNotPresent() { final DocumentationOutput expectedOutput = DocumentationOutput.EMPTY; final DocumentationOutput actualOutput = service.generate(null); assertEquals(expectedOutput, actualOutput); }
### Question: DMNDocumentationFactory { protected String getDiagramImage() { return getCanvasHandler() .map(canvasFileExport::exportToPng) .orElse(EMPTY); } @Inject DMNDocumentationFactory(final CanvasFileExport canvasFileExport, final TranslationService translationService, final DMNDocumentationDRDsFactory drdsFactory, final SessionInfo sessionInfo, final DMNGraphUtils graphUtils); DMNDocumentation create(final Diagram diagram); }### Answer: @Test public void testGetDiagramImageWhenCanvasHandlerIsNotPresent() { when(graphUtils.getCurrentSession()).thenReturn(Optional.empty()); assertEquals(EMPTY, documentationFactory.getDiagramImage()); }
### Question: DMNDocumentationFactory { protected boolean hasGraphNodes(final Diagram diagram) { return !graphUtils.getDRGElements(diagram).isEmpty(); } @Inject DMNDocumentationFactory(final CanvasFileExport canvasFileExport, final TranslationService translationService, final DMNDocumentationDRDsFactory drdsFactory, final SessionInfo sessionInfo, final DMNGraphUtils graphUtils); DMNDocumentation create(final Diagram diagram); }### Answer: @Test public void testGetHasGraphNodesWhenIsReturnsFalse() { when(graphUtils.getDRGElements(diagram)).thenReturn(emptyList()); assertFalse(documentationFactory.hasGraphNodes(diagram)); } @Test public void testGetHasGraphNodesWhenIsReturnsTrue() { when(graphUtils.getDRGElements(diagram)).thenReturn(singletonList(mock(DRGElement.class))); assertTrue(documentationFactory.hasGraphNodes(diagram)); }
### Question: NameAndUrlPopoverViewImpl extends AbstractPopoverViewImpl implements NameAndUrlPopoverView { @EventHandler("cancelButton") @SuppressWarnings("unused") public void onClickCancelButton(final ClickEvent clickEvent) { hide(); } NameAndUrlPopoverViewImpl(); @Inject NameAndUrlPopoverViewImpl(final Div popoverElement, final Div popoverContentElement, final JQueryProducer.JQuery<Popover> jQueryPopover, final TranslationService translationService, final HTMLButtonElement cancelButton, final HTMLButtonElement okButton, final HTMLInputElement urlInput, final HTMLInputElement attachmentNameInput, @Named("span") final HTMLElement urlLabel, @Named("span") final HTMLElement attachmentName, @Named("span") final HTMLElement attachmentTip); @PostConstruct void init(); @EventHandler("okButton") @SuppressWarnings("unused") void onClickOkButton(final ClickEvent clickEvent); @EventHandler("cancelButton") @SuppressWarnings("unused") void onClickCancelButton(final ClickEvent clickEvent); @Override void init(final NameAndUrlPopoverView.Presenter presenter); Consumer<DMNExternalLink> getOnExternalLinkCreated(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); @Override void show(final Optional<String> popoverTitle); }### Answer: @Test public void testOnClickCancelButton() { popover.onClickCancelButton(null); verify(popover).hide(); }
### Question: NameAndUrlPopoverViewImpl extends AbstractPopoverViewImpl implements NameAndUrlPopoverView { @Override public void show(final Optional<String> popoverTitle) { clear(); superShow(popoverTitle); } NameAndUrlPopoverViewImpl(); @Inject NameAndUrlPopoverViewImpl(final Div popoverElement, final Div popoverContentElement, final JQueryProducer.JQuery<Popover> jQueryPopover, final TranslationService translationService, final HTMLButtonElement cancelButton, final HTMLButtonElement okButton, final HTMLInputElement urlInput, final HTMLInputElement attachmentNameInput, @Named("span") final HTMLElement urlLabel, @Named("span") final HTMLElement attachmentName, @Named("span") final HTMLElement attachmentTip); @PostConstruct void init(); @EventHandler("okButton") @SuppressWarnings("unused") void onClickOkButton(final ClickEvent clickEvent); @EventHandler("cancelButton") @SuppressWarnings("unused") void onClickCancelButton(final ClickEvent clickEvent); @Override void init(final NameAndUrlPopoverView.Presenter presenter); Consumer<DMNExternalLink> getOnExternalLinkCreated(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); @Override void show(final Optional<String> popoverTitle); }### Answer: @Test public void testShow() { doNothing().when(popover).superShow(any()); popover.show(Optional.of("")); verify(popover).clear(); }
### Question: NameAndUrlPopoverViewImpl extends AbstractPopoverViewImpl implements NameAndUrlPopoverView { void clear() { attachmentNameInput.value = ""; urlInput.value = ""; } NameAndUrlPopoverViewImpl(); @Inject NameAndUrlPopoverViewImpl(final Div popoverElement, final Div popoverContentElement, final JQueryProducer.JQuery<Popover> jQueryPopover, final TranslationService translationService, final HTMLButtonElement cancelButton, final HTMLButtonElement okButton, final HTMLInputElement urlInput, final HTMLInputElement attachmentNameInput, @Named("span") final HTMLElement urlLabel, @Named("span") final HTMLElement attachmentName, @Named("span") final HTMLElement attachmentTip); @PostConstruct void init(); @EventHandler("okButton") @SuppressWarnings("unused") void onClickOkButton(final ClickEvent clickEvent); @EventHandler("cancelButton") @SuppressWarnings("unused") void onClickCancelButton(final ClickEvent clickEvent); @Override void init(final NameAndUrlPopoverView.Presenter presenter); Consumer<DMNExternalLink> getOnExternalLinkCreated(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); @Override void show(final Optional<String> popoverTitle); }### Answer: @Test public void testClear() { attachmentNameInput.value = "old"; urlInput.value = "old value"; popover.clear(); assertEquals("", attachmentNameInput.value); assertEquals("", urlInput.value); }
### Question: NameAndUriPopoverImpl extends AbstractPopoverImpl<NameAndUrlPopoverView, NameAndUrlPopoverView.Presenter> implements NameAndUrlPopoverView.Presenter { @PostConstruct public void init() { view.init(this); } NameAndUriPopoverImpl(); @Inject NameAndUriPopoverImpl(final NameAndUrlPopoverView view); @PostConstruct void init(); @Override HTMLElement getElement(); @Override void setOnClosedByKeyboardCallback(final Consumer<CanBeClosedByKeyboard> callback); @Override void show(); @Override void hide(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); }### Answer: @Test public void testInit() { popover.init(); verify(view).init(popover); }
### Question: NameAndUriPopoverImpl extends AbstractPopoverImpl<NameAndUrlPopoverView, NameAndUrlPopoverView.Presenter> implements NameAndUrlPopoverView.Presenter { @Override public HTMLElement getElement() { return view.getElement(); } NameAndUriPopoverImpl(); @Inject NameAndUriPopoverImpl(final NameAndUrlPopoverView view); @PostConstruct void init(); @Override HTMLElement getElement(); @Override void setOnClosedByKeyboardCallback(final Consumer<CanBeClosedByKeyboard> callback); @Override void show(); @Override void hide(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); }### Answer: @Test public void testGetElement() { final HTMLElement element = mock(HTMLElement.class); when(view.getElement()).thenReturn(element); final HTMLElement actual = popover.getElement(); assertEquals(element, actual); }
### Question: NameAndUriPopoverImpl extends AbstractPopoverImpl<NameAndUrlPopoverView, NameAndUrlPopoverView.Presenter> implements NameAndUrlPopoverView.Presenter { @Override public void show() { view.show(Optional.ofNullable(getPopoverTitle())); } NameAndUriPopoverImpl(); @Inject NameAndUriPopoverImpl(final NameAndUrlPopoverView view); @PostConstruct void init(); @Override HTMLElement getElement(); @Override void setOnClosedByKeyboardCallback(final Consumer<CanBeClosedByKeyboard> callback); @Override void show(); @Override void hide(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); }### Answer: @Test public void testShow() { popover.show(); verify(view).show(Optional.ofNullable(popover.getPopoverTitle())); }
### Question: NameAndUriPopoverImpl extends AbstractPopoverImpl<NameAndUrlPopoverView, NameAndUrlPopoverView.Presenter> implements NameAndUrlPopoverView.Presenter { @Override public void hide() { view.hide(); } NameAndUriPopoverImpl(); @Inject NameAndUriPopoverImpl(final NameAndUrlPopoverView view); @PostConstruct void init(); @Override HTMLElement getElement(); @Override void setOnClosedByKeyboardCallback(final Consumer<CanBeClosedByKeyboard> callback); @Override void show(); @Override void hide(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); }### Answer: @Test public void testHide() { popover.hide(); verify(view).hide(); }
### Question: NameAndUriPopoverImpl extends AbstractPopoverImpl<NameAndUrlPopoverView, NameAndUrlPopoverView.Presenter> implements NameAndUrlPopoverView.Presenter { @Override public void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated) { view.setOnExternalLinkCreated(onExternalLinkCreated); } NameAndUriPopoverImpl(); @Inject NameAndUriPopoverImpl(final NameAndUrlPopoverView view); @PostConstruct void init(); @Override HTMLElement getElement(); @Override void setOnClosedByKeyboardCallback(final Consumer<CanBeClosedByKeyboard> callback); @Override void show(); @Override void hide(); @Override void setOnExternalLinkCreated(final Consumer<DMNExternalLink> onExternalLinkCreated); }### Answer: @Test public void testSetOnExternalLinkCreated() { final Consumer<DMNExternalLink> consumer = mock(Consumer.class); popover.setOnExternalLinkCreated(consumer); verify(view).setOnExternalLinkCreated(consumer); }
### Question: DMNDocumentationView extends DefaultDiagramDocumentationView { @Override public DocumentationView<Diagram> refresh() { refreshDocumentationHTML(); refreshDocumentationHTMLAfter200ms(); if (!buttonsVisibilitySupplier.isButtonsVisible()) { hide(printButton); hide(downloadHtmlFile); } return this; } @Inject DMNDocumentationView(final HTMLDivElement documentationPanel, final HTMLDivElement documentationContent, final HTMLButtonElement printButton, final HTMLButtonElement downloadHtmlFile, final PrintHelper printHelper, final DMNDocumentationService documentationService, final HTMLDownloadHelper downloadHelper, final DMNDocumentationViewButtonsVisibilitySupplier buttonsVisibilitySupplier); @Override DocumentationView<Diagram> refresh(); @Override boolean isEnabled(); @EventHandler("print-button") void onPrintButtonClick(final ClickEvent e); @EventHandler("download-html-file") void onDownloadHtmlFile(final ClickEvent e); }### Answer: @Test public void testRefresh() { doNothing().when(view).setTimeout(any(), anyInt()); when(buttonsVisibilitySupplier.isButtonsVisible()).thenReturn(true); view.refresh(); verify(downloadButtonClassList, never()).add(HiddenHelper.HIDDEN_CSS_CLASS); verify(printButtonClassList, never()).add(HiddenHelper.HIDDEN_CSS_CLASS); verify(buttonsVisibilitySupplier).isButtonsVisible(); verify(view).refreshDocumentationHTML(); verify(view).refreshDocumentationHTMLAfter200ms(); }
### Question: DMNDocumentationView extends DefaultDiagramDocumentationView { void refreshDocumentationHTML() { documentationContent.innerHTML = getDocumentationHTML(); } @Inject DMNDocumentationView(final HTMLDivElement documentationPanel, final HTMLDivElement documentationContent, final HTMLButtonElement printButton, final HTMLButtonElement downloadHtmlFile, final PrintHelper printHelper, final DMNDocumentationService documentationService, final HTMLDownloadHelper downloadHelper, final DMNDocumentationViewButtonsVisibilitySupplier buttonsVisibilitySupplier); @Override DocumentationView<Diagram> refresh(); @Override boolean isEnabled(); @EventHandler("print-button") void onPrintButtonClick(final ClickEvent e); @EventHandler("download-html-file") void onDownloadHtmlFile(final ClickEvent e); }### Answer: @Test public void testRefreshDocumentationHTMLWhenDiagramIsPresent() { final String expectedHTML = "<html />"; final DocumentationOutput output = new DocumentationOutput(expectedHTML); doReturn(Optional.of(diagram)).when(view).getDiagram(); when(documentationService.generate(diagram)).thenReturn(output); documentationContent.innerHTML = "something"; view.refreshDocumentationHTML(); final String actualHTML = documentationContent.innerHTML; assertEquals(expectedHTML, actualHTML); } @Test public void testRefreshDocumentationHTMLWhenDiagramIsNotPresent() { final String expectedHTML = EMPTY.getValue(); doReturn(Optional.empty()).when(view).getDiagram(); documentationContent.innerHTML = "something"; view.refreshDocumentationHTML(); final String actualHTML = documentationContent.innerHTML; assertEquals(expectedHTML, actualHTML); }
### Question: DMNDocumentationView extends DefaultDiagramDocumentationView { void refreshDocumentationHTMLAfter200ms() { setTimeout((w) -> refreshDocumentationHTML(), 200); } @Inject DMNDocumentationView(final HTMLDivElement documentationPanel, final HTMLDivElement documentationContent, final HTMLButtonElement printButton, final HTMLButtonElement downloadHtmlFile, final PrintHelper printHelper, final DMNDocumentationService documentationService, final HTMLDownloadHelper downloadHelper, final DMNDocumentationViewButtonsVisibilitySupplier buttonsVisibilitySupplier); @Override DocumentationView<Diagram> refresh(); @Override boolean isEnabled(); @EventHandler("print-button") void onPrintButtonClick(final ClickEvent e); @EventHandler("download-html-file") void onDownloadHtmlFile(final ClickEvent e); }### Answer: @Test public void testRefreshDocumentationHTMLAfter200ms() { doNothing().when(view).setTimeout(any(), anyInt()); view.refreshDocumentationHTMLAfter200ms(); verify(view).setTimeout(callback.capture(), eq(200)); callback.getValue().onInvoke(new Object()); verify(view).refreshDocumentationHTML(); }
### Question: DMNDocumentationView extends DefaultDiagramDocumentationView { @Override public boolean isEnabled() { return true; } @Inject DMNDocumentationView(final HTMLDivElement documentationPanel, final HTMLDivElement documentationContent, final HTMLButtonElement printButton, final HTMLButtonElement downloadHtmlFile, final PrintHelper printHelper, final DMNDocumentationService documentationService, final HTMLDownloadHelper downloadHelper, final DMNDocumentationViewButtonsVisibilitySupplier buttonsVisibilitySupplier); @Override DocumentationView<Diagram> refresh(); @Override boolean isEnabled(); @EventHandler("print-button") void onPrintButtonClick(final ClickEvent e); @EventHandler("download-html-file") void onDownloadHtmlFile(final ClickEvent e); }### Answer: @Test public void testIsEnabled() { assertTrue(view.isEnabled()); }
### Question: DMNDocumentationView extends DefaultDiagramDocumentationView { @EventHandler("print-button") public void onPrintButtonClick(final ClickEvent e) { printHelper.print(documentationContent); } @Inject DMNDocumentationView(final HTMLDivElement documentationPanel, final HTMLDivElement documentationContent, final HTMLButtonElement printButton, final HTMLButtonElement downloadHtmlFile, final PrintHelper printHelper, final DMNDocumentationService documentationService, final HTMLDownloadHelper downloadHelper, final DMNDocumentationViewButtonsVisibilitySupplier buttonsVisibilitySupplier); @Override DocumentationView<Diagram> refresh(); @Override boolean isEnabled(); @EventHandler("print-button") void onPrintButtonClick(final ClickEvent e); @EventHandler("download-html-file") void onDownloadHtmlFile(final ClickEvent e); }### Answer: @Test public void testOnPrintButtonClick() { view.onPrintButtonClick(mock(ClickEvent.class)); verify(printHelper).print(documentationContent); }
### Question: DMNDocumentationView extends DefaultDiagramDocumentationView { @EventHandler("download-html-file") public void onDownloadHtmlFile(final ClickEvent e) { final String html = getCurrentDocumentationHTML(); downloadHelper.download(getCurrentDocumentationModelName(), html); } @Inject DMNDocumentationView(final HTMLDivElement documentationPanel, final HTMLDivElement documentationContent, final HTMLButtonElement printButton, final HTMLButtonElement downloadHtmlFile, final PrintHelper printHelper, final DMNDocumentationService documentationService, final HTMLDownloadHelper downloadHelper, final DMNDocumentationViewButtonsVisibilitySupplier buttonsVisibilitySupplier); @Override DocumentationView<Diagram> refresh(); @Override boolean isEnabled(); @EventHandler("print-button") void onPrintButtonClick(final ClickEvent e); @EventHandler("download-html-file") void onDownloadHtmlFile(final ClickEvent e); }### Answer: @Test public void testOnDownloadHtmlFile() { final String html = "<html><body>Hi</body></html>"; final String modelName = "model name"; doReturn(modelName).when(view).getCurrentDocumentationModelName(); doReturn(html).when(view).getCurrentDocumentationHTML(); view.onDownloadHtmlFile(mock(ClickEvent.class)); verify(view).getCurrentDocumentationHTML(); verify(downloadHelper).download(modelName, html); }
### Question: DMNContentServiceImpl extends KieService<String> implements DMNContentService { @Override protected String constructContent(final Path path, final Overview _overview) { return getSource(path); } @Inject DMNContentServiceImpl(final CommentedOptionFactory commentedOptionFactory, final DMNIOHelper dmnIOHelper, final DMNPathsHelper pathsHelper, final PMMLIncludedDocumentFactory pmmlIncludedDocumentFactory); @Override String getContent(final Path path); @Override DMNContentResource getProjectContent(final Path path, final String defSetId); @Override void saveContent(final Path path, final String content, final Metadata metadata, final String comment); @Override List<Path> getModelsPaths(final WorkspaceProject workspaceProject); @Override List<Path> getDMNModelsPaths(final WorkspaceProject workspaceProject); @Override List<Path> getPMMLModelsPaths(final WorkspaceProject workspaceProject); @Override PMMLDocumentMetadata loadPMMLDocumentMetadata(final Path path); @Override String getSource(final Path path); }### Answer: @Test public void constructContent() { service.constructContent(path, null); final String actual = "<xml/>"; doReturn(actual).when(service).getSource(path); final String expected = service.constructContent(path, null); assertEquals(expected, actual); }
### Question: RoomResourceTemplate implements RoomResource { @Override public List<Room> listRooms() { return Arrays.asList(restTemplate.getForEntity("https: } RoomResourceTemplate(final RestTemplate restTemplate); @Override List<Room> listRooms(); }### Answer: @Test void listRooms() { mockServer.expect(requestTo("https: .andExpect(method(GET)) .andRespond(withSuccess(new ClassPathResource("/room/rooms.json", getClass()), APPLICATION_JSON)); final List<Room> rooms = roomResource.listRooms(); assertThat(rooms).isEqualTo(RoomMother.rooms()); }
### Question: CoinMarketCapClientImpl implements CoinMarketCapClient { @Override public CmcListingsResult getListings() { return restTemplate.getForObject(endpoint + "/v1/cryptocurrency/listings/latest?limit=5000", CmcListingsResult.class); } CoinMarketCapClientImpl(@Value("${coinmarketcap.apikey}") String apiKey); @Override CmcListingsResult getListings(); }### Answer: @Test void getListings() { CmcListingsResult listings = client.getListings(); assertThat(listings).isNotNull(); }
### Question: CryptoCompareClientImpl implements CryptoCompareClient { public PriceResultDto getPrice(String symbol) { return restTemplate.getForObject(endpoint + "/data/price?fsym={symbol}&tsyms=USD", PriceResultDto.class, symbol); } CryptoCompareClientImpl(@Value("${cryptocompare.apikey}") String apiKey); PriceResultDto getPrice(String symbol); }### Answer: @Test void getPrice() { PriceResultDto result = client.getPrice("DAI"); System.out.println(result); }
### Question: UpdateRequestLastModifiedDateOnFundedHandler { @EventListener public void handle(final RequestFundedEvent event) { final Request request = requestRepository.findOne(event.getRequestId()) .orElseThrow(() -> new RuntimeException("Unable to find request")); request.setLastModifiedDate(LocalDateTime.now()); requestRepository.saveAndFlush(request); } UpdateRequestLastModifiedDateOnFundedHandler(final RequestRepository requestRepository); @EventListener void handle(final RequestFundedEvent event); }### Answer: @Test void handle_updateLastModifiedDate() { final long requestId = 6578L; final RequestFundedEvent event = RequestFundedEvent.builder().requestId(requestId).build(); final Request request = RequestMother.fundRequestArea51() .withLastModifiedDate(LocalDateTime.now().minusWeeks(3)) .build(); when(requestRepository.findOne(requestId)).thenReturn(Optional.of(request)); handler.handle(event); assertThat(request.getLastModifiedDate()).isEqualToIgnoringSeconds(LocalDateTime.now()); verify(requestRepository).saveAndFlush(request); } @Test void handle_requestNotFound() { final long requestId = 234; final RequestFundedEvent event = RequestFundedEvent.builder().requestId(requestId).build(); when(requestRepository.findOne(requestId)).thenReturn(Optional.empty()); try { handler.handle(event); fail("Expected new RuntimeException(\"Unable to find request\") to be thrown"); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("Unable to find request"); } }
### Question: ChangeRequestStatusOnFundedHandler { @EventListener public void handle(final RequestFundedEvent event) { final Request request = requestRepository.findOne(event.getRequestId()) .orElseThrow(() -> new RuntimeException("Unable to find request")); if (RequestStatus.OPEN == request.getStatus()) { request.setStatus(RequestStatus.FUNDED); requestRepository.saveAndFlush(request); } } ChangeRequestStatusOnFundedHandler(final RequestRepository requestRepository); @EventListener void handle(final RequestFundedEvent event); }### Answer: @Test void handle_requestOPEN() { final long requestId = 6578L; final RequestFundedEvent event = RequestFundedEvent.builder().requestId(requestId).build(); final Request request = RequestMother.fundRequestArea51().withStatus(OPEN).build(); when(requestRepository.findOne(requestId)).thenReturn(Optional.of(request)); handler.handle(event); assertThat(request.getStatus()).isEqualTo(FUNDED); verify(requestRepository).saveAndFlush(request); } @Test void handle_requestNotFound() { final long requestId = 908978; final RequestFundedEvent event = RequestFundedEvent.builder().requestId(requestId).build(); when(requestRepository.findOne(requestId)).thenReturn(Optional.empty()); try { handler.handle(event); fail("Expected new RuntimeException(\"Unable to find request\") to be thrown"); } catch (RuntimeException e) { assertThat(e.getMessage()).isEqualTo("Unable to find request"); } }
### Question: GithubPlatformIdParser { public IssueInformation parseIssue(String platformId) { IssueInformation issueInformation = IssueInformation.builder().build(); String[] splitted = platformId.split(Pattern.quote(PLATFORM_ID_GITHUB_DELIMTER)); issueInformation.setOwner(splitted[0]); issueInformation.setRepo(splitted[1]); issueInformation.setNumber(splitted[2]); GithubResult githubResult = githubGateway.getIssue( issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber() ); issueInformation.setTitle(githubResult.getTitle()); issueInformation.setPlatform(Platform.GITHUB); issueInformation.setPlatformId(platformId); return issueInformation; } GithubPlatformIdParser(GithubGateway githubGateway); static String extractOwner(final String platformId); static String extractRepo(String platformId); static String extractIssueNumber(final String platformId); IssueInformation parseIssue(String platformId); static final String PLATFORM_ID_GITHUB_DELIMTER; }### Answer: @Test public void parseIssueInformation() throws Exception { GithubResult githubResult = GithubResultMother.kazuki43zooApiStub42().build(); String owner = "kazuki43zoo"; String repo = "api-stub"; String number = "42"; when(githubGateway.getIssue(owner, repo, number)) .thenReturn(githubResult); String platformId = owner + PLATFORM_ID_GITHUB_DELIMTER + repo + PLATFORM_ID_GITHUB_DELIMTER + number; IssueInformation result = parser.parseIssue(platformId); assertThat(result.getNumber()).isEqualTo(number); assertThat(result.getOwner()).isEqualTo(owner); assertThat(result.getRepo()).isEqualTo(repo); assertThat(result.getTitle()).isEqualTo(githubResult.getTitle()); assertThat(result.getPlatform()).isEqualTo(Platform.GITHUB); assertThat(result.getPlatformId()).isEqualTo(platformId); }
### Question: GithubPlatformIdParser { public static String extractOwner(final String platformId) { return extract(platformId, OWNER_GROUP_NAME); } GithubPlatformIdParser(GithubGateway githubGateway); static String extractOwner(final String platformId); static String extractRepo(String platformId); static String extractIssueNumber(final String platformId); IssueInformation parseIssue(String platformId); static final String PLATFORM_ID_GITHUB_DELIMTER; }### Answer: @Test public void extractOwner() { final String owner = "sgsgsg"; final String repo = "utyejy"; final String issueNumber = "6453"; final String result = GithubPlatformIdParser.extractOwner(owner + "|FR|" + repo + "|FR|" + issueNumber); assertThat(result).isEqualTo(owner); } @Test public void extractOwner_invalidPlatformId() { final String platformId = "sgsgsg|FR|utyejy"; assertThatIllegalArgumentException().isThrownBy(() -> GithubPlatformIdParser.extractOwner(platformId)) .withMessage("platformId '" + platformId + "' has an invalid format, <owner> could not be extracted"); }
### Question: GithubPlatformIdParser { public static String extractRepo(String platformId) { return extract(platformId, REPO_GROUP_NAME); } GithubPlatformIdParser(GithubGateway githubGateway); static String extractOwner(final String platformId); static String extractRepo(String platformId); static String extractIssueNumber(final String platformId); IssueInformation parseIssue(String platformId); static final String PLATFORM_ID_GITHUB_DELIMTER; }### Answer: @Test public void extractRepo() { final String owner = "sgsgsg"; final String repo = "utyejy"; final String issueNumber = "6453"; final String result = GithubPlatformIdParser.extractRepo(owner + "|FR|" + repo + "|FR|" + issueNumber); assertThat(result).isEqualTo(repo); } @Test public void extractRepo_invalidPlatformId() { final String platformId = "sgsgsg|FR|utyejy"; assertThatIllegalArgumentException().isThrownBy(() -> GithubPlatformIdParser.extractRepo(platformId)) .withMessage("platformId '" + platformId + "' has an invalid format, <repo> could not be extracted"); }
### Question: GithubPlatformIdParser { public static String extractIssueNumber(final String platformId) { return extract(platformId, ISSUE_NUMBER_GROUP_NAME); } GithubPlatformIdParser(GithubGateway githubGateway); static String extractOwner(final String platformId); static String extractRepo(String platformId); static String extractIssueNumber(final String platformId); IssueInformation parseIssue(String platformId); static final String PLATFORM_ID_GITHUB_DELIMTER; }### Answer: @Test public void extractIssueNumber() { final String owner = "sgsgsg"; final String repo = "utyejy"; final String issueNumber = "6453"; final String result = GithubPlatformIdParser.extractIssueNumber(owner + "|FR|" + repo + "|FR|" + issueNumber); assertThat(result).isEqualTo(issueNumber); } @Test public void extractIssueNumber_invalidPlatformId() { final String platformId = "sgsgsg|FR|utyejy"; assertThatIllegalArgumentException().isThrownBy(() -> GithubPlatformIdParser.extractIssueNumber(platformId)) .withMessage("platformId '" + platformId + "' has an invalid format, <issueNumber> could not be extracted"); }
### Question: BlockchainEventServiceImpl implements BlockchainEventService { @Override public Optional<BlockchainEventDto> findOne(final Long id) { return mapper.mapToOptional(blockchainEventRepo.findOne(id).orElse(null)); } BlockchainEventServiceImpl(final BlockchainEventRepository blockchainEventRepo, final BlockchainEventDtoMapper mapper); @Override Optional<BlockchainEventDto> findOne(final Long id); }### Answer: @Test void findOne() { final long blockcheinEventId = 7546L; final BlockchainEvent blockchainEvent = mock(BlockchainEvent.class); final BlockchainEventDto blockchainEventDto = mock(BlockchainEventDto.class); when(blockchainEventRepo.findOne(blockcheinEventId)).thenReturn(Optional.of(blockchainEvent)); when(mapper.mapToOptional(same(blockchainEvent))).thenReturn(Optional.of(blockchainEventDto)); final Optional<BlockchainEventDto> result = service.findOne(blockcheinEventId); assertThat(result).containsSame(blockchainEventDto); } @Test void findOne_notFound() { final long blockcheinEventId = 7546L; when(blockchainEventRepo.findOne(blockcheinEventId)).thenReturn(Optional.empty()); when(mapper.mapToOptional(null)).thenReturn(Optional.empty()); final Optional<BlockchainEventDto> result = service.findOne(blockcheinEventId); assertThat(result).isEmpty(); }
### Question: Request extends AbstractEntity { public Set<String> getTechnologies() { return this.technologies != null && !this.technologies.isEmpty() ? this.technologies.stream() .map(RequestTechnology::getTechnology) .collect(Collectors.toSet()) : new HashSet<>(); } protected Request(); void setStatus(RequestStatus status); Long getId(); RequestStatus getStatus(); RequestType getType(); IssueInformation getIssueInformation(); void setIssueInformation(IssueInformation issueInformation); void addWatcher(String email); void removeWatcher(String email); Set<String> getWatchers(); void addTechnology(RequestTechnology requestTechnology); Set<String> getTechnologies(); @Override void setLastModifiedDate(final LocalDateTime lastModifiedDate); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void getTechnologies() { Set<RequestTechnology> technologies = new HashSet<>(); technologies.add(RequestTechnology.builder().technology("python").weight(2L).build()); technologies.add(RequestTechnology.builder().technology("kotlin").weight(3L).build()); technologies.add(RequestTechnology.builder().technology("html").weight(4L).build()); technologies.add(RequestTechnology.builder().technology("css").weight(5L).build()); Request request = RequestMother.fundRequestArea51().withTechnologies(technologies).build(); assertThat(request.getTechnologies()).containsExactlyInAnyOrder("python", "kotlin", "html", "css"); }
### Question: Request extends AbstractEntity { @Override public void setLastModifiedDate(final LocalDateTime lastModifiedDate) { super.setLastModifiedDate(lastModifiedDate); } protected Request(); void setStatus(RequestStatus status); Long getId(); RequestStatus getStatus(); RequestType getType(); IssueInformation getIssueInformation(); void setIssueInformation(IssueInformation issueInformation); void addWatcher(String email); void removeWatcher(String email); Set<String> getWatchers(); void addTechnology(RequestTechnology requestTechnology); Set<String> getTechnologies(); @Override void setLastModifiedDate(final LocalDateTime lastModifiedDate); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void setLastModifiedDate() { final LocalDateTime expectedLastModifiedDate = LocalDateTime.now().minusDays(3); final Request request = RequestMother.fundRequestArea51().build(); request.setLastModifiedDate(expectedLastModifiedDate); assertThat(request.getLastModifiedDate()).isEqualTo(expectedLastModifiedDate); }
### Question: MessagesController extends AbstractController { @RequestMapping("/messages") public ModelAndView showAllMessagesPage(final Model model) { model.addAttribute("referralMessages", messageService.getMessagesByType(MessageType.REFERRAL_SHARE)); return new ModelAndView("messages/index"); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void showAllMessagesPage() throws Exception { MessageDto messageDto1 = mock(MessageDto.class); MessageDto messageDto2 = mock(MessageDto.class); MessageDto messageDto3 = mock(MessageDto.class); List<MessageDto> messages = Arrays.asList(messageDto1, messageDto2, messageDto3); when(messageService.getMessagesByType(MessageType.REFERRAL_SHARE)).thenReturn(messages); this.mockMvc.perform(get("/messages")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.model().attribute("referralMessages", messages)) .andExpect(MockMvcResultMatchers.view().name("messages/index")); }
### Question: CommentDtoMapperDecorator implements CommentDtoMapper { @Override public CommentDto map(GithubIssueCommentsResult in) { CommentDto comment = delegate.map(in); if (comment != null) { comment.setUserName(in.getUser().getLogin()); comment.setUserUrl(in.getUser().getUrl()); comment.setUserAvatar(in.getUser().getAvatarUrl()); } return comment; } @Override CommentDto map(GithubIssueCommentsResult in); }### Answer: @Test public void maps() { final String login = "davyvanroy"; final String userUrl = "fxghcgjv"; final String userAvatarUrl = "fgjhkj"; when(delegate.map(any())).thenReturn(CommentDto.builder().build()); final CommentDto result = decorator.map(GithubIssueCommentsResult.builder() .user(GithubUser.builder() .login(login) .url(userUrl) .avatarUrl(userAvatarUrl) .build()) .build()); assertThat(result.getUserName()).isEqualTo(login); assertThat(result.getUserUrl()).isEqualTo(userUrl); assertThat(result.getUserAvatar()).isEqualTo(userAvatarUrl); }
### Question: UserFundsDto { public boolean hasRefunds() { return fndRefunds != null || otherRefunds != null; } boolean hasRefunds(); }### Answer: @Test void hasRefunds_noRefunds() { assertThat(UserFundsDto.builder().build().hasRefunds()).isFalse(); } @Test void hasRefunds_fndRefunds() { assertThat(UserFundsDto.builder().fndRefunds(TokenValueDto.builder().build()).build().hasRefunds()).isTrue(); } @Test void hasRefunds_otherRefunds() { assertThat(UserFundsDto.builder().otherRefunds(TokenValueDto.builder().build()).build().hasRefunds()).isTrue(); } @Test void hasRefunds_fndAndOtherRefunds() { assertThat(UserFundsDto.builder().fndRefunds(TokenValueDto.builder().build()).otherRefunds(TokenValueDto.builder().build()).build().hasRefunds()).isTrue(); }
### Question: PublishRequestClaimedNotificationHandler { @TransactionalEventListener public void onClaimed(final RequestClaimedEvent claimedEvent) { eventPublisher.publishEvent(RequestClaimedNotificationDto.builder() .blockchainEventId(claimedEvent.getBlockchainEventId()) .date(claimedEvent.getTimestamp()) .requestId(claimedEvent.getRequestDto().getId()) .claimId(claimedEvent.getClaimDto().getId()) .build()); } PublishRequestClaimedNotificationHandler(final ApplicationEventPublisher eventPublisher); @TransactionalEventListener void onClaimed(final RequestClaimedEvent claimedEvent); }### Answer: @Test void onClaimed() { final RequestClaimedEvent claimedEvent = RequestClaimedEvent.builder() .claimDto(ClaimDtoMother.aClaimDto().build()) .timestamp(LocalDateTime.now()) .blockchainEventId(24L) .requestDto(RequestDtoMother.fundRequestArea51()) .solver("sbsgdb") .build(); final RequestClaimedNotificationDto expected = RequestClaimedNotificationDto.builder() .blockchainEventId(claimedEvent.getBlockchainEventId()) .date(claimedEvent.getTimestamp()) .requestId(claimedEvent.getRequestDto().getId()) .claimId(claimedEvent.getClaimDto().getId()) .build(); eventHandler.onClaimed(claimedEvent); verify(eventPublisher).publishEvent(refEq(expected, "uuid")); }
### Question: MessagesController extends AbstractController { @RequestMapping("/messages/{type}/add") public ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type) { model.addAttribute("message", MessageDto.builder().type(MessageType.valueOf(type)).build()); return new ModelAndView("messages/add"); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void showAddMessageToTypePage() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); this.mockMvc.perform(get("/messages/{type}/add", type)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.model().attribute("message", MessageDto.builder().type(MessageType.valueOf(type)).build())) .andExpect(MockMvcResultMatchers.view().name("messages/add")); }
### Question: PublishRequestFundedNotificationHandler { @TransactionalEventListener public void onFunded(final RequestFundedEvent fundedEvent) { eventPublisher.publishEvent(new RequestFundedNotificationDto(fundedEvent.getFundDto().getBlockchainEventId(), fundedEvent.getTimestamp(), fundedEvent.getRequestId(), fundedEvent.getFundDto().getId())); } PublishRequestFundedNotificationHandler(final ApplicationEventPublisher eventPublisher); @TransactionalEventListener void onFunded(final RequestFundedEvent fundedEvent); }### Answer: @Test public void onFunded() { final RequestFundedEvent fundedEvent = RequestFundedEvent.builder() .fundDto(FundDtoMother.aFundDto().build()) .timestamp(LocalDateTime.now()) .requestId(35L).build(); final RequestFundedNotificationDto expected = RequestFundedNotificationDto.builder() .blockchainEventId(fundedEvent.getFundDto().getBlockchainEventId()) .date(fundedEvent.getTimestamp()) .requestId(fundedEvent.getRequestId()) .fundId(fundedEvent.getFundDto().getId()) .build(); eventHandler.onFunded(fundedEvent); verify(applicationEventPublisher).publishEvent(refEq(expected, "uuid")); }
### Question: RefundServiceImpl implements RefundService { @Override @Transactional public void requestRefund(final RequestRefundCommand requestRefundCommand) { refundRequestRepository.save(RefundRequest.builder() .requestId(requestRefundCommand.getRequestId()) .funderAddress(requestRefundCommand.getFunderAddress()) .requestedBy(requestRefundCommand.getRequestedBy()) .build()); } RefundServiceImpl(final RefundRequestRepository refundRequestRepository, final RefundRepository refundRepository, final RefundRequestDtoMapper refundRequestDtoMapper, final CacheManager cacheManager, final ApplicationEventPublisher applicationEventPublisher); @Override @Transactional void requestRefund(final RequestRefundCommand requestRefundCommand); @Override @Transactional(readOnly = true) List<RefundRequestDto> findAllRefundRequestsFor(final long requestId, final RefundRequestStatus... statuses); @Override @Transactional(readOnly = true) List<RefundRequestDto> findAllRefundRequestsFor(final long requestId, final String funderAddress, final RefundRequestStatus status); @Override @Transactional void refundProcessed(final RefundProcessedCommand command); }### Answer: @Test void requestRefund() { final long requestId = 547L; final String funderAddress = "hjfgkh"; final String requestedBy = "4567gjfh"; refundService.requestRefund(RequestRefundCommand.builder().requestId(requestId).funderAddress(funderAddress).requestedBy(requestedBy).build()); verify(refundRequestRepository).save(refEq(RefundRequest.builder() .requestId(requestId) .funderAddress(funderAddress) .requestedBy(requestedBy) .build())); }
### Question: MessagesController extends AbstractController { @RequestMapping("/messages/{type}/{name}/edit") public ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name) { model.addAttribute("message", messageService.getMessageByTypeAndName(MessageType.valueOf(type.toUpperCase()), name)); return new ModelAndView("messages/edit"); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void showEditPage() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); String name = "name"; MessageDto messageDto = mock(MessageDto.class); when(messageService.getMessageByTypeAndName(MessageType.REFERRAL_SHARE, name)).thenReturn(messageDto); this.mockMvc.perform(get("/messages/{type}/{name}/edit", type, name)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.model().attribute("message", messageDto)) .andExpect(MockMvcResultMatchers.view().name("messages/edit")); }
### Question: GetAllPossibleTokensKeyGenerator implements KeyGenerator { @Override public Object generate(final Object target, final Method method, final Object... params) { final String platform = (String) params[0]; if (Platform.GITHUB.name().equalsIgnoreCase(platform)) { return generateGitHubKey(platform, (String) params[1]); } return fallbackKeyGenerator.generate(target, method, params); } GetAllPossibleTokensKeyGenerator(final KeyGenerator simpleKeyGenerator); @Override Object generate(final Object target, final Method method, final Object... params); }### Answer: @Test void generate_GitHubKey() { final String owner = "sgfgs"; final String repo = "szgff"; final String platform = Platform.GITHUB.name(); final String result = (String) keyGenerator.generate(randomTarget, randomMethod, platform, owner + "|FR|" + repo + "|FR|435"); assertThat(result).isEqualTo(platform + "-" + owner + "-" + repo); } @Test void generate_OtherPlatformKey() { final String platform = Platform.STACK_OVERFLOW.name(); final String platformId = "sgfgasfdgshd5"; final String expected = "someKey"; when(fallbackKeyGenerator.generate(randomTarget, randomMethod, platform, platformId)).thenReturn(expected); final String result = (String) keyGenerator.generate(randomTarget, randomMethod, platform, platformId); assertThat(result).isEqualTo(expected); }
### Question: TweetRequestFundedHandler { @EventListener @Async("taskExecutor") @Transactional(readOnly = true, propagation = REQUIRES_NEW) public void handle(final RequestFundedNotificationDto notification) { final FundDto fund = fundService.findOne(notification.getFundId()); Context context = new Context(); context.setVariable("platformBasePath", platformBasePath); context.setVariable("fund", fund); final String message = githubTemplateEngine.process("notification-templates/request-funded-tweet", context); tweetOnFundTwitterTemplate.timelineOperations().updateStatus(message); } TweetRequestFundedHandler(final Twitter tweetOnFundTwitterTemplate, final ITemplateEngine githubTemplateEngine, final FundService fundService, @Value("${io.fundrequest.platform.base-path}") final String platformBasePath); @EventListener @Async("taskExecutor") @Transactional(readOnly = true, propagation = REQUIRES_NEW) void handle(final RequestFundedNotificationDto notification); }### Answer: @Test public void handle() { long fundId = 243L; long requestId = 764L; final String message = "ewfegdbf"; final RequestFundedNotificationDto notification = RequestFundedNotificationDto.builder().fundId(fundId).requestId(requestId).build(); final TokenValueDto tokenValue = TokenValueDtoMother.FND().build(); final FundDto fund = FundDto.builder().tokenValue(tokenValue).build(); final Context context = new Context(); context.setVariable("platformBasePath", platformBasePath); context.setVariable("fund", fund); when(fundService.findOne(fundId)).thenReturn(fund); when(githubTemplateEngine.process(eq("notification-templates/request-funded-tweet"), refEq(context, "locale"))).thenReturn(message); handler.handle(notification); verify(twitter.timelineOperations()).updateStatus(message); }
### Question: PersistNotificationHandler { @EventListener @Transactional(propagation = REQUIRES_NEW) public void handle(final RequestFundedNotificationDto notification) { notificationRepository.save(requestFundedNotificationMapper.map(notification)); } PersistNotificationHandler(final NotificationRepository notificationRepository, final RequestFundedNotificationMapper requestFundedNotificationMapper, final RequestClaimedNotificationMapper requestClaimedNotificationMapper); @EventListener @Transactional(propagation = REQUIRES_NEW) void handle(final RequestFundedNotificationDto notification); @EventListener @Transactional(propagation = REQUIRES_NEW) void handle(final RequestClaimedNotificationDto notification); }### Answer: @Test void handleRequestFunded() { final RequestFundedNotificationDto notificationDto = RequestFundedNotificationDto.builder().build(); final RequestFundedNotification notification = RequestFundedNotificationMother.aRequestFundedNotification(); when(requestFundedNotificationMapper.map(same(notificationDto))).thenReturn(notification); handler.handle(notificationDto); verify(notificationRepository).save(same(notification)); } @Test void handleRequestClaimed() { final RequestClaimedNotificationDto notificationDto = RequestClaimedNotificationDto.builder().build(); final RequestClaimedNotification notification = RequestClaimedNotificationMother.aRequestClaimedNotification(); when(requestClaimedNotificationMapper.map(same(notificationDto))).thenReturn(notification); handler.handle(notificationDto); verify(notificationRepository).save(same(notification)); }
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/add") public ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes) { MessageDto messageDto = MessageDto.builder() .name(request.getParameter("name")) .type(MessageType.valueOf(type.toUpperCase())) .title(request.getParameter("title")) .description(request.getParameter("description")) .link(request.getParameter("link")) .build(); messageService.add(messageDto); return redirectView(redirectAttributes) .withSuccessMessage("Message added") .url("/messages/" + type) .build(); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void add() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); this.mockMvc.perform(post("/messages/{type}/add", type)) .andExpect(redirectAlert("success", "Message added")) .andExpect(redirectedUrl("/messages/" + type)); }
### Question: ThymeleafSvgConfig implements ApplicationContextAware { @Bean public ITemplateResolver svgTemplateResolver() { final SpringResourceTemplateResolver svgTemplateResolver = new SpringResourceTemplateResolver(); svgTemplateResolver.setApplicationContext(applicationContext); svgTemplateResolver.setPrefix("classpath:/templates/svg/"); svgTemplateResolver.setTemplateMode(TemplateMode.XML); svgTemplateResolver.setCharacterEncoding("UTF-8"); svgTemplateResolver.setOrder(0); svgTemplateResolver.setCheckExistence(true); return svgTemplateResolver; } @Bean ITemplateResolver svgTemplateResolver(); @Bean ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine); @Override void setApplicationContext(final ApplicationContext applicationContext); }### Answer: @Test public void svgTemplateResolver() { final ApplicationContext applicationContext = mock(ApplicationContext.class); config.setApplicationContext(applicationContext); final SpringResourceTemplateResolver templateResolver = (SpringResourceTemplateResolver) config.svgTemplateResolver(); assertThat(templateResolver).hasFieldOrPropertyWithValue("applicationContext", applicationContext); assertThat(templateResolver.getPrefix()).isEqualTo("classpath:/templates/svg/"); assertThat(templateResolver.getTemplateMode()).isEqualTo(TemplateMode.XML); assertThat(templateResolver.getCharacterEncoding()).isEqualTo("UTF-8"); }
### Question: ThymeleafSvgConfig implements ApplicationContextAware { @Bean public ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine) { final ThymeleafViewResolver thymeleafViewResolver = new ThymeleafViewResolver(); thymeleafViewResolver.setTemplateEngine(templateEngine); thymeleafViewResolver.setOrder(0); thymeleafViewResolver.setCharacterEncoding("UTF-8"); thymeleafViewResolver.setContentType("image/svg+xml"); thymeleafViewResolver.setViewNames(new String[] {"*.svg"}); return thymeleafViewResolver; } @Bean ITemplateResolver svgTemplateResolver(); @Bean ThymeleafViewResolver svgViewResolver(final SpringTemplateEngine templateEngine); @Override void setApplicationContext(final ApplicationContext applicationContext); }### Answer: @Test public void svgViewResolver() { final SpringTemplateEngine templateEngine = mock(SpringTemplateEngine.class); final ThymeleafViewResolver viewResolver = config.svgViewResolver(templateEngine); assertThat(viewResolver.getTemplateEngine()).isEqualTo(templateEngine); assertThat(viewResolver.getOrder()).isEqualTo(0); assertThat(viewResolver.getCharacterEncoding()).isEqualTo("UTF-8"); assertThat(viewResolver.getContentType()).isEqualTo("image/svg+xml"); assertThat(viewResolver.getViewNames()).isEqualTo(new String[] {"*.svg"}); }
### Question: ProfileController { @PostMapping("/profile/headline") public ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline) { profileService.updateHeadline(principal, headline); return redirectToProfile(); } ProfileController(final ApplicationEventPublisher eventPublisher, final ProfileService profileService, final MessageService messageService, final ReferralService referralService, final GithubBountyService githubBountyService, final @Value("${network.arkane.environment}") String arkaneEnvironment, final StackOverflowBountyService stackOverflowBountyService); @GetMapping("/profile") ModelAndView showProfile(Principal principal); @GetMapping("/profile/link/{provider}") ModelAndView linkProfile(@PathVariable String provider, HttpServletRequest request, Principal principal, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); @GetMapping("/profile/managewallets") ModelAndView manageWallets(Principal principal, HttpServletRequest request); @PostMapping("/profile/headline") ModelAndView updateHeadline(Principal principal, @RequestParam("headline") String headline); @GetMapping("/profile/link/{provider}/redirect") ModelAndView redirectToHereAfterProfileLink(Principal principal, @PathVariable("provider") String provider, @RequestParam(value = "redirectUrl", required = false) String redirectUrl); }### Answer: @Test void updateHeadline() throws Exception { KeycloakAuthenticationToken principal = mock(KeycloakAuthenticationToken.class); when(profileService.getArkaneAccessToken(principal)).thenReturn("token"); mockMvc.perform(post("/profile/headline") .param("headline", "headline") .principal(principal)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/profile")); verify(profileService).updateHeadline(principal, "headline"); }
### Question: FundrequestExpressionObjectFactory implements IExpressionObjectFactory { @Override public Set<String> getAllExpressionObjectNames() { return expressionObjectsMap.keySet(); } FundrequestExpressionObjectFactory(final Map<String, Object> expressionObjectsMap); @Override Set<String> getAllExpressionObjectNames(); @Override Object buildObject(IExpressionContext context, String expressionObjectName); @Override boolean isCacheable(String expressionObjectName); }### Answer: @Test void getAllExpressionObjectNames() { assertThat(objectFactory.getAllExpressionObjectNames()).containsExactlyInAnyOrder(expressionObjectsMap.keySet().toArray(new String[0])); }
### Question: FundrequestDialect extends AbstractDialect implements IExpressionObjectDialect { @Override public IExpressionObjectFactory getExpressionObjectFactory() { return fundrequestExpressionObjectFactory; } FundrequestDialect(final IExpressionObjectFactory fundrequestExpressionObjectFactory); @Override IExpressionObjectFactory getExpressionObjectFactory(); }### Answer: @Test void getExpressionObjectFactory() { assertThat(fundrequestDialect.getExpressionObjectFactory()).isSameAs(fundrequestExpressionObjectFactory); }
### Question: ProfilesExpressionObject { public Optional<UserProfile> findByUserId(final String userId) { try { return StringUtils.isBlank(userId) ? Optional.empty() : Optional.ofNullable(profileService.getNonLoggedInUserProfile(userId)); } catch (Exception e) { LOGGER.error("Error getting profile for: \"" + userId + "\"", e); return Optional.empty(); } } ProfilesExpressionObject(final ProfileService profileService); Optional<UserProfile> findByUserId(final String userId); Function<UserProfile, String> getName(); }### Answer: @Test public void findByUserId() { final UserProfile expected = mock(UserProfile.class); Principal principal = PrincipalMother.davyvanroy(); when(profileService.getNonLoggedInUserProfile(principal.getName())).thenReturn(expected); final Optional<UserProfile> result = profiles.findByUserId(principal.getName()); assertThat(result).contains(expected); } @Test public void findByUserId_profileNull() { final String userId = "hgj"; when(profileService.getUserProfile(() -> userId)).thenReturn(null); final Optional<UserProfile> result = profiles.findByUserId(userId); assertThat(result).isEmpty(); } @Test public void findByUserId_inputNull() { final Optional<UserProfile> result = profiles.findByUserId(null); verifyZeroInteractions(profileService); assertThat(result).isEmpty(); }
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/{name}/edit") public ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes) { MessageDto messageDto = MessageDto.builder() .name(name) .type(MessageType.valueOf(type.toUpperCase())) .title(request.getParameter("title")) .description(request.getParameter("description")) .link(request.getParameter("link")) .build(); messageService.update(messageDto); return redirectView(redirectAttributes) .withSuccessMessage("Saved") .url("/messages/" + type) .build(); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void update() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); String name = "name"; this.mockMvc.perform(post("/messages/{type}/{name}/edit", type, name)) .andExpect(redirectAlert("success", "Saved")) .andExpect(redirectedUrl("/messages/" + type)); }
### Question: ProfilesExpressionObject { public Function<UserProfile, String> getName() { return UserProfile::getName; } ProfilesExpressionObject(final ProfileService profileService); Optional<UserProfile> findByUserId(final String userId); Function<UserProfile, String> getName(); }### Answer: @Test public void getName() { final String name = "jhgk"; final UserProfile userProfile = UserProfile.builder().name(name).build(); final Function<UserProfile, String> result = profiles.getName(); assertThat(result.apply(userProfile)).isEqualTo(name); }
### Question: HomeController extends AbstractController { @RequestMapping("/") public ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal) { final List<RequestView> requests = mappers.mapList(RequestDto.class, RequestView.class, requestService.findAll()) .stream() .filter(request -> request.getPhase().toLowerCase().equals("open") && (hasFunds(request.getFunds().getFndFunds()) || hasFunds(request.getFunds().getOtherFunds()))) .collect(toList()); if (principal != null && StringUtils.isNotBlank(ref)) { eventPublisher.publishEvent(RefSignupEvent.builder().principal(principal).ref(ref).build()); return redirectView(redirectAttributes).url("/").build(); } return redirectView(redirectAttributes) .url("/requests") .build(); } HomeController(ProfileService profileService, ApplicationEventPublisher eventPublisher, final RequestService requestService, final ObjectMapper objectMapper, final Mappers mappers); @RequestMapping("/") ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal); @GetMapping(value = {"/requestsActiveCount"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String getRequestsActiveCount(Principal principal); @RequestMapping("/user/login") ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request); @GetMapping(path = "/logout") String logout(Principal principal, HttpServletRequest request); }### Answer: @Test public void home() throws Exception { mockMvc.perform(get("/")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/requests")); }
### Question: HomeController extends AbstractController { @RequestMapping("/user/login") public ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request) { return redirectView(redirectAttributes) .url(request.getHeader("referer")) .build(); } HomeController(ProfileService profileService, ApplicationEventPublisher eventPublisher, final RequestService requestService, final ObjectMapper objectMapper, final Mappers mappers); @RequestMapping("/") ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal); @GetMapping(value = {"/requestsActiveCount"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String getRequestsActiveCount(Principal principal); @RequestMapping("/user/login") ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request); @GetMapping(path = "/logout") String logout(Principal principal, HttpServletRequest request); }### Answer: @Test public void login() throws Exception { mockMvc.perform(get("/user/login").header("referer", "localhost")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("localhost")); }
### Question: HomeController extends AbstractController { @GetMapping(path = "/logout") public String logout(Principal principal, HttpServletRequest request) throws ServletException { if (principal != null) { profileService.logout(principal); } request.logout(); return "redirect:/"; } HomeController(ProfileService profileService, ApplicationEventPublisher eventPublisher, final RequestService requestService, final ObjectMapper objectMapper, final Mappers mappers); @RequestMapping("/") ModelAndView home(@RequestParam(value = "ref", required = false) String ref, RedirectAttributes redirectAttributes, Principal principal); @GetMapping(value = {"/requestsActiveCount"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody String getRequestsActiveCount(Principal principal); @RequestMapping("/user/login") ModelAndView login(RedirectAttributes redirectAttributes, HttpServletRequest request); @GetMapping(path = "/logout") String logout(Principal principal, HttpServletRequest request); }### Answer: @Test public void logoutWithPrincipal() throws Exception { Principal principal = PrincipalMother.davyvanroy(); mockMvc.perform(get("/logout").principal(principal)) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/")); verify(profileService).logout(principal); }
### Question: MessagesController extends AbstractController { @PostMapping("/messages/{type}/{name}/delete") public ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes) { messageService.delete(MessageType.valueOf(type.toUpperCase()), name); return redirectView(redirectAttributes) .withSuccessMessage("Deleted") .url("/messages/" + type) .build(); } MessagesController(final MessageService messageService); @RequestMapping("/messages") ModelAndView showAllMessagesPage(final Model model); @RequestMapping("/messages/{type}") ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/add") ModelAndView showAddMessageToTypePage(final Model model, @PathVariable String type); @RequestMapping("/messages/{type}/{name}/edit") ModelAndView showEditPage(final Model model, @PathVariable String type, @PathVariable String name); @PostMapping("/messages/{type}/add") ModelAndView add(WebRequest request, @PathVariable String type, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/edit") ModelAndView update(WebRequest request, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); @PostMapping("/messages/{type}/{name}/delete") ModelAndView delete(final Model model, @PathVariable String type, @PathVariable String name, RedirectAttributes redirectAttributes); }### Answer: @Test public void delete() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); String name = "name"; this.mockMvc.perform(post("/messages/{type}/{name}/delete", type, name)) .andExpect(redirectAlert("success", "Deleted")) .andExpect(redirectedUrl("/messages/" + type)); }