method2testcases
stringlengths 118
6.63k
|
---|
### Question:
DMNParseServiceImpl implements DMNParseService { @Override public RangeValue parseRangeValue(final String source) { final FEEL_1_1Parser parser = makeParser(source); final BaseNode baseNode = makeVisitor().visit(parser.expression()); final RangeValue rangeValue = new RangeValue(); if (baseNode instanceof RangeNode) { final RangeNode rangeNode = (RangeNode) baseNode; rangeValue.setStartValue(parseRangeValue(rangeNode.getStart())); rangeValue.setIncludeStartValue(rangeNode.getLowerBound() == RangeNode.IntervalBoundary.CLOSED); rangeValue.setEndValue(parseRangeValue(rangeNode.getEnd())); rangeValue.setIncludeEndValue(rangeNode.getUpperBound() == RangeNode.IntervalBoundary.CLOSED); } return rangeValue; } @Override List<String> parseFEELList(final String source); @Override RangeValue parseRangeValue(final String source); }### Answer:
@Test public void testParseRange() { final RangeValue rangeValue = service.parseRangeValue("[1..2]"); assertTrue(rangeValue.getIncludeStartValue()); assertTrue(rangeValue.getIncludeEndValue()); assertEquals("1", rangeValue.getStartValue()); assertEquals("2", rangeValue.getEndValue()); }
@Test public void testParseString() { final RangeValue rangeValue = service.parseRangeValue("[abc..def]"); assertTrue(rangeValue.getIncludeStartValue()); assertTrue(rangeValue.getIncludeEndValue()); assertEquals("abc", rangeValue.getStartValue()); assertEquals("def", rangeValue.getEndValue()); }
@Test public void testParseStringWithDots() { final RangeValue rangeValue = service.parseRangeValue("[\"abc..\"..\"d..ef\"]"); assertTrue(rangeValue.getIncludeStartValue()); assertTrue(rangeValue.getIncludeEndValue()); assertEquals("\"abc..\"", rangeValue.getStartValue()); assertEquals("\"d..ef\"", rangeValue.getEndValue()); }
@Test public void testParseFunctionInvocation() { final RangeValue rangeValue = service.parseRangeValue("[ date ( \"2018-01-01\" ) .. date( \"2018-02-02\" ) ]"); assertEquals("date(\"2018-01-01\")", rangeValue.getStartValue()); assertEquals("date(\"2018-02-02\")", rangeValue.getEndValue()); }
@Test public void testParseFunctionInvocation_MissingEnd() { final RangeValue rangeValue = service.parseRangeValue("[date(\"2018-01-01\")..]"); assertNotNull(rangeValue); assertEquals("", rangeValue.getStartValue()); assertEquals("", rangeValue.getEndValue()); }
@Test public void testParseWithInteger() { final RangeValue rangeValue = service.parseRangeValue("[0..5]"); assertTrue(rangeValue.getIncludeStartValue()); assertTrue(rangeValue.getIncludeEndValue()); assertEquals("0", rangeValue.getStartValue()); assertEquals("5", rangeValue.getEndValue()); }
@Test public void testParseExcludeStart() { final RangeValue rangeValue = service.parseRangeValue("(0..5]"); assertFalse(rangeValue.getIncludeStartValue()); }
@Test public void testParseExcludeEnd() { final RangeValue rangeValue = service.parseRangeValue("[0..5)"); assertFalse(rangeValue.getIncludeEndValue()); } |
### 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 refresh() { final List<DMNExternalLink> all = getValue().getLinks(); RemoveHelper.removeChildren(linksContainer); for (final DMNExternalLink link : all) { final DocumentationLinkItem listItem = listItems.get(); listItem.init(link); listItem.setOnDeleted(this::onExternalLinkDeleted); linksContainer.appendChild(listItem.getElement()); } refreshContainersVisibility(); } @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 testRefresh() { final DocumentationLinks value = mock(DocumentationLinks.class); final DMNExternalLink externalLink = mock(DMNExternalLink.class); final List<DMNExternalLink> links = new ArrayList<>(); links.add(externalLink); final DocumentationLinkItem listItem = mock(DocumentationLinkItem.class); final HTMLElement element = mock(HTMLElement.class); when(listItem.getElement()).thenReturn(element); when(listItems.get()).thenReturn(listItem); widget.setValue(value); when(value.getLinks()).thenReturn(links); widget.refresh(); verify(listItem).init(externalLink); verify(linksContainer).appendChild(element); verify(widget).refreshContainersVisibility(); } |
### Question:
DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>,
HasEnabled { void refreshContainersVisibility() { if (getValue().getLinks().size() == 0) { HiddenHelper.show(noneContainer); HiddenHelper.hide(linksContainer); } else { HiddenHelper.hide(noneContainer); HiddenHelper.show(linksContainer); } } @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 testRefreshContainersVisibility() { 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.refreshContainersVisibility(); verify(noneContainerClassList).add(HiddenHelper.HIDDEN_CSS_CLASS); verify(linksContainerClassList).remove(HiddenHelper.HIDDEN_CSS_CLASS); links.clear(); widget.refreshContainersVisibility(); verify(noneContainerClassList).remove(HiddenHelper.HIDDEN_CSS_CLASS); verify(linksContainerClassList).add(HiddenHelper.HIDDEN_CSS_CLASS); } |
### 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:
DocumentationLinksWidget extends Composite implements HasValue<DocumentationLinks>,
HasEnabled { void setupAddButtonReadOnlyStatus() { if (readOnlyProvider.isReadOnlyDiagram()) { addButton.classList.add(READ_ONLY_CSS_CLASS); } else { addButton.classList.remove(READ_ONLY_CSS_CLASS); } } @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 testSetupAddButtonReadOnlyStatusWhenIsReadOnly() { when(readOnlyProvider.isReadOnlyDiagram()).thenReturn(true); widget.setupAddButtonReadOnlyStatus(); verify(addButtonClassList).add(READ_ONLY_CSS_CLASS); verify(addButtonClassList, never()).remove(READ_ONLY_CSS_CLASS); }
@Test public void testSetupAddButtonReadOnlyStatusWhenIsNotReadOnly() { when(readOnlyProvider.isReadOnlyDiagram()).thenReturn(false); widget.setupAddButtonReadOnlyStatus(); verify(addButtonClassList, never()).add(READ_ONLY_CSS_CLASS); verify(addButtonClassList).remove(READ_ONLY_CSS_CLASS); } |
### 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 { public List<DMNDocumentationDRD> create(final Diagram diagram) { final Optional<String> previousNodeUUID = getExpressionContainerGrid().getNodeUUID(); final List<DMNDocumentationDRD> drds = createDMNDocumentationDRDs(diagram); previousNodeUUID.ifPresent(uuid -> setExpressionContainerGrid(diagram, uuid)); return drds; } @Inject DMNDocumentationDRDsFactory(final SessionManager sessionManager,
final BoxedExpressionHelper expressionHelper); List<DMNDocumentationDRD> create(final Diagram diagram); }### Answer:
@Test public void testCreate() { final String nodeUUID1 = "1111-1111-1111-1111"; final String nodeUUID2 = "2222-2222-2222-2222"; final Node<View, Edge> node1 = new NodeImpl<>(nodeUUID1); final Node<View, Edge> node2 = new NodeImpl<>(nodeUUID2); final View view1 = mock(View.class); final View view2 = mock(View.class); final HasExpression hasExpression1 = mock(HasExpression.class); final List<Node<View, Edge>> nodes = asList(node1, node2); final Decision drgElement1 = new Decision(); final InputData drgElement2 = new InputData(); final String name1 = "Decision-1"; final String name2 = "Input-data-2"; final String description1 = "Description..."; final InformationItemPrimary variable1 = new InformationItemPrimary(); final QName typeRef1 = BOOLEAN.asQName(); final String image1 = "<image1>"; final DMNExternalLink externalLink = new DMNExternalLink(); final DocumentationLinksHolder linksHolder = new DocumentationLinksHolder(); linksHolder.getValue().addLink(externalLink); drgElement2.setLinksHolder(linksHolder); node1.setContent(view1); node2.setContent(view2); when(view1.getDefinition()).thenReturn(drgElement1); when(view2.getDefinition()).thenReturn(drgElement2); when(expressionHelper.getOptionalHasExpression(node1)).thenReturn(Optional.ofNullable(hasExpression1)); when(expressionHelper.getOptionalHasExpression(node2)).thenReturn(Optional.empty()); when(expressionContainerGrid.getNodeUUID()).thenReturn(Optional.of(nodeUUID2)); when(graph.nodes()).thenReturn(nodes); doReturn(image1).when(factory).getNodeImage(diagram, node1); doNothing().when(factory).setExpressionContainerGrid(any(), any()); variable1.setTypeRef(typeRef1); drgElement1.setVariable(variable1); drgElement1.setDescription(new Description(description1)); drgElement1.setName(new Name(name1)); drgElement2.setName(new Name(name2)); final List<DMNDocumentationDRD> drds = factory.create(diagram); final DMNDocumentationDRD documentationDRD1 = drds.get(0); final DMNDocumentationDRD documentationDRD2 = drds.get(1); assertEquals(2, drds.size()); assertEquals(name1, documentationDRD1.getDrdName()); assertEquals(BOOLEAN.getName(), documentationDRD1.getDrdType()); assertEquals(description1, documentationDRD1.getDrdDescription()); assertEquals(image1, documentationDRD1.getDrdBoxedExpressionImage()); assertEquals(NONE, documentationDRD2.getDrdDescription()); assertEquals(UNDEFINED.getName(), documentationDRD2.getDrdType()); assertEquals(name2, documentationDRD2.getDrdName()); assertEquals(NONE, documentationDRD2.getDrdBoxedExpressionImage()); assertFalse(documentationDRD1.getHasExternalLinks()); assertTrue(documentationDRD2.getHasExternalLinks()); verify(factory).setExpressionContainerGrid(diagram, nodeUUID2); } |
### Question:
DMNDocumentationDRDsFactory { String getNodeImage(final Diagram diagram, final Node<View, Edge> node) { if (!hasExpression(node)) { return NONE; } setExpressionContainerGrid(diagram, node.getUUID()); final ExpressionContainerGrid grid = getExpressionContainerGrid(); final Viewport viewport = grid.getViewport(); final int padding = 10; final int wide = (int) (grid.getWidth() + padding); final int high = (int) (grid.getHeight() + padding); viewport.setPixelSize(wide, high); return viewport.toDataURL(DataURLType.PNG); } @Inject DMNDocumentationDRDsFactory(final SessionManager sessionManager,
final BoxedExpressionHelper expressionHelper); List<DMNDocumentationDRD> create(final Diagram diagram); }### Answer:
@Test public void testGetNodeImage() { final String uuid = "0000-1111-2222-3333"; final Node<View, Edge> node = new NodeImpl<>(uuid); final HasExpression hasExpression = mock(HasExpression.class); final String expectedImage = "<image>"; final double wide = 800; final double high = 600; doNothing().when(factory).setExpressionContainerGrid(any(), any()); when(expressionHelper.getOptionalHasExpression(node)).thenReturn(Optional.of(hasExpression)); when(expressionContainerGrid.getWidth()).thenReturn(wide); when(expressionContainerGrid.getHeight()).thenReturn(high); when(viewport.toDataURL(DataURLType.PNG)).thenReturn(expectedImage); final String actualImage = factory.getNodeImage(diagram, node); verify(viewport).setPixelSize(810, 610); verify(factory).setExpressionContainerGrid(diagram, uuid); assertEquals(expectedImage, actualImage); }
@Test public void testGetNodeImageWhenNodeDoesNotHaveExpression() { final String uuid = "0000-1111-2222-3333"; final Node<View, Edge> node = new NodeImpl<>(uuid); when(expressionHelper.getOptionalHasExpression(node)).thenReturn(Optional.empty()); final String image = factory.getNodeImage(diagram, node); assertEquals(NONE, image); } |
### 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 { @PostConstruct public void init() { okButton.disabled = true; urlLabel.textContent = translationService.getTranslation(DMNDocumentationI18n_URL); attachmentName.textContent = translationService.getTranslation(DMNDocumentationI18n_Name); urlInput.placeholder = translationService.getTranslation(DMNDocumentationI18n_URLPlaceholder); attachmentNameInput.placeholder = translationService.getTranslation(DMNDocumentationI18n_NamePlaceholder); okButton.textContent = translationService.getTranslation(DMNDocumentationI18n_Ok); cancelButton.textContent = translationService.getTranslation(DMNDocumentationI18n_Cancel); attachmentTip.textContent = translationService.getTranslation(DMNDocumentationI18n_AttachmentTip); setOnChangedHandlers(); } 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 testInit() { final String url = "url"; final String name = "name"; final String urlPlaceholder = "urlPlaceholder"; final String namePlaceholder = "namePlaceholder"; when(translationService.getTranslation(DMNDocumentationI18n_URL)).thenReturn(url); when(translationService.getTranslation(DMNDocumentationI18n_Name)).thenReturn(name); when(translationService.getTranslation(DMNDocumentationI18n_URLPlaceholder)).thenReturn(urlPlaceholder); when(translationService.getTranslation(DMNDocumentationI18n_NamePlaceholder)).thenReturn(namePlaceholder); popover.init(); assertEquals(url, urlLabel.textContent); assertEquals(name, attachmentName.textContent); assertEquals(urlPlaceholder, urlInput.placeholder); assertEquals(namePlaceholder, attachmentNameInput.placeholder); } |
### Question:
NameAndUrlPopoverViewImpl extends AbstractPopoverViewImpl implements NameAndUrlPopoverView { @EventHandler("okButton") @SuppressWarnings("unused") public void onClickOkButton(final ClickEvent clickEvent) { final Consumer<DMNExternalLink> consumer = getOnExternalLinkCreated(); if (!Objects.isNull(consumer)) { final String description = attachmentNameInput.value; final String url = urlInput.value; final DMNExternalLink externalLink = new DMNExternalLink(url, description); consumer.accept(externalLink); } 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 testOnClickOkButton() { final String description = "description"; final String url = "url"; final ArgumentCaptor<DMNExternalLink> captor = ArgumentCaptor.forClass(DMNExternalLink.class); final Consumer onExternalLinkCreated = mock(Consumer.class); attachmentNameInput.value = description; urlInput.value = url; popover.setOnExternalLinkCreated(onExternalLinkCreated); popover.onClickOkButton(null); verify(onExternalLinkCreated).accept(captor.capture()); final DMNExternalLink externalLink = captor.getValue(); assertEquals(description, externalLink.getDescription()); assertEquals(url, externalLink.getUrl()); verify(popover).hide(); } |
### 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:
GithubClaimResolver { public ClaimableResultDto claimableResult(final String owner, final String repo, final String number, final RequestStatus requestStatus) { final GithubIssue githubIssue = githubScraper.fetchGithubIssue(owner, repo, number); if (isIssueClosed(githubIssue) && githubIssue.getSolver() != null && (requestStatus == FUNDED || requestStatus == CLAIMABLE)) { return ClaimableResultDto.builder() .claimable(true) .platform(Platform.GITHUB) .claimableByPlatformUserName(githubIssue.getSolver()) .build(); } return ClaimableResultDto.builder().claimable(false).platform(Platform.GITHUB).build(); } GithubClaimResolver(final GithubScraper githubScraper,
final AzraelClient azraelClient,
final KeycloakRepository keycloakRepository); SignedClaim getSignedClaim(final Principal user, final UserClaimRequest userClaimRequest, final RequestDto request); Boolean canClaim(final Principal user, final RequestDto request); ClaimableResultDto claimableResult(final String owner, final String repo, final String number, final RequestStatus requestStatus); Optional<String> getUserPlatformUsername(final Principal user, final Platform platform); }### Answer:
@Test public void claimableResult_currentStatusClaimable() { final String owner = "FundRequest"; final String repo = "area51"; final String number = "983"; final String solver = "davyvanroy"; when(githubScraper.fetchGithubIssue(owner, repo, number)).thenReturn(GithubIssue.builder() .solver(solver) .status("Closed") .build()); final ClaimableResultDto result = claimResolver.claimableResult(owner, repo, number, RequestStatus.CLAIMABLE); assertThat(result.isClaimable()).isTrue(); assertThat(result.getPlatform()).isEqualTo(Platform.GITHUB); assertThat(result.getClaimableByPlatformUserName()).isEqualTo(solver); }
@Test public void claimableResult_currentStatusFunded() { final String owner = "FundRequest"; final String repo = "area51"; final String number = "983"; final String solver = "davyvanroy"; when(githubScraper.fetchGithubIssue(owner, repo, number)).thenReturn(GithubIssue.builder() .solver(solver) .status("Closed") .build()); final ClaimableResultDto result = claimResolver.claimableResult(owner, repo, number, RequestStatus.FUNDED); assertThat(result.isClaimable()).isTrue(); assertThat(result.getPlatform()).isEqualTo(Platform.GITHUB); assertThat(result.getClaimableByPlatformUserName()).isEqualTo(solver); }
@Test public void claimableResult_githubIssueNotClosed() { final String owner = "FundRequest"; final String repo = "area51"; final String number = "983"; final String solver = "davyvanroy"; when(githubScraper.fetchGithubIssue(owner, repo, number)).thenReturn(GithubIssue.builder() .status("Open") .solver(solver) .build()); final ClaimableResultDto result = claimResolver.claimableResult(owner, repo, number, RequestStatus.FUNDED); assertThat(result.isClaimable()).isFalse(); assertThat(result.getPlatform()).isEqualTo(Platform.GITHUB); assertThat(result.getClaimableByPlatformUserName()).isNull(); }
@Test public void claimableResult_githubIssueNoSolver() { final String owner = "FundRequest"; final String repo = "area51"; final String number = "983"; when(githubScraper.fetchGithubIssue(owner, repo, number)).thenReturn(GithubIssue.builder() .status("Closed") .build()); final ClaimableResultDto result = claimResolver.claimableResult(owner, repo, number, RequestStatus.FUNDED); assertThat(result.isClaimable()).isFalse(); assertThat(result.getPlatform()).isEqualTo(Platform.GITHUB); assertThat(result.getClaimableByPlatformUserName()).isNull(); } |
### Question:
GithubClaimResolver { public Boolean canClaim(final Principal user, final RequestDto request) { final String owner = request.getIssueInformation().getOwner(); final String repo = request.getIssueInformation().getRepo(); final String number = request.getIssueInformation().getNumber(); final GithubIssue githubIssue = githubScraper.fetchGithubIssue(owner, repo, number); return isIssueClosed(githubIssue) && isClaimalbeByLoggedInUser(user, request, githubIssue.getSolver()); } GithubClaimResolver(final GithubScraper githubScraper,
final AzraelClient azraelClient,
final KeycloakRepository keycloakRepository); SignedClaim getSignedClaim(final Principal user, final UserClaimRequest userClaimRequest, final RequestDto request); Boolean canClaim(final Principal user, final RequestDto request); ClaimableResultDto claimableResult(final String owner, final String repo, final String number, final RequestStatus requestStatus); Optional<String> getUserPlatformUsername(final Principal user, final Platform platform); }### Answer:
@Test public void canClaim() { final Principal principal = PrincipalMother.davyvanroy(); final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final IssueInformationDto issueInformation = requestDto.getIssueInformation(); when(githubScraper.fetchGithubIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber())).thenReturn(GithubIssue.builder() .solver("davyvanroy") .status("Closed") .build()); when(keycloakRepository.getUserIdentities(principal.getName())).thenReturn(Stream.of(UserIdentity.builder().provider(Provider.GITHUB).username("davyvanroy").build())); assertThat(claimResolver.canClaim(principal, requestDto)).isTrue(); }
@Test public void canClaim_differentUser() { final Principal principal = PrincipalMother.davyvanroy(); final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final IssueInformationDto issueInformation = requestDto.getIssueInformation(); when(githubScraper.fetchGithubIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber())).thenReturn(GithubIssue.builder() .solver("dfgj") .status("Closed") .build()); when(keycloakRepository.getUserIdentities(principal.getName())).thenReturn(Stream.of(UserIdentity.builder().provider(Provider.GITHUB).username("davyvanroy").build())); assertThat(claimResolver.canClaim(principal, requestDto)).isFalse(); }
@Test public void canClaim_issueNotClosed() { final Principal principal = PrincipalMother.davyvanroy(); final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final IssueInformationDto issueInformation = requestDto.getIssueInformation(); when(githubScraper.fetchGithubIssue(issueInformation.getOwner(), issueInformation.getRepo(), issueInformation.getNumber())).thenReturn(GithubIssue.builder() .status("Open") .build()); assertThat(claimResolver.canClaim(principal, requestDto)).isFalse(); } |
### Question:
FiatService { public double getUsdPrice(TokenValueDto... funds) { return Arrays.stream(funds) .filter(f -> f != null && StringUtils.isNotBlank(f.getTokenSymbol())) .map(this::getValue) .mapToDouble(f -> f) .sum(); } FiatService(CryptoCompareService cryptoCompareService, CoinMarketCapService coinMarketCapService); double getUsdPrice(TokenValueDto... funds); }### Answer:
@Test public void getUsdPriceOneCryptoCompare() { TokenValueDto totalFund = TokenValueDto.builder().tokenAddress("0x0").tokenSymbol("FND").totalAmount(BigDecimal.TEN).build(); when(coinMarketCapService.getCurrentPriceInUsd("FND")).thenReturn(Optional.empty()); when(cryptoCompareService.getCurrentPriceInUsd("FND")).thenReturn(Optional.of(0.56)); double result = fiatService.getUsdPrice(totalFund); assertThat(result).isEqualTo(5.6); }
@Test public void getUsdPriceMultipleCryptoCompare() { TokenValueDto totalFund1 = TokenValueDto.builder().tokenAddress("0x0").tokenSymbol("FND").totalAmount(new BigDecimal("8457.858")).build(); TokenValueDto totalFund2 = TokenValueDto.builder().tokenAddress("0x0").tokenSymbol("ZRX").totalAmount(new BigDecimal("123.464")).build(); when(coinMarketCapService.getCurrentPriceInUsd("FND")).thenReturn(Optional.empty()); when(coinMarketCapService.getCurrentPriceInUsd("ZRX")).thenReturn(Optional.empty()); when(cryptoCompareService.getCurrentPriceInUsd("FND")).thenReturn(Optional.of(0.56)); when(cryptoCompareService.getCurrentPriceInUsd("ZRX")).thenReturn(Optional.of(0.98)); double result = fiatService.getUsdPrice(totalFund1, totalFund2); assertThat(result).isEqualTo(4857.3952); }
@Test public void coinMarketCapHasPriority() { TokenValueDto totalFund = TokenValueDto.builder().tokenAddress("0x0").tokenSymbol("FND").totalAmount(BigDecimal.TEN).build(); when(coinMarketCapService.getCurrentPriceInUsd("FND")).thenReturn(Optional.of(0.56)); double result = fiatService.getUsdPrice(totalFund); assertThat(result).isEqualTo(5.6); verifyZeroInteractions(cryptoCompareService); }
@Test public void cryptoCompareIsFallback() { TokenValueDto totalFund = TokenValueDto.builder().tokenAddress("0x0").tokenSymbol("FND").totalAmount(BigDecimal.TEN).build(); when(coinMarketCapService.getCurrentPriceInUsd("FND")).thenReturn(Optional.empty()); when(cryptoCompareService.getCurrentPriceInUsd("FND")).thenReturn(Optional.of(0.56)); double result = fiatService.getUsdPrice(totalFund); assertThat(result).isEqualTo(5.6); verify(coinMarketCapService).getCurrentPriceInUsd("FND"); verify(cryptoCompareService).getCurrentPriceInUsd("FND"); } |
### 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:
RequestFundedGitterHandler { @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 List<String> fundedNotificationChannels = gitterService.listFundedNotificationRooms(); if (fundedNotificationChannels.size() > 0) { final String message = githubTemplateEngine.process("notification-templates/request-funded-gitter", context); gitter.roomResource() .listRooms() .stream() .filter(room -> fundedNotificationChannels.contains(room.getName())) .forEach(room -> gitter.messageResource().sendMessage(room.getId(), message)); } } RequestFundedGitterHandler(final Gitter gitter,
final ITemplateEngine githubTemplateEngine,
final FundService fundService,
final String platformBasePath,
final GitterService gitterService); @EventListener @Async("taskExecutor") @Transactional(readOnly = true, propagation = REQUIRES_NEW) void handle(final RequestFundedNotificationDto notification); }### Answer:
@Test 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(); final List<String> fundedNotificationChannels = Arrays.asList(allRooms.get(0).getName(), allRooms.get(2).getName()); context.setVariable("platformBasePath", platformBasePath); context.setVariable("fund", fund); when(fundService.findOne(fundId)).thenReturn(fund); when(templateEngine.process(eq("notification-templates/request-funded-gitter"), refEq(context, "locale"))).thenReturn(message); when(gitter.roomResource().listRooms()).thenReturn(allRooms); when(gitterService.listFundedNotificationRooms()).thenReturn(fundedNotificationChannels); handler.handle(notification); allRooms.stream() .filter(room -> fundedNotificationChannels.contains(room.getName())) .forEach(room -> verify(gitter.messageResource()).sendMessage(room.getId(), message)); verifyNoMoreInteractions(gitter.messageResource()); }
@Test void handle_noFundedNotificationChannels() { 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(); final List<String> fundedNotificationChannels = Arrays.asList(allRooms.get(0).getName(), allRooms.get(2).getName()); context.setVariable("platformBasePath", platformBasePath); context.setVariable("fund", fund); when(fundService.findOne(fundId)).thenReturn(fund); when(templateEngine.process(eq("notification-templates/request-funded-gitter"), refEq(context, "locale"))).thenReturn(message); when(gitterService.listFundedNotificationRooms()).thenReturn(new ArrayList<>()); handler.handle(notification); verifyZeroInteractions(gitter); } |
### 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:
RequestServiceImpl implements RequestService { @Override @Transactional(readOnly = true) public List<RequestDto> findAll() { return mappers.mapList(Request.class, RequestDto.class, requestRepository.findAll()); } RequestServiceImpl(final RequestRepository requestRepository,
final Mappers mappers,
final GithubPlatformIdParser githubLinkParser,
final ProfileService profileService,
final ClaimRepository claimRepository,
final GithubGateway githubGateway,
final GithubClaimResolver githubClaimResolver,
final ApplicationEventPublisher eventPublisher,
final Erc67Generator erc67Generator,
final Environment environment); @Override @Transactional(readOnly = true) List<RequestDto> findAll(); @Transactional(readOnly = true) List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays); @Override @Transactional(readOnly = true) List<RequestDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) @Cacheable(value = "technologies", key = "'all'") Set<String> findAllTechnologies(); @Override @Transactional(readOnly = true) @Cacheable(value = "projects", key = "'all'") Set<String> findAllProjects(); @Override @Transactional UserClaimableDto getUserClaimableResult(final Principal principal, final Long requestId); @Override @Transactional ClaimableResultDto getClaimableResult(final Long requestId); @Override @Transactional(readOnly = true) List<RequestDto> findRequestsForUser(Principal principal); @Override @Transactional(readOnly = true) RequestDto findRequest(Long id); @Override @Transactional(readOnly = true) List<CommentDto> getComments(Long requestId); @Override @Transactional(readOnly = true) RequestDto findRequest(Platform platform, String platformId); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Long createRequest(CreateRequestCommand command); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Request requestClaimed(RequestClaimedCommand command); @Override @Transactional(readOnly = true) SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) Boolean canClaim(Principal user, CanClaimRequest canClaimRequest); @Override @Transactional void addWatcherToRequest(Principal principal, Long requestId); @Override @Transactional void removeWatcherFromRequest(Principal principal, Long requestId); @Override String generateERC67(final CreateERC67FundRequest createERC67FundRequest); @Override void update(final UpdateRequestStatusCommand command); }### Answer:
@Test public void findAll() { List<Request> requests = singletonList(RequestMother.freeCodeCampNoUserStories().build()); when(requestRepository.findAll()).thenReturn(requests); List<RequestDto> expectedRequests = singletonList(RequestDtoMother.freeCodeCampNoUserStories()); when(mappers.mapList(Request.class, RequestDto.class, requests)).thenReturn(expectedRequests); List<RequestDto> result = requestService.findAll(); assertThat(result).isEqualTo(expectedRequests); }
@Test public void findAllByIterable() { List<Request> requests = singletonList(RequestMother.freeCodeCampNoUserStories().build()); Set<Long> ids = requests.stream().map(Request::getId).collect(Collectors.toSet()); when(requestRepository.findAll(ids)).thenReturn(requests); List<RequestDto> expectedRequests = singletonList(RequestDtoMother.freeCodeCampNoUserStories()); when(mappers.mapList(Request.class, RequestDto.class, requests)).thenReturn(expectedRequests); List<RequestDto> result = requestService.findAll(ids); assertThat(result).isEqualTo(expectedRequests); } |
### Question:
RequestServiceImpl implements RequestService { @Transactional(readOnly = true) public List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays) { final RequestSpecification specification = new RequestSpecification(projects, technologies, lastUpdatedSinceDays); return mappers.mapList(Request.class, RequestDto.class, requestRepository.findAll(specification)); } RequestServiceImpl(final RequestRepository requestRepository,
final Mappers mappers,
final GithubPlatformIdParser githubLinkParser,
final ProfileService profileService,
final ClaimRepository claimRepository,
final GithubGateway githubGateway,
final GithubClaimResolver githubClaimResolver,
final ApplicationEventPublisher eventPublisher,
final Erc67Generator erc67Generator,
final Environment environment); @Override @Transactional(readOnly = true) List<RequestDto> findAll(); @Transactional(readOnly = true) List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays); @Override @Transactional(readOnly = true) List<RequestDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) @Cacheable(value = "technologies", key = "'all'") Set<String> findAllTechnologies(); @Override @Transactional(readOnly = true) @Cacheable(value = "projects", key = "'all'") Set<String> findAllProjects(); @Override @Transactional UserClaimableDto getUserClaimableResult(final Principal principal, final Long requestId); @Override @Transactional ClaimableResultDto getClaimableResult(final Long requestId); @Override @Transactional(readOnly = true) List<RequestDto> findRequestsForUser(Principal principal); @Override @Transactional(readOnly = true) RequestDto findRequest(Long id); @Override @Transactional(readOnly = true) List<CommentDto> getComments(Long requestId); @Override @Transactional(readOnly = true) RequestDto findRequest(Platform platform, String platformId); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Long createRequest(CreateRequestCommand command); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Request requestClaimed(RequestClaimedCommand command); @Override @Transactional(readOnly = true) SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) Boolean canClaim(Principal user, CanClaimRequest canClaimRequest); @Override @Transactional void addWatcherToRequest(Principal principal, Long requestId); @Override @Transactional void removeWatcherFromRequest(Principal principal, Long requestId); @Override String generateERC67(final CreateERC67FundRequest createERC67FundRequest); @Override void update(final UpdateRequestStatusCommand command); }### Answer:
@Test public void findAllFor() { final List<String> projects = new ArrayList<>(); final List<String> technologies = new ArrayList<>(); final long lastUpdatedSinceDays = 10L; final List<Request> requests = new ArrayList<>(); final List<RequestDto> expected = new ArrayList<>(); when(requestRepository.findAll(refEq(new RequestSpecification(projects, technologies, lastUpdatedSinceDays)))).thenReturn(requests); when(mappers.mapList(eq(Request.class), eq(RequestDto.class), same(requests))).thenReturn(expected); final List<RequestDto> result = requestService.findAllFor(projects, technologies, lastUpdatedSinceDays); assertThat(result).isSameAs(expected); } |
### Question:
RequestServiceImpl implements RequestService { @Override @Transactional(readOnly = true) public RequestDto findRequest(Long id) { Request request = findOne(id); return mappers.map(Request.class, RequestDto.class, request); } RequestServiceImpl(final RequestRepository requestRepository,
final Mappers mappers,
final GithubPlatformIdParser githubLinkParser,
final ProfileService profileService,
final ClaimRepository claimRepository,
final GithubGateway githubGateway,
final GithubClaimResolver githubClaimResolver,
final ApplicationEventPublisher eventPublisher,
final Erc67Generator erc67Generator,
final Environment environment); @Override @Transactional(readOnly = true) List<RequestDto> findAll(); @Transactional(readOnly = true) List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays); @Override @Transactional(readOnly = true) List<RequestDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) @Cacheable(value = "technologies", key = "'all'") Set<String> findAllTechnologies(); @Override @Transactional(readOnly = true) @Cacheable(value = "projects", key = "'all'") Set<String> findAllProjects(); @Override @Transactional UserClaimableDto getUserClaimableResult(final Principal principal, final Long requestId); @Override @Transactional ClaimableResultDto getClaimableResult(final Long requestId); @Override @Transactional(readOnly = true) List<RequestDto> findRequestsForUser(Principal principal); @Override @Transactional(readOnly = true) RequestDto findRequest(Long id); @Override @Transactional(readOnly = true) List<CommentDto> getComments(Long requestId); @Override @Transactional(readOnly = true) RequestDto findRequest(Platform platform, String platformId); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Long createRequest(CreateRequestCommand command); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Request requestClaimed(RequestClaimedCommand command); @Override @Transactional(readOnly = true) SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) Boolean canClaim(Principal user, CanClaimRequest canClaimRequest); @Override @Transactional void addWatcherToRequest(Principal principal, Long requestId); @Override @Transactional void removeWatcherFromRequest(Principal principal, Long requestId); @Override String generateERC67(final CreateERC67FundRequest createERC67FundRequest); @Override void update(final UpdateRequestStatusCommand command); }### Answer:
@Test public void findRequest() { Optional<Request> request = Optional.of(RequestMother.freeCodeCampNoUserStories().withWatchers(singletonList("davy")).withId(1L).build()); when(requestRepository.findOne(request.get().getId())).thenReturn(request); RequestDto expectedRequest = RequestDtoMother.freeCodeCampNoUserStories(); when(mappers.map(Request.class, RequestDto.class, request.get())).thenReturn(expectedRequest); RequestDto result = requestService.findRequest(request.get().getId()); assertThat(result).isEqualTo(expectedRequest); } |
### Question:
RequestServiceImpl implements RequestService { @Override @Transactional(readOnly = true) public SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest) { return githubClaimResolver.getSignedClaim(user, userClaimRequest, findRequest(userClaimRequest.getPlatform(), userClaimRequest.getPlatformId())); } RequestServiceImpl(final RequestRepository requestRepository,
final Mappers mappers,
final GithubPlatformIdParser githubLinkParser,
final ProfileService profileService,
final ClaimRepository claimRepository,
final GithubGateway githubGateway,
final GithubClaimResolver githubClaimResolver,
final ApplicationEventPublisher eventPublisher,
final Erc67Generator erc67Generator,
final Environment environment); @Override @Transactional(readOnly = true) List<RequestDto> findAll(); @Transactional(readOnly = true) List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays); @Override @Transactional(readOnly = true) List<RequestDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) @Cacheable(value = "technologies", key = "'all'") Set<String> findAllTechnologies(); @Override @Transactional(readOnly = true) @Cacheable(value = "projects", key = "'all'") Set<String> findAllProjects(); @Override @Transactional UserClaimableDto getUserClaimableResult(final Principal principal, final Long requestId); @Override @Transactional ClaimableResultDto getClaimableResult(final Long requestId); @Override @Transactional(readOnly = true) List<RequestDto> findRequestsForUser(Principal principal); @Override @Transactional(readOnly = true) RequestDto findRequest(Long id); @Override @Transactional(readOnly = true) List<CommentDto> getComments(Long requestId); @Override @Transactional(readOnly = true) RequestDto findRequest(Platform platform, String platformId); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Long createRequest(CreateRequestCommand command); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Request requestClaimed(RequestClaimedCommand command); @Override @Transactional(readOnly = true) SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) Boolean canClaim(Principal user, CanClaimRequest canClaimRequest); @Override @Transactional void addWatcherToRequest(Principal principal, Long requestId); @Override @Transactional void removeWatcherFromRequest(Principal principal, Long requestId); @Override String generateERC67(final CreateERC67FundRequest createERC67FundRequest); @Override void update(final UpdateRequestStatusCommand command); }### Answer:
@Test public void signClaimRequest() { final UserClaimRequest command = UserClaimRequest.builder() .platform(Platform.GITHUB) .platformId("1") .build(); final Principal principal = () -> "davyvanroy"; final Request request = RequestMother.freeCodeCampNoUserStories().build(); final RequestDto requestDto = RequestDtoMother.freeCodeCampNoUserStories(); final SignedClaim expected = SignedClaim.builder().solver("").solverAddress("").platform(Platform.GITHUB).platformId("1").r("r").s("s").v(27).build(); when(requestRepository.findByPlatformAndPlatformId(command.getPlatform(), command.getPlatformId())).thenReturn(Optional.of(request)); when(mappers.map(Request.class, RequestDto.class, request)).thenReturn(requestDto); when(githubClaimResolver.getSignedClaim(principal, command, requestDto)).thenReturn(expected); final SignedClaim result = requestService.signClaimRequest(principal, command); assertThat(result).isEqualTo(expected); } |
### Question:
RequestServiceImpl implements RequestService { @Override @Transactional(readOnly = true) public List<CommentDto> getComments(Long requestId) { Request request = requestRepository.findOne(requestId).orElseThrow(() -> new EntityNotFoundException("Request not found")); return mappers.mapList(GithubIssueCommentsResult.class, CommentDto.class, githubGateway.getCommentsForIssue(request.getIssueInformation().getOwner(), request.getIssueInformation().getRepo(), request.getIssueInformation().getNumber())); } RequestServiceImpl(final RequestRepository requestRepository,
final Mappers mappers,
final GithubPlatformIdParser githubLinkParser,
final ProfileService profileService,
final ClaimRepository claimRepository,
final GithubGateway githubGateway,
final GithubClaimResolver githubClaimResolver,
final ApplicationEventPublisher eventPublisher,
final Erc67Generator erc67Generator,
final Environment environment); @Override @Transactional(readOnly = true) List<RequestDto> findAll(); @Transactional(readOnly = true) List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays); @Override @Transactional(readOnly = true) List<RequestDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) @Cacheable(value = "technologies", key = "'all'") Set<String> findAllTechnologies(); @Override @Transactional(readOnly = true) @Cacheable(value = "projects", key = "'all'") Set<String> findAllProjects(); @Override @Transactional UserClaimableDto getUserClaimableResult(final Principal principal, final Long requestId); @Override @Transactional ClaimableResultDto getClaimableResult(final Long requestId); @Override @Transactional(readOnly = true) List<RequestDto> findRequestsForUser(Principal principal); @Override @Transactional(readOnly = true) RequestDto findRequest(Long id); @Override @Transactional(readOnly = true) List<CommentDto> getComments(Long requestId); @Override @Transactional(readOnly = true) RequestDto findRequest(Platform platform, String platformId); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Long createRequest(CreateRequestCommand command); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Request requestClaimed(RequestClaimedCommand command); @Override @Transactional(readOnly = true) SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) Boolean canClaim(Principal user, CanClaimRequest canClaimRequest); @Override @Transactional void addWatcherToRequest(Principal principal, Long requestId); @Override @Transactional void removeWatcherFromRequest(Principal principal, Long requestId); @Override String generateERC67(final CreateERC67FundRequest createERC67FundRequest); @Override void update(final UpdateRequestStatusCommand command); }### Answer:
@Test public void getComments() { Request request = RequestMother.fundRequestArea51().build(); when(requestRepository.findOne(1L)).thenReturn(Optional.of(request)); List<GithubIssueCommentsResult> githubComments = Collections.singletonList(GithubIssueCommentsResult.builder().title("title").body("#body").build()); when(githubGateway.getCommentsForIssue(request.getIssueInformation().getOwner(), request.getIssueInformation().getRepo(), request.getIssueInformation().getNumber())) .thenReturn(githubComments); CommentDto expected = CommentDto.builder().userName("davyvanroy").title("title").body("#body").build(); when(mappers.mapList(GithubIssueCommentsResult.class, CommentDto.class, githubComments)).thenReturn(Collections.singletonList(expected)); List<CommentDto> comments = requestService.getComments(1L); assertThat(comments.get(0)).isEqualTo(expected); } |
### Question:
RequestServiceImpl implements RequestService { @Override public void update(final UpdateRequestStatusCommand command) { requestRepository.findOne(command.getRequestId()).ifPresent(request -> { request.setStatus(command.getNewStatus()); requestRepository.save(request); }); } RequestServiceImpl(final RequestRepository requestRepository,
final Mappers mappers,
final GithubPlatformIdParser githubLinkParser,
final ProfileService profileService,
final ClaimRepository claimRepository,
final GithubGateway githubGateway,
final GithubClaimResolver githubClaimResolver,
final ApplicationEventPublisher eventPublisher,
final Erc67Generator erc67Generator,
final Environment environment); @Override @Transactional(readOnly = true) List<RequestDto> findAll(); @Transactional(readOnly = true) List<RequestDto> findAllFor(final List<String> projects, final List<String> technologies, final Long lastUpdatedSinceDays); @Override @Transactional(readOnly = true) List<RequestDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) @Cacheable(value = "technologies", key = "'all'") Set<String> findAllTechnologies(); @Override @Transactional(readOnly = true) @Cacheable(value = "projects", key = "'all'") Set<String> findAllProjects(); @Override @Transactional UserClaimableDto getUserClaimableResult(final Principal principal, final Long requestId); @Override @Transactional ClaimableResultDto getClaimableResult(final Long requestId); @Override @Transactional(readOnly = true) List<RequestDto> findRequestsForUser(Principal principal); @Override @Transactional(readOnly = true) RequestDto findRequest(Long id); @Override @Transactional(readOnly = true) List<CommentDto> getComments(Long requestId); @Override @Transactional(readOnly = true) RequestDto findRequest(Platform platform, String platformId); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Long createRequest(CreateRequestCommand command); @Override @Transactional @CacheEvict(value = {"projects", "technologies"}, key = "'all'") Request requestClaimed(RequestClaimedCommand command); @Override @Transactional(readOnly = true) SignedClaim signClaimRequest(Principal user, UserClaimRequest userClaimRequest); @Override @Transactional(readOnly = true) Boolean canClaim(Principal user, CanClaimRequest canClaimRequest); @Override @Transactional void addWatcherToRequest(Principal principal, Long requestId); @Override @Transactional void removeWatcherFromRequest(Principal principal, Long requestId); @Override String generateERC67(final CreateERC67FundRequest createERC67FundRequest); @Override void update(final UpdateRequestStatusCommand command); }### Answer:
@Test public void update() { final long requestId = 213L; final Request request = RequestMother.fundRequestArea51().withStatus(OPEN).build(); when(requestRepository.findOne(requestId)).thenReturn(Optional.of(request)); requestService.update(new UpdateRequestStatusCommand(requestId, FUNDED)); assertThat(request.getStatus()).isEqualTo(FUNDED); verify(requestRepository).save(same(request)); } |
### Question:
Erc67Generator { public String toFunction(CreateERC67FundRequest erc67FundRequest) { TokenInfoDto tokenInfo = tokenInfoService.getTokenInfo(erc67FundRequest.getTokenAddress()); final StringBuilder builder = new StringBuilder("approveAndCall").append("("); builder.append("address ").append(fundRequestContractAddress).append(", "); builder.append("uint256 ").append(getRawValue(erc67FundRequest.getAmount(), tokenInfo.getDecimals()).toString()).append(", "); builder.append("bytes ").append("0x").append(Hex.encodeHexString((getData(erc67FundRequest)).getBytes())); builder.append(")"); return builder.toString(); } Erc67Generator(TokenInfoService tokenInfoService, final @Value("${io.fundrequest.contract.fund-request.address}") String fundRequestContractAddress); String toByteData(CreateERC67FundRequest erc67FundRequest); String toFunction(CreateERC67FundRequest erc67FundRequest); }### Answer:
@Test public void toFunction() { CreateERC67FundRequest erc67FundRequest = CreateERC67FundRequest .builder() .amount(new BigDecimal("100.837483")) .tokenAddress("0x02F96eF85cAd6639500CA1cc8356F0b5CA5bF1D2") .platform("github") .platformId("1") .build(); when(tokenInfoService.getTokenInfo(erc67FundRequest.getTokenAddress())).thenReturn(TokenInfoDto.builder().decimals(18).build()); String result = erc67Generator.toFunction(erc67FundRequest); assertThat(result).isEqualTo("approveAndCall(address 0xC16a102813B7bD98b0BEF2dF28FFCaf1Fbee97c0, uint256 100837483000000000000, bytes 0x6769746875627c4141437c31)"); } |
### 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:
RequestClaimedUserNotificationHandler { @EventListener @Async("taskExecutor") @Transactional(readOnly = true, propagation = REQUIRES_NEW) public void handle(final RequestClaimedNotificationDto notification) { claimService.findOne(notification.getClaimId()) .ifPresent(claim -> { final RequestDto request = requestService.findRequest(notification.getRequestId()); final UserRepresentation user = identityAPIClient.findByIdentityProviderAndFederatedUsername(request.getIssueInformation().getPlatform().name().toLowerCase(), claim.getSolver()); final Context context = new Context(); context.setVariable("platformBasepath", platformBasepath); context.setVariable("request", request); final String messageBody = githubTemplateEngine.process("notification-templates/claimed-claimer-notification", context); intercomApiClient.postMessage(AdminMessageBuilder.newInstanceWith() .messageType("email") .template("plain") .admin(AdminBuilder.newInstanceWith().id(adminId).build()) .subject("Your reward has been transferred to your account") .body(messageBody) .user(UserBuilder.newInstanceWith().email(user.getEmail()).build()) .build()); }); } RequestClaimedUserNotificationHandler(@Value("${io.fundrequest.intercom.message.admin-id}") final String adminId,
@Value("${io.fundrequest.platform.base-path:https://fundrequest.io}") final String platformBasepath,
final ClaimService claimService,
final RequestService requestService,
final IdentityAPIClient identityAPIClient,
final ITemplateEngine githubTemplateEngine,
final IntercomApiClient intercomApiClient); @EventListener @Async("taskExecutor") @Transactional(readOnly = true, propagation = REQUIRES_NEW) void handle(final RequestClaimedNotificationDto notification); }### Answer:
@Test void handle() { final long blockchainEventId = 2435L; final long requestId = 54657L; final long claimId = 7657L; final String solver = "afsg"; final String userEmail = "[email protected]"; final UserRepresentation userRepresentation = new UserRepresentation(); userRepresentation.setEmail(userEmail); final RequestClaimedNotificationDto notification = RequestClaimedNotificationDto.builder() .blockchainEventId(blockchainEventId) .requestId(requestId) .claimId(claimId) .date(LocalDateTime.now()) .build(); final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setId(requestId); final String body = "szgsg"; final Context context = new Context(); context.setVariable("platformBasepath", platformBasepath); context.setVariable("request", requestDto); when(claimService.findOne(claimId)).thenReturn(Optional.of(ClaimDtoMother.aClaimDto().solver(solver).requestId(requestId).build())); when(requestService.findRequest(requestId)).thenReturn(requestDto); when(identityAPIClient.findByIdentityProviderAndFederatedUsername(requestDto.getIssueInformation().getPlatform().name().toLowerCase(), solver)).thenReturn(userRepresentation); when(githubTemplateEngine.process(eq("notification-templates/claimed-claimer-notification"), refEq(context, "locale"))).thenReturn(body); handler.handle(notification); verify(intercomApiClient).postMessage(AdminMessageBuilder.newInstanceWith() .messageType("email") .template("plain") .admin(AdminBuilder.newInstanceWith().id(adminId).build()) .subject("Your reward has been transferred to your account") .body(body) .user(UserBuilder.newInstanceWith().email(userEmail).build()) .build()); } |
### 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:
PendingFundService { @Transactional public void save(final Principal principal, final PendingFundCommand command) { final IssueInformation issueInformation = githubLinkParser.parseIssue(command.getPlatformId()); final PendingFund pf = PendingFund.builder() .amount(toWei(command)) .description(command.getDescription()) .fromAddress(command.getFromAddress()) .tokenAddress(command.getTokenAddress()) .transactionhash(command.getTransactionId()) .issueInformation(issueInformation) .userId(principal == null ? null : principal.getName()) .build(); pendingFundRepository.save(pf); } PendingFundService(final PendingFundRepository pendingFundRepository,
final GithubPlatformIdParser githubLinkParser,
final Mappers mappers,
final TokenInfoService tokenInfoService); @Transactional(readOnly = true) List<PendingFund> findAll(); @Transactional void save(final Principal principal, final PendingFundCommand command); @Transactional void removePendingFund(final String transactionHash); @Transactional void removePendingFund(final PendingFund pendingFund); @Transactional(readOnly = true) List<PendingFundDto> findByUser(final Principal principal); }### Answer:
@Test public void save() { TokenInfoDto token = TokenInfoDtoMother.fnd(); PendingFundCommand command = PendingFundCommand.builder() .amount("1.2") .description("description") .fromAddress("0x0") .tokenAddress(token.getAddress()) .platform(Platform.GITHUB) .platformId("FundRequest|FR|area51|FR|12") .transactionId("0x3") .build(); when(tokenInfoService.getTokenInfo(token.getAddress())).thenReturn(token); Principal davyvanroy = PrincipalMother.davyvanroy(); pendingFundService.save(davyvanroy, command); ArgumentCaptor<PendingFund> pendingFundArgumentCaptor = ArgumentCaptor.forClass(PendingFund.class); verify(pendingFundRepository).save(pendingFundArgumentCaptor.capture()); PendingFund pendingFund = pendingFundArgumentCaptor.getValue(); assertThat(pendingFund.getAmount()).isEqualTo(new BigInteger("1200000000000000000")); assertThat(pendingFund.getTokenAddress()).isEqualTo(command.getTokenAddress()); assertThat(pendingFund.getDescription()).isEqualTo(command.getDescription()); assertThat(pendingFund.getTransactionHash()).isEqualTo(command.getTransactionId()); assertThat(pendingFund.getFromAddress()).isEqualTo(command.getFromAddress()); assertThat(pendingFund.getUserId()).isEqualTo(davyvanroy.getName()); } |
### 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:
FundsAndRefundsAggregator { public List<UserFundsDto> aggregate(final List<FundsByFunderDto> fundsByFunder) { return fundsByFunder.stream() .collect(Collectors.groupingBy(funds -> funds.getFunderAddress().toLowerCase() + funds.getFunderUserId(), Collectors.mapping(mapToUserFundDto(), Collectors.reducing(mergeFundsAndRefunds())))) .values() .stream() .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); } List<UserFundsDto> aggregate(final List<FundsByFunderDto> fundsByFunder); }### Answer:
@Test public void aggregate() { final String funder1UserId = "dgfhj"; final String funder1Address = "0xFHDsad"; final String funder2UserId = "jghf"; final String funder2Address = "0xtrdkl"; final String funder3UserId = "hfg"; final String funder3Address = "0xeytru"; final FundsByFunderDto fundsByFunderDto1 = buildFundsByFunderDto(funder1UserId, funder1Address, "10", "20"); final FundsByFunderDto fundsByFunderDto2 = buildFundsByFunderDto(funder2UserId, funder2Address, null, "-30"); final FundsByFunderDto fundsByFunderDto3 = buildFundsByFunderDto(funder3UserId, funder3Address, "65", null); final FundsByFunderDto fundsByFunderDto4 = buildFundsByFunderDto(funder1UserId, funder1Address.toUpperCase(), "-10", "-10"); final FundsByFunderDto fundsByFunderDto5 = buildFundsByFunderDto(funder2UserId, funder2Address, null, "60"); final FundsByFunderDto fundsByFunderDto6 = buildFundsByFunderDto(funder3UserId, funder3Address, "-35", null); final List<UserFundsDto> result = fundsAndRefundsAggregator.aggregate(Arrays.asList(fundsByFunderDto1, fundsByFunderDto2, fundsByFunderDto3, fundsByFunderDto4, fundsByFunderDto5, fundsByFunderDto6)); assertThat(result).contains(buildUserFundsDtoFrom(fundsByFunderDto1, fundsByFunderDto4), buildUserFundsDtoFrom(fundsByFunderDto5, fundsByFunderDto2), buildUserFundsDtoFrom(fundsByFunderDto3, fundsByFunderDto6)); } |
### 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:
FundServiceImpl implements FundService { @Transactional(readOnly = true) @Override public List<FundDto> findAll() { return mappers.mapList(Fund.class, FundDto.class, fundRepository.findAll()); } @Autowired FundServiceImpl(final FundRepository fundRepository,
final RefundRepository refundRepository,
final PendingFundRepository pendingFundRepository,
final RequestRepository requestRepository,
final Mappers mappers,
final ApplicationEventPublisher eventPublisher,
final CacheManager cacheManager,
final FundRequestContractsService fundRequestContractsService,
final FiatService fiatService,
final TokenValueMapper tokenValueMapper,
final FundFundsByFunderAggregator fundFundsByFunderAggregator,
final RefundFundsByFunderAggregator refundFundsByFunderAggregator,
final FundsAndRefundsAggregator fundsAndRefundsAggregator); @Transactional(readOnly = true) @Override List<FundDto> findAll(); @Transactional(readOnly = true) @Override List<FundDto> findAll(Iterable<Long> ids); @Override @Transactional(readOnly = true) FundDto findOne(Long id); @Override @Transactional(readOnly = true) @Cacheable(value = "funds", key = "#requestId", unless = "#result.isEmpty()") List<TokenValueDto> getTotalFundsForRequest(Long requestId); @Override @Transactional(readOnly = true) FundsForRequestDto getFundsForRequestGroupedByFunder(final Long requestId); @Override @CacheEvict(value = "funds", key = "#requestId") void clearTotalFundsCache(Long requestId); @Override @Transactional void addFunds(final FundsAddedCommand command); @Override Optional<TokenValueDto> getFundsFor(final Long requestId, final String funderAddress, final String tokenAddress); }### Answer:
@Test public void findAll() { List<Fund> funds = singletonList(FundMother.fndFundFunderKnown().build()); when(fundRepository.findAll()).thenReturn(funds); List<FundDto> expecedFunds = singletonList(FundDtoMother.aFundDto().build()); when(mappers.mapList(Fund.class, FundDto.class, funds)).thenReturn(expecedFunds); List<FundDto> result = fundService.findAll(); assertThat(result).isEqualTo(expecedFunds); }
@Test public void findAllByIterable() { List<Fund> funds = singletonList(FundMother.fndFundFunderKnown().build()); Set<Long> ids = funds.stream().map(Fund::getId).collect(Collectors.toSet()); when(fundRepository.findAll(ids)).thenReturn(funds); List<FundDto> expecedFunds = singletonList(FundDtoMother.aFundDto().build()); when(mappers.mapList(Fund.class, FundDto.class, funds)).thenReturn(expecedFunds); List<FundDto> result = fundService.findAll(ids); assertThat(result).isEqualTo(expecedFunds); } |
### 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:
MessagesController extends AbstractController { @RequestMapping("/messages/{type}") public ModelAndView showMessagesOfTypePage(final Model model, @PathVariable String type) { model.addAttribute("type", type.toUpperCase()); model.addAttribute("messages", messageService.getMessagesByType(MessageType.valueOf(type.toUpperCase()))); return new ModelAndView("messages/type"); } 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 showMessagesOfTypePage() throws Exception { String type = MessageType.REFERRAL_SHARE.toString(); 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/{type}", type)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.model().attribute("type", type)) .andExpect(MockMvcResultMatchers.model().attribute("messages", messages)) .andExpect(MockMvcResultMatchers.view().name("messages/type")); } |
### Question:
CheckFundsGtZeroHandler { @EventListener public void handleRefund(final RefundProcessedEvent refundProcessedEvent) { final Long requestId = refundProcessedEvent.getRefund().getRequestId(); if (!hasTokenValueGtZero(fundService.getTotalFundsForRequest(requestId)) && hasRequestStatus(requestId, FUNDED)) { requestService.update(new UpdateRequestStatusCommand(requestId, OPEN)); } } CheckFundsGtZeroHandler(final FundService fundService, final RequestService requestService); @EventListener void handleFund(final RequestFundedEvent requestFundedEvent); @EventListener void handleRefund(final RefundProcessedEvent refundProcessedEvent); }### Answer:
@Test void onRefund_fundsPresent() { final long requestId = 254L; when(fundService.getTotalFundsForRequest(requestId)).thenReturn(Arrays.asList(TokenValueDtoMother.FND().totalAmount(new BigDecimal("45")).build(), TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("23")).build())); handler.handleRefund(new RefundProcessedEvent(Refund.builder().requestId(requestId).build())); verifyZeroInteractions(requestService); }
@Test void onRefund_noMoreFundsPresent() { final long requestId = 32L; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setStatus(FUNDED); when(fundService.getTotalFundsForRequest(requestId)).thenReturn(Arrays.asList(TokenValueDtoMother.FND().totalAmount(new BigDecimal("0")).build(), TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("0")).build())); when(requestService.findRequest(requestId)).thenReturn(requestDto); handler.handleRefund(new RefundProcessedEvent(Refund.builder().requestId(requestId).build())); verify(requestService).update(new UpdateRequestStatusCommand(requestId, OPEN)); }
@Test void onRefund_nothingPresent() { final long requestId = 87L; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setStatus(FUNDED); when(fundService.getTotalFundsForRequest(requestId)).thenReturn(new ArrayList<>()); when(requestService.findRequest(requestId)).thenReturn(requestDto); handler.handleRefund(new RefundProcessedEvent(Refund.builder().requestId(requestId).build())); verify(requestService).update(new UpdateRequestStatusCommand(requestId, OPEN)); }
@Test void onRefund_statusNotFUNDED() { final long requestId = 254L; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setStatus(OPEN); when(fundService.getTotalFundsForRequest(requestId)).thenReturn(Arrays.asList(TokenValueDtoMother.FND().totalAmount(new BigDecimal("0")).build(), TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("0")).build())); when(requestService.findRequest(requestId)).thenReturn(requestDto); handler.handleRefund(new RefundProcessedEvent(Refund.builder().requestId(requestId).build())); verify(requestService).findRequest(requestId); verifyNoMoreInteractions(requestService); } |
### Question:
CheckFundsGtZeroHandler { @EventListener public void handleFund(final RequestFundedEvent requestFundedEvent) { final Long requestId = requestFundedEvent.getRequestId(); if (hasTokenValueGtZero(fundService.getTotalFundsForRequest(requestId)) && hasRequestStatus(requestId, OPEN)) { requestService.update(new UpdateRequestStatusCommand(requestId, FUNDED)); } } CheckFundsGtZeroHandler(final FundService fundService, final RequestService requestService); @EventListener void handleFund(final RequestFundedEvent requestFundedEvent); @EventListener void handleRefund(final RefundProcessedEvent refundProcessedEvent); }### Answer:
@Test void onFund_fundsPresent() { final long requestId = 254L; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setStatus(OPEN); when(fundService.getTotalFundsForRequest(requestId)).thenReturn(Arrays.asList(TokenValueDtoMother.FND().totalAmount(new BigDecimal("45")).build(), TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("23")).build())); when(requestService.findRequest(requestId)).thenReturn(requestDto); handler.handleFund(RequestFundedEvent.builder().requestId(requestId).build()); verify(requestService).update(new UpdateRequestStatusCommand(requestId, FUNDED)); }
@Test void onFund_statusNotOPEN() { final long requestId = 254L; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); requestDto.setStatus(FUNDED); when(fundService.getTotalFundsForRequest(requestId)).thenReturn(Arrays.asList(TokenValueDtoMother.FND().totalAmount(new BigDecimal("45")).build(), TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("23")).build())); when(requestService.findRequest(requestId)).thenReturn(requestDto); handler.handleFund(RequestFundedEvent.builder().requestId(requestId).build()); verify(requestService).findRequest(requestId); verifyNoMoreInteractions(requestService); }
@Test void onFund_noMoreFundsPresent() { final long requestId = 32L; when(fundService.getTotalFundsForRequest(requestId)).thenReturn(Arrays.asList(TokenValueDtoMother.FND().totalAmount(new BigDecimal("0")).build(), TokenValueDtoMother.ZRX().totalAmount(new BigDecimal("0")).build())); handler.handleFund(RequestFundedEvent.builder().requestId(requestId).build()); verifyZeroInteractions(requestService); }
@Test void onFund_nothingPresent() { final long requestId = 87L; when(fundService.getTotalFundsForRequest(requestId)).thenReturn(new ArrayList<>()); handler.handleFund(RequestFundedEvent.builder().requestId(requestId).build()); verifyZeroInteractions(requestService); } |
### 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:
CreateGithubCommentOnFundHandler { @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) public void createGithubCommentOnRequestFunded(final RequestFundedEvent event) { if (addComment) { final IssueInformationDto issueInformation = requestService.findRequest(event.getRequestId()).getIssueInformation(); if (issueInformation.getPlatform() == Platform.GITHUB && !isCommentAlreadyPresent(issueInformation.getNumber(), issueInformation.getOwner(), issueInformation.getRepo())) { placeComment(event.getRequestId(), issueInformation.getNumber(), issueInformation.getOwner(), issueInformation.getRepo()); } } } CreateGithubCommentOnFundHandler(final GithubGateway githubGateway,
final GithubCommentFactory githubCommentFactory,
final RequestService requestService,
@Value("${github.add-comments:false}") final Boolean addComment,
@Value("${feign.client.github.username:fundrequest-notifier}") final String githubUser); @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) void createGithubCommentOnRequestFunded(final RequestFundedEvent event); }### Answer:
@Test public void ignoresGithubComment() { handler = new CreateGithubCommentOnFundHandler(githubGateway, githubCommentFactory, requestService, false, "fundrequest-notifier"); handler.createGithubCommentOnRequestFunded(createEvent(65478L)); verifyZeroInteractions(githubGateway); }
@Test public void postsGithubComment() { final long requestId = 65478L; final RequestFundedEvent event = createEvent(requestId); final String expectedMessage = "sgdhfjgkh"; final RequestDto requestDto = RequestDtoMother.fundRequestArea51(); final IssueInformationDto issueInformation = requestDto.getIssueInformation(); final ArgumentCaptor<CreateGithubComment> createGithubCommentArgumentCaptor = ArgumentCaptor.forClass(CreateGithubComment.class); when(githubCommentFactory.createFundedComment(requestId, issueInformation.getNumber())).thenReturn(expectedMessage); when(requestService.findRequest(requestId)).thenReturn(requestDto); handler.createGithubCommentOnRequestFunded(event); verify(githubGateway).createCommentOnIssue(eq(issueInformation.getOwner()), eq(issueInformation.getRepo()), eq(issueInformation.getNumber()), createGithubCommentArgumentCaptor.capture()); final CreateGithubComment githubComment = createGithubCommentArgumentCaptor.getValue(); assertThat(githubComment.getBody()).isEqualTo(expectedMessage); } |
### 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:
PendingFundCleaner { @Scheduled(fixedDelay = 300_000 ) public void cleanupPendingFunds() { pendingFundService.findAll() .stream() .filter(fund -> { try { return hasFailed(fund) || hasAged(fund); } catch (final Exception ex) { log.error("Unable to fetch status for transaction {} : ", fund.getTransactionHash(), ex.getMessage()); return false; } }) .forEach(pendingFundService::removePendingFund); } PendingFundCleaner(final PendingFundService pendingFundService,
final AzraelClient azraelClient); @Scheduled(fixedDelay = 300_000 /* 5 minutes */) void cleanupPendingFunds(); }### Answer:
@Test public void shouldRemoveFailedPendingFunds() { final PendingFund pendingFund = PendingFundMother.aPendingFund(); when(pendingFundService.findAll()) .thenReturn(of(pendingFund)); when(azraelClient.getTransactionStatus(prettify(pendingFund.getTransactionHash()))).thenReturn(TransactionStatus.FAILED); pendingFundCleaner.cleanupPendingFunds(); verify(pendingFundService).removePendingFund(pendingFund); }
@Test public void shouldRemoveAgedPendingFunds() { final PendingFund pendingFund = PendingFundMother.aPendingFund(); when(pendingFundService.findAll()) .thenReturn(of(pendingFund)); when(azraelClient.getTransactionStatus(prettify(pendingFund.getTransactionHash()))).thenReturn(TransactionStatus.SUCCEEDED); ReflectionUtils.set(pendingFund, "creationDate", LocalDateTime.now().minusDays(2)); pendingFundCleaner.cleanupPendingFunds(); verify(pendingFundService).removePendingFund(pendingFund); }
@Test public void shouldntRemoveWhenThrownExceptionFromAzrael() { final PendingFund pendingFund = PendingFundMother.aPendingFund(); when(pendingFundService.findAll()) .thenReturn(of(pendingFund)); when(azraelClient.getTransactionStatus(prettify(pendingFund.getTransactionHash()))).thenThrow(new IllegalArgumentException("problemos")); pendingFundCleaner.cleanupPendingFunds(); verify(pendingFundService, times(0)).removePendingFund(any(PendingFund.class)); } |
### 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:
RefundServiceImpl implements RefundService { @Override @Transactional(readOnly = true) public List<RefundRequestDto> findAllRefundRequestsFor(final long requestId, final RefundRequestStatus... statuses) { return refundRequestDtoMapper.mapToList(refundRequestRepository.findAllByRequestIdAndStatusIn(requestId, statuses)); } 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 public void findAllRefundRequestsForRequestIdAndStatus() { final long requestId = 3389L; final RefundRequestStatus status = PENDING; final List<RefundRequest> refundRequests = new ArrayList<>(); final ArrayList<RefundRequestDto> refundRequestDtos = new ArrayList<>(); when(refundRequestRepository.findAllByRequestIdAndStatusIn(requestId, status)).thenReturn(refundRequests); when(refundRequestDtoMapper.mapToList(same(refundRequests))).thenReturn(refundRequestDtos); final List<RefundRequestDto> result = refundService.findAllRefundRequestsFor(requestId, status); assertThat(result).isSameAs(refundRequestDtos); }
@Test public void findAllRefundRequestsForRequestIdAndFunderAddressAndStatus() { final long requestId = 347L; final String funderAddress = "0x6457hfd"; final RefundRequestStatus status = PROCESSED; final List<RefundRequest> refundRequests = new ArrayList<>(); final ArrayList<RefundRequestDto> refundRequestDtos = new ArrayList<>(); when(refundRequestRepository.findAllByRequestIdAndFunderAddressAndStatus(requestId, funderAddress, status)).thenReturn(refundRequests); when(refundRequestDtoMapper.mapToList(same(refundRequests))).thenReturn(refundRequestDtos); final List<RefundRequestDto> result = refundService.findAllRefundRequestsFor(requestId, funderAddress, status); assertThat(result).isSameAs(refundRequestDtos); } |
### 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:
FundRequestContractsService { @Cacheable(value = "possible_tokens", keyGenerator = "getAllPossibleTokensKeyGenerator") public List<TokenInfoDto> getAllPossibleTokens(final String platform, final String platformId) { return checkNotEmpty(getAllPossibleTokens().stream() .filter(token -> tokenWhitelistPreconditionContract.isValid(platform, platformId, token.getAddress())) .collect(Collectors.toList())); } FundRequestContractsService(final FundRequestContract fundRequestContract,
final TokenWhitelistPreconditionContract tokenWhitelistPreconditionContract,
final Web3j web3j,
final TokenInfoService tokenInfoService); FundRepositoryContract fundRepository(); ClaimRepositoryContract claimRepository(); @PostConstruct void init(); @Cacheable(value = "possible_tokens", keyGenerator = "getAllPossibleTokensKeyGenerator") List<TokenInfoDto> getAllPossibleTokens(final String platform, final String platformId); }### Answer:
@Test void testNoDuplicates() throws Exception { String platform = "GITHUB"; String platformId = "FundRequest|FR|area51|FR|3"; when(tokenWhitelistPreconditionContract.amountOftokens().send().intValue()).thenReturn(3); when(tokenWhitelistPreconditionContract.token(BigInteger.valueOf(0))).thenReturn(Optional.of("FND")); when(tokenWhitelistPreconditionContract.token(BigInteger.valueOf(1))).thenReturn(Optional.of("ZRX")); when(tokenWhitelistPreconditionContract.token(BigInteger.valueOf(2))).thenReturn(Optional.of("ZRX")); when(tokenInfoService.getTokenInfo("FND")).thenReturn(TokenInfoDto.builder().symbol("FND").address("FND").build()); when(tokenInfoService.getTokenInfo("ZRX")).thenReturn(TokenInfoDto.builder().symbol("ZRX").address("ZRX").build()); when(tokenWhitelistPreconditionContract.isValid(platform, platformId, "FND")).thenReturn(true); when(tokenWhitelistPreconditionContract.isValid(platform, platformId, "ZRX")).thenReturn(true); List<TokenInfoDto> possibleTokens = fundRequestContractsService.getAllPossibleTokens(platform, platformId); assertThat(possibleTokens.stream().map(TokenInfoDto::getSymbol).collect(Collectors.toList())).containsExactly("FND", "ZRX"); }
@Test public void getAllPossibleTokens_throwsResourceNotFoundException_whenEmpty() { final String platform = "GITHUB"; final String platformId = "FundRequest|FR|area51|FR|3"; when(tokenWhitelistPreconditionContract.token(any(BigInteger.class))).thenReturn(Optional.empty()); try { fundRequestContractsService.getAllPossibleTokens(platform, platformId); fail("A ResourceNotFoundException should have been thrown"); } catch (ResourceNotFoundException e) { assertThat(e).isNotNull(); } } |
### 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); } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.