repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewAttributesTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import org.sonar.api.resources.Qualifiers; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ViewAttributes.Type.APPLICATION; import static org.sonar.ce.task.projectanalysis.component.ViewAttributes.Type.PORTFOLIO; public class ViewAttributesTest { private ViewAttributes underTest; @Test public void create_portfolio() { underTest = new ViewAttributes(PORTFOLIO); assertThat(underTest.getType()).isEqualTo(PORTFOLIO); assertThat(underTest.getType().getQualifier()).isEqualTo(Qualifiers.VIEW); } @Test public void create_application() { underTest = new ViewAttributes(APPLICATION); assertThat(underTest.getType()).isEqualTo(APPLICATION); assertThat(underTest.getType().getQualifier()).isEqualTo(Qualifiers.APP); } @Test public void type_from_qualifier() { assertThat(ViewAttributes.Type.fromQualifier(Qualifiers.VIEW)).isEqualTo(PORTFOLIO); assertThat(ViewAttributes.Type.fromQualifier(Qualifiers.APP)).isEqualTo(APPLICATION); } @Test public void fail_if_unknown_view_qualifier() { assertThatThrownBy(() -> ViewAttributes.Type.fromQualifier(Qualifiers.PROJECT)) .isInstanceOf(IllegalStateException.class) .hasMessage("Qualifier 'TRK' is not supported"); } }
2,293
35.412698
90
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPathAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.junit.Test; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ViewsPathAwareVisitorTest { private static final int ROOT_KEY = 1; private static final Component SOME_TREE_ROOT = ViewsComponent.builder(VIEW, ROOT_KEY) .addChildren( ViewsComponent.builder(SUBVIEW, 11) .addChildren( ViewsComponent.builder(SUBVIEW, 111) .addChildren( ViewsComponent.builder(PROJECT_VIEW, 1111).build(), ViewsComponent.builder(PROJECT_VIEW, 1112).build() ) .build(), ViewsComponent.builder(SUBVIEW, 112) .addChildren( ViewsComponent.builder(PROJECT_VIEW, 1121).build() ) .build()) .build(), ViewsComponent.builder(SUBVIEW, 12) .addChildren( ViewsComponent.builder(SUBVIEW, 121) .addChildren( ViewsComponent.builder(SUBVIEW, 1211) .addChildren( ViewsComponent.builder(PROJECT_VIEW, 12111).build() ) .build() ).build() ).build() ).build(); @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, PRE_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitProjectView", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitAny", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitProjectView", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitProjectView", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitAny", 12111, 1211, of(12111, 1211, 121, 12, 1)), viewsCallRecord("visitProjectView", 12111, 1211, of(12111, 1211, 121, 12, 1)) ).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_SUBVIEW() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.SUBVIEW, PRE_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)) ).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_VIEW() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.VIEW, PRE_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)) ).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitProjectView", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitAny", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitProjectView", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitProjectView", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 12111, 1211, of(12111, 1211, 121, 12, 1)), viewsCallRecord("visitProjectView", 12111, 1211, of(12111, 1211, 121, 12, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)) ).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_SUBVIEW() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.SUBVIEW, POST_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)) ).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_VIEW() { CallRecorderPathAwareVisitor underTest = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.VIEW, POST_ORDER); new PathAwareCrawler<>(underTest).visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)) ).iterator(); verifyCallRecords(expected, underTest.callsRecords.iterator()); } private static void verifyCallRecords(Iterator<PathAwareCallRecord> expected, Iterator<PathAwareCallRecord> actual) { int i = 1; while (expected.hasNext()) { assertThat(actual.next()).describedAs(String.format("Expected call n°%s does not match actual call n°%s", i, i)).isEqualTo(expected.next()); i++; } assertThat(expected.hasNext()).isEqualTo(actual.hasNext()); } private static PathAwareCallRecord viewsCallRecord(String method, int currentRef, @Nullable Integer parentRef, List<Integer> path) { return PathAwareCallRecord.viewsCallRecord(method, String.valueOf(currentRef), currentRef, parentRef, ROOT_KEY, path); } }
10,479
47.294931
146
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPostOrderDepthTraversalTypeAwareCrawlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; public class ViewsPostOrderDepthTraversalTypeAwareCrawlerTest { private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); private static final Component PROJECT_VIEW_6 = component(PROJECT_VIEW, 6); private static final Component SUBVIEW_4 = component(SUBVIEW, 4, PROJECT_VIEW_5, PROJECT_VIEW_6); private static final Component SUBVIEW_3 = component(SUBVIEW, 3, SUBVIEW_4); private static final Component SUBVIEW_2 = component(SUBVIEW, 2, SUBVIEW_3); private static final Component COMPONENT_TREE = component(VIEW, 1, SUBVIEW_2); private final CallRecorderTypeAwareVisitor viewVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.VIEW, POST_ORDER); private final CallRecorderTypeAwareVisitor subViewVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.SUBVIEW, POST_ORDER); private final CallRecorderTypeAwareVisitor projectViewVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER); private final DepthTraversalTypeAwareCrawler viewCrawler = new DepthTraversalTypeAwareCrawler(viewVisitor); private final DepthTraversalTypeAwareCrawler subViewCrawler = new DepthTraversalTypeAwareCrawler(subViewVisitor); private final DepthTraversalTypeAwareCrawler projectViewCrawler = new DepthTraversalTypeAwareCrawler(projectViewVisitor); @Test public void visit_null_Component_throws_NPE() { assertThatThrownBy(() -> projectViewCrawler.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_viewView_with_depth_PROJECT_VIEW_calls_visit_viewView() { Component component = component(PROJECT_VIEW, 1); projectViewCrawler.visit(component); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitProjectView", component)); } @Test public void visit_subView_with_depth_PROJECT_VIEW_calls_visit_subView() { Component component = component(SUBVIEW, 1); projectViewCrawler.visit(component); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitSubView", component)); } @Test public void visit_view_with_depth_PROJECT_VIEW_calls_visit_view() { Component component = component(VIEW, 1); projectViewCrawler.visit(component); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitView", component)); } @Test public void visit_viewView_with_depth_SUBVIEW_does_not_call_visit_viewView_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); subViewCrawler.visit(component); assertThat(subViewVisitor.callsRecords).isEmpty(); } @Test public void visit_subView_with_depth_SUBVIEW_calls_visit_subView() { Component component = component(SUBVIEW, 1); subViewCrawler.visit(component); assertThat(subViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitSubView", component)); } @Test public void visit_view_with_depth_SUBVIEW_calls_visit_view() { Component component = component(VIEW, 1); subViewCrawler.visit(component); assertThat(subViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitView", component)); } @Test public void visit_viewView_with_depth_VIEW_does_not_call_visit_viewView_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); viewCrawler.visit(component); assertThat(viewVisitor.callsRecords).isEmpty(); } @Test public void visit_subView_with_depth_VIEW_does_not_call_visit_subView_nor_visitAny() { Component component = component(SUBVIEW, 1); viewCrawler.visit(component); assertThat(viewVisitor.callsRecords).isEmpty(); } @Test public void visit_view_with_depth_VIEW_calls_visit_view() { Component component = component(VIEW, 1); viewCrawler.visit(component); assertThat(viewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitView", component)); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { projectViewCrawler.visit(COMPONENT_TREE); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", PROJECT_VIEW_5), viewsCallRecord("visitProjectView", PROJECT_VIEW_5), viewsCallRecord("visitAny", PROJECT_VIEW_6), viewsCallRecord("visitProjectView", PROJECT_VIEW_6), viewsCallRecord("visitAny", SUBVIEW_4), viewsCallRecord("visitSubView", SUBVIEW_4), viewsCallRecord("visitAny", SUBVIEW_3), viewsCallRecord("visitSubView", SUBVIEW_3), viewsCallRecord("visitAny", SUBVIEW_2), viewsCallRecord("visitSubView", SUBVIEW_2), viewsCallRecord("visitAny", COMPONENT_TREE), viewsCallRecord("visitView", COMPONENT_TREE)); } @Test public void verify_visit_call_when_visit_tree_with_depth_SUBVIEW() { subViewCrawler.visit(COMPONENT_TREE); assertThat(subViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", SUBVIEW_4), viewsCallRecord("visitSubView", SUBVIEW_4), viewsCallRecord("visitAny", SUBVIEW_3), viewsCallRecord("visitSubView", SUBVIEW_3), viewsCallRecord("visitAny", SUBVIEW_2), viewsCallRecord("visitSubView", SUBVIEW_2), viewsCallRecord("visitAny", COMPONENT_TREE), viewsCallRecord("visitView", COMPONENT_TREE)); } @Test public void verify_visit_call_when_visit_tree_with_depth_VIEW() { viewCrawler.visit(COMPONENT_TREE); assertThat(viewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", COMPONENT_TREE), viewsCallRecord("visitView", COMPONENT_TREE)); } private static Component component(Component.Type type, int ref, Component... children) { return ViewsComponent.builder(type, ref).addChildren(children).build(); } private static CallRecord viewsCallRecord(String methodName, Component component) { return CallRecord.viewsCallRecord(methodName, component.getKey()); } }
7,610
39.057895
143
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsPreOrderDepthTraversalTypeAwareCrawlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ViewsPreOrderDepthTraversalTypeAwareCrawlerTest { private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); private static final Component PROJECT_VIEW_6 = component(PROJECT_VIEW, 6); private static final Component SUBVIEW_4 = component(SUBVIEW, 4, PROJECT_VIEW_5, PROJECT_VIEW_6); private static final Component SUBVIEW_3 = component(SUBVIEW, 3, SUBVIEW_4); private static final Component SUBVIEW_2 = component(SUBVIEW, 2, SUBVIEW_3); private static final Component COMPONENT_TREE = component(VIEW, 1, SUBVIEW_2); private final CallRecorderTypeAwareVisitor viewVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.VIEW, PRE_ORDER); private final CallRecorderTypeAwareVisitor subViewVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.SUBVIEW, PRE_ORDER); private final CallRecorderTypeAwareVisitor projectViewVisitor = new CallRecorderTypeAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, PRE_ORDER); private final DepthTraversalTypeAwareCrawler viewCrawler = new DepthTraversalTypeAwareCrawler(viewVisitor); private final DepthTraversalTypeAwareCrawler subViewCrawler = new DepthTraversalTypeAwareCrawler(subViewVisitor); private final DepthTraversalTypeAwareCrawler projectViewCrawler = new DepthTraversalTypeAwareCrawler(projectViewVisitor); @Test public void visit_null_Component_throws_NPE() { assertThatThrownBy(() -> projectViewCrawler.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_projectView_with_depth_PROJECT_VIEW_calls_visit_projectView() { Component component = component(PROJECT_VIEW, 1); projectViewCrawler.visit(component); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitProjectView", component)); } @Test public void visit_subView_with_depth_PROJECT_VIEW_calls_visit_subView() { Component component = component(SUBVIEW, 1); projectViewCrawler.visit(component); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitSubView", component)); } @Test public void visit_view_with_depth_PROJECT_VIEW_calls_visit_view() { Component component = component(VIEW, 1); projectViewCrawler.visit(component); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitView", component)); } @Test public void visit_projectView_with_depth_SUBVIEW_does_not_call_visit_projectView_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); subViewCrawler.visit(component); assertThat(subViewVisitor.callsRecords).isEmpty(); } @Test public void visit_subView_with_depth_SUBVIEW_calls_visit_subView() { Component component = component(SUBVIEW, 1); subViewCrawler.visit(component); assertThat(subViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitSubView", component)); } @Test public void visit_view_with_depth_SUBVIEW_calls_visit_view() { Component component = component(VIEW, 1); subViewCrawler.visit(component); assertThat(subViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitView", component)); } @Test public void visit_projectView_with_depth_VIEW_does_not_call_visit_projectView_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); viewCrawler.visit(component); assertThat(viewVisitor.callsRecords).isEmpty(); } @Test public void visit_subView_with_depth_VIEW_does_not_call_visit_subView_nor_visitAny() { Component component = component(SUBVIEW, 1); viewCrawler.visit(component); assertThat(viewVisitor.callsRecords).isEmpty(); } @Test public void visit_view_with_depth_VIEW_calls_visit_view_nor_visitAny() { Component component = component(VIEW, 1); viewCrawler.visit(component); assertThat(viewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", component), viewsCallRecord("visitView", component)); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { projectViewCrawler.visit(COMPONENT_TREE); assertThat(projectViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", COMPONENT_TREE), viewsCallRecord("visitView", COMPONENT_TREE), viewsCallRecord("visitAny", SUBVIEW_2), viewsCallRecord("visitSubView", SUBVIEW_2), viewsCallRecord("visitAny", SUBVIEW_3), viewsCallRecord("visitSubView", SUBVIEW_3), viewsCallRecord("visitAny", SUBVIEW_4), viewsCallRecord("visitSubView", SUBVIEW_4), viewsCallRecord("visitAny", PROJECT_VIEW_5), viewsCallRecord("visitProjectView", PROJECT_VIEW_5), viewsCallRecord("visitAny", PROJECT_VIEW_6), viewsCallRecord("visitProjectView", PROJECT_VIEW_6)); } @Test public void verify_visit_call_when_visit_tree_with_depth_SUBVIEW() { subViewCrawler.visit(COMPONENT_TREE); assertThat(subViewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", COMPONENT_TREE), viewsCallRecord("visitView", COMPONENT_TREE), viewsCallRecord("visitAny", SUBVIEW_2), viewsCallRecord("visitSubView", SUBVIEW_2), viewsCallRecord("visitAny", SUBVIEW_3), viewsCallRecord("visitSubView", SUBVIEW_3), viewsCallRecord("visitAny", SUBVIEW_4), viewsCallRecord("visitSubView", SUBVIEW_4)); } @Test public void verify_visit_call_when_visit_tree_with_depth_VIEW() { viewCrawler.visit(COMPONENT_TREE); assertThat(viewVisitor.callsRecords).containsExactly( viewsCallRecord("visitAny", COMPONENT_TREE), viewsCallRecord("visitView", COMPONENT_TREE)); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ViewsComponent.builder(type, ref).addChildren(children).build(); } private static CallRecord viewsCallRecord(String methodName, Component component) { return CallRecord.viewsCallRecord(methodName, component.getKey()); } }
7,654
39.289474
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; import org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.spy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ViewsVisitorsCrawlerTest { private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); private static final Component SUBVIEW_4 = component(SUBVIEW, 4, PROJECT_VIEW_5); private static final Component SUBVIEW_3 = component(SUBVIEW, 3, SUBVIEW_4); private static final Component SUBVIEW_2 = component(SUBVIEW, 2, SUBVIEW_3); private static final Component COMPONENT_TREE = component(VIEW, 1, SUBVIEW_2); private final TypeAwareVisitor spyPreOrderTypeAwareVisitor = spy(new TestTypeAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, PRE_ORDER)); private final TypeAwareVisitor spyPostOrderTypeAwareVisitor = spy(new TestTypeAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER)); private final TestPathAwareVisitor spyPathAwareVisitor = spy(new TestPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER)); @Test public void execute_each_visitor_on_each_level() { InOrder inOrder = inOrder(spyPostOrderTypeAwareVisitor, spyPathAwareVisitor); VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPostOrderTypeAwareVisitor, spyPathAwareVisitor), false); underTest.visit(COMPONENT_TREE); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(PROJECT_VIEW_5); inOrder.verify(spyPostOrderTypeAwareVisitor).visitProjectView(PROJECT_VIEW_5); inOrder.verify(spyPathAwareVisitor).visitAny(eq(PROJECT_VIEW_5), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitProjectView(eq(PROJECT_VIEW_5), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(SUBVIEW_4); inOrder.verify(spyPostOrderTypeAwareVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spyPathAwareVisitor).visitAny(eq(SUBVIEW_4), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitSubView(eq(SUBVIEW_4), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(SUBVIEW_3); inOrder.verify(spyPostOrderTypeAwareVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spyPathAwareVisitor).visitAny(eq(SUBVIEW_3), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitSubView(eq(SUBVIEW_3), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(SUBVIEW_2); inOrder.verify(spyPostOrderTypeAwareVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spyPathAwareVisitor).visitAny(eq(SUBVIEW_2), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitSubView(eq(SUBVIEW_2), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPostOrderTypeAwareVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyPostOrderTypeAwareVisitor).visitView(COMPONENT_TREE); inOrder.verify(spyPathAwareVisitor).visitAny(eq(COMPONENT_TREE), any(PathAwareVisitor.Path.class)); inOrder.verify(spyPathAwareVisitor).visitView(eq(COMPONENT_TREE), any(PathAwareVisitor.Path.class)); } @Test public void execute_pre_visitor_before_post_visitor() { InOrder inOrder = inOrder(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor); VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor), false); underTest.visit(COMPONENT_TREE); inOrder.verify(spyPreOrderTypeAwareVisitor).visitView(COMPONENT_TREE); inOrder.verify(spyPreOrderTypeAwareVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spyPreOrderTypeAwareVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spyPreOrderTypeAwareVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spyPreOrderTypeAwareVisitor).visitProjectView(PROJECT_VIEW_5); inOrder.verify(spyPostOrderTypeAwareVisitor).visitProjectView(PROJECT_VIEW_5); inOrder.verify(spyPostOrderTypeAwareVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spyPostOrderTypeAwareVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spyPostOrderTypeAwareVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spyPostOrderTypeAwareVisitor).visitView(COMPONENT_TREE); } @Test public void fail_with_IAE_when_visitor_is_not_path_aware_or_type_aware() { assertThatThrownBy(() -> { ComponentVisitor componentVisitor = new ComponentVisitor() { @Override public Order getOrder() { return PRE_ORDER; } @Override public CrawlerDepthLimit getMaxDepth() { return CrawlerDepthLimit.PROJECT_VIEW; } }; new VisitorsCrawler(Arrays.asList(componentVisitor)); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only TypeAwareVisitor and PathAwareVisitor can be used"); } @Test public void getCumulativeDurations_returns_an_empty_map_when_computation_is_disabled_in_constructor() { VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor), false); underTest.visit(COMPONENT_TREE); assertThat(underTest.getCumulativeDurations()).isEmpty(); } @Test public void getCumulativeDurations_returns_an_non_empty_map_when_computation_is_enabled_in_constructor() { VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(spyPreOrderTypeAwareVisitor, spyPostOrderTypeAwareVisitor), true); underTest.visit(COMPONENT_TREE); assertThat(underTest.getCumulativeDurations()).hasSize(2); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ViewsComponent.builder(type, ref).addChildren(children).build(); } private static class TestTypeAwareVisitor extends TypeAwareVisitorAdapter { public TestTypeAwareVisitor(CrawlerDepthLimit maxDepth, Order order) { super(maxDepth, order); } } private static class TestPathAwareVisitor extends PathAwareVisitorAdapter<Integer> { public TestPathAwareVisitor(CrawlerDepthLimit maxDepth, Order order) { super(maxDepth, order, new SimpleStackElementFactory<Integer>() { @Override public Integer createForAny(Component component) { return Integer.valueOf(component.getKey()); } }); } } }
7,848
47.153374
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPathAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; import java.util.Iterator; import java.util.List; import javax.annotation.Nullable; import org.junit.Test; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ViewsVisitorsCrawlerWithPathAwareVisitorTest { private static final int ROOT_REF = 1; private static final ViewsComponent SOME_TREE_ROOT = ViewsComponent.builder(VIEW, ROOT_REF) .addChildren( ViewsComponent.builder(SUBVIEW, 11) .addChildren( ViewsComponent.builder(SUBVIEW, 111) .addChildren( ViewsComponent.builder(PROJECT_VIEW, 1111).build(), ViewsComponent.builder(PROJECT_VIEW, 1112).build()) .build(), ViewsComponent.builder(SUBVIEW, 112) .addChildren( ViewsComponent.builder(PROJECT_VIEW, 1121).build()) .build()) .build(), ViewsComponent.builder(SUBVIEW, 12) .addChildren( ViewsComponent.builder(SUBVIEW, 121) .addChildren( ViewsComponent.builder(SUBVIEW, 1211) .addChildren( ViewsComponent.builder(PROJECT_VIEW, 12111).build()) .build()) .build()) .build()) .build(); @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, PRE_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitProjectView", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitAny", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitProjectView", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitProjectView", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitAny", 12111, 1211, of(12111, 1211, 121, 12, 1)), viewsCallRecord("visitProjectView", 12111, 1211, of(12111, 1211, 121, 12, 1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_SUBVIEW() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.SUBVIEW, PRE_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_preOrder_visit_call_when_visit_tree_with_depth_VIEW() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.VIEW, PRE_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitProjectView", 1111, 111, of(1111, 111, 11, 1)), viewsCallRecord("visitAny", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitProjectView", 1112, 111, of(1112, 111, 11, 1)), viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitProjectView", 1121, 112, of(1121, 112, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 12111, 1211, of(12111, 1211, 121, 12, 1)), viewsCallRecord("visitProjectView", 12111, 1211, of(12111, 1211, 121, 12, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_SUBVIEW() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.SUBVIEW, POST_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 111, 11, of(111, 11, 1)), viewsCallRecord("visitSubView", 111, 11, of(111, 11, 1)), viewsCallRecord("visitAny", 112, 11, of(112, 11, 1)), viewsCallRecord("visitSubView", 112, 11, of(112, 11, 1)), viewsCallRecord("visitAny", 11, 1, of(11, 1)), viewsCallRecord("visitSubView", 11, 1, of(11, 1)), viewsCallRecord("visitAny", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitSubView", 1211, 121, of(1211, 121, 12, 1)), viewsCallRecord("visitAny", 121, 12, of(121, 12, 1)), viewsCallRecord("visitSubView", 121, 12, of(121, 12, 1)), viewsCallRecord("visitAny", 12, 1, of(12, 1)), viewsCallRecord("visitSubView", 12, 1, of(12, 1)), viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } @Test public void verify_postOrder_visit_call_when_visit_tree_with_depth_VIEW() { CallRecorderPathAwareVisitor visitor = new CallRecorderPathAwareVisitor(CrawlerDepthLimit.VIEW, POST_ORDER); VisitorsCrawler underTest = newVisitorsCrawler(visitor); underTest.visit(SOME_TREE_ROOT); Iterator<PathAwareCallRecord> expected = of( viewsCallRecord("visitAny", 1, null, of(1)), viewsCallRecord("visitView", 1, null, of(1))).iterator(); verifyCallRecords(expected, visitor.callsRecords.iterator()); } private static void verifyCallRecords(Iterator<PathAwareCallRecord> expected, Iterator<PathAwareCallRecord> actual) { while (expected.hasNext()) { assertThat(actual.next()).isEqualTo(expected.next()); } } private static PathAwareCallRecord viewsCallRecord(String method, int currentRef, @Nullable Integer parentRef, List<Integer> path) { return PathAwareCallRecord.viewsCallRecord(method, String.valueOf(currentRef), currentRef, parentRef, ROOT_REF, path); } private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) { return new VisitorsCrawler(Arrays.asList(componentVisitor)); } }
10,635
48.240741
134
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; import org.junit.Test; import org.mockito.InOrder; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ViewsVisitorsCrawlerWithPostOrderTypeAwareVisitorTest { private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); private static final Component PROJECT_VIEW_6 = component(PROJECT_VIEW, 6); private static final Component SUBVIEW_4 = component(SUBVIEW, 4, PROJECT_VIEW_5, PROJECT_VIEW_6); private static final Component SUBVIEW_3 = component(SUBVIEW, 3, SUBVIEW_4); private static final Component SUBVIEW_2 = component(SUBVIEW, 2, SUBVIEW_3); private static final Component COMPONENT_TREE = component(VIEW, 1, SUBVIEW_2); private final TypeAwareVisitor spyViewVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.VIEW, POST_ORDER) { }); private final TypeAwareVisitor spySubViewVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.SUBVIEW, POST_ORDER) { }); private final TypeAwareVisitor spyProjectViewVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT_VIEW, POST_ORDER) { }); private final InOrder inOrder = inOrder(spyViewVisitor, spySubViewVisitor, spyProjectViewVisitor); @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); assertThatThrownBy(() -> underTest.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_projectView_with_depth_PROJECT_VIEW_calls_visit_projectView() { Component component = component(PROJECT_VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(component); inOrder.verify(spyProjectViewVisitor).visitAny(component); inOrder.verify(spyProjectViewVisitor).visitProjectView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_subview_with_depth_PROJECT_VIEW_calls_visit_subview() { Component component = component(SUBVIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(component); inOrder.verify(spyProjectViewVisitor).visitAny(component); inOrder.verify(spyProjectViewVisitor).visitSubView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_view_with_depth_PROJECT_VIEW_calls_visit_view() { Component component = component(VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(component); inOrder.verify(spyProjectViewVisitor).visitAny(component); inOrder.verify(spyProjectViewVisitor).visitView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_projectView_with_depth_SUBVIEW_does_not_call_visit_projectView_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(component); inOrder.verify(spySubViewVisitor, never()).visitProjectView(component); inOrder.verify(spySubViewVisitor, never()).visitAny(component); } @Test public void visit_subview_with_depth_SUBVIEW_calls_visit_subview() { Component component = component(SUBVIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(component); inOrder.verify(spySubViewVisitor).visitAny(component); inOrder.verify(spySubViewVisitor).visitSubView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_view_with_depth_SUBVIEW_calls_visit_view() { Component component = component(VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(component); inOrder.verify(spySubViewVisitor).visitAny(component); inOrder.verify(spySubViewVisitor).visitView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_projectView_with_depth_VIEW_does_not_call_visit_projectView_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(component); inOrder.verify(spyViewVisitor, never()).visitProjectView(component); inOrder.verify(spyViewVisitor, never()).visitAny(component); } @Test public void visit_subview_with_depth_VIEW_does_not_call_visit_subview_nor_visitAny() { Component component = component(SUBVIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(component); inOrder.verify(spyViewVisitor, never()).visitSubView(component); inOrder.verify(spyViewVisitor, never()).visitProjectView(component); inOrder.verify(spyViewVisitor, never()).visitAny(component); } @Test public void visit_view_with_depth_VIEW_calls_visit_view() { Component component = component(VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(component); inOrder.verify(spyViewVisitor).visitAny(component); inOrder.verify(spyViewVisitor).visitView(component); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyProjectViewVisitor).visitAny(PROJECT_VIEW_5); inOrder.verify(spyProjectViewVisitor).visitProjectView(PROJECT_VIEW_5); inOrder.verify(spyProjectViewVisitor).visitAny(PROJECT_VIEW_6); inOrder.verify(spyProjectViewVisitor).visitProjectView(PROJECT_VIEW_6); inOrder.verify(spyProjectViewVisitor).visitAny(SUBVIEW_4); inOrder.verify(spyProjectViewVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spyProjectViewVisitor).visitAny(SUBVIEW_3); inOrder.verify(spyProjectViewVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spyProjectViewVisitor).visitAny(SUBVIEW_2); inOrder.verify(spyProjectViewVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spyProjectViewVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyProjectViewVisitor).visitView(COMPONENT_TREE); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_SUBVIEW() { VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spySubViewVisitor).visitAny(SUBVIEW_4); inOrder.verify(spySubViewVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spySubViewVisitor).visitAny(SUBVIEW_3); inOrder.verify(spySubViewVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spySubViewVisitor).visitAny(SUBVIEW_2); inOrder.verify(spySubViewVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spySubViewVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spySubViewVisitor).visitView(COMPONENT_TREE); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_VIEW() { VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyViewVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyViewVisitor).visitView(COMPONENT_TREE); inOrder.verifyNoMoreInteractions(); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ViewsComponent.builder(type, ref).addChildren(children).build(); } private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) { return new VisitorsCrawler(Arrays.asList(componentVisitor)); } }
8,988
41.804762
134
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/component/ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import java.util.Arrays; import org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.PRE_ORDER; public class ViewsVisitorsCrawlerWithPreOrderTypeAwareVisitorTest { private static final Component PROJECT_VIEW_5 = component(PROJECT_VIEW, 5); private static final Component PROJECT_VIEW_6 = component(PROJECT_VIEW, 6); private static final Component SUBVIEW_4 = component(SUBVIEW, 4, PROJECT_VIEW_5, PROJECT_VIEW_6); private static final Component SUBVIEW_3 = component(SUBVIEW, 3, SUBVIEW_4); private static final Component SUBVIEW_2 = component(SUBVIEW, 2, SUBVIEW_3); private static final Component COMPONENT_TREE = component(VIEW, 1, SUBVIEW_2); private final TypeAwareVisitor spyViewVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.VIEW, PRE_ORDER) { }); private final TypeAwareVisitor spySubViewVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.SUBVIEW, PRE_ORDER) { }); private final TypeAwareVisitor spyProjectViewVisitor = spy(new TypeAwareVisitorAdapter(CrawlerDepthLimit.PROJECT_VIEW, PRE_ORDER) { }); private final InOrder inOrder = inOrder(spyViewVisitor, spySubViewVisitor, spyProjectViewVisitor); @Test public void visit_null_Component_throws_NPE() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); assertThatThrownBy(() -> underTest.visit(null)) .isInstanceOf(NullPointerException.class); } @Test public void visit_file_with_depth_PROJECT_VIEW_calls_visit_file() { Component component = component(PROJECT_VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(component); inOrder.verify(spyProjectViewVisitor).visitAny(component); inOrder.verify(spyProjectViewVisitor).visitProjectView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_subview_with_depth_PROJECT_VIEW_calls_visit_subview() { Component component = component(SUBVIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(component); inOrder.verify(spyProjectViewVisitor).visitAny(component); inOrder.verify(spyProjectViewVisitor).visitSubView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_view_with_depth_PROJECT_VIEW_calls_visit_view() { Component component = component(VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(component); inOrder.verify(spyProjectViewVisitor).visitView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_file_with_depth_SUBVIEW_does_not_call_visit_file_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(component); inOrder.verify(spySubViewVisitor, never()).visitProjectView(component); inOrder.verify(spySubViewVisitor, never()).visitAny(component); } @Test public void visit_subview_with_depth_SUBVIEW_calls_visit_subview() { Component component = component(SUBVIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(component); inOrder.verify(spySubViewVisitor).visitAny(component); inOrder.verify(spySubViewVisitor).visitSubView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_view_with_depth_SUBVIEW_calls_visit_view() { Component component = component(VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(component); inOrder.verify(spySubViewVisitor).visitAny(component); inOrder.verify(spySubViewVisitor).visitView(component); inOrder.verifyNoMoreInteractions(); } @Test public void visit_file_with_depth_VIEW_does_not_call_visit_file_nor_visitAny() { Component component = component(PROJECT_VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(component); inOrder.verify(spyViewVisitor, never()).visitProjectView(component); inOrder.verify(spyViewVisitor, never()).visitAny(component); } @Test public void visit_subview_with_depth_VIEW_does_not_call_visit_subview_nor_visitAny() { Component component = component(SUBVIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(component); inOrder.verify(spyViewVisitor, never()).visitProjectView(component); inOrder.verify(spyViewVisitor, never()).visitAny(component); } @Test public void visit_view_with_depth_VIEW_calls_visit_view_nor_visitAny() { Component component = component(VIEW, 1); VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(component); inOrder.verify(spyViewVisitor).visitAny(component); inOrder.verify(spyViewVisitor).visitView(component); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_PROJECT_VIEW() { VisitorsCrawler underTest = newVisitorsCrawler(spyProjectViewVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyProjectViewVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyProjectViewVisitor).visitView(COMPONENT_TREE); inOrder.verify(spyProjectViewVisitor).visitAny(SUBVIEW_2); inOrder.verify(spyProjectViewVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spyProjectViewVisitor).visitAny(SUBVIEW_3); inOrder.verify(spyProjectViewVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spyProjectViewVisitor).visitAny(SUBVIEW_4); inOrder.verify(spyProjectViewVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spyProjectViewVisitor).visitAny(PROJECT_VIEW_5); inOrder.verify(spyProjectViewVisitor).visitProjectView(PROJECT_VIEW_5); inOrder.verify(spyProjectViewVisitor).visitAny(PROJECT_VIEW_6); inOrder.verify(spyProjectViewVisitor).visitProjectView(PROJECT_VIEW_6); inOrder.verifyNoMoreInteractions(); } @Test public void verify_visit_call_when_visit_tree_with_depth_SUBVIEW() { VisitorsCrawler underTest = newVisitorsCrawler(spySubViewVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spySubViewVisitor).visitView(COMPONENT_TREE); inOrder.verify(spySubViewVisitor).visitSubView(SUBVIEW_2); inOrder.verify(spySubViewVisitor).visitSubView(SUBVIEW_3); inOrder.verify(spySubViewVisitor).visitSubView(SUBVIEW_4); inOrder.verify(spyViewVisitor, never()).visitProjectView(PROJECT_VIEW_5); inOrder.verify(spyViewVisitor, never()).visitProjectView(PROJECT_VIEW_6); } @Test public void verify_visit_call_when_visit_tree_with_depth_VIEW() { VisitorsCrawler underTest = newVisitorsCrawler(spyViewVisitor); underTest.visit(COMPONENT_TREE); inOrder.verify(spyViewVisitor).visitAny(COMPONENT_TREE); inOrder.verify(spyViewVisitor).visitView(COMPONENT_TREE); inOrder.verify(spyViewVisitor, never()).visitSubView(SUBVIEW_2); inOrder.verify(spyViewVisitor, never()).visitSubView(SUBVIEW_3); } private static Component component(final Component.Type type, final int ref, final Component... children) { return ViewsComponent.builder(type, ref).addChildren(children).build(); } private static VisitorsCrawler newVisitorsCrawler(ComponentVisitor componentVisitor) { return new VisitorsCrawler(Arrays.asList(componentVisitor)); } }
8,797
41.298077
133
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/container/ProjectAnalysisTaskContainerPopulatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.container; import com.google.common.collect.ImmutableList; import java.lang.reflect.Modifier; import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; import org.junit.Test; import org.reflections.Reflections; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.projectanalysis.step.PersistComponentsStep; import org.sonar.ce.task.projectanalysis.task.ListTaskContainer; import org.sonar.ce.task.step.ComputationStep; import static com.google.common.collect.Sets.difference; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ProjectAnalysisTaskContainerPopulatorTest { private static final String PROJECTANALYSIS_STEP_PACKAGE = "org.sonar.ce.task.projectanalysis.step"; private final CeTask task = mock(CeTask.class); private final ProjectAnalysisTaskContainerPopulator underTest = new ProjectAnalysisTaskContainerPopulator(task, null); @Test public void item_is_added_to_the_container() { ListTaskContainer container = new ListTaskContainer(); underTest.populateContainer(container); assertThat(container.getAddedComponents()).contains(task); } @Test public void all_computation_steps_are_added_in_order_to_the_container() { ListTaskContainer container = new ListTaskContainer(); underTest.populateContainer(container); Set<String> computationStepClassNames = container.getAddedComponents().stream() .map(s -> { if (s instanceof Class) { return (Class<?>) s; } return null; }) .filter(Objects::nonNull) .filter(ComputationStep.class::isAssignableFrom) .map(Class::getCanonicalName) .collect(Collectors.toSet()); assertThat(difference(retrieveStepPackageStepsCanonicalNames(PROJECTANALYSIS_STEP_PACKAGE), computationStepClassNames)).isEmpty(); } /** * Compute set of canonical names of classes implementing ComputationStep in the specified package using reflection. */ private static Set<Object> retrieveStepPackageStepsCanonicalNames(String packageName) { Reflections reflections = new Reflections(packageName); return reflections.getSubTypesOf(ComputationStep.class).stream() .filter(input -> !Modifier.isAbstract(input.getModifiers())) .map(Class::getCanonicalName) .filter(Objects::nonNull) .collect(Collectors.toSet()); } @Test public void at_least_one_core_step_is_added_to_the_container() { ListTaskContainer container = new ListTaskContainer(); underTest.populateContainer(container); assertThat(container.getAddedComponents()).contains(PersistComponentsStep.class); } @Test public void Components_of_ReportAnalysisComponentProvider_are_added_to_the_container() { Object object = new Object(); Class<MyClass> clazz = MyClass.class; ReportAnalysisComponentProvider componentProvider = mock(ReportAnalysisComponentProvider.class); when(componentProvider.getComponents()).thenReturn(ImmutableList.of(object, clazz)); ProjectAnalysisTaskContainerPopulator populator = new ProjectAnalysisTaskContainerPopulator(task, new ReportAnalysisComponentProvider[] {componentProvider}); ListTaskContainer container = new ListTaskContainer(); container.add(componentProvider); populator.populateContainer(container); assertThat(container.getAddedComponents()).contains(object, clazz); } private static final class MyClass { } }
4,382
37.447368
161
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicateTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CrossProjectDuplicateTest { private static final String FILE_KEY_1 = "file key 1"; private static final String FILE_KEY_2 = "file key 2"; @Test public void constructors_throws_NPE_if_fileKey_is_null() { assertThatThrownBy(() -> new CrossProjectDuplicate(null, new TextBlock(1, 1))) .isInstanceOf(NullPointerException.class) .hasMessage("fileKey can not be null"); } @Test public void constructors_throws_NPE_if_textBlock_is_null() { assertThatThrownBy(() -> new CrossProjectDuplicate(FILE_KEY_1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("textBlock of duplicate can not be null"); } @Test public void getTextBlock_returns_TextBlock_constructor_argument() { TextBlock textBlock = new TextBlock(2, 3); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock).getTextBlock()).isSameAs(textBlock); } @Test public void getFileKey_returns_constructor_argument() { assertThat(new CrossProjectDuplicate(FILE_KEY_1, new TextBlock(2, 3)).getFileKey()).isEqualTo(FILE_KEY_1); } @Test public void equals_compares_on_file_and_TextBlock() { TextBlock textBlock1 = new TextBlock(1, 2); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock1)).isEqualTo(new CrossProjectDuplicate(FILE_KEY_1, new TextBlock(1, 2))); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock1)).isNotEqualTo(new CrossProjectDuplicate(FILE_KEY_1, new TextBlock(1, 1))); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock1)).isNotEqualTo(new CrossProjectDuplicate(FILE_KEY_2, textBlock1)); } @Test public void hashcode_depends_on_file_and_TextBlock() { TextBlock textBlock = new TextBlock(1, 2); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock)).hasSameHashCodeAs(new CrossProjectDuplicate(FILE_KEY_1, textBlock)); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock).hashCode()).isNotEqualTo(new CrossProjectDuplicate(FILE_KEY_2, textBlock).hashCode()); assertThat(new CrossProjectDuplicate(FILE_KEY_1, textBlock).hashCode()).isNotEqualTo(new CrossProjectDuplicate(FILE_KEY_2, new TextBlock(1, 1)).hashCode()); } @Test public void verify_toString() { assertThat(new CrossProjectDuplicate(FILE_KEY_1, new TextBlock(1, 2))).hasToString("CrossProjectDuplicate{fileKey='file key 1', textBlock=TextBlock{start=1, end=2}}"); } }
3,440
40.963415
171
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/CrossProjectDuplicationStatusHolderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class CrossProjectDuplicationStatusHolderImplTest { @Rule public LogTester logTester = new LogTester(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private CrossProjectDuplicationStatusHolderImpl underTest = new CrossProjectDuplicationStatusHolderImpl(analysisMetadataHolder); @Before public void before() { logTester.setLevel(Level.DEBUG); } @Test public void cross_project_duplication_is_enabled_when_enabled_in_report_and_no_branch() { analysisMetadataHolder .setCrossProjectDuplicationEnabled(true) .setBranch(newBranch(true)); underTest.start(); assertThat(underTest.isEnabled()).isTrue(); assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is enabled"); } @Test public void cross_project_duplication_is_disabled_when_not_enabled_in_report() { analysisMetadataHolder .setCrossProjectDuplicationEnabled(false) .setBranch(newBranch(true)); underTest.start(); assertThat(underTest.isEnabled()).isFalse(); assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is disabled because it's disabled in the analysis report"); } @Test public void cross_project_duplication_is_disabled_when_branch_is_used() { analysisMetadataHolder .setCrossProjectDuplicationEnabled(true) .setBranch(newBranch(false)); underTest.start(); assertThat(underTest.isEnabled()).isFalse(); assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is disabled because of a branch is used"); } @Test public void cross_project_duplication_is_disabled_when_not_enabled_in_report_and_when_branch_is_used() { analysisMetadataHolder .setCrossProjectDuplicationEnabled(false) .setBranch(newBranch(false)); underTest.start(); assertThat(underTest.isEnabled()).isFalse(); assertThat(logTester.logs(Level.DEBUG)).containsOnly("Cross project duplication is disabled because it's disabled in the analysis report"); } @Test public void flag_is_build_in_start() { analysisMetadataHolder .setCrossProjectDuplicationEnabled(true) .setBranch(newBranch(true)); underTest.start(); assertThat(underTest.isEnabled()).isTrue(); // Change the boolean from the report. This can never happen, it's only to validate that the flag is build in the start method analysisMetadataHolder.setCrossProjectDuplicationEnabled(false); assertThat(underTest.isEnabled()).isTrue(); } @Test public void isEnabled_throws_ISE_when_start_have_not_been_called_before() { assertThatThrownBy(() -> underTest.isEnabled()) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Flag hasn't been initialized, the start() should have been called before"); } private static Branch newBranch(boolean supportsCrossProjectCpd) { Branch branch = mock(Branch.class); when(branch.supportsCrossProjectCpd()).thenReturn(supportsCrossProjectCpd); return branch; } }
4,468
36.554622
143
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicateTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; public class DuplicateTest { @Test public void duplicate_implementations_are_not_equals_to_each_other_even_if_TextBlock_is_the_same() { TextBlock textBlock = new TextBlock(1, 2); InnerDuplicate innerDuplicate = new InnerDuplicate(textBlock); InProjectDuplicate inProjectDuplicate = new InProjectDuplicate(ReportComponent.builder(Component.Type.FILE, 1).build(), textBlock); CrossProjectDuplicate crossProjectDuplicate = new CrossProjectDuplicate("file key", textBlock); assertThat(innerDuplicate.equals(inProjectDuplicate)).isFalse(); assertThat(innerDuplicate.equals(crossProjectDuplicate)).isFalse(); assertThat(inProjectDuplicate.equals(crossProjectDuplicate)).isFalse(); } }
1,827
42.52381
135
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationMeasuresTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static com.google.common.base.Preconditions.checkArgument; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class DuplicationMeasuresTest { private static final int ROOT_REF = 1; private static final int DIRECTORY_REF = 1234; private static final int FILE_1_REF = 12341; private static final int FILE_2_REF = 12342; private static final int FILE_3_REF = 1261; private static final int FILE_4_REF = 1262; private static final int FILE_5_REF = 1263; private static final FileAttributes FILE_1_ATTRS = mock(FileAttributes.class); private static final FileAttributes FILE_2_ATTRS = mock(FileAttributes.class); private static final FileAttributes FILE_3_ATTRS = mock(FileAttributes.class); private static final FileAttributes FILE_4_ATTRS = mock(FileAttributes.class); private static final FileAttributes FILE_5_ATTRS = mock(FileAttributes.class); private static final String SOME_FILE_KEY = "some file key"; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF) .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(FILE_1_ATTRS).build(), builder(FILE, FILE_2_REF).setFileAttributes(FILE_2_ATTRS).build()) .build(), builder(FILE, FILE_3_REF).setFileAttributes(FILE_3_ATTRS).build(), builder(FILE, FILE_4_REF).setFileAttributes(FILE_4_ATTRS).build(), builder(FILE, FILE_5_REF).setFileAttributes(FILE_5_ATTRS).build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(DUPLICATED_BLOCKS) .add(DUPLICATED_FILES) .add(DUPLICATED_LINES) .add(DUPLICATED_LINES_DENSITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(treeRootHolder); private DuplicationMeasures underTest = new DuplicationMeasures(treeRootHolder, metricRepository, measureRepository, duplicationRepository); @Before public void before() { when(FILE_5_ATTRS.isUnitTest()).thenReturn(true); } @Test public void compute_duplicated_blocks_one_for_original_one_for_each_InnerDuplicate() { TextBlock original = new TextBlock(1, 1); duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(2, 2), new TextBlock(3, 3), new TextBlock(2, 3)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_BLOCKS_KEY, 4); } @Test public void dont_compute_duplicated_blocks_for_test_files() { duplicationRepository.addDuplication(FILE_5_REF, new TextBlock(1, 1), new TextBlock(3, 3)); duplicationRepository.addDuplication(FILE_5_REF, new TextBlock(2, 2), new TextBlock(3, 3)); underTest.execute(); assertRawMeasureValue(FILE_5_REF, DUPLICATED_BLOCKS_KEY, 0); assertRawMeasureValue(FILE_5_REF, DUPLICATED_FILES_KEY, 0); } @Test public void compute_duplicated_blocks_does_not_count_blocks_only_once_it_assumes_consistency_from_duplication_data() { duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(1, 1), new TextBlock(3, 3)); duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(2, 2), new TextBlock(3, 3)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_BLOCKS_KEY, 4); } @Test public void compute_duplicated_blocks_one_for_original_and_ignores_InProjectDuplicate() { duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(1, 1), FILE_2_REF, new TextBlock(2, 2)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_BLOCKS_KEY, 1); } @Test public void compute_duplicated_blocks_one_for_original_and_ignores_CrossProjectDuplicate() { duplicationRepository.addCrossProjectDuplication(FILE_1_REF, new TextBlock(1, 1), SOME_FILE_KEY, new TextBlock(2, 2)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_BLOCKS_KEY, 1); } @Test public void compute_and_aggregate_duplicated_blocks_from_single_duplication() { addDuplicatedBlock(FILE_1_REF, 10); addDuplicatedBlock(FILE_2_REF, 40); addDuplicatedBlock(FILE_4_REF, 5); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_BLOCKS_KEY, 10); assertRawMeasureValue(FILE_2_REF, DUPLICATED_BLOCKS_KEY, 40); assertRawMeasureValue(FILE_3_REF, DUPLICATED_BLOCKS_KEY, 0); assertRawMeasureValue(FILE_4_REF, DUPLICATED_BLOCKS_KEY, 5); assertRawMeasureValue(DIRECTORY_REF, DUPLICATED_BLOCKS_KEY, 50); assertRawMeasureValue(ROOT_REF, DUPLICATED_BLOCKS_KEY, 55); } @Test public void compute_and_aggregate_duplicated_blocks_to_zero_when_no_duplication() { underTest.execute(); assertComputedAndAggregatedToZeroInt(DUPLICATED_BLOCKS_KEY); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_of_a_single_line() { TextBlock original = new TextBlock(1, 1); duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(2, 2)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_KEY, 2); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_ignores_InProjectDuplicate() { TextBlock original = new TextBlock(1, 1); duplicationRepository.addDuplication(FILE_1_REF, original, FILE_2_REF, new TextBlock(2, 2)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_KEY, 1); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_ignores_CrossProjectDuplicate() { TextBlock original = new TextBlock(1, 1); duplicationRepository.addCrossProjectDuplication(FILE_1_REF, original, SOME_FILE_KEY, new TextBlock(2, 2)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_KEY, 1); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate() { TextBlock original = new TextBlock(1, 5); duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(10, 11)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_KEY, 7); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_only_once() { TextBlock original = new TextBlock(1, 12); duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(10, 11), new TextBlock(11, 15)); duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(2, 2), new TextBlock(96, 96)); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_KEY, 16); } @Test public void compute_and_aggregate_duplicated_files() { addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_3_REF, 10); addDuplicatedBlock(FILE_4_REF, 50); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_FILES_KEY, 1); assertRawMeasureValue(FILE_2_REF, DUPLICATED_FILES_KEY, 0); assertRawMeasureValue(FILE_3_REF, DUPLICATED_FILES_KEY, 1); assertRawMeasureValue(FILE_4_REF, DUPLICATED_FILES_KEY, 1); assertRawMeasureValue(DIRECTORY_REF, DUPLICATED_FILES_KEY, 1); assertRawMeasureValue(ROOT_REF, DUPLICATED_FILES_KEY, 3); } @Test public void compute_and_aggregate_zero_duplicated_files_when_no_duplication_data() { underTest.execute(); assertComputedAndAggregatedToZeroInt(DUPLICATED_FILES_KEY); } @Test public void compute_and_aggregate_duplicated_lines() { addDuplicatedBlock(FILE_1_REF, 10); addDuplicatedBlock(FILE_2_REF, 9); addDuplicatedBlock(FILE_4_REF, 7); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_KEY, 10); assertRawMeasureValue(FILE_2_REF, DUPLICATED_LINES_KEY, 9); assertRawMeasureValue(FILE_3_REF, DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(FILE_4_REF, DUPLICATED_LINES_KEY, 7); assertRawMeasureValue(DIRECTORY_REF, DUPLICATED_LINES_KEY, 19); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_KEY, 26); } @Test public void compute_and_aggregate_zero_duplicated_line_when_no_duplication() { underTest.execute(); assertComputedAndAggregatedToZeroInt(DUPLICATED_LINES_KEY); } @Test public void compute_and_aggregate_duplicated_lines_density_using_lines() { addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_2_REF, 3); when(FILE_1_ATTRS.getLines()).thenReturn(10); when(FILE_2_ATTRS.getLines()).thenReturn(40); // this should have no effect as it's a test file when(FILE_5_ATTRS.getLines()).thenReturn(1_000_000); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_DENSITY_KEY, 20d); assertRawMeasureValue(FILE_2_REF, DUPLICATED_LINES_DENSITY_KEY, 7.5d); assertNoRawMeasure(FILE_3_REF, DUPLICATED_LINES_DENSITY_KEY); assertNoRawMeasure(FILE_4_REF, DUPLICATED_LINES_DENSITY_KEY); assertRawMeasureValue(DIRECTORY_REF, DUPLICATED_LINES_DENSITY_KEY, 10d); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_DENSITY_KEY, 10d); } @Test public void compute_zero_percent_duplicated_lines_density_when_there_is_no_duplication() { when(FILE_1_ATTRS.getLines()).thenReturn(10); when(FILE_2_ATTRS.getLines()).thenReturn(40); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); assertRawMeasureValue(FILE_2_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); assertNoRawMeasure(FILE_3_REF, DUPLICATED_LINES_DENSITY_KEY); assertNoRawMeasure(FILE_4_REF, DUPLICATED_LINES_DENSITY_KEY); assertRawMeasureValue(DIRECTORY_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); } @Test public void dont_compute_duplicated_lines_density_when_lines_is_zero() { when(FILE_1_ATTRS.getLines()).thenReturn(0); when(FILE_2_ATTRS.getLines()).thenReturn(0); underTest.execute(); assertNoRawMeasures(DUPLICATED_LINES_DENSITY_KEY); } @Test public void compute_100_percent_duplicated_lines_density() { addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_2_REF, 3); when(FILE_1_ATTRS.getLines()).thenReturn(2); when(FILE_2_ATTRS.getLines()).thenReturn(3); underTest.execute(); assertRawMeasureValue(FILE_1_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); assertRawMeasureValue(FILE_2_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); assertNoRawMeasure(FILE_3_REF, DUPLICATED_LINES_DENSITY_KEY); assertNoRawMeasure(FILE_4_REF, DUPLICATED_LINES_DENSITY_KEY); assertRawMeasureValue(DIRECTORY_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); } /** * Adds duplication blocks of a single line (each line is specific to its block). * This is a very simple use case, convenient for unit tests but more realistic and complex use cases must be tested separately. */ private void addDuplicatedBlock(int fileRef, int blockCount) { checkArgument(blockCount > 1, "BlockCount can not be less than 2"); TextBlock original = new TextBlock(1, 1); TextBlock[] duplicates = new TextBlock[blockCount - 1]; for (int i = 10; i < blockCount + 9; i++) { duplicates[i - 10] = new TextBlock(i, i); } duplicationRepository.addDuplication(fileRef, original, duplicates); } private void assertNoRawMeasures(String metricKey) { assertThat(measureRepository.getAddedRawMeasures(FILE_1_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(FILE_2_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(DIRECTORY_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF).get(metricKey)).isNull(); } private void assertNoRawMeasure(int componentRef, String metricKey) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey)).isNotPresent(); } private void assertRawMeasureValue(int componentRef, String metricKey, int value) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getIntValue()).isEqualTo(value); } private void assertRawMeasureValue(int componentRef, String metricKey, double value) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getDoubleValue()).isEqualTo(value); } private void assertComputedAndAggregatedToZeroInt(String metricKey) { assertRawMeasureValue(FILE_1_REF, metricKey, 0); assertRawMeasureValue(FILE_2_REF, metricKey, 0); assertRawMeasureValue(FILE_3_REF, metricKey, 0); assertRawMeasureValue(FILE_4_REF, metricKey, 0); assertRawMeasureValue(DIRECTORY_REF, metricKey, 0); assertRawMeasureValue(ROOT_REF, metricKey, 0); } }
15,140
39.811321
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import org.assertj.core.api.Assertions; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.util.WrapInSingleElementArray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class DuplicationRepositoryImplTest { private static final Component FILE_COMPONENT_1 = ReportComponent.builder(Component.Type.FILE, 1).build(); private static final Component FILE_COMPONENT_2 = ReportComponent.builder(Component.Type.FILE, 2).build(); private static final Duplication SOME_DUPLICATION = createDuplication(1, 2); private DuplicationRepository underTest = new DuplicationRepositoryImpl(); @Test public void getDuplications_throws_NPE_if_Component_argument_is_null() { assertThatThrownBy(() -> underTest.getDuplications(null)) .isInstanceOf(NullPointerException.class) .hasMessage("file can not be null"); } @Test @UseDataProvider("allComponentTypesButFile") public void getDuplications_throws_IAE_if_Component_type_is_not_FILE(Component.Type type) { assertThatThrownBy(() -> { Component component = mockComponentGetType(type); underTest.getDuplications(component); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("type of file must be FILE"); } @Test public void getDuplications_returns_empty_set_when_repository_is_empty() { assertNoDuplication(FILE_COMPONENT_1); } @Test public void add_throws_NPE_if_file_argument_is_null() { assertThatThrownBy(() -> underTest.add(null, SOME_DUPLICATION)) .isInstanceOf(NullPointerException.class) .hasMessage("file can not be null"); } @Test public void addDuplication_inner_throws_NPE_if_duplication_argument_is_null() { assertThatThrownBy(() -> underTest.add(FILE_COMPONENT_1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("duplication can not be null"); } @Test @UseDataProvider("allComponentTypesButFile") public void addDuplication_inner_throws_IAE_if_file_type_is_not_FILE(Component.Type type) { assertThatThrownBy(() -> { Component component = mockComponentGetType(type); underTest.add(component, SOME_DUPLICATION); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("type of file must be FILE"); } @Test public void added_duplication_is_returned_as_is_by_getDuplications() { underTest.add(FILE_COMPONENT_1, SOME_DUPLICATION); Iterable<Duplication> duplications = underTest.getDuplications(FILE_COMPONENT_1); Assertions.assertThat(duplications).hasSize(1); assertThat(duplications.iterator().next()).isSameAs(SOME_DUPLICATION); assertNoDuplication(FILE_COMPONENT_2); } @Test public void added_duplication_does_not_avoid_same_duplication_inserted_twice_but_only_one_is_returned() { underTest.add(FILE_COMPONENT_1, SOME_DUPLICATION); underTest.add(FILE_COMPONENT_1, SOME_DUPLICATION); Iterable<Duplication> duplications = underTest.getDuplications(FILE_COMPONENT_1); Assertions.assertThat(duplications).hasSize(1); assertThat(duplications.iterator().next()).isSameAs(SOME_DUPLICATION); assertNoDuplication(FILE_COMPONENT_2); } @Test public void added_duplications_are_returned_in_any_order_and_associated_to_the_right_file() { underTest.add(FILE_COMPONENT_1, SOME_DUPLICATION); underTest.add(FILE_COMPONENT_1, createDuplication(2, 4)); underTest.add(FILE_COMPONENT_1, createDuplication(2, 3)); underTest.add(FILE_COMPONENT_2, createDuplication(2, 3)); underTest.add(FILE_COMPONENT_2, createDuplication(1, 2)); assertThat(underTest.getDuplications(FILE_COMPONENT_1)).containsOnly(SOME_DUPLICATION, createDuplication(2, 3), createDuplication(2, 4)); assertThat(underTest.getDuplications(FILE_COMPONENT_2)).containsOnly(createDuplication(1, 2), createDuplication(2, 3)); } private static Duplication createDuplication(int originalLine, int duplicateLine) { return new Duplication(new TextBlock(originalLine, originalLine), Arrays.asList(new InnerDuplicate(new TextBlock(duplicateLine, duplicateLine)))); } @DataProvider public static Object[][] allComponentTypesButFile() { return Arrays.stream(Component.Type.values()) .filter(t -> t != Component.Type.FILE) .map(WrapInSingleElementArray.INSTANCE) .toArray(Object[][]::new); } private void assertNoDuplication(Component component) { assertThat(underTest.getDuplications(component)).isEmpty(); } private Component mockComponentGetType(Component.Type type) { Component component = mock(Component.class); when(component.getType()).thenReturn(type); return component; } }
6,096
39.111842
150
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationRepositoryRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.util.Arrays; import java.util.Collections; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ComponentProvider; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderComponentProvider; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public class DuplicationRepositoryRule extends ExternalResource implements DuplicationRepository { @CheckForNull private final ComponentProvider componentProvider; private DuplicationRepositoryImpl delegate; private final Multimap<Component, TextBlock> componentRefsWithInnerDuplications = ArrayListMultimap.create(); private final Multimap<Component, TextBlock> componentRefsWithInProjectDuplications = ArrayListMultimap.create(); private final Multimap<Component, TextBlock> componentRefsWithCrossProjectDuplications = ArrayListMultimap.create(); private DuplicationRepositoryRule(TreeRootHolder treeRootHolder) { this.componentProvider = new TreeRootHolderComponentProvider(treeRootHolder); } public DuplicationRepositoryRule() { this.componentProvider = null; } public static DuplicationRepositoryRule create(TreeRootHolderRule treeRootHolder) { return new DuplicationRepositoryRule(treeRootHolder); } public static DuplicationRepositoryRule create() { return new DuplicationRepositoryRule(); } @Override protected void before() { this.delegate = new DuplicationRepositoryImpl(); } @Override protected void after() { if (this.componentProvider != null) { this.componentProvider.reset(); } this.componentRefsWithInnerDuplications.clear(); this.componentRefsWithInProjectDuplications.clear(); this.componentRefsWithCrossProjectDuplications.clear(); this.delegate = null; } public Iterable<Duplication> getDuplications(int fileRef) { ensureComponentProviderInitialized(); return delegate.getDuplications(componentProvider.getByRef(fileRef)); } public void add(int fileRef, Duplication duplication) { ensureComponentProviderInitialized(); delegate.add(componentProvider.getByRef(fileRef), duplication); } public DuplicationRepositoryRule addDuplication(int fileRef, TextBlock original, TextBlock... duplicates) { ensureComponentProviderInitialized(); Component component = componentProvider.getByRef(fileRef); checkArgument(!componentRefsWithInnerDuplications.containsEntry(component, original), "Inner duplications for file %s and original %s already set", fileRef, original); checkArgument(!componentRefsWithInProjectDuplications.containsEntry(component, original), "InProject duplications for file %s and original %s already set. Use add(int, Duplication) instead", fileRef, original); componentRefsWithInnerDuplications.put(component, original); delegate.add( component, new Duplication( original, Arrays.stream(duplicates).map(InnerDuplicate::new).collect(Collectors.toList()))); return this; } public DuplicationRepositoryRule addDuplication(int fileRef, TextBlock original, int otherFileRef, TextBlock duplicate) { ensureComponentProviderInitialized(); Component component = componentProvider.getByRef(fileRef); checkArgument(!componentRefsWithInProjectDuplications.containsEntry(component, original), "InProject duplications for file %s and original %s already set", fileRef, original); checkArgument(!componentRefsWithInnerDuplications.containsEntry(component, original), "Inner duplications for file %s and original %s already set. Use add(int, Duplication) instead", fileRef, original); componentRefsWithInProjectDuplications.put(component, original); delegate.add(component, new Duplication( original, Collections.singletonList(new InProjectDuplicate(componentProvider.getByRef(otherFileRef), duplicate)))); return this; } public DuplicationRepositoryRule addExtendedProjectDuplication(int fileRef, TextBlock original, int otherFileRef, TextBlock duplicate) { ensureComponentProviderInitialized(); Component component = componentProvider.getByRef(fileRef); checkArgument(!componentRefsWithCrossProjectDuplications.containsEntry(component, original), "CrossProject duplications for file %s and original %s already set", fileRef); componentRefsWithCrossProjectDuplications.put(component, original); delegate.add(componentProvider.getByRef(fileRef), new Duplication( original, Collections.singletonList(new InExtendedProjectDuplicate(componentProvider.getByRef(otherFileRef), duplicate)))); return this; } public DuplicationRepositoryRule addCrossProjectDuplication(int fileRef, TextBlock original, String otherFileKey, TextBlock duplicate) { ensureComponentProviderInitialized(); Component component = componentProvider.getByRef(fileRef); checkArgument(!componentRefsWithCrossProjectDuplications.containsEntry(component, original), "CrossProject duplications for file %s and original %s already set", fileRef); componentRefsWithCrossProjectDuplications.put(component, original); delegate.add(componentProvider.getByRef(fileRef), new Duplication( original, Collections.singletonList(new CrossProjectDuplicate(otherFileKey, duplicate)))); return this; } @Override public Iterable<Duplication> getDuplications(Component file) { return delegate.getDuplications(file); } @Override public void add(Component file, Duplication duplication) { TextBlock original = duplication.getOriginal(); checkArgument(!componentRefsWithInnerDuplications.containsEntry(file, original), "Inner duplications for file %s and original %s already set", file, original); checkArgument(!componentRefsWithInProjectDuplications.containsEntry(file, original), "InProject duplications for file %s and original %s already set", file, original); checkArgument(!componentRefsWithCrossProjectDuplications.containsEntry(file, original), "CrossProject duplications for file %s and original %s already set", file, original); delegate.add(file, duplication); } private void ensureComponentProviderInitialized() { requireNonNull(this.componentProvider, "Methods with component reference can not be used unless a TreeRootHolder has been provided when instantiating the rule"); this.componentProvider.ensureInitialized(); } }
7,740
44.269006
179
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/DuplicationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class DuplicationTest { private static final TextBlock SOME_ORIGINAL_TEXTBLOCK = new TextBlock(1, 2); private static final TextBlock TEXT_BLOCK_1 = new TextBlock(2, 2); private static final TextBlock TEXT_BLOCK_2 = new TextBlock(2, 3); private static final ReportComponent FILE_COMPONENT_1 = ReportComponent.builder(Component.Type.FILE, 1).build(); private static final ReportComponent FILE_COMPONENT_2 = ReportComponent.builder(Component.Type.FILE, 2).build(); private static final String FILE_KEY_1 = "1"; private static final String FILE_KEY_2 = "2"; @Test public void constructor_throws_NPE_if_original_is_null() { assertThatThrownBy(() -> new Duplication(null, Collections.emptyList())) .isInstanceOf(NullPointerException.class) .hasMessage("original TextBlock can not be null"); } @Test public void constructor_throws_NPE_if_duplicates_is_null() { assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, null)) .isInstanceOf(NullPointerException.class) .hasMessage("duplicates can not be null"); } @Test public void constructor_throws_IAE_if_duplicates_is_empty() { assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Collections.emptyList())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("duplicates can not be empty"); } @Test public void constructor_throws_NPE_if_duplicates_contains_null() { assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(mock(Duplicate.class), null, mock(Duplicate.class)))) .isInstanceOf(NullPointerException.class) .hasMessage("duplicates can not contain null"); } @Test public void constructor_throws_IAE_if_duplicates_contains_InnerDuplicate_of_original() { assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(mock(Duplicate.class), new InnerDuplicate(SOME_ORIGINAL_TEXTBLOCK), mock(Duplicate.class)))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("TextBlock of an InnerDuplicate can not be the original TextBlock"); } @Test public void constructor_throws_IAE_when_attempting_to_sort_Duplicate_of_unkown_type() { assertThatThrownBy(() -> new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new MyDuplicate(), new MyDuplicate()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported type of Duplicate " + MyDuplicate.class.getName()); } private static final class MyDuplicate implements Duplicate { @Override public TextBlock getTextBlock() { throw new UnsupportedOperationException("getTextBlock not implemented"); } } @Test public void getOriginal_returns_original() { assertThat(new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_1))) .getOriginal()).isSameAs(SOME_ORIGINAL_TEXTBLOCK); } @Test public void getDuplicates_sorts_duplicates_by_Inner_then_InProject_then_CrossProject() { CrossProjectDuplicate crossProjectDuplicate = new CrossProjectDuplicate("some key", TEXT_BLOCK_1); InProjectDuplicate inProjectDuplicate = new InProjectDuplicate(FILE_COMPONENT_1, TEXT_BLOCK_1); InnerDuplicate innerDuplicate = new InnerDuplicate(TEXT_BLOCK_1); Duplication duplication = new Duplication( SOME_ORIGINAL_TEXTBLOCK, shuffledList(crossProjectDuplicate, inProjectDuplicate, innerDuplicate)); assertThat(duplication.getDuplicates()).containsExactly(innerDuplicate, inProjectDuplicate, crossProjectDuplicate); } @Test public void getDuplicates_sorts_duplicates_of_InnerDuplicate_by_TextBlock() { InnerDuplicate innerDuplicate1 = new InnerDuplicate(TEXT_BLOCK_2); InnerDuplicate innerDuplicate2 = new InnerDuplicate(new TextBlock(3, 3)); InnerDuplicate innerDuplicate3 = new InnerDuplicate(new TextBlock(3, 4)); InnerDuplicate innerDuplicate4 = new InnerDuplicate(new TextBlock(4, 4)); assertGetDuplicatesSorting(innerDuplicate1, innerDuplicate2, innerDuplicate3, innerDuplicate4); } @Test public void getDuplicates_sorts_duplicates_of_InProjectDuplicate_by_component_then_TextBlock() { InProjectDuplicate innerDuplicate1 = new InProjectDuplicate(FILE_COMPONENT_1, TEXT_BLOCK_1); InProjectDuplicate innerDuplicate2 = new InProjectDuplicate(FILE_COMPONENT_1, TEXT_BLOCK_2); InProjectDuplicate innerDuplicate3 = new InProjectDuplicate(FILE_COMPONENT_2, TEXT_BLOCK_1); InProjectDuplicate innerDuplicate4 = new InProjectDuplicate(FILE_COMPONENT_2, TEXT_BLOCK_2); assertGetDuplicatesSorting(innerDuplicate1, innerDuplicate2, innerDuplicate3, innerDuplicate4); } @Test public void getDuplicates_sorts_duplicates_of_CrossProjectDuplicate_by_fileKey_then_TextBlock() { CrossProjectDuplicate innerDuplicate1 = new CrossProjectDuplicate(FILE_KEY_1, TEXT_BLOCK_1); CrossProjectDuplicate innerDuplicate2 = new CrossProjectDuplicate(FILE_KEY_1, TEXT_BLOCK_2); CrossProjectDuplicate innerDuplicate3 = new CrossProjectDuplicate(FILE_KEY_2, TEXT_BLOCK_1); CrossProjectDuplicate innerDuplicate4 = new CrossProjectDuplicate(FILE_KEY_2, TEXT_BLOCK_2); assertGetDuplicatesSorting(innerDuplicate1, innerDuplicate2, innerDuplicate3, innerDuplicate4); } @Test public void equals_compares_on_original_and_duplicates() { Duplication duplication = new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_1))); assertThat(duplication) .isEqualTo(duplication) .isEqualTo(new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_1)))) .isNotEqualTo(new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_2)))) .isNotEqualTo(new Duplication(TEXT_BLOCK_1, Arrays.asList(new InnerDuplicate(SOME_ORIGINAL_TEXTBLOCK)))); } @Test public void hashcode_is_based_on_original_only() { Duplication duplication = new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_1))); assertThat(duplication).hasSameHashCodeAs(new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_1)))); assertThat(duplication.hashCode()).isNotEqualTo(new Duplication(SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_2))).hashCode()); assertThat(duplication.hashCode()).isNotEqualTo(new Duplication(TEXT_BLOCK_1, Arrays.asList(new InnerDuplicate(SOME_ORIGINAL_TEXTBLOCK))).hashCode()); } @Test public void verify_toString() { Duplication duplication = new Duplication( SOME_ORIGINAL_TEXTBLOCK, Arrays.asList(new InnerDuplicate(TEXT_BLOCK_1))); assertThat(duplication) .hasToString("Duplication{original=TextBlock{start=1, end=2}, duplicates=[InnerDuplicate{textBlock=TextBlock{start=2, end=2}}]}"); } @SafeVarargs private final <T extends Duplicate> void assertGetDuplicatesSorting(T... expected) { Duplication duplication = new Duplication(SOME_ORIGINAL_TEXTBLOCK, shuffledList(expected)); assertThat(duplication.getDuplicates()).containsExactly(expected); } private static List<Duplicate> shuffledList(Duplicate... duplicates) { List<Duplicate> res = new ArrayList<>(Arrays.asList(duplicates)); Collections.shuffle(res); return res; } }
8,613
45.311828
177
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InProjectDuplicateTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class InProjectDuplicateTest { private static final Component FILE_1 = ReportComponent.builder(Component.Type.FILE, 1).build(); private static final Component FILE_2 = ReportComponent.builder(Component.Type.FILE, 2).build(); @Test public void constructors_throws_NPE_if_file_is_null() { assertThatThrownBy(() -> new InProjectDuplicate(null, new TextBlock(1, 1))) .isInstanceOf(NullPointerException.class) .hasMessage("file can not be null"); } @Test public void constructors_throws_NPE_if_textBlock_is_null() { assertThatThrownBy(() -> new InProjectDuplicate(FILE_1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("textBlock of duplicate can not be null"); } @Test public void constructors_throws_IAE_if_type_of_file_argument_is_not_FILE() { assertThatThrownBy(() -> new InProjectDuplicate(ReportComponent.builder(Component.Type.PROJECT, 1).build(), new TextBlock(1, 1))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("file must be of type FILE"); } @Test public void getTextBlock_returns_TextBlock_constructor_argument() { TextBlock textBlock = new TextBlock(2, 3); assertThat(new InProjectDuplicate(FILE_1, textBlock).getTextBlock()).isSameAs(textBlock); } @Test public void getFile_returns_Component_constructor_argument() { assertThat(new InProjectDuplicate(FILE_1, new TextBlock(2, 3)).getFile()).isSameAs(FILE_1); } @Test public void equals_compares_on_file_and_TextBlock() { TextBlock textBlock1 = new TextBlock(1, 2); assertThat(new InProjectDuplicate(FILE_1, textBlock1)).isEqualTo(new InProjectDuplicate(FILE_1, new TextBlock(1, 2))); assertThat(new InProjectDuplicate(FILE_1, textBlock1)).isNotEqualTo(new InProjectDuplicate(FILE_1, new TextBlock(1, 1))); assertThat(new InProjectDuplicate(FILE_1, textBlock1)).isNotEqualTo(new InProjectDuplicate(FILE_2, textBlock1)); } @Test public void hashcode_depends_on_file_and_TextBlock() { TextBlock textBlock = new TextBlock(1, 2); assertThat(new InProjectDuplicate(FILE_1, textBlock)).hasSameHashCodeAs(new InProjectDuplicate(FILE_1, textBlock)); assertThat(new InProjectDuplicate(FILE_1, textBlock).hashCode()).isNotEqualTo(new InProjectDuplicate(FILE_2, textBlock).hashCode()); assertThat(new InProjectDuplicate(FILE_1, textBlock).hashCode()).isNotEqualTo(new InProjectDuplicate(FILE_2, new TextBlock(1, 1)).hashCode()); } @Test public void verify_toString() { assertThat(new InProjectDuplicate(FILE_1, new TextBlock(1, 2))) .hasToString("InProjectDuplicate{file=ReportComponent{ref=1, key='key_1', type=FILE}, textBlock=TextBlock{start=1, end=2}}"); } }
3,891
40.849462
146
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/InnerDuplicateTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class InnerDuplicateTest { @Test public void constructors_throws_NPE_if_textBlock_is_null() { assertThatThrownBy(() -> new InnerDuplicate(null)) .isInstanceOf(NullPointerException.class) .hasMessage("textBlock of duplicate can not be null"); } @Test public void getTextBlock_returns_TextBlock_constructor_argument() { TextBlock textBlock = new TextBlock(2, 3); assertThat(new InnerDuplicate(textBlock).getTextBlock()).isSameAs(textBlock); } @Test public void equals_compares_on_TextBlock() { assertThat(new InnerDuplicate(new TextBlock(1, 2))).isEqualTo(new InnerDuplicate(new TextBlock(1, 2))); assertThat(new InnerDuplicate(new TextBlock(1, 2))).isNotEqualTo(new InnerDuplicate(new TextBlock(1, 1))); } @Test public void hashcode_is_TextBlock_hashcode() { TextBlock textBlock = new TextBlock(1, 2); assertThat(new InnerDuplicate(textBlock)).hasSameHashCodeAs(textBlock); } @Test public void verify_toString() { assertThat(new InnerDuplicate(new TextBlock(1, 2))).hasToString("InnerDuplicate{textBlock=TextBlock{start=1, end=2}}"); } }
2,171
35.813559
123
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/IntegrateCrossProjectDuplicationsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.log.CeTaskMessages; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.duplications.block.Block; import org.sonar.duplications.block.ByteArray; import static com.google.common.base.Strings.padStart; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class IntegrateCrossProjectDuplicationsTest { private static final String XOO_LANGUAGE = "xoo"; private static final String ORIGIN_FILE_KEY = "ORIGIN_FILE_KEY"; private static final Component ORIGIN_FILE = builder(FILE, 1) .setKey(ORIGIN_FILE_KEY) .setFileAttributes(new FileAttributes(false, XOO_LANGUAGE, 1)) .build(); private static final String OTHER_FILE_KEY = "OTHER_FILE_KEY"; @Rule public LogTester logTester = new LogTester(); @Rule public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(); private final TestSystem2 system = new TestSystem2(); private final MapSettings settings = new MapSettings(); private final CeTaskMessages ceTaskMessages = mock(CeTaskMessages.class); private final CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder = mock(CrossProjectDuplicationStatusHolder.class); private final IntegrateCrossProjectDuplications underTest = new IntegrateCrossProjectDuplications(crossProjectDuplicationStatusHolder, settings.asConfig(), duplicationRepository, ceTaskMessages, system); @Test public void add_duplications_from_two_blocks() { settings.setProperty("sonar.cpd.xoo.minimumTokens", 10); Collection<Block> originBlocks = asList( new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 43) .setUnit(0, 5) .build(), new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("2b5747f0e4c59124")) .setIndexInFile(1) .setLines(32, 45) .setUnit(5, 20) .build()); Collection<Block> duplicatedBlocks = asList( new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(40, 53) .build(), new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("2b5747f0e4c59124")) .setIndexInFile(1) .setLines(42, 55) .build()); underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertThat(duplicationRepository.getDuplications(ORIGIN_FILE)) .containsExactly( crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))); } @Test public void add_duplications_from_a_single_block() { settings.setProperty("sonar.cpd.xoo.minimumTokens", 10); Collection<Block> originBlocks = singletonList( // This block contains 11 tokens -> a duplication will be created new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 10) .build()); Collection<Block> duplicatedBlocks = singletonList( new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(40, 55) .build()); underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertThat(duplicationRepository.getDuplications(ORIGIN_FILE)) .containsExactly( crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))); } @Test public void add_no_duplication_from_current_file() { settings.setProperty("sonar.cpd.xoo.minimumTokens", 10); Collection<Block> originBlocks = asList( new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 10) .build(), // Duplication is on the same file new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(46, 60) .setUnit(0, 10) .build()); Collection<Block> duplicatedBlocks = singletonList( new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ed")) .setIndexInFile(0) .setLines(40, 55) .build()); underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertNoDuplicationAdded(ORIGIN_FILE); } @Test public void add_no_duplication_when_not_enough_tokens() { settings.setProperty("sonar.cpd.xoo.minimumTokens", 10); Collection<Block> originBlocks = singletonList( // This block contains 5 tokens -> not enough to consider it as a duplication new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 4) .build()); Collection<Block> duplicatedBlocks = singletonList( new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(40, 55) .build()); underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertNoDuplicationAdded(ORIGIN_FILE); } @Test public void add_no_duplication_when_no_duplicated_blocks() { settings.setProperty("sonar.cpd.xoo.minimumTokens", 10); Collection<Block> originBlocks = singletonList( new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 10) .build()); underTest.computeCpd(ORIGIN_FILE, originBlocks, Collections.emptyList()); assertNoDuplicationAdded(ORIGIN_FILE); } @Test public void add_duplication_for_java_even_when_no_token() { Component javaFile = builder(FILE, 1) .setKey(ORIGIN_FILE_KEY) .setFileAttributes(new FileAttributes(false, "java", 10)) .build(); Collection<Block> originBlocks = singletonList( // This block contains 0 token new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 0) .build()); Collection<Block> duplicatedBlocks = singletonList( new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(40, 55) .build()); underTest.computeCpd(javaFile, originBlocks, duplicatedBlocks); assertThat(duplicationRepository.getDuplications(ORIGIN_FILE)) .containsExactly( crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))); } @Test public void default_minimum_tokens_is_one_hundred() { settings.setProperty("sonar.cpd.xoo.minimumTokens", (Integer) null); Collection<Block> originBlocks = singletonList( new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 100) .build()); Collection<Block> duplicatedBlocks = singletonList( new Block.Builder() .setResourceId(OTHER_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(40, 55) .build()); underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertThat(duplicationRepository.getDuplications(ORIGIN_FILE)) .containsExactly( crossProjectDuplication(new TextBlock(30, 45), OTHER_FILE_KEY, new TextBlock(40, 55))); } @Test public void do_not_compute_more_than_one_hundred_duplications_when_too_many_duplicated_references() { Collection<Block> originBlocks = new ArrayList<>(); Collection<Block> duplicatedBlocks = new ArrayList<>(); Block.Builder blockBuilder = new Block.Builder() .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray("a8998353e96320ec")) .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 100); originBlocks.add(blockBuilder.build()); // Generate more than 100 duplications of the same block for (int i = 0; i < 110; i++) { duplicatedBlocks.add( blockBuilder .setResourceId(randomAlphanumeric(16)) .build()); } underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertThat(logTester.logs(Level.WARN)).containsOnly( "Too many duplication references on file " + ORIGIN_FILE_KEY + " for block at line 30. Keeping only the first 100 references."); Iterable<Duplication> duplications = duplicationRepository.getDuplications(ORIGIN_FILE); assertThat(duplications).hasSize(1); assertThat(duplications.iterator().next().getDuplicates()).hasSize(100); } @Test public void do_not_compute_more_than_one_hundred_duplications_when_too_many_duplications() { Collection<Block> originBlocks = new ArrayList<>(); Collection<Block> duplicatedBlocks = new ArrayList<>(); Block.Builder blockBuilder = new Block.Builder() .setIndexInFile(0) .setLines(30, 45) .setUnit(0, 100); // Generate more than 100 duplication on different files for (int i = 0; i < 110; i++) { String hash = padStart("hash" + i, 16, 'a'); originBlocks.add( blockBuilder .setResourceId(ORIGIN_FILE_KEY) .setBlockHash(new ByteArray(hash)) .build()); duplicatedBlocks.add( blockBuilder .setResourceId("resource" + i) .setBlockHash(new ByteArray(hash)) .build()); } underTest.computeCpd(ORIGIN_FILE, originBlocks, duplicatedBlocks); assertThat(duplicationRepository.getDuplications(ORIGIN_FILE)).hasSize(100); assertThat(logTester.logs(Level.WARN)).containsOnly("Too many duplication groups on file " + ORIGIN_FILE_KEY + ". Keeping only the first 100 groups."); } @Test public void log_warning_if_this_deprecated_feature_is_enabled() { when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true); system.setNow(1000L); new IntegrateCrossProjectDuplications(crossProjectDuplicationStatusHolder, settings.asConfig(), duplicationRepository, ceTaskMessages, system); assertThat(logTester.logs()).containsExactly("This analysis uses the deprecated cross-project duplication feature."); verify(ceTaskMessages).add(new CeTaskMessages.Message("This project uses the deprecated cross-project duplication feature.", 1000L)); } private static Duplication crossProjectDuplication(TextBlock original, String otherFileKey, TextBlock duplicate) { return new Duplication(original, Arrays.asList(new CrossProjectDuplicate(otherFileKey, duplicate))); } private void assertNoDuplicationAdded(Component file) { assertThat(duplicationRepository.getDuplications(file)).isEmpty(); } }
13,115
35.433333
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/TextBlockTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class TextBlockTest { @Test public void constructor_throws_IAE_if_start_is_0() { assertThatThrownBy(() -> new TextBlock(0, 2)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("First line index must be >= 1"); } @Test public void constructor_throws_IAE_if_end_is_less_than_start() { assertThatThrownBy(() -> new TextBlock(1, 0)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Last line index must be >= first line index"); } @Test public void getStart_returns_constructor_argument() { TextBlock textBlock = new TextBlock(15, 300); assertThat(textBlock.getStart()).isEqualTo(15); } @Test public void getEnd_returns_constructor_argument() { TextBlock textBlock = new TextBlock(15, 300); assertThat(textBlock.getEnd()).isEqualTo(300); } @Test public void equals_compares_on_start_and_end() { assertThat(new TextBlock(15, 15)).isEqualTo(new TextBlock(15, 15)); assertThat(new TextBlock(15, 300)).isEqualTo(new TextBlock(15, 300)); assertThat(new TextBlock(15, 300)).isNotEqualTo(new TextBlock(15, 15)); } @Test public void hashcode_is_based__on_start_and_end() { assertThat(new TextBlock(15, 15)).hasSameHashCodeAs(new TextBlock(15, 15)); assertThat(new TextBlock(15, 300)).hasSameHashCodeAs(new TextBlock(15, 300)); assertThat(new TextBlock(15, 300).hashCode()).isNotEqualTo(new TextBlock(15, 15).hashCode()); } @Test public void TextBlock_defines_natural_order_by_start_then_end() { TextBlock textBlock1 = new TextBlock(1, 1); TextBlock textBlock2 = new TextBlock(1, 2); TextBlock textBlock3 = new TextBlock(2, 3); TextBlock textBlock4 = new TextBlock(2, 4); TextBlock textBlock5 = new TextBlock(5, 5); List<TextBlock> shuffledList = new ArrayList<>(Arrays.asList(textBlock1, textBlock2, textBlock3, textBlock4, textBlock5)); Collections.shuffle(shuffledList, new Random()); Collections.sort(shuffledList); assertThat(shuffledList).containsExactly(textBlock1, textBlock2, textBlock3, textBlock4, textBlock5); } @Test public void verify_toString() { assertThat(new TextBlock(13, 400)).hasToString("TextBlock{start=13, end=400}"); } }
3,411
34.175258
126
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/duplication/ViewsDuplicationMeasuresTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.duplication; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_BLOCKS_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_FILES_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.DUPLICATED_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.LINES; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ViewsComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; public class ViewsDuplicationMeasuresTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_REF = 12; private static final int SUB_SUBVIEW_REF = 123; private static final int PROJECT_VIEW_1_REF = 1231; private static final int PROJECT_VIEW_2_REF = 1232; private static final int PROJECT_VIEW_3_REF = 13; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot(builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, SUBVIEW_REF) .addChildren( builder(SUBVIEW, SUB_SUBVIEW_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECT_VIEW_2_REF).build()) .build()) .build(), builder(PROJECT_VIEW, PROJECT_VIEW_3_REF).build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(LINES) .add(NCLOC) .add(COMMENT_LINES) .add(DUPLICATED_BLOCKS) .add(DUPLICATED_FILES) .add(DUPLICATED_LINES) .add(DUPLICATED_LINES_DENSITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private DuplicationMeasures underTest = new DuplicationMeasures(treeRootHolder, metricRepository, measureRepository); @Test public void aggregate_duplicated_blocks() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_BLOCKS_KEY, 10); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_BLOCKS_KEY, 40); addRawMeasure(PROJECT_VIEW_3_REF, DUPLICATED_BLOCKS_KEY, 60); underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_BLOCKS_KEY, 50); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_BLOCKS_KEY, 50); assertRawMeasureValue(ROOT_REF, DUPLICATED_BLOCKS_KEY, 110); } @Test public void aggregate_zero_duplicated_blocks() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_BLOCKS_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_BLOCKS_KEY, 0); // no raw measure for PROJECT_VIEW_3_REF underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_BLOCKS_KEY, 0); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_BLOCKS_KEY, 0); assertRawMeasureValue(ROOT_REF, DUPLICATED_BLOCKS_KEY, 0); } @Test public void aggregate_zero_duplicated_blocks_when_no_data() { underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_BLOCKS_KEY, 0); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_BLOCKS_KEY, 0); assertRawMeasureValue(ROOT_REF, DUPLICATED_BLOCKS_KEY, 0); } @Test public void aggregate_duplicated_files() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_FILES_KEY, 10); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_FILES_KEY, 40); addRawMeasure(PROJECT_VIEW_3_REF, DUPLICATED_FILES_KEY, 70); underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_FILES_KEY, 50); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_FILES_KEY, 50); assertRawMeasureValue(ROOT_REF, DUPLICATED_FILES_KEY, 120); } @Test public void aggregate_zero_duplicated_files() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_FILES_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_FILES_KEY, 0); // no raw measure for PROJECT_VIEW_3_REF underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_FILES_KEY, 0); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_FILES_KEY, 0); assertRawMeasureValue(ROOT_REF, DUPLICATED_FILES_KEY, 0); } @Test public void aggregate_zero_duplicated_files_when_no_data() { underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_FILES_KEY, 0); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_FILES_KEY, 0); assertRawMeasureValue(ROOT_REF, DUPLICATED_FILES_KEY, 0); } @Test public void aggregate_duplicated_lines() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_LINES_KEY, 10); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_LINES_KEY, 40); addRawMeasure(PROJECT_VIEW_3_REF, DUPLICATED_LINES_KEY, 50); underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_LINES_KEY, 50); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_LINES_KEY, 50); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_KEY, 100); } @Test public void aggregate_zero_duplicated_line() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_LINES_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_LINES_KEY, 0); // no raw measure for PROJECT_VIEW_3_REF underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_KEY, 0); } @Test public void aggregate_zero_duplicated_line_when_no_data() { underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_KEY, 0); } @Test public void compute_and_aggregate_duplicated_lines_density_using_lines() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_LINES_KEY, 2); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_LINES_KEY, 3); addRawMeasure(PROJECT_VIEW_3_REF, DUPLICATED_LINES_KEY, 4); addRawMeasure(PROJECT_VIEW_1_REF, LINES_KEY, 10); addRawMeasure(PROJECT_VIEW_2_REF, LINES_KEY, 40); addRawMeasure(PROJECT_VIEW_3_REF, LINES_KEY, 70); underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_LINES_DENSITY_KEY, 10d); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_LINES_DENSITY_KEY, 10d); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_DENSITY_KEY, 7.5d); } @Test public void compute_zero_percent_duplicated_lines_density_when_duplicated_lines_are_zero() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_LINES_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_LINES_KEY, 0); // no raw measure for PROJECT_VIEW_3_REF addRawMeasure(PROJECT_VIEW_1_REF, LINES_KEY, 10); addRawMeasure(PROJECT_VIEW_2_REF, LINES_KEY, 40); underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_DENSITY_KEY, 0d); } @Test public void not_compute_duplicated_lines_density_when_lines_is_zero() { addRawMeasure(PROJECT_VIEW_1_REF, LINES_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, LINES_KEY, 0); // no raw measure for PROJECT_VIEW_3_REF addRawMeasure(SUB_SUBVIEW_REF, LINES_KEY, 0); addRawMeasure(SUBVIEW_REF, LINES_KEY, 0); addRawMeasure(ROOT_REF, LINES_KEY, 0); underTest.execute(); assertNoRawMeasures(DUPLICATED_LINES_DENSITY_KEY); } @Test public void not_compute_duplicated_lines_density_when_ncloc_and_comment_are_zero() { addRawMeasure(PROJECT_VIEW_1_REF, COMMENT_LINES_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, COMMENT_LINES_KEY, 0); // no raw measure for PROJECT_VIEW_3_REF addRawMeasure(SUB_SUBVIEW_REF, COMMENT_LINES_KEY, 0); addRawMeasure(SUBVIEW_REF, COMMENT_LINES_KEY, 0); addRawMeasure(ROOT_REF, COMMENT_LINES_KEY, 0); addRawMeasure(PROJECT_VIEW_1_REF, NCLOC_KEY, 0); addRawMeasure(PROJECT_VIEW_2_REF, NCLOC_KEY, 0); addRawMeasure(SUB_SUBVIEW_REF, NCLOC_KEY, 0); addRawMeasure(SUBVIEW_REF, NCLOC_KEY, 0); addRawMeasure(ROOT_REF, NCLOC_KEY, 0); underTest.execute(); assertNoRawMeasures(DUPLICATED_LINES_DENSITY_KEY); } @Test public void compute_100_percent_duplicated_lines_density() { addRawMeasure(PROJECT_VIEW_1_REF, DUPLICATED_LINES_KEY, 2); addRawMeasure(PROJECT_VIEW_2_REF, DUPLICATED_LINES_KEY, 3); // no raw measure for PROJECT_VIEW_3_REF addRawMeasure(PROJECT_VIEW_1_REF, LINES_KEY, 2); addRawMeasure(PROJECT_VIEW_2_REF, LINES_KEY, 3); addRawMeasure(SUB_SUBVIEW_REF, LINES_KEY, 5); addRawMeasure(SUBVIEW_REF, LINES_KEY, 5); addRawMeasure(ROOT_REF, LINES_KEY, 5); underTest.execute(); assertNoNewRawMeasuresOnProjectViews(); assertRawMeasureValue(SUB_SUBVIEW_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); assertRawMeasureValue(SUBVIEW_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); assertRawMeasureValue(ROOT_REF, DUPLICATED_LINES_DENSITY_KEY, 100d); } private void addRawMeasure(int componentRef, String metricKey, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertNoRawMeasures(String metricKey) { assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_1_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_2_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(SUB_SUBVIEW_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(SUBVIEW_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF).get(metricKey)).isNull(); } private void assertNoNewRawMeasuresOnProjectViews() { assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_1_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_2_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_3_REF)).isEmpty(); } private void assertRawMeasureValue(int componentRef, String metricKey, int value) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getIntValue()).isEqualTo(value); } private void assertRawMeasureValue(int componentRef, String metricKey, double value) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getDoubleValue()).isEqualTo(value); } }
12,949
39.981013
119
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.event; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EventRepositoryImplTest { private static final Event EVENT_1 = Event.createProfile("event_1", null, null); private static final Event EVENT_2 = Event.createProfile("event_2", null, null); private final EventRepositoryImpl underTest = new EventRepositoryImpl(); @Test public void getEvents_returns_empty_iterable_when_repository_is_empty() { assertThat(underTest.getEvents()).isEmpty(); } @Test public void add_throws_NPE_if_even_arg_is_null() { assertThatThrownBy(() -> underTest.add(null)) .isInstanceOf(NullPointerException.class); } @Test public void can_add_and_retrieve_many_events() { underTest.add(EVENT_1); underTest.add(EVENT_2); assertThat(underTest.getEvents()).extracting("name").containsOnly(EVENT_1.getName(), EVENT_2.getName()); } private static Component newComponent(int i) { return ReportComponent.builder(Component.Type.PROJECT, i).build(); } }
2,113
35.448276
108
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/event/EventTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.event; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EventTest { private static final String SOME_NAME = "someName"; private static final String SOME_DATA = "some data"; private static final String SOME_DESCRIPTION = "some description"; @Test public void createAlert_fail_fast_null_check_on_null_name() { assertThatThrownBy(() -> Event.createAlert(null, SOME_DATA, SOME_DESCRIPTION)) .isInstanceOf(NullPointerException.class); } @Test public void createProfile_fail_fast_null_check_on_null_name() { assertThatThrownBy(() -> Event.createProfile(null, SOME_DATA, SOME_DESCRIPTION)) .isInstanceOf(NullPointerException.class); } @Test public void createAlert_verify_fields() { Event event = Event.createAlert(SOME_NAME, SOME_DATA, SOME_DESCRIPTION); assertThat(event.getName()).isEqualTo(SOME_NAME); assertThat(event.getCategory()).isEqualTo(Event.Category.ALERT); assertThat(event.getData()).isEqualTo(SOME_DATA); assertThat(event.getDescription()).isEqualTo(SOME_DESCRIPTION); } @Test public void createProfile_verify_fields() { Event event = Event.createProfile(SOME_NAME, SOME_DATA, SOME_DESCRIPTION); assertThat(event.getName()).isEqualTo(SOME_NAME); assertThat(event.getCategory()).isEqualTo(Event.Category.PROFILE); assertThat(event.getData()).isEqualTo(SOME_DATA); assertThat(event.getDescription()).isEqualTo(SOME_DESCRIPTION); } @Test public void same_name_and_category_make_equal_events() { Event source = Event.createAlert(SOME_NAME, null, null); assertThat(source) .isEqualTo(Event.createAlert(SOME_NAME, null, null)) .isEqualTo(source) .isNotNull(); } }
2,694
36.430556
84
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/AddedFileRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.component.Component; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class AddedFileRepositoryImplTest { private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private AddedFileRepositoryImpl underTest = new AddedFileRepositoryImpl(analysisMetadataHolder); @Test public void isAdded_fails_with_NPE_if_component_is_null() { assertThatThrownBy(() -> underTest.isAdded(null)) .isInstanceOf(NullPointerException.class) .hasMessage("component can't be null"); } @Test public void isAdded_returns_true_for_any_component_type_on_first_analysis() { when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); Arrays.stream(Component.Type.values()).forEach(type -> { Component component = newComponent(type); assertThat(underTest.isAdded(component)).isTrue(); }); } @Test public void isAdded_returns_false_for_unregistered_component_type_when_not_on_first_analysis() { when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false); Arrays.stream(Component.Type.values()).forEach(type -> { Component component = newComponent(type); assertThat(underTest.isAdded(component)).isFalse(); }); } @Test public void isAdded_returns_true_for_registered_file_when_not_on_first_analysis() { when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false); Component file1 = newComponent(Component.Type.FILE); Component file2 = newComponent(Component.Type.FILE); underTest.register(file1); assertThat(underTest.isAdded(file1)).isTrue(); assertThat(underTest.isAdded(file2)).isFalse(); } @Test public void register_fails_with_NPE_if_component_is_null() { assertThatThrownBy(() -> underTest.register(null)) .isInstanceOf(NullPointerException.class) .hasMessage("component can't be null"); } @Test @UseDataProvider("anyTypeButFile") public void register_fails_with_IAE_if_component_is_not_a_file(Component.Type anyTypeButFile) { Component component = newComponent(anyTypeButFile); assertThatThrownBy(() -> underTest.register(component)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("component must be a file"); } @DataProvider public static Object[][] anyTypeButFile() { return Arrays.stream(Component.Type.values()) .filter(t -> t != Component.Type.FILE) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } @Test public void register_fails_with_ISE_if_called_on_first_analysis() { when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); Component component = newComponent(Component.Type.FILE); assertThatThrownBy(() -> underTest.register(component)) .isInstanceOf(IllegalStateException.class) .hasMessage("No file can be registered on first branch analysis"); } private static Component newComponent(Component.Type type) { Component component = mock(Component.class); when(component.getType()).thenReturn(type); return component; } }
4,512
35.691057
98
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MatchTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MatchTest { private static final String SOME_REPORT_KEY = "reportKey"; private static final String SOME_KEY = "key"; private Match underTest = new Match(SOME_KEY, SOME_REPORT_KEY); @Test public void constructor_key_argument_can_be_null() { new Match(null, SOME_REPORT_KEY); } @Test public void constructor_reportKey_argument_can_be_null() { new Match(SOME_KEY, null); } @Test public void getDbKey_returns_first_constructor_argument() { assertThat(underTest.dbUuid()).isEqualTo(SOME_KEY); } @Test public void getDbKey_returns_second_constructor_argument() { assertThat(underTest.reportUuid()).isEqualTo(SOME_REPORT_KEY); } @Test public void equals_is_based_on_both_properties() { assertThat(underTest) .isEqualTo(new Match(SOME_KEY, SOME_REPORT_KEY)) .isNotEqualTo(new Match("other key", SOME_REPORT_KEY)) .isNotEqualTo(new Match(SOME_KEY, "other report key")) .isNotEqualTo(new Match(null, SOME_REPORT_KEY)) .isNotEqualTo(new Match(SOME_KEY, null)) .isNotEqualTo(new Match(null, null)); } @Test public void hashcode_is_base_on_both_properties() { int hashCode = underTest.hashCode(); assertThat(hashCode) .isEqualTo(new Match(SOME_KEY, SOME_REPORT_KEY).hashCode()) .isNotEqualTo(new Match("other key", SOME_REPORT_KEY).hashCode()) .isNotEqualTo(new Match(SOME_KEY, "other report key").hashCode()) .isNotEqualTo(new Match(null, SOME_REPORT_KEY).hashCode()) .isNotEqualTo(new Match(SOME_KEY, null).hashCode()) .isNotEqualTo(new Match(null, null).hashCode()); } @Test public void toString_prints_both_properties() { assertThat(underTest).hasToString("{key=>reportKey}"); } }
2,725
32.654321
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MatchesByScoreTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import java.util.Arrays; import java.util.List; import java.util.Random; import org.junit.Test; import org.sonar.ce.task.projectanalysis.filemove.ScoreMatrix.ScoreFile; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStep.MIN_REQUIRED_SCORE; public class MatchesByScoreTest { private static final List<Match> NO_MATCH = null; @Test public void creates_returns_always_the_same_instance_of_maxScore_is_less_than_min_required_score() { ScoreFile[] doesNotMatterRemovedFiles = new ScoreFile[0]; ScoreFile[] doesNotMatterNewFiles = new ScoreFile[0]; int[][] doesNotMatterScores = new int[0][0]; ScoreMatrix scoreMatrix1 = new ScoreMatrix(doesNotMatterRemovedFiles, doesNotMatterNewFiles, doesNotMatterScores, MIN_REQUIRED_SCORE - 1); MatchesByScore matchesByScore = MatchesByScore.create(scoreMatrix1); assertThat(matchesByScore.getSize()).isZero(); assertThat(matchesByScore).isEmpty(); ScoreMatrix scoreMatrix2 = new ScoreMatrix(doesNotMatterRemovedFiles, doesNotMatterNewFiles, doesNotMatterScores, MIN_REQUIRED_SCORE - 5); assertThat(MatchesByScore.create(scoreMatrix2)).isSameAs(matchesByScore); } @Test public void creates_supports_score_with_same_value_as_min_required_score() { int maxScore = 92; int[][] scores = { {maxScore}, {8}, {85}, }; MatchesByScore matchesByScore = MatchesByScore.create(new ScoreMatrix(of("A", "B", "C"), of("1"), scores, maxScore)); assertThat(matchesByScore.getSize()).isEqualTo(2); assertThat(Lists.newArrayList(matchesByScore)).isEqualTo(Arrays.asList( ImmutableList.of(new Match("A", "1")), // 92 NO_MATCH, NO_MATCH, NO_MATCH, NO_MATCH, NO_MATCH, NO_MATCH, ImmutableList.of(new Match("C", "1")) // 85 )); } private ScoreFile[] of(String... fileKeys) { return Arrays.stream(fileKeys) .map(key -> new ScoreFile(key, new Random().nextInt(40))) .toArray(ScoreFile[]::new); } }
3,050
35.759036
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import java.util.Random; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class MutableMovedFilesRepositoryImplTest { private static final Component SOME_FILE = builder(Component.Type.FILE, 1).build(); private static final Component[] COMPONENTS_EXCEPT_FILE = { builder(Component.Type.PROJECT, 1).build(), builder(Component.Type.DIRECTORY, 1).build(), ViewsComponent.builder(Component.Type.VIEW, 1).build(), ViewsComponent.builder(Component.Type.SUBVIEW, 1).build(), ViewsComponent.builder(Component.Type.PROJECT_VIEW, 1).build() }; private static final MovedFilesRepository.OriginalFile SOME_ORIGINAL_FILE = new MovedFilesRepository.OriginalFile("uuid for 100", "key for 100"); private MutableMovedFilesRepositoryImpl underTest = new MutableMovedFilesRepositoryImpl(); @Test public void setOriginalFile_throws_NPE_when_file_is_null() { assertThatThrownBy(() -> underTest.setOriginalFile(null, SOME_ORIGINAL_FILE)) .isInstanceOf(NullPointerException.class) .hasMessage("file can't be null"); } @Test public void setOriginalFile_throws_NPE_when_originalFile_is_null() { assertThatThrownBy(() -> underTest.setOriginalFile(SOME_FILE, null)) .isInstanceOf(NullPointerException.class) .hasMessage("originalFile can't be null"); } @Test public void setOriginalFile_throws_IAE_when_type_is_no_FILE() { for (Component component : COMPONENTS_EXCEPT_FILE) { try { underTest.setOriginalFile(component, SOME_ORIGINAL_FILE); fail("should have raised a NPE"); } catch (IllegalArgumentException e) { assertThat(e) .isInstanceOf(IllegalArgumentException.class) .hasMessage("file must be of type FILE"); } } } @Test public void setOriginalFile_throws_ISE_if_settings_another_originalFile() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); assertThatThrownBy(() -> underTest.setOriginalFile(SOME_FILE, new MovedFilesRepository.OriginalFile("uudi", "key"))) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Original file OriginalFile{uuid='uuid for 100', key='key for 100'} " + "already registered for file ReportComponent{ref=1, key='key_1', type=FILE}"); } @Test public void setOriginalFile_does_not_fail_if_same_original_file_is_added_multiple_times_for_the_same_component() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); for (int i = 0; i < 1 + Math.abs(new Random().nextInt(10)); i++) { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); } } @Test public void setOriginalFile_does_not_fail_when_originalFile_is_added_twice_for_different_files() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); underTest.setOriginalFile(builder(Component.Type.FILE, 2).build(), SOME_ORIGINAL_FILE); } @Test public void getOriginalFile_throws_NPE_when_file_is_null() { assertThatThrownBy(() -> underTest.getOriginalFile(null)) .isInstanceOf(NullPointerException.class) .hasMessage("file can't be null"); } @Test public void getOriginalFile_returns_absent_for_any_component_type_when_empty() { assertThat(underTest.getOriginalFile(SOME_FILE)).isEmpty(); for (Component component : COMPONENTS_EXCEPT_FILE) { assertThat(underTest.getOriginalFile(component)).isEmpty(); } } @Test public void getOriginalFile_returns_absent_for_any_type_of_Component_but_file_when_non_empty() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); for (Component component : COMPONENTS_EXCEPT_FILE) { assertThat(underTest.getOriginalFile(component)).isEmpty(); } assertThat(underTest.getOriginalFile(SOME_FILE)).contains(SOME_ORIGINAL_FILE); } @Test public void getOriginalFile_returns_originalFile_base_on_file_key() { underTest.setOriginalFile(SOME_FILE, SOME_ORIGINAL_FILE); assertThat(underTest.getOriginalFile(SOME_FILE)).contains(SOME_ORIGINAL_FILE); assertThat(underTest.getOriginalFile(builder(Component.Type.FILE, 1).setUuid("toto").build())).contains(SOME_ORIGINAL_FILE); } }
5,392
40.167939
147
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/MutableMovedFilesRepositoryRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import java.util.HashSet; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; public class MutableMovedFilesRepositoryRule extends ExternalResource implements MutableMovedFilesRepository { @CheckForNull private MutableMovedFilesRepository delegate; private final Set<Component> componentsWithOriginal = new HashSet<>(); @Override protected void before() { this.delegate = new MutableMovedFilesRepositoryImpl(); this.componentsWithOriginal.clear(); } @Override protected void after() { this.delegate = null; this.componentsWithOriginal.clear(); } @Override public void setOriginalFile(Component file, OriginalFile originalFile) { this.delegate.setOriginalFile(file, originalFile); this.componentsWithOriginal.add(file); } @Override public void setOriginalPullRequestFile(Component file, OriginalFile originalFile) { this.delegate.setOriginalPullRequestFile(file, originalFile); this.componentsWithOriginal.add(file); } @Override public Optional<OriginalFile> getOriginalFile(Component file) { return this.delegate.getOriginalFile(file); } @Override public Optional<OriginalFile> getOriginalPullRequestFile(Component file) { return this.delegate.getOriginalPullRequestFile(file); } public Set<Component> getComponentsWithOriginal() { return componentsWithOriginal; } }
2,399
32.333333
110
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/ScoreMatrixDumperImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.config.Configuration; import org.sonar.api.config.internal.MapSettings; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.projectanalysis.filemove.ScoreMatrix.ScoreFile; import org.sonar.server.platform.ServerFileSystem; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class ScoreMatrixDumperImplTest { private static final ScoreMatrix A_SCORE_MATRIX = new ScoreMatrix( new ScoreFile[] {new ScoreFile("A", 12), new ScoreFile("B", 8)}, new ScoreFile[] {new ScoreFile("1", 7)}, new int[][] {{10}, {2}}, 10); private MapSettings settings = new MapSettings(); private Configuration configuration = settings.asConfig(); private CeTask ceTask = mock(CeTask.class); private ServerFileSystem serverFileSystem = mock(ServerFileSystem.class); private ScoreMatrixDumper underTest = new ScoreMatrixDumperImpl(configuration, ceTask, serverFileSystem); private Path tempDir; @Before public void before() throws IOException { Path tempFile = Files.createTempFile("a", "b"); Files.delete(tempFile); tempDir = tempFile.getParent(); when(serverFileSystem.getTempDir()).thenReturn(tempDir.toFile()); } @After public void cleanUp() { try { Files.list(tempDir.toAbsolutePath()).filter(p -> p.getFileName().toString().contains("score-matrix-")).forEach((p) -> { try { Files.deleteIfExists(p); } catch (Exception e) { System.out.println("Could not delete file. Details: " + e.getMessage()); } }); } catch (Exception e) { System.out.println("Cleaning up temp directory failed. Details: " + e.getMessage()); } } @Test public void dumpAsCsv_creates_csv_dump_of_score_matrix_if_property_is_true() throws IOException { String taskUuid = "acme"; when(ceTask.getUuid()).thenReturn(taskUuid); settings.setProperty("sonar.filemove.dumpCsv", "true"); underTest.dumpAsCsv(A_SCORE_MATRIX); Collection<File> files = listDumpFilesForTaskUuid(taskUuid); assertThat(files).hasSize(1); assertThat(files.iterator().next()).hasContent(A_SCORE_MATRIX.toCsv(';')); } @Test public void dumpAsCsv_has_no_effect_if_configuration_is_empty() throws IOException { String taskUuid = randomAlphabetic(6); when(ceTask.getUuid()).thenReturn(taskUuid); underTest.dumpAsCsv(A_SCORE_MATRIX); assertThat(listDumpFilesForTaskUuid(taskUuid)).isEmpty(); } @Test @UseDataProvider("notTruePropertyValues") public void dumpAsCsv_has_no_effect_if_property_is_not_true(String value) throws IOException { String taskUuid = randomAlphabetic(6); when(ceTask.getUuid()).thenReturn(taskUuid); settings.setProperty("sonar.filemove.dumpCsv", value); underTest.dumpAsCsv(A_SCORE_MATRIX); assertThat(listDumpFilesForTaskUuid(taskUuid)).isEmpty(); } @DataProvider public static Object[][] notTruePropertyValues() { return new Object[][] { {randomAlphabetic(6)}, {"false"}, }; } private Collection<File> listDumpFilesForTaskUuid(String taskUuid) { Collection<File> dumpFiles = new ArrayList<>(); File dir = tempDir.toFile(); File[] files = dir.listFiles(); if (!dir.exists() || files == null) { throw new IllegalStateException("Temp directory does not exist"); } for (File file : files) { if (file.exists()) { String name = file.getName(); if (name.startsWith("score-matrix-" + taskUuid) && name.endsWith(".csv")) { dumpFiles.add(file); } } } return dumpFiles; } }
5,112
34.020548
125
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filemove/SourceSimilarityImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filemove; import java.util.List; import java.util.stream.IntStream; import org.junit.Test; import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; public class SourceSimilarityImplTest { private SourceSimilarityImpl underTest = new SourceSimilarityImpl(); @Test public void zero_if_fully_different() { List<String> left = asList("a", "b", "c"); List<String> right = asList("d", "e"); assertThat(underTest.score(left, right)).isZero(); } @Test public void one_hundred_if_same() { assertThat(underTest.score(asList("a", "b", "c"), asList("a", "b", "c"))).isEqualTo(100); assertThat(underTest.score(asList(""), asList(""))).isEqualTo(100); } @Test public void partially_same() { assertThat(underTest.score(asList("a", "b", "c", "d"), asList("a", "b", "e", "f"))).isEqualTo(50); assertThat(underTest.score(asList("a"), asList("a", "b", "c"))).isEqualTo(33); assertThat(underTest.score(asList("a", "b", "c"), asList("a"))).isEqualTo(33); } @Test public void finding_threshold_in_line_count_to_go_below_85_score() { assertThat(underTest.score(listOf(100), listOf(115))).isEqualTo(86); assertThat(underTest.score(listOf(100), listOf(116))).isEqualTo(86); assertThat(underTest.score(listOf(100), listOf(117))).isEqualTo(85); // 85.47% - 117% assertThat(underTest.score(listOf(100), listOf(118))).isEqualTo(84); // 84.74% - 118% assertThat(underTest.score(listOf(50), listOf(58))).isEqualTo(86); // 86.20% - 116% assertThat(underTest.score(listOf(50), listOf(59))).isEqualTo(84); // 84.74% - 118% assertThat(underTest.score(listOf(25), listOf(29))).isEqualTo(86); // 86.20% - 116% assertThat(underTest.score(listOf(25), listOf(30))).isEqualTo(83); // 83.33% - 120% assertThat(underTest.score(listOf(12), listOf(14))).isEqualTo(85); // 85.71% - 116.67% assertThat(underTest.score(listOf(12), listOf(15))).isEqualTo(80); // 80.00% - 125% assertThat(underTest.score(listOf(10), listOf(11))).isEqualTo(90); // 90.90% - 110% assertThat(underTest.score(listOf(10), listOf(12))).isEqualTo(83); // 83.33% - 120% assertThat(underTest.score(listOf(5), listOf(5))).isEqualTo(100); // 100% - 100% assertThat(underTest.score(listOf(5), listOf(6))).isEqualTo(83); // 83.33% - 120% assertThat(underTest.score(listOf(200), listOf(234))).isEqualTo(85); // 85.47% - 117% assertThat(underTest.score(listOf(200), listOf(236))).isEqualTo(84); // 84.75% - 118% assertThat(underTest.score(listOf(300), listOf(352))).isEqualTo(85); // 85.23% - 117.33% assertThat(underTest.score(listOf(300), listOf(354))).isEqualTo(84); // 84.74% - 118% assertThat(underTest.score(listOf(400), listOf(470))).isEqualTo(85); // 85.10% - 117.50% assertThat(underTest.score(listOf(400), listOf(471))).isEqualTo(84); // 84.92% - 117.75% assertThat(underTest.score(listOf(500), listOf(588))).isEqualTo(85); // 85.03% - 117.60% assertThat(underTest.score(listOf(500), listOf(589))).isEqualTo(84); // 84.88% - 117.80% } @Test public void verify_84_percent_ratio_for_lower_bound() { IntStream.range(0, 1000) .forEach(ref -> lowerBoundGivesNonMeaningfulScore(ref, 0.84)); } @Test public void verify_118_percent_ratio_for_upper_bound() { IntStream.range(0, 1000) .forEach(ref -> upperBoundGivesNonMeaningfulScore(ref, 1.18)); } private void lowerBoundGivesNonMeaningfulScore(Integer ref, double ratio) { int lowerBound = (int) Math.floor(ref * ratio); assertThat(underTest.score(listOf(ref), listOf(lowerBound))) .describedAs("Score for %s%% lines of %s (ie. %s lines) should be 84 or less", ratio * 100, ref, lowerBound) .isLessThanOrEqualTo(84); } private void upperBoundGivesNonMeaningfulScore(Integer ref, double ratio) { int upperBound = (int) Math.ceil(ref * ratio); assertThat(underTest.score(listOf(ref), listOf(upperBound))) .describedAs("Score for %s%% lines of %s (ie. %s lines) should be 84 or less", ratio * 100, ref, upperBound) .isLessThanOrEqualTo(84); } /** * Creates a list of {@code numberOfElements} int values as String, starting with zero. */ private static List<String> listOf(int numberOfElements) { return IntStream.range(0, numberOfElements).mapToObj(String::valueOf).toList(); } @Test public void two_empty_lists_are_not_considered_as_equal() { assertThat(underTest.score(emptyList(), emptyList())).isZero(); } }
5,429
41.421875
114
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/filesystem/ComputationTempFolderProviderTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.filesystem; import org.apache.commons.io.FileUtils; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.sonar.api.utils.TempFolder; import org.sonar.server.platform.ServerFileSystem; import java.io.File; public class ComputationTempFolderProviderTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private final ComputationTempFolderProvider underTest = new ComputationTempFolderProvider(); @Test public void existing_temp_dir() throws Exception { ServerFileSystem fs = mock(ServerFileSystem.class); File tmpDir = temp.newFolder(); when(fs.getTempDir()).thenReturn(tmpDir); TempFolder folder = underTest.provide(fs); assertThat(folder).isNotNull(); File newDir = folder.newDir(); assertThat(newDir).exists().isDirectory(); assertThat(newDir.getParentFile().getCanonicalPath()).startsWith(tmpDir.getCanonicalPath()); } @Test public void create_temp_dir_if_missing() throws Exception { ServerFileSystem fs = mock(ServerFileSystem.class); File tmpDir = temp.newFolder(); when(fs.getTempDir()).thenReturn(tmpDir); FileUtils.forceDelete(tmpDir); TempFolder folder = underTest.provide(fs); assertThat(folder).isNotNull(); File newDir = folder.newDir(); assertThat(newDir).exists().isDirectory(); assertThat(newDir.getParentFile().getCanonicalPath()).startsWith(tmpDir.getCanonicalPath()); } }
2,464
35.25
96
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/AverageFormulaExecutionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; public class AverageFormulaExecutionTest { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.FUNCTION_COMPLEXITY) .add(CoreMetrics.COMPLEXITY_IN_FUNCTIONS) .add(CoreMetrics.FUNCTIONS); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public PeriodHolderRule periodsHolder = new PeriodHolderRule(); private FormulaExecutorComponentVisitor underTest; @Before public void setUp() { underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(Lists.newArrayList( AverageFormula.Builder.newBuilder() .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) .setByMetricKey(FUNCTIONS_KEY) .build())); } @Test public void add_measures() { ReportComponent project = builder(PROJECT, 1) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(Component.Type.FILE, 1111).build(), builder(Component.Type.FILE, 1112).build()) .build(), builder(DIRECTORY, 121) .addChildren( builder(Component.Type.FILE, 1211).build()) .build()) .build(); treeRootHolder.setRoot(project); measureRepository.addRawMeasure(1111, COMPLEXITY_IN_FUNCTIONS_KEY, newMeasureBuilder().create(5)); measureRepository.addRawMeasure(1111, FUNCTIONS_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(1112, COMPLEXITY_IN_FUNCTIONS_KEY, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(1112, FUNCTIONS_KEY, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(1211, COMPLEXITY_IN_FUNCTIONS_KEY, newMeasureBuilder().create(9)); measureRepository.addRawMeasure(1211, FUNCTIONS_KEY, newMeasureBuilder().create(2)); new PathAwareCrawler<>(underTest).visit(project); assertThat(toEntries(measureRepository.getAddedRawMeasures(1))).containsOnly(entryOf(FUNCTION_COMPLEXITY_KEY, newMeasureBuilder().create(3d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(111))).containsOnly(entryOf(FUNCTION_COMPLEXITY_KEY, newMeasureBuilder().create(2d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(1111))).containsOnly(entryOf(FUNCTION_COMPLEXITY_KEY, newMeasureBuilder().create(2.5d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(1112))).containsOnly(entryOf(FUNCTION_COMPLEXITY_KEY, newMeasureBuilder().create(1d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(121))).containsOnly(entryOf(FUNCTION_COMPLEXITY_KEY, newMeasureBuilder().create(4.5d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(1211))).containsOnly(entryOf(FUNCTION_COMPLEXITY_KEY, newMeasureBuilder().create(4.5d, 1))); } @Test public void not_add_measures_when_no_data_on_file() { ReportComponent project = builder(PROJECT, 1) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(Component.Type.FILE, 1111).build()) .build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(underTest).visit(project); assertThat(measureRepository.getAddedRawMeasures(1)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(111)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(1111)).isEmpty(); } }
5,911
44.829457
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/AverageFormulaTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_KEY; import static org.sonar.ce.task.projectanalysis.formula.AverageFormula.Builder; public class AverageFormulaTest { private static final AverageFormula BASIC_AVERAGE_FORMULA = Builder.newBuilder() .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) .setByMetricKey(FUNCTIONS_KEY) .build(); CounterInitializationContext counterInitializationContext = mock(CounterInitializationContext.class); CreateMeasureContext createMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); @Test public void fail_with_NPE_when_building_formula_without_output_metric() { assertThatThrownBy(() -> { Builder.newBuilder() .setOutputMetricKey(null) .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) .setByMetricKey(FUNCTIONS_KEY) .build(); }) .isInstanceOf(NullPointerException.class) .hasMessage("Output metric key cannot be null"); } @Test public void fail_with_NPE_when_building_formula_without_main_metric() { assertThatThrownBy(() -> { Builder.newBuilder() .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) .setMainMetricKey(null) .setByMetricKey(FUNCTIONS_KEY) .build(); }) .isInstanceOf(NullPointerException.class) .hasMessage("Main metric Key cannot be null"); } @Test public void fail_with_NPE_when_building_formula_without_by_metric() { assertThatThrownBy(() -> { Builder.newBuilder() .setOutputMetricKey(FUNCTION_COMPLEXITY_KEY) .setMainMetricKey(COMPLEXITY_IN_FUNCTIONS_KEY) .setByMetricKey(null) .build(); }) .isInstanceOf(NullPointerException.class) .hasMessage("By metric Key cannot be null"); } @Test public void check_new_counter_class() { assertThat(BASIC_AVERAGE_FORMULA.createNewCounter().getClass()).isEqualTo(AverageFormula.AverageCounter.class); } @Test public void check_output_metric_key_is_function_complexity_key() { assertThat(BASIC_AVERAGE_FORMULA.getOutputMetricKeys()).containsOnly(FUNCTION_COMPLEXITY_KEY); } @Test public void create_measure_when_counter_is_aggregated_from_context() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10d); addMeasure(FUNCTIONS_KEY, 2d); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext).get().getDoubleValue()).isEqualTo(5d); } @Test public void create_measure_when_counter_is_aggregated_from_another_counter() { AverageFormula.AverageCounter anotherCounter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10d); addMeasure(FUNCTIONS_KEY, 2d); anotherCounter.initialize(counterInitializationContext); AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); counter.aggregate(anotherCounter); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext).get().getDoubleValue()).isEqualTo(5d); } @Test public void create_double_measure() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10d); addMeasure(FUNCTIONS_KEY, 2d); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext).get().getDoubleValue()).isEqualTo(5d); } @Test public void create_integer_measure() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10); addMeasure(FUNCTIONS_KEY, 2); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext).get().getDoubleValue()).isEqualTo(5); } @Test public void create_long_measure() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10L); addMeasure(FUNCTIONS_KEY, 2L); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext).get().getDoubleValue()).isEqualTo(5L); } @Test public void not_create_measure_when_aggregated_measure_has_no_value() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10L); when(counterInitializationContext.getMeasure(FUNCTIONS_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().createNoValue())); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext)).isNotPresent(); } @Test public void fail_with_IAE_when_aggregate_from_component_and_context_with_not_numeric_measures() { assertThatThrownBy(() -> { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10L); when(counterInitializationContext.getMeasure(FUNCTIONS_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create("data"))); counter.initialize(counterInitializationContext); BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Measure of type 'STRING' are not supported"); } @Test public void no_measure_created_when_counter_has_no_value() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); when(counterInitializationContext.getMeasure(anyString())).thenReturn(Optional.empty()); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext)).isNotPresent(); } @Test public void not_create_measure_when_only_one_measure() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10L); when(counterInitializationContext.getMeasure(FUNCTIONS_KEY)).thenReturn(Optional.empty()); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext)).isNotPresent(); } @Test public void not_create_measure_when_by_value_is_zero() { AverageFormula.AverageCounter counter = BASIC_AVERAGE_FORMULA.createNewCounter(); addMeasure(COMPLEXITY_IN_FUNCTIONS_KEY, 10d); addMeasure(FUNCTIONS_KEY, 0d); counter.initialize(counterInitializationContext); assertThat(BASIC_AVERAGE_FORMULA.createMeasure(counter, createMeasureContext)).isNotPresent(); } private void addMeasure(String metricKey, double value) { when(counterInitializationContext.getMeasure(metricKey)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(value, 1))); } private void addMeasure(String metricKey, int value) { when(counterInitializationContext.getMeasure(metricKey)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(value))); } private void addMeasure(String metricKey, long value) { when(counterInitializationContext.getMeasure(metricKey)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(value))); } }
9,077
40.263636
135
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormulaExecutionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; public class DistributionFormulaExecutionTest { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule().add(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); FormulaExecutorComponentVisitor underTest; @Before public void setUp() throws Exception { underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(Lists.newArrayList(new DistributionFormula(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY))); } @Test public void add_measures() { ReportComponent project = builder(PROJECT, 1) .addChildren( builder(DIRECTORY, 11) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(Component.Type.FILE, 1111).build(), builder(Component.Type.FILE, 1112).build()) .build()) .build(), builder(DIRECTORY, 12) .addChildren( builder(DIRECTORY, 121) .addChildren( builder(Component.Type.FILE, 1211).build()) .build()) .build()) .build(); treeRootHolder.setRoot(project); measureRepository.addRawMeasure(1111, FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=3;3.5=5;6.5=9")); measureRepository.addRawMeasure(1112, FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=0;3.5=2;6.5=1")); measureRepository.addRawMeasure(1211, FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=1;3.5=3;6.5=2")); new PathAwareCrawler<>(underTest).visit(project); assertThat(toEntries(measureRepository.getAddedRawMeasures(1))).containsOnly(entryOf(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=4;3.5=10;6.5=12"))); assertThat(toEntries(measureRepository.getAddedRawMeasures(11))).containsOnly(entryOf(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=3;3.5=7;6.5=10"))); assertThat(toEntries(measureRepository.getAddedRawMeasures(111))).containsOnly(entryOf(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=3;3.5=7;6.5=10"))); assertThat(measureRepository.getAddedRawMeasures(1111)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(1112)).isEmpty(); assertThat(toEntries(measureRepository.getAddedRawMeasures(12))).containsOnly(entryOf(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=1;3.5=3;6.5=2"))); assertThat(toEntries(measureRepository.getAddedRawMeasures(121))).containsOnly(entryOf(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, newMeasureBuilder().create("0.5=1;3.5=3;6.5=2"))); assertThat(measureRepository.getAddedRawMeasures(1211)).isEmpty(); } @Test public void not_add_measures_when_no_data_on_file() { ReportComponent project = builder(PROJECT, 1) .addChildren( builder(DIRECTORY, 11) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(Component.Type.FILE, 1111).build()) .build()) .build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(underTest).visit(project); assertThat(measureRepository.getAddedRawMeasures(1)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(11)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(111)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(1111)).isEmpty(); } }
5,777
45.97561
180
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DistributionFormulaTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY; public class DistributionFormulaTest { private static final DistributionFormula BASIC_DISTRIBUTION_FORMULA = new DistributionFormula(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY); CounterInitializationContext counterInitializationContext = mock(CounterInitializationContext.class); CreateMeasureContext projectCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); CreateMeasureContext fileCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.FILE, 1).build(), mock(Metric.class)); @Test public void check_new_counter_class() { assertThat(BASIC_DISTRIBUTION_FORMULA.createNewCounter().getClass()).isEqualTo(DistributionFormula.DistributionCounter.class); } @Test public void fail_with_NPE_when_creating_counter_with_null_metric() { assertThatThrownBy(() -> new DistributionFormula(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Metric key cannot be null"); } @Test public void check_output_metric_key_is_function_complexity_distribution() { assertThat(BASIC_DISTRIBUTION_FORMULA.getOutputMetricKeys()).containsOnly(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY); } @Test public void create_measure() { DistributionFormula.DistributionCounter counter = BASIC_DISTRIBUTION_FORMULA.createNewCounter(); addMeasure(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, "0=3;3=7;6=10"); counter.initialize(counterInitializationContext); assertThat(BASIC_DISTRIBUTION_FORMULA.createMeasure(counter, projectCreateMeasureContext).get().getData()).isEqualTo("0=3;3=7;6=10"); } @Test public void create_measure_when_counter_is_aggregating_from_another_counter() { DistributionFormula.DistributionCounter anotherCounter = BASIC_DISTRIBUTION_FORMULA.createNewCounter(); addMeasure(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, "0=3;3=7;6=10"); anotherCounter.initialize(counterInitializationContext); DistributionFormula.DistributionCounter counter = BASIC_DISTRIBUTION_FORMULA.createNewCounter(); counter.aggregate(anotherCounter); assertThat(BASIC_DISTRIBUTION_FORMULA.createMeasure(counter, projectCreateMeasureContext).get().getData()).isEqualTo("0=3;3=7;6=10"); } @Test public void create_no_measure_when_no_value() { DistributionFormula.DistributionCounter counter = BASIC_DISTRIBUTION_FORMULA.createNewCounter(); when(counterInitializationContext.getMeasure(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(Optional.empty()); counter.initialize(counterInitializationContext); assertThat(BASIC_DISTRIBUTION_FORMULA.createMeasure(counter, projectCreateMeasureContext)).isNotPresent(); } @Test public void not_create_measure_when_on_file() { DistributionFormula.DistributionCounter counter = BASIC_DISTRIBUTION_FORMULA.createNewCounter(); addMeasure(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY, "0=3;3=7;6=10"); counter.initialize(counterInitializationContext); assertThat(BASIC_DISTRIBUTION_FORMULA.createMeasure(counter, fileCreateMeasureContext)).isNotPresent(); } private void addMeasure(String metricKey, String value) { when(counterInitializationContext.getMeasure(metricKey)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(value))); } }
4,793
43.803738
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/DumbCreateMeasureContext.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.metric.Metric; public class DumbCreateMeasureContext implements CreateMeasureContext { private final Component component; private final Metric metric; public DumbCreateMeasureContext(Component component, Metric metric) { this.component = component; this.metric = metric; } @Override public Component getComponent() { return component; } @Override public Metric getMetric() { return metric; } }
1,433
30.866667
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/IntSumFormulaTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.formula.SumFormula.IntSumFormula; import org.sonar.ce.task.projectanalysis.formula.counter.IntSumCounter; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumFormula; public class IntSumFormulaTest { private static final IntSumFormula INT_SUM_FORMULA = createIntSumFormula(LINES_KEY); private static final IntSumFormula INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE = createIntSumFormula(LINES_KEY, null); private static final IntSumFormula INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15 = createIntSumFormula(LINES_KEY, 15); CreateMeasureContext projectCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); CreateMeasureContext fileCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.FILE, 2).build(), mock(Metric.class)); @Test public void check_create_new_counter_class() { assertThat(INT_SUM_FORMULA.createNewCounter().getClass()).isEqualTo(IntSumCounter.class); } @Test public void fail_with_NPE_when_creating_formula_with_null_metric() { assertThatThrownBy(() -> createIntSumFormula(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Metric key cannot be null"); } @Test public void check_output_metric_key_is_lines() { assertThat(INT_SUM_FORMULA.getOutputMetricKeys()).containsOnly(LINES_KEY); assertThat(INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.getOutputMetricKeys()).containsOnly(LINES_KEY); assertThat(INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.getOutputMetricKeys()).containsOnly(LINES_KEY); } @Test public void create_measure_when_initialized_and_input_measure_exists() { IntSumCounter counter = INT_SUM_FORMULA.createNewCounter(); counter.initialize(createMeasureInInitContext(10)); assertCreateMeasureValue(counter, 10); } @Test public void does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist() { IntSumCounter counter = INT_SUM_FORMULA.createNewCounter(); does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist(counter); } @Test public void does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist_and_defaultInputValue_is_null() { IntSumCounter counter = INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter(); does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist(counter); } private void does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist(IntSumCounter counter) { counter.initialize(createNoMeasureInInitContext()); assertCreateNoMeasure(counter); } @Test public void creates_measure_when_only_initialized_and_input_measure_does_not_exist_and_defaultInputValue_is_non_null() { IntSumCounter counter = INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter(); counter.initialize(createNoMeasureInInitContext()); assertCreateMeasureValue(counter, 15); } @Test public void create_measure_sum_of_init_and_aggregated_other_counter_when_input_measure_exists() { create_measure_sum_of_init_and_aggregated_other_counter(INT_SUM_FORMULA.createNewCounter(), 10, 30); create_measure_sum_of_init_and_aggregated_other_counter(INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter(), 10, 30); create_measure_sum_of_init_and_aggregated_other_counter(INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter(), 10, 30); } @Test public void create_measure_when_aggregated_other_counter_but_input_measure_does_not_exist() { create_measure_sum_of_init_and_aggregated_other_counter(INT_SUM_FORMULA.createNewCounter(), null, 20); create_measure_sum_of_init_and_aggregated_other_counter(INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter(), null, 20); create_measure_sum_of_init_and_aggregated_other_counter(INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter(), null, 35); } private void create_measure_sum_of_init_and_aggregated_other_counter(IntSumCounter counter, @Nullable Integer inputMeasure, int expectedMeasureValue) { // init with value 10 if (inputMeasure != null) { counter.initialize(createMeasureInInitContext(10)); } else { counter.initialize(createNoMeasureInInitContext()); } // second counter with value 20 IntSumCounter anotherCounter = INT_SUM_FORMULA.createNewCounter(); anotherCounter.initialize(createMeasureInInitContext(20)); counter.aggregate(anotherCounter); assertCreateMeasureValue(counter, expectedMeasureValue); } @Test public void initialize_does_not_create_measure_on_file() { initialize_does_not_create_measure_on_file(INT_SUM_FORMULA.createNewCounter()); initialize_does_not_create_measure_on_file(INT_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter()); initialize_does_not_create_measure_on_file(INT_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter()); } private void assertCreateNoMeasure(IntSumCounter counter) { assertThat(INT_SUM_FORMULA.createMeasure(counter, projectCreateMeasureContext)).isNotPresent(); } private void assertCreateMeasureValue(IntSumCounter counter, int expectMeasureValue) { assertThat(INT_SUM_FORMULA.createMeasure(counter, projectCreateMeasureContext).get().getIntValue()).isEqualTo(expectMeasureValue); } private void initialize_does_not_create_measure_on_file(IntSumCounter counter) { counter.initialize(createMeasureInInitContext(10)); assertThat(INT_SUM_FORMULA.createMeasure(counter, fileCreateMeasureContext)).isNotPresent(); } private static CounterInitializationContext createMeasureInInitContext(int value) { CounterInitializationContext initContext = mock(CounterInitializationContext.class); when(initContext.getMeasure(LINES_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(value))); return initContext; } private static CounterInitializationContext createNoMeasureInInitContext() { CounterInitializationContext initContext = mock(CounterInitializationContext.class); when(initContext.getMeasure(LINES_KEY)).thenReturn(Optional.empty()); return initContext; } }
7,711
44.904762
153
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/LongSumFormulaTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.formula.counter.LongSumCounter; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createLongSumFormula; public class LongSumFormulaTest { private static final SumFormula.LongSumFormula LONG_SUM_FORMULA = createLongSumFormula(LINES_KEY); private static final SumFormula.LongSumFormula LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE = createLongSumFormula(LINES_KEY, null); private static final SumFormula.LongSumFormula LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15 = createLongSumFormula(LINES_KEY, 15L); CreateMeasureContext projectCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.PROJECT, 1).build(), mock(Metric.class)); CreateMeasureContext fileCreateMeasureContext = new DumbCreateMeasureContext( ReportComponent.builder(Component.Type.FILE, 2).build(), mock(Metric.class)); @Test public void check_create_new_counter_class() { assertThat(LONG_SUM_FORMULA.createNewCounter().getClass()).isEqualTo(LongSumCounter.class); } @Test public void fail_with_NPE_when_creating_formula_with_null_metric() { assertThatThrownBy(() -> createLongSumFormula(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Metric key cannot be null"); } @Test public void check_output_metric_key_is_lines() { assertThat(LONG_SUM_FORMULA.getOutputMetricKeys()).containsOnly(LINES_KEY); assertThat(LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.getOutputMetricKeys()).containsOnly(LINES_KEY); assertThat(LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.getOutputMetricKeys()).containsOnly(LINES_KEY); } @Test public void create_measure_when_initialized_and_input_measure_exists() { LongSumCounter counter = LONG_SUM_FORMULA.createNewCounter(); counter.initialize(createMeasureInInitContext(10)); assertCreateMeasureValue(counter, 10); } @Test public void does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist() { LongSumCounter counter = LONG_SUM_FORMULA.createNewCounter(); does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist(counter); } @Test public void does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist_and_defaultInputValue_is_null() { LongSumCounter counter = LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter(); does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist(counter); } private void does_not_create_measure_when_only_initialized_and_input_measure_does_not_exist(LongSumCounter counter) { counter.initialize(createNoMeasureInInitContext()); assertCreateNoMeasure(counter); } @Test public void creates_measure_when_only_initialized_and_input_measure_does_not_exist_and_defaultInputValue_is_non_null() { LongSumCounter counter = LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter(); counter.initialize(createNoMeasureInInitContext()); assertCreateMeasureValue(counter, 15); } @Test public void create_measure_sum_of_init_and_aggregated_other_counter_when_input_measure_exists() { create_measure_sum_of_init_and_aggregated_other_counter(LONG_SUM_FORMULA.createNewCounter(), 10L, 30); create_measure_sum_of_init_and_aggregated_other_counter(LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter(), 10L, 30); create_measure_sum_of_init_and_aggregated_other_counter(LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter(), 10L, 30); } private void create_measure_sum_of_init_and_aggregated_other_counter(LongSumCounter counter, @Nullable Long inputMeasure, long expectedMeasureValue) { // init with value 10 if (inputMeasure != null) { counter.initialize(createMeasureInInitContext(10)); } else { counter.initialize(createNoMeasureInInitContext()); } // second counter with value 20 LongSumCounter anotherCounter = LONG_SUM_FORMULA.createNewCounter(); anotherCounter.initialize(createMeasureInInitContext(20)); counter.aggregate(anotherCounter); assertCreateMeasureValue(counter, expectedMeasureValue); } @Test public void create_measure_when_aggregated_other_counter_but_input_measure_does_not_exist() { create_measure_sum_of_init_and_aggregated_other_counter(LONG_SUM_FORMULA.createNewCounter(), null, 20); create_measure_sum_of_init_and_aggregated_other_counter(LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter(), null, 20); create_measure_sum_of_init_and_aggregated_other_counter(LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter(), null, 35); } @Test public void initialize_does_not_create_measure_on_file() { initialize_does_not_create_measure_on_file(LONG_SUM_FORMULA.createNewCounter()); initialize_does_not_create_measure_on_file(LONG_SUM_FORMULA_NULL_DEFAULT_INPUT_VALUE.createNewCounter()); initialize_does_not_create_measure_on_file(LONG_SUM_FORMULA_DEFAULT_INPUT_VALUE_15.createNewCounter()); } private void assertCreateNoMeasure(LongSumCounter counter) { assertThat(LONG_SUM_FORMULA.createMeasure(counter, projectCreateMeasureContext)).isNotPresent(); } private void assertCreateMeasureValue(LongSumCounter counter, long expectMeasureValue) { assertThat(LONG_SUM_FORMULA.createMeasure(counter, projectCreateMeasureContext).get().getLongValue()).isEqualTo(expectMeasureValue); } private void initialize_does_not_create_measure_on_file(LongSumCounter counter) { counter.initialize(createMeasureInInitContext(10)); assertThat(LONG_SUM_FORMULA.createMeasure(counter, fileCreateMeasureContext)).isNotPresent(); } private static CounterInitializationContext createMeasureInInitContext(long value) { CounterInitializationContext initContext = mock(CounterInitializationContext.class); when(initContext.getMeasure(LINES_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(value))); return initContext; } private static CounterInitializationContext createNoMeasureInInitContext() { CounterInitializationContext initContext = mock(CounterInitializationContext.class); when(initContext.getMeasure(LINES_KEY)).thenReturn(Optional.empty()); return initContext; } }
7,719
45.227545
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/ReportFormulaExecutorComponentVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import com.google.common.collect.ImmutableList; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_LINES_TO_COVER_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; public class ReportFormulaExecutorComponentVisitorTest { private static final int ROOT_REF = 1; private static final int DIRECTORY_1_REF = 111; private static final int FILE_1_REF = 1111; private static final int FILE_2_REF = 1112; private static final int DIRECTORY_2_REF = 121; private static final int FILE_3_REF = 1211; private static final ReportComponent BALANCED_COMPONENT_TREE = ReportComponent.builder(PROJECT, ROOT_REF) .addChildren( ReportComponent.builder(DIRECTORY, DIRECTORY_1_REF) .addChildren( builder(Component.Type.FILE, FILE_1_REF).build(), builder(Component.Type.FILE, FILE_2_REF).build()) .build(), ReportComponent.builder(DIRECTORY, DIRECTORY_2_REF) .addChildren( builder(Component.Type.FILE, FILE_3_REF).build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.LINES) .add(CoreMetrics.NCLOC) .add(CoreMetrics.NEW_LINES_TO_COVER) .add(CoreMetrics.NEW_COVERAGE); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Test public void verify_aggregation_on_value() { treeRootHolder.setRoot(BALANCED_COMPONENT_TREE); measureRepository.addRawMeasure(FILE_1_REF, LINES_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, LINES_KEY, newMeasureBuilder().create(8)); measureRepository.addRawMeasure(FILE_3_REF, LINES_KEY, newMeasureBuilder().create(2)); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(BALANCED_COMPONENT_TREE); assertAddedRawMeasure(ROOT_REF, 20); assertAddedRawMeasure(111, 18); assertAddedRawMeasure(FILE_1_REF, 10); assertAddedRawMeasure(FILE_2_REF, 8); assertAddedRawMeasure(DIRECTORY_2_REF, 2); assertAddedRawMeasure(FILE_3_REF, 2); } @Test public void verify_multi_metric_formula_support_and_aggregation() { treeRootHolder.setRoot(BALANCED_COMPONENT_TREE); measureRepository.addRawMeasure(FILE_1_REF, LINES_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, LINES_KEY, newMeasureBuilder().create(8)); measureRepository.addRawMeasure(FILE_3_REF, LINES_KEY, newMeasureBuilder().create(2)); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeMultiMetricFormula())) .visit(BALANCED_COMPONENT_TREE); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(30)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(120))); assertThat(toEntries(measureRepository.getAddedRawMeasures(111))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(28)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(118))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_1_REF))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(20)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(110))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_2_REF))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(18)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(108))); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_2_REF))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(12)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(102))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_3_REF))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(12)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(102))); } @Test public void measures_are_0_when_there_is_no_input_measure() { ReportComponent project = ReportComponent.builder(PROJECT, ROOT_REF) .addChildren( ReportComponent.builder(DIRECTORY, DIRECTORY_1_REF) .addChildren( builder(Component.Type.FILE, FILE_1_REF).build()) .build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(project); assertAddedRawMeasure(ROOT_REF, 0); assertAddedRawMeasure(DIRECTORY_1_REF, 0); assertAddedRawMeasure(FILE_1_REF, 0); } @Test public void add_measure_even_when_leaf_is_not_FILE() { ReportComponent project = ReportComponent.builder(PROJECT, ROOT_REF) .addChildren( ReportComponent.builder(DIRECTORY, 111).build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(project); assertAddedRawMeasure(DIRECTORY_1_REF, 0); } @Test public void compute_measure_on_project_without_children() { ReportComponent root = builder(PROJECT, ROOT_REF).build(); treeRootHolder.setRoot(root); measureRepository.addRawMeasure(ROOT_REF, LINES_KEY, newMeasureBuilder().create(10)); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(root); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly(entryOf(NCLOC_KEY, newMeasureBuilder().create(10))); } @Test public void ignore_measure_defined_on_project_when_measure_is_defined_on_leaf() { ReportComponent root = builder(PROJECT, ROOT_REF) .addChildren( builder(Component.Type.FILE, FILE_1_REF).build()) .build(); treeRootHolder.setRoot(root); measureRepository.addRawMeasure(ROOT_REF, LINES_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_1_REF, LINES_KEY, newMeasureBuilder().create(2)); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(root); assertAddedRawMeasure(ROOT_REF, 2); assertAddedRawMeasure(FILE_1_REF, 2); } @Test public void fail_when_trying_to_compute_file_measure_already_existing_in_report() { ReportComponent root = builder(PROJECT, ROOT_REF) .addChildren( builder(Component.Type.FILE, FILE_1_REF).build()) .build(); treeRootHolder.setRoot(root); measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(2)); // expectedException.expectCause( // hasType(UnsupportedOperationException.class) // .andMessage(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", FILE_1_REF, NCLOC_KEY)) // ); assertThatThrownBy(() -> new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())).visit(root)) .hasCause(new UnsupportedOperationException(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", FILE_1_REF, NCLOC_KEY))); } @Test public void fail_on_project_without_children_already_having_computed_measure() { ReportComponent root = builder(PROJECT, ROOT_REF).build(); treeRootHolder.setRoot(root); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(10)); // expectedException.expectCause(hasType(UnsupportedOperationException.class) // .andMessage(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", ROOT_REF, NCLOC_KEY))); assertThatThrownBy(() -> { new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(root); }) .hasCause(new UnsupportedOperationException(String.format("A measure can only be set once for Component (ref=%s), Metric (key=%s)", ROOT_REF, NCLOC_KEY))); } private FormulaExecutorComponentVisitor formulaExecutorComponentVisitor(Formula formula) { return FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(ImmutableList.of(formula)); } private void assertAddedRawMeasure(int componentRef, int expectedValue) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).containsOnly(entryOf(NCLOC_KEY, newMeasureBuilder().create(expectedValue))); } private class FakeFormula implements Formula<FakeCounter> { @Override public FakeCounter createNewCounter() { return new FakeCounter(); } @Override public Optional<Measure> createMeasure(FakeCounter counter, CreateMeasureContext context) { // verify the context which is passed to the method assertThat(context.getComponent()).isNotNull(); assertThat(context.getMetric()).isSameAs(metricRepository.getByKey(NCLOC_KEY)); return Optional.of(Measure.newMeasureBuilder().create(counter.value)); } @Override public String[] getOutputMetricKeys() { return new String[] {NCLOC_KEY}; } } private class FakeMultiMetricFormula implements Formula<FakeCounter> { @Override public FakeCounter createNewCounter() { return new FakeCounter(); } @Override public Optional<Measure> createMeasure(FakeCounter counter, CreateMeasureContext context) { // verify the context which is passed to the method assertThat(context.getComponent()).isNotNull(); assertThat(context.getMetric()) .isIn(metricRepository.getByKey(NEW_LINES_TO_COVER_KEY), metricRepository.getByKey(NEW_COVERAGE_KEY)); return Optional.of(Measure.newMeasureBuilder().create(counter.value + metricOffset(context.getMetric()))); } private int metricOffset(Metric metric) { if (metric.getKey().equals(NEW_LINES_TO_COVER_KEY)) { return 10; } if (metric.getKey().equals(NEW_COVERAGE_KEY)) { return 100; } throw new IllegalArgumentException("Unsupported metric " + metric); } @Override public String[] getOutputMetricKeys() { return new String[] {NEW_LINES_TO_COVER_KEY, NEW_COVERAGE_KEY}; } } private static class FakeCounter implements Counter<FakeCounter> { private int value = 0; @Override public void aggregate(FakeCounter counter) { this.value += counter.value; } @Override public void initialize(CounterInitializationContext context) { // verify the context which is passed to the method assertThat(context.getLeaf().getChildren()).isEmpty(); Optional<Measure> measureOptional = context.getMeasure(LINES_KEY); if (measureOptional.isPresent()) { value += measureOptional.get().getIntValue(); } } } }
13,137
41.244373
163
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/SumFormulaExecutionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.formula.SumFormula.createIntSumFormula; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; public class SumFormulaExecutionTest { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule().add(CoreMetrics.LINES); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); FormulaExecutorComponentVisitor underTest; @Before public void setUp() { underTest = FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(Lists.newArrayList(createIntSumFormula(LINES_KEY))); } @Test public void add_measures() { ReportComponent project = builder(PROJECT, 1) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(Component.Type.FILE, 1111).build(), builder(Component.Type.FILE, 1112).build()) .build(), builder(DIRECTORY, 121) .addChildren( builder(Component.Type.FILE, 1211).build()) .build()) .build(); treeRootHolder.setRoot(project); measureRepository.addRawMeasure(1111, LINES_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(1112, LINES_KEY, newMeasureBuilder().create(8)); measureRepository.addRawMeasure(1211, LINES_KEY, newMeasureBuilder().create(2)); new PathAwareCrawler<>(underTest).visit(project); assertThat(toEntries(measureRepository.getAddedRawMeasures(1))).containsOnly(entryOf(LINES_KEY, newMeasureBuilder().create(20))); assertThat(toEntries(measureRepository.getAddedRawMeasures(111))).containsOnly(entryOf(LINES_KEY, newMeasureBuilder().create(18))); assertThat(measureRepository.getAddedRawMeasures(1111)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(1112)).isEmpty(); assertThat(toEntries(measureRepository.getAddedRawMeasures(121))).containsOnly(entryOf(LINES_KEY, newMeasureBuilder().create(2))); assertThat(measureRepository.getAddedRawMeasures(1211)).isEmpty(); } @Test public void not_add_measures_when_no_data_on_file() { ReportComponent project = builder(PROJECT, 1) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(Component.Type.FILE, 1111).build()) .build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(underTest).visit(project); assertThat(measureRepository.getAddedRawMeasures(1)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(111)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(1111)).isEmpty(); } }
4,779
41.678571
135
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/ViewsFormulaExecutorComponentVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula; import com.google.common.collect.ImmutableList; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.PathAwareCrawler; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import org.sonar.ce.task.projectanalysis.formula.counter.IntValue; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_LINES_TO_COVER_KEY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW; import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW; import static org.sonar.ce.task.projectanalysis.component.ViewsComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; public class ViewsFormulaExecutorComponentVisitorTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_1_REF = 11; private static final int SUB_SUBVIEW_REF = 111; private static final int PROJECT_VIEW_1_REF = 1111; private static final int PROJECT_VIEW_2_REF = 1113; private static final int SUBVIEW_2_REF = 12; private static final int PROJECT_VIEW_3_REF = 121; private static final int PROJECT_VIEW_4_REF = 13; private static final ViewsComponent BALANCED_COMPONENT_TREE = ViewsComponent.builder(VIEW, ROOT_REF) .addChildren( ViewsComponent.builder(SUBVIEW, SUBVIEW_1_REF) .addChildren( ViewsComponent.builder(SUBVIEW, SUB_SUBVIEW_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECT_VIEW_2_REF).build()) .build()) .build(), ViewsComponent.builder(SUBVIEW, SUBVIEW_2_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_3_REF).build()) .build(), builder(PROJECT_VIEW, PROJECT_VIEW_4_REF).build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.LINES) .add(CoreMetrics.NCLOC) .add(CoreMetrics.NEW_LINES_TO_COVER) .add(CoreMetrics.NEW_COVERAGE); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Test public void verify_aggregation_on_value() { treeRootHolder.setRoot(BALANCED_COMPONENT_TREE); addRawMeasure(PROJECT_VIEW_1_REF, 1, LINES_KEY); addRawMeasure(PROJECT_VIEW_2_REF, 2, LINES_KEY); addRawMeasure(PROJECT_VIEW_3_REF, 3, LINES_KEY); addRawMeasure(PROJECT_VIEW_4_REF, 4, LINES_KEY); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(BALANCED_COMPONENT_TREE); verifyProjectViewsHasNoAddedRawMeasures(); verifySingleMetricValue(SUB_SUBVIEW_REF, 3); verifySingleMetricValue(SUBVIEW_1_REF, 3); verifySingleMetricValue(SUBVIEW_2_REF, 3); verifySingleMetricValue(ROOT_REF, 10); } private MeasureRepositoryRule addRawMeasure(int componentRef, int value, String metricKey) { return measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } @Test public void verify_multi_metric_formula_support_and_aggregation() { treeRootHolder.setRoot(BALANCED_COMPONENT_TREE); addRawMeasure(PROJECT_VIEW_1_REF, 1, LINES_KEY); addRawMeasure(PROJECT_VIEW_2_REF, 2, LINES_KEY); addRawMeasure(PROJECT_VIEW_3_REF, 5, LINES_KEY); addRawMeasure(PROJECT_VIEW_4_REF, 4, LINES_KEY); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeMultiMetricFormula())) .visit(BALANCED_COMPONENT_TREE); verifyProjectViewsHasNoAddedRawMeasures(); verifyMultiMetricValues(SUB_SUBVIEW_REF, 13, 103); verifyMultiMetricValues(SUBVIEW_1_REF, 13, 103); verifyMultiMetricValues(SUBVIEW_2_REF, 15, 105); verifyMultiMetricValues(ROOT_REF, 22, 112); } @Test public void verify_no_measure_added_on_projectView() { ViewsComponent project = ViewsComponent.builder(VIEW, ROOT_REF) .addChildren( ViewsComponent.builder(SUBVIEW, SUBVIEW_1_REF) .addChildren( ViewsComponent.builder(SUBVIEW, SUB_SUBVIEW_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_1_REF).build()) .build()) .build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(project); assertNoAddedRawMeasure(PROJECT_VIEW_1_REF); verifySingleMetricValue(SUB_SUBVIEW_REF, 0); verifySingleMetricValue(SUBVIEW_1_REF, 0); verifySingleMetricValue(ROOT_REF, 0); } @Test public void add_measure_even_if_leaf_is_not_a_PROJECT_VIEW() { ViewsComponent project = ViewsComponent.builder(VIEW, ROOT_REF) .addChildren( ViewsComponent.builder(SUBVIEW, SUBVIEW_1_REF) .addChildren( ViewsComponent.builder(SUBVIEW, SUB_SUBVIEW_REF).build()) .build()) .build(); treeRootHolder.setRoot(project); new PathAwareCrawler<>(formulaExecutorComponentVisitor(new FakeFormula())) .visit(project); verifySingleMetricValue(SUB_SUBVIEW_REF, 0); verifySingleMetricValue(SUBVIEW_1_REF, 0); verifySingleMetricValue(ROOT_REF, 0); } private class FakeFormula implements Formula<FakeCounter> { @Override public FakeCounter createNewCounter() { return new FakeCounter(); } @Override public Optional<Measure> createMeasure(FakeCounter counter, CreateMeasureContext context) { // verify the context which is passed to the method assertThat(context.getComponent()).isNotNull(); assertThat(context.getMetric()).isSameAs(metricRepository.getByKey(NCLOC_KEY)); return Optional.of(Measure.newMeasureBuilder().create(counter.value)); } @Override public String[] getOutputMetricKeys() { return new String[] {NCLOC_KEY}; } } private class FakeMultiMetricFormula implements Formula<FakeCounter> { @Override public FakeCounter createNewCounter() { return new FakeCounter(); } @Override public Optional<Measure> createMeasure(FakeCounter counter, CreateMeasureContext context) { // verify the context which is passed to the method assertThat(context.getComponent()).isNotNull(); assertThat(context.getMetric()) .isIn(metricRepository.getByKey(NEW_LINES_TO_COVER_KEY), metricRepository.getByKey(NEW_COVERAGE_KEY)); return Optional.of(Measure.newMeasureBuilder().create(counter.value + metricOffset(context.getMetric()))); } private int metricOffset(Metric metric) { if (metric.getKey().equals(NEW_LINES_TO_COVER_KEY)) { return 10; } if (metric.getKey().equals(NEW_COVERAGE_KEY)) { return 100; } throw new IllegalArgumentException("Unsupported metric " + metric); } @Override public String[] getOutputMetricKeys() { return new String[] {NEW_LINES_TO_COVER_KEY, NEW_COVERAGE_KEY}; } } private class FakeCounter implements Counter<FakeCounter> { private int value = 0; @Override public void aggregate(FakeCounter counter) { this.value += counter.value; } @Override public void initialize(CounterInitializationContext context) { verifyLeafContext(context); Optional<Measure> measureOptional = context.getMeasure(LINES_KEY); if (measureOptional.isPresent()) { value += measureOptional.get().getIntValue(); } } } private class FakeVariationFormula implements Formula<FakeVariationCounter> { @Override public FakeVariationCounter createNewCounter() { return new FakeVariationCounter(); } @Override public Optional<Measure> createMeasure(FakeVariationCounter counter, CreateMeasureContext context) { // verify the context which is passed to the method assertThat(context.getComponent()).isNotNull(); assertThat(context.getMetric()).isSameAs(metricRepository.getByKey(NEW_COVERAGE_KEY)); IntValue measureVariations = counter.values; if (measureVariations.isSet()) { return Optional.of(newMeasureBuilder().create(measureVariations.getValue())); } return Optional.empty(); } @Override public String[] getOutputMetricKeys() { return new String[] {NEW_COVERAGE_KEY}; } } private class FakeVariationCounter implements Counter<FakeVariationCounter> { private final IntValue values = new IntValue(); @Override public void aggregate(FakeVariationCounter counter) { values.increment(counter.values); } @Override public void initialize(CounterInitializationContext context) { verifyLeafContext(context); Optional<Measure> measureOptional = context.getMeasure(NEW_LINES_TO_COVER_KEY); if (!measureOptional.isPresent()) { return; } this.values.increment(measureOptional.get().getIntValue()); } } private FormulaExecutorComponentVisitor formulaExecutorComponentVisitor(Formula formula) { return FormulaExecutorComponentVisitor.newBuilder(metricRepository, measureRepository) .buildFor(ImmutableList.of(formula)); } private void verifyProjectViewsHasNoAddedRawMeasures() { assertNoAddedRawMeasure(PROJECT_VIEW_1_REF); assertNoAddedRawMeasure(PROJECT_VIEW_2_REF); assertNoAddedRawMeasure(PROJECT_VIEW_3_REF); assertNoAddedRawMeasure(PROJECT_VIEW_4_REF); } private void assertNoAddedRawMeasure(int componentRef) { assertThat(measureRepository.getAddedRawMeasures(componentRef)).isEmpty(); } private void verifySingleMetricValue(int componentRef, int measureValue) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))) .containsOnly(entryOf(NCLOC_KEY, newMeasureBuilder().create(measureValue))); } private void verifyMultiMetricValues(int componentRef, int valueLinesToCover, int valueItCoverage) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))) .containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, newMeasureBuilder().create(valueLinesToCover)), entryOf(NEW_COVERAGE_KEY, newMeasureBuilder().create(valueItCoverage))); } private void verifyLeafContext(CounterInitializationContext context) { assertThat(context.getLeaf().getChildren()).isEmpty(); } }
12,176
36.69969
114
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/counter/DoubleValueTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.counter; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class DoubleValueTest { @Test public void newly_created_DoubleVariationValue_is_unset_and_has_value_0() { verifyUnsetVariationValue(new DoubleValue()); } @Test public void increment_double_sets_DoubleVariationValue_and_increments_value() { verifySetVariationValue(new DoubleValue().increment(10.6), 10.6); } @Test public void increment_DoubleVariationValue_has_no_effect_if_arg_is_null() { verifyUnsetVariationValue(new DoubleValue().increment(null)); } @Test public void increment_DoubleVariationValue_has_no_effect_if_arg_is_unset() { verifyUnsetVariationValue(new DoubleValue().increment(new DoubleValue())); } @Test public void increment_DoubleVariationValue_increments_by_the_value_of_the_arg() { DoubleValue source = new DoubleValue().increment(10); DoubleValue target = new DoubleValue().increment(source); verifySetVariationValue(target, 10); } @Test public void multiple_calls_to_increment_DoubleVariationValue_increments_by_the_value_of_the_arg() { DoubleValue target = new DoubleValue() .increment(new DoubleValue().increment(35)) .increment(new DoubleValue().increment(10)); verifySetVariationValue(target, 45); } @Test public void multiples_calls_to_increment_double_increment_the_value() { DoubleValue variationValue = new DoubleValue() .increment(10.6) .increment(95.4); verifySetVariationValue(variationValue, 106); } private static void verifyUnsetVariationValue(DoubleValue variationValue) { assertThat(variationValue.isSet()).isFalse(); assertThat(variationValue.getValue()).isZero(); } private static void verifySetVariationValue(DoubleValue variationValue, double expected) { assertThat(variationValue.isSet()).isTrue(); assertThat(variationValue.getValue()).isEqualTo(expected); } }
2,843
33.26506
101
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/counter/IntSumCounterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.counter; import java.util.Optional; import org.junit.Test; import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext; import org.sonar.ce.task.projectanalysis.measure.Measure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IntSumCounterTest { private final static String METRIC_KEY = "metric"; CounterInitializationContext counterInitializationContext = mock(CounterInitializationContext.class); SumCounter sumCounter = new IntSumCounter(METRIC_KEY); @Test public void no_value_when_no_aggregation() { assertThat(sumCounter.getValue()).isNotPresent(); } @Test public void aggregate_from_context() { when(counterInitializationContext.getMeasure(METRIC_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(10))); sumCounter.initialize(counterInitializationContext); assertThat(sumCounter.getValue()).contains(10); } @Test public void no_value_when_aggregate_from_context_but_no_measure() { when(counterInitializationContext.getMeasure(anyString())).thenReturn(Optional.empty()); sumCounter.initialize(counterInitializationContext); assertThat(sumCounter.getValue()).isNotPresent(); } @Test public void aggregate_from_counter() { when(counterInitializationContext.getMeasure(METRIC_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(10))); SumCounter anotherCounter = new IntSumCounter(METRIC_KEY); anotherCounter.initialize(counterInitializationContext); sumCounter.aggregate(anotherCounter); assertThat(sumCounter.getValue()).contains(10); } @Test public void no_value_when_aggregate_from_empty_aggregator() { SumCounter anotherCounter = new IntSumCounter(METRIC_KEY); sumCounter.aggregate(anotherCounter); assertThat(sumCounter.getValue()).isNotPresent(); } }
2,871
33.190476
126
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/counter/IntValueTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.counter; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class IntValueTest { @Test public void newly_created_IntValue_is_unset_and_has_value_0() { verifyUnsetValue(new IntValue()); } @Test public void increment_int_sets_IntValue_and_increments_value() { verifySetValue(new IntValue().increment(10), 10); } @Test public void increment_IntValue_has_no_effect_if_arg_is_null() { verifyUnsetValue(new IntValue().increment(null)); } @Test public void increment_IntValue_has_no_effect_if_arg_is_unset() { verifyUnsetValue(new IntValue().increment(new IntValue())); } @Test public void increment_IntValue_increments_by_the_value_of_the_arg() { IntValue source = new IntValue().increment(10); IntValue target = new IntValue().increment(source); verifySetValue(target, 10); } @Test public void multiple_calls_to_increment_IntValue_increments_by_the_value_of_the_arg() { IntValue target = new IntValue() .increment(new IntValue().increment(35)) .increment(new IntValue().increment(10)); verifySetValue(target, 45); } @Test public void multiples_calls_to_increment_int_increment_the_value() { IntValue value = new IntValue() .increment(10) .increment(95); verifySetValue(value, 105); } private static void verifyUnsetValue(IntValue value) { assertThat(value.isSet()).isFalse(); assertThat(value.getValue()).isZero(); } private static void verifySetValue(IntValue value, int expected) { assertThat(value.isSet()).isTrue(); assertThat(value.getValue()).isEqualTo(expected); } }
2,547
29.698795
89
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/counter/LongSumCounterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.counter; import java.util.Optional; import org.junit.Test; import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext; import org.sonar.ce.task.projectanalysis.measure.Measure; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LongSumCounterTest { private static final String METRIC_KEY = "metric"; private static final long MEASURE_VALUE = 10L; CounterInitializationContext counterInitializationContext = mock(CounterInitializationContext.class); SumCounter sumCounter = new LongSumCounter(METRIC_KEY); @Test public void no_value_when_no_aggregation() { assertThat(sumCounter.getValue()).isNotPresent(); } @Test public void aggregate_from_context() { when(counterInitializationContext.getMeasure(METRIC_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(MEASURE_VALUE))); sumCounter.initialize(counterInitializationContext); assertThat(sumCounter.getValue()).contains(MEASURE_VALUE); } @Test public void no_value_when_aggregate_from_context_but_no_measure() { when(counterInitializationContext.getMeasure(anyString())).thenReturn(Optional.empty()); sumCounter.initialize(counterInitializationContext); assertThat(sumCounter.getValue()).isNotPresent(); } @Test public void aggregate_from_counter() { when(counterInitializationContext.getMeasure(METRIC_KEY)).thenReturn(Optional.of(Measure.newMeasureBuilder().create(MEASURE_VALUE))); SumCounter anotherCounter = new LongSumCounter(METRIC_KEY); anotherCounter.initialize(counterInitializationContext); sumCounter.aggregate(anotherCounter); assertThat(sumCounter.getValue()).contains(MEASURE_VALUE); } @Test public void no_value_when_aggregate_from_empty_aggregator() { SumCounter anotherCounter = new LongSumCounter(METRIC_KEY); sumCounter.aggregate(anotherCounter); assertThat(sumCounter.getValue()).isNotPresent(); } }
2,968
33.929412
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/counter/LongValueTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.counter; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class LongValueTest { @Test public void newly_created_LongVariationValue_is_unset_and_has_value_0() { verifyUnsetVariationValue(new LongValue()); } @Test public void increment_long_sets_LongVariationValue_and_increments_value() { verifySetVariationValue(new LongValue().increment(10L), 10L); } @Test public void increment_LongVariationValue_has_no_effect_if_arg_is_null() { verifyUnsetVariationValue(new LongValue().increment(null)); } @Test public void increment_LongVariationValue_has_no_effect_if_arg_is_unset() { verifyUnsetVariationValue(new LongValue().increment(new LongValue())); } @Test public void increment_LongVariationValue_increments_by_the_value_of_the_arg() { LongValue source = new LongValue().increment(10L); LongValue target = new LongValue().increment(source); verifySetVariationValue(target, 10L); } @Test public void multiple_calls_to_increment_LongVariationValue_increments_by_the_value_of_the_arg() { LongValue target = new LongValue() .increment(new LongValue().increment(35L)) .increment(new LongValue().increment(10L)); verifySetVariationValue(target, 45L); } @Test public void multiples_calls_to_increment_long_increment_the_value() { LongValue variationValue = new LongValue() .increment(10L) .increment(95L); verifySetVariationValue(variationValue, 105L); } private static void verifyUnsetVariationValue(LongValue variationValue) { assertThat(variationValue.isSet()).isFalse(); assertThat(variationValue.getValue()).isZero(); } private static void verifySetVariationValue(LongValue variationValue, long expected) { assertThat(variationValue.isSet()).isTrue(); assertThat(variationValue.getValue()).isEqualTo(expected); } }
2,791
32.638554
99
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/counter/RatingValueTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.counter; import org.junit.Test; import org.sonar.server.measure.Rating; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.B; import static org.sonar.server.measure.Rating.C; import static org.sonar.server.measure.Rating.D; public class RatingValueTest { @Test public void newly_created_value_is_unset_and_has_value_0() { verifyUnsetValue(new RatingValue()); } @Test public void increment_sets_value_and_increments_value() { verifySetValue(new RatingValue().increment(B), B); } @Test public void increment_has_no_effect_if_arg_is_null() { verifyUnsetValue(new RatingValue().increment((RatingValue) null)); } @Test public void increment_has_no_effect_if_arg_is_unset() { verifyUnsetValue(new RatingValue().increment(new RatingValue())); } @Test public void increment_increments_by_the_value_of_the_arg() { RatingValue source = new RatingValue().increment(B); RatingValue target = new RatingValue().increment(source); verifySetValue(target, B); } @Test public void multiple_calls_to_increment_increments_by_the_value_of_the_arg() { RatingValue target = new RatingValue() .increment(new RatingValue().increment(B)) .increment(new RatingValue().increment(D)); verifySetValue(target, D); } @Test public void multiples_calls_to_increment_increments_the_value() { RatingValue variationValue = new RatingValue() .increment(B) .increment(C); verifySetValue(variationValue, C); } private static void verifyUnsetValue(RatingValue ratingValue) { assertThat(ratingValue.isSet()).isFalse(); assertThat(ratingValue.getValue()).isEqualTo(A); } private static void verifySetValue(RatingValue ratingValue, Rating expected) { assertThat(ratingValue.isSet()).isTrue(); assertThat(ratingValue.getValue()).isEqualTo(expected); } }
2,854
30.722222
80
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/formula/coverage/CoverageUtilsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.formula.coverage; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.formula.CounterInitializationContext; import org.sonar.ce.task.projectanalysis.measure.Measure; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.formula.coverage.CoverageUtils.getLongMeasureValue; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; public class CoverageUtilsTest { private static final String SOME_METRIC_KEY = "some key"; public static final double DEFAULT_VARIATION = 0d; @Rule public CounterInitializationContextRule fileAggregateContext = new CounterInitializationContextRule(); @Test public void verify_calculate_coverage() { assertThat(CoverageUtils.calculateCoverage(5, 10)).isEqualTo(50d); } @Test public void getLongMeasureValue_returns_0_if_measure_does_not_exist() { assertThat(getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY)).isZero(); } @Test public void getLongMeasureValue_returns_0_if_measure_is_NO_VALUE() { fileAggregateContext.put(SOME_METRIC_KEY, newMeasureBuilder().createNoValue()); assertThat(getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY)).isZero(); } @Test public void getLongMeasureValue_returns_value_if_measure_is_INT() { fileAggregateContext.put(SOME_METRIC_KEY, newMeasureBuilder().create(152)); assertThat(getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY)).isEqualTo(152L); } @Test public void getLongMeasureValue_returns_value_if_measure_is_LONG() { fileAggregateContext.put(SOME_METRIC_KEY, newMeasureBuilder().create(152L)); assertThat(getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY)).isEqualTo(152L); } @Test public void getLongMeasureValue_throws_ISE_if_measure_is_DOUBLE() { assertThatThrownBy(() -> { fileAggregateContext.put(SOME_METRIC_KEY, newMeasureBuilder().create(152d, 1)); getLongMeasureValue(fileAggregateContext, SOME_METRIC_KEY); }) .isInstanceOf(IllegalStateException.class) .hasMessage("value can not be converted to long because current value type is a DOUBLE"); } private static class CounterInitializationContextRule extends ExternalResource implements CounterInitializationContext { private final Map<String, Measure> measures = new HashMap<>(); public CounterInitializationContextRule put(String metricKey, Measure measure) { checkNotNull(metricKey); checkNotNull(measure); checkState(!measures.containsKey(metricKey)); measures.put(metricKey, measure); return this; } @Override protected void after() { measures.clear(); } @Override public Component getLeaf() { throw new UnsupportedOperationException("getFile is not supported"); } @Override public Optional<Measure> getMeasure(String metricKey) { return Optional.ofNullable(measures.get(metricKey)); } } }
4,253
35.672414
122
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/CloseIssuesOnRemovedComponentsVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Arrays; import java.util.Collections; import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.util.CloseableIterator; import static com.google.common.collect.Sets.newHashSet; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; public class CloseIssuesOnRemovedComponentsVisitorTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); ComponentIssuesLoader issuesLoader = mock(ComponentIssuesLoader.class); ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues = mock(ComponentsWithUnprocessedIssues.class); IssueLifecycle issueLifecycle = mock(IssueLifecycle.class); ProtoIssueCache protoIssueCache; VisitorsCrawler underTest; @Before public void setUp() throws Exception { protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE); underTest = new VisitorsCrawler( Arrays.asList(new CloseIssuesOnRemovedComponentsVisitor(issuesLoader, componentsWithUnprocessedIssues, protoIssueCache, issueLifecycle))); } @Test public void close_issue() { String fileUuid = "FILE1"; String issueUuid = "ABCD"; when(componentsWithUnprocessedIssues.getUuids()).thenReturn(newHashSet(fileUuid)); DefaultIssue issue = new DefaultIssue().setKey(issueUuid).setType(RuleType.BUG).setCreationDate(new Date()) .setComponentKey("c").setProjectUuid("u").setProjectKey("k").setRuleKey(RuleKey.of("r", "r")).setStatus("OPEN"); when(issuesLoader.loadOpenIssues(fileUuid)).thenReturn(Collections.singletonList(issue)); underTest.visit(ReportComponent.builder(PROJECT, 1).build()); verify(issueLifecycle).doAutomaticTransition(issue); CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse(); assertThat(issues.hasNext()).isTrue(); DefaultIssue result = issues.next(); assertThat(result.key()).isEqualTo(issueUuid); assertThat(result.isBeingClosed()).isTrue(); assertThat(result.isOnDisabledRule()).isFalse(); } @Test public void do_nothing_on_directory() { underTest.visit(ReportComponent.builder(DIRECTORY, 1).build()); verifyNoInteractions(issueLifecycle); CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse(); assertThat(issues.hasNext()).isFalse(); } @Test public void do_nothing_on_file() { underTest.visit(ReportComponent.builder(FILE, 1).build()); verifyNoInteractions(issueLifecycle); CloseableIterator<DefaultIssue> issues = protoIssueCache.traverse(); assertThat(issues.hasNext()).isFalse(); } }
4,224
38.858491
118
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Arrays; import java.util.Collections; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class ComponentIssuesRepositoryImplTest { static final Component FILE_1 = builder(Component.Type.FILE, 1).build(); static final Component FILE_2 = builder(Component.Type.FILE, 2).build(); static final DefaultIssue DUMB_ISSUE = new DefaultIssue().setKey("ISSUE"); ComponentIssuesRepositoryImpl sut = new ComponentIssuesRepositoryImpl(); @Test public void get_issues() { sut.setIssues(FILE_1, Arrays.asList(DUMB_ISSUE)); assertThat(sut.getIssues(FILE_1)).containsOnly(DUMB_ISSUE); } @Test public void no_issues_on_dir() { assertThat(sut.getIssues(builder(Component.Type.DIRECTORY, 1).build())).isEmpty(); } @Test public void set_empty_issues() { sut.setIssues(FILE_1, Collections.emptyList()); assertThat(sut.getIssues(FILE_1)).isEmpty(); } @Test public void fail_with_NPE_when_setting_issues_with_null_component() { assertThatThrownBy(() -> sut.setIssues(null, Arrays.asList(DUMB_ISSUE))) .isInstanceOf(NullPointerException.class) .hasMessage("component cannot be null"); } @Test public void fail_with_NPE_when_setting_issues_with_null_issues() { assertThatThrownBy(() -> sut.setIssues(FILE_1, null)) .isInstanceOf(NullPointerException.class) .hasMessage("issues cannot be null"); } @Test public void fail_with_IAE_when_getting_issues_on_different_component() { assertThatThrownBy(() -> { sut.setIssues(FILE_1, Arrays.asList(DUMB_ISSUE)); sut.getIssues(FILE_2); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Only issues from component '1' are available, but wanted component is '2'."); } @Test public void fail_with_ISE_when_getting_issues_but_issues_are_null() { assertThatThrownBy(() -> { sut.getIssues(FILE_1); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Issues have not been initialized"); } }
3,192
32.968085
96
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Collections; import java.util.List; import javax.annotation.CheckForNull; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.core.issue.DefaultIssue; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; public class ComponentIssuesRepositoryRule extends ExternalResource implements MutableComponentIssuesRepository, ComponentIssuesRepository { private final TreeRootHolder treeRootHolder; @CheckForNull private List<DefaultIssue> issues; @CheckForNull private Component component; public ComponentIssuesRepositoryRule(TreeRootHolder treeRootHolder) { this.treeRootHolder = treeRootHolder; } @Override public void setIssues(Component component, List<DefaultIssue> issues) { checkNotNull(component, "component cannot be null"); setIssues(component.getReportAttributes().getRef(), issues); } public void setIssues(int componentRef, List<DefaultIssue> issues) { this.issues = requireNonNull(issues, "issues cannot be null"); Component component = treeRootHolder.getComponentByRef(componentRef); checkArgument(component != null, String.format("Component '%s' does not exists in the report ", componentRef)); this.component = component; } @Override public List<DefaultIssue> getIssues(Component component) { checkNotNull(component, "component cannot be null"); // Views has no issues if (component.getType().equals(Component.Type.PROJECT_VIEW) || component.getType().equals(Component.Type.SUBVIEW) || component.getType().equals(Component.Type.VIEW)) { return Collections.emptyList(); } return getIssues(component.getReportAttributes().getRef()); } public List<DefaultIssue> getIssues(int componentRef) { checkState(this.component != null && this.issues != null, "Issues have not been initialized"); Component component = treeRootHolder.getComponentByRef(componentRef); checkArgument(component != null, String.format("Component '%s' does not exists in the report ", componentRef)); checkArgument(component == this.component, String.format("Only issues from component '%s' are available, but wanted component is '%s'.", this.component.getReportAttributes().getRef(), component.getReportAttributes().getRef())); return issues; } }
3,502
40.211765
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComponentsWithUnprocessedIssuesTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Set; import org.junit.Test; import static com.google.common.collect.Sets.newHashSet; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ComponentsWithUnprocessedIssuesTest { ComponentsWithUnprocessedIssues sut = new ComponentsWithUnprocessedIssues(); @Test public void set_uuids() { sut.setUuids(newHashSet("ABCD", "EFGH")); assertThat(sut.getUuids()).containsOnly("ABCD", "EFGH"); } @Test public void set_uuids_makes_a_copy_of_input_issues() { Set<String> issues = newHashSet("ABCD", "EFGH"); sut.setUuids(issues); assertThat(sut.getUuids()).containsOnly("ABCD", "EFGH"); // Remove a element from the list, number of issues from the queue should remain the same issues.remove("ABCD"); assertThat(sut.getUuids()).containsOnly("ABCD", "EFGH"); } @Test public void fail_with_NPE_when_setting_null_uuids() { assertThatThrownBy(() -> sut.setUuids(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Uuids cannot be null"); } @Test public void fail_with_ISE_when_setting_uuids_twice() { assertThatThrownBy(() -> { sut.setUuids(newHashSet("ABCD")); sut.setUuids(newHashSet("EFGH")); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Uuids have already been initialized"); } @Test public void remove_uuid() { sut.setUuids(newHashSet("ABCD", "EFGH")); sut.remove("ABCD"); assertThat(sut.getUuids()).containsOnly("EFGH"); } @Test public void fail_with_ISE_when_removing_uuid_and_not_initialized() { assertThatThrownBy(() -> sut.remove("ABCD")) .isInstanceOf(IllegalStateException.class) .hasMessage("Uuids have not been initialized yet"); } @Test public void fail_with_ISE_when_getting_uuid_and_not_initialized() { assertThatThrownBy(() -> sut.getUuids()) .isInstanceOf(IllegalStateException.class) .hasMessage("Uuids have not been initialized yet"); } }
2,944
31.01087
93
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ComputeLocationHashesVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.IntStream; import org.apache.commons.codec.digest.DigestUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.source.SourceLinesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.util.CloseableIterator; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.server.issue.TaintChecker; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class ComputeLocationHashesVisitorTest { private static final String EXAMPLE_LINE_OF_CODE_FORMAT = "int example = line + of + code + %d; "; private static final String LINE_IN_THE_MAIN_FILE = "String string = 'line-in-the-main-file';"; private static final String ANOTHER_LINE_IN_THE_MAIN_FILE = "String string = 'another-line-in-the-main-file';"; private static final String LINE_IN_ANOTHER_FILE = "String string = 'line-in-the-another-file';"; private static final RuleKey RULE_KEY = RuleKey.of("javasecurity", "S001"); private static final Component FILE_1 = ReportComponent.builder(Component.Type.FILE, 2).build(); private static final Component FILE_2 = ReportComponent.builder(Component.Type.FILE, 3).build(); private static final Component ROOT = ReportComponent.builder(Component.Type.PROJECT, 1) .addChildren(FILE_1, FILE_2) .build(); private final SourceLinesRepository sourceLinesRepository = mock(SourceLinesRepository.class); private final MutableConfiguration configuration = new MutableConfiguration(); private final TaintChecker taintChecker = new TaintChecker(configuration); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); private final ComputeLocationHashesVisitor underTest = new ComputeLocationHashesVisitor(taintChecker, sourceLinesRepository, treeRootHolder); @Before public void before() { Iterator<String> stringIterator = IntStream.rangeClosed(1, 9) .mapToObj(i -> String.format(EXAMPLE_LINE_OF_CODE_FORMAT, i)) .iterator(); when(sourceLinesRepository.readLines(FILE_1)).thenReturn(CloseableIterator.from(stringIterator)); when(sourceLinesRepository.readLines(FILE_2)).thenReturn(newOneLineIterator(LINE_IN_ANOTHER_FILE)); treeRootHolder.setRoot(ROOT); } @Test public void do_nothing_if_issue_is_unchanged() { DefaultIssue issue = createIssue() .setLocationsChanged(false) .setNew(false) .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 0, 3, EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1)).build()); underTest.beforeComponent(FILE_1); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); DbIssues.Locations locations = issue.getLocations(); assertThat(locations.getChecksum()).isEmpty(); verifyNoInteractions(sourceLinesRepository); } @Test public void do_nothing_if_issue_is_not_taint_vulnerability() { DefaultIssue issue = createIssue() .setRuleKey(RuleKey.of("repo", "rule")) .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 0, 3, EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1)).build()); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); DbIssues.Locations locations = issue.getLocations(); assertThat(locations.getChecksum()).isEmpty(); verifyNoInteractions(sourceLinesRepository); } @Test public void calculates_hash_for_multiple_lines() { DefaultIssue issue = createIssue() .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 0, 3, EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1)).build()); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); assertLocationHashIsMadeOf(issue, "intexample=line+of+code+1;intexample=line+of+code+2;intexample=line+of+code+3;"); } @Test public void calculates_hash_for_multiple_files() { DefaultIssue issue1 = createIssue() .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 0, 3, EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1)).build()); DefaultIssue issue2 = createIssue() .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 0, 1, LINE_IN_ANOTHER_FILE.length())).build()); underTest.onIssue(FILE_1, issue1); underTest.beforeCaching(FILE_1); underTest.onIssue(FILE_2, issue2); underTest.beforeCaching(FILE_2); assertLocationHashIsMadeOf(issue1, "intexample=line+of+code+1;intexample=line+of+code+2;intexample=line+of+code+3;"); assertLocationHashIsMadeOf(issue2, "Stringstring='line-in-the-another-file';"); } @Test public void calculates_hash_for_partial_line() { DefaultIssue issue = createIssue() .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 13, 1, EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1)).build()); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); assertLocationHashIsMadeOf(issue, "line+of+code+1;"); } @Test public void calculates_hash_for_partial_multiple_lines() { DefaultIssue issue = createIssue() .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 13, 3, 11)).build()); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); assertLocationHashIsMadeOf(issue, "line+of+code+1;intexample=line+of+code+2;intexample"); } @Test public void dont_calculate_hash_if_no_textRange() { // primary location and one of the secondary locations have no text range DefaultIssue issue = createIssue() .setLocations(DbIssues.Locations.newBuilder() .addFlow(DbIssues.Flow.newBuilder() .addLocation(DbIssues.Location.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .setComponentId(FILE_1.getUuid()) .build()) .addLocation(DbIssues.Location.newBuilder() .setComponentId(FILE_2.getUuid()) .build()) .build()) .build()); when(sourceLinesRepository.readLines(FILE_1)).thenReturn(newOneLineIterator(LINE_IN_THE_MAIN_FILE)); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); verify(sourceLinesRepository).readLines(FILE_1); verifyNoMoreInteractions(sourceLinesRepository); DbIssues.Locations locations = issue.getLocations(); assertThat(locations.getFlow(0).getLocation(0).getChecksum()).isEqualTo(DigestUtils.md5Hex("Stringstring='line-in-the-main-file';")); assertThat(locations.getFlow(0).getLocation(1).getChecksum()).isEmpty(); } @Test public void calculates_hash_for_multiple_locations() { DefaultIssue issue = createIssue() .setLocations(DbIssues.Locations.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .addFlow(DbIssues.Flow.newBuilder() .addLocation(DbIssues.Location.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .setComponentId(FILE_1.getUuid()) .build()) .addLocation(DbIssues.Location.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_ANOTHER_FILE.length())) .setComponentId(FILE_2.getUuid()) .build()) .build()) .build()); when(sourceLinesRepository.readLines(FILE_1)).thenReturn(newOneLineIterator(LINE_IN_THE_MAIN_FILE)); when(sourceLinesRepository.readLines(FILE_2)).thenReturn(newOneLineIterator(LINE_IN_ANOTHER_FILE)); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); DbIssues.Locations locations = issue.getLocations(); assertThat(locations.getFlow(0).getLocation(0).getChecksum()).isEqualTo(DigestUtils.md5Hex("Stringstring='line-in-the-main-file';")); assertThat(locations.getFlow(0).getLocation(1).getChecksum()).isEqualTo(DigestUtils.md5Hex("Stringstring='line-in-the-another-file';")); } @Test public void calculates_hash_for_multiple_locations_in_same_file() { DefaultIssue issue = createIssue() .setComponentUuid(FILE_1.getUuid()) .setLocations(DbIssues.Locations.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .addFlow(DbIssues.Flow.newBuilder() .addLocation(DbIssues.Location.newBuilder() .setComponentId(FILE_1.getUuid()) .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .build()) .addLocation(DbIssues.Location.newBuilder() // component id can be empty if location is in the same file .setTextRange(createRange(2, 0, 2, ANOTHER_LINE_IN_THE_MAIN_FILE.length())) .build()) .build()) .build()); when(sourceLinesRepository.readLines(FILE_1)).thenReturn(manyLinesIterator(LINE_IN_THE_MAIN_FILE, ANOTHER_LINE_IN_THE_MAIN_FILE)); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); DbIssues.Locations locations = issue.getLocations(); assertThat(locations.getFlow(0).getLocation(0).getChecksum()).isEqualTo(DigestUtils.md5Hex("Stringstring='line-in-the-main-file';")); assertThat(locations.getFlow(0).getLocation(1).getChecksum()).isEqualTo(DigestUtils.md5Hex("Stringstring='another-line-in-the-main-file';")); } @Test public void beforeCaching_whenSecurityHotspots_shouldCalculateHashForPrimaryLocation() { DefaultIssue issue = createIssue() .setRuleKey(RuleKey.of("repo", "rule")) .setType(RuleType.SECURITY_HOTSPOT) .setLocations(DbIssues.Locations.newBuilder().setTextRange(createRange(1, 0, 3, EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1)).build()); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); assertLocationHashIsMadeOf(issue, "intexample=line+of+code+1;intexample=line+of+code+2;intexample=line+of+code+3;"); } @Test public void beforeCaching_whenSecurityHotspots_shouldNotCalculateHashForSecondaryLocations() { DefaultIssue issue = createIssue() .setType(RuleType.SECURITY_HOTSPOT) .setLocations(DbIssues.Locations.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .addFlow(DbIssues.Flow.newBuilder() .addLocation(DbIssues.Location.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_THE_MAIN_FILE.length())) .setComponentId(FILE_1.getUuid()) .build()) .addLocation(DbIssues.Location.newBuilder() .setTextRange(createRange(1, 0, 1, LINE_IN_ANOTHER_FILE.length())) .setComponentId(FILE_2.getUuid()) .build()) .build()) .build()); when(sourceLinesRepository.readLines(FILE_1)).thenReturn(newOneLineIterator(LINE_IN_THE_MAIN_FILE)); when(sourceLinesRepository.readLines(FILE_2)).thenReturn(newOneLineIterator(LINE_IN_ANOTHER_FILE)); underTest.onIssue(FILE_1, issue); underTest.beforeCaching(FILE_1); DbIssues.Locations locations = issue.getLocations(); assertLocationHashIsMadeOf(issue, "Stringstring='line-in-the-main-file';"); assertThat(locations.getFlow(0).getLocation(0).getChecksum()).isEmpty(); assertThat(locations.getFlow(0).getLocation(1).getChecksum()).isEmpty(); } private DbCommons.TextRange createRange(int startLine, int startOffset, int endLine, int endOffset) { return DbCommons.TextRange.newBuilder() .setStartLine(startLine).setStartOffset(startOffset) .setEndLine(endLine).setEndOffset(endOffset) .build(); } private DefaultIssue createIssue() { return new DefaultIssue() .setLocationsChanged(true) .setRuleKey(RULE_KEY) .setIsFromExternalRuleEngine(false) .setType(RuleType.CODE_SMELL); } private void assertLocationHashIsMadeOf(DefaultIssue issue, String stringToHash) { String expectedHash = DigestUtils.md5Hex(stringToHash); DbIssues.Locations locations = issue.getLocations(); assertThat(locations.getChecksum()).isEqualTo(expectedHash); } private CloseableIterator<String> newOneLineIterator(String lineContent) { return CloseableIterator.from(List.of(lineContent).iterator()); } private CloseableIterator<String> manyLinesIterator(String... lines) { return CloseableIterator.from(List.of(lines).iterator()); } private static class MutableConfiguration implements Configuration { private final Map<String, String> keyValues = new HashMap<>(); public Configuration put(String key, String value) { keyValues.put(key, value.trim()); return this; } @Override public Optional<String> get(String key) { return Optional.ofNullable(keyValues.get(key)); } @Override public boolean hasKey(String key) { return keyValues.containsKey(key); } @Override public String[] getStringArray(String key) { throw new UnsupportedOperationException("getStringArray not implemented"); } } }
14,513
41.314869
145
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DebtCalculatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import org.sonar.api.server.debt.DebtRemediationFunction; import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction; import org.sonar.api.utils.Duration; import org.sonar.api.utils.Durations; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.rule.RuleTesting; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class DebtCalculatorTest { DumbRule rule = new DumbRule(RuleTesting.XOO_X1); DefaultIssue issue = new DefaultIssue().setRuleKey(rule.getKey()); @org.junit.Rule public RuleRepositoryRule ruleRepository = new RuleRepositoryRule().add(rule); DebtCalculator underTest = new DebtCalculator(ruleRepository, new Durations()); @Test public void no_debt_if_function_is_not_defined() { DefaultIssue issue = new DefaultIssue().setRuleKey(rule.getKey()); assertThat(underTest.calculate(issue)).isNull(); } @Test public void no_debt_if_no_sqale_characteristic() { rule.setFunction(null); DefaultIssue issue = new DefaultIssue().setRuleKey(rule.getKey()); assertThat(underTest.calculate(issue)).isNull(); } @Test public void default_effort_to_fix_is_one_for_linear_function() { int coefficient = 2; rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, coefficient + "min", null)); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo(coefficient * 1); } @Test public void linear_function() { double effortToFix = 3.0; int coefficient = 2; issue.setGap(effortToFix); rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, coefficient + "min", null)); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo((int) (coefficient * effortToFix)); } @Test public void copy_effort_for_external_issues() { issue.setGap(null); issue.setIsFromExternalRuleEngine(true); issue.setEffort(Duration.create(20L)); rule.setFunction(null); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo(20L); } @Test public void constant_function() { int constant = 2; issue.setGap(null); rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, constant + "min")); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo(2); } @Test public void effort_to_fix_must_not_be_set_with_constant_function() { int constant = 2; issue.setGap(3.0); rule.setFunction(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, constant + "min")); assertThatThrownBy(() -> underTest.calculate(issue)) .isInstanceOf(IllegalArgumentException.class); } @Test public void linear_with_offset_function() { double effortToFix = 3.0; int coefficient = 2; int offset = 5; issue.setGap(effortToFix); rule.setFunction(new DefaultDebtRemediationFunction( DebtRemediationFunction.Type.LINEAR_OFFSET, coefficient + "min", offset + "min")); assertThat(underTest.calculate(issue).toMinutes()).isEqualTo((int) ((coefficient * effortToFix) + offset)); } }
4,107
33.813559
126
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DefaultTrackingInputTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Collection; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.BlockHashSequence; import org.sonar.core.issue.tracking.LineHashSequence; import static org.assertj.core.api.Assertions.assertThat; public class DefaultTrackingInputTest { @Mock private Collection<DefaultIssue> issues; @Mock private BlockHashSequence blockHashes; @Mock private LineHashSequence lineHashes; @Before public void setUp() { MockitoAnnotations.initMocks(this); } @Test public void test_getters() { DefaultTrackingInput underTest = new DefaultTrackingInput(issues, lineHashes, blockHashes); assertThat(underTest.getBlockHashSequence()).isEqualTo(blockHashes); assertThat(underTest.getLineHashSequence()).isEqualTo(lineHashes); assertThat(underTest.getIssues()).isEqualTo(issues); } }
1,856
33.388889
95
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/DumbRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.HashSet; import java.util.Set; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.server.debt.DebtRemediationFunction; import static java.util.Objects.requireNonNull; public class DumbRule implements Rule { private String uuid; private RuleKey key; private String name; private String language; private RuleStatus status = RuleStatus.READY; private RuleType type = RuleType.CODE_SMELL; private Set<String> tags = new HashSet<>(); private DebtRemediationFunction function; private String pluginKey; private boolean isExternal; private boolean isAdHoc; private Set<String> securityStandards = new HashSet<>(); public DumbRule(RuleKey key) { this.key = key; this.uuid = key.rule(); this.name = "name_" + key; } @Override public String getUuid() { return requireNonNull(uuid); } @Override public RuleKey getKey() { return requireNonNull(key); } @Override public String getName() { return requireNonNull(name); } @Override @CheckForNull public String getLanguage() { return language; } @Override public RuleStatus getStatus() { return requireNonNull(status); } @Override public Set<String> getTags() { return requireNonNull(tags); } @Override public RuleType getType() { return type; } @Override public DebtRemediationFunction getRemediationFunction() { return function; } @Override public String getPluginKey() { return pluginKey; } @Override public String getDefaultRuleDescription() { return null; } @Override public String getSeverity() { return null; } @Override public Set<String> getSecurityStandards() { return securityStandards; } @Override public boolean isExternal() { return isExternal; } @Override public boolean isAdHoc() { return isAdHoc; } public DumbRule setUuid(String uuid) { this.uuid = uuid; return this; } public DumbRule setName(String name) { this.name = name; return this; } public DumbRule setLanguage(@Nullable String language) { this.language = language; return this; } public DumbRule setStatus(RuleStatus status) { this.status = status; return this; } public DumbRule setFunction(@Nullable DebtRemediationFunction function) { this.function = function; return this; } public DumbRule setTags(Set<String> tags) { this.tags = tags; return this; } public DumbRule setType(RuleType type) { this.type = type; return this; } public DumbRule setPluginKey(String pluginKey) { this.pluginKey = pluginKey; return this; } public DumbRule setIsExternal(boolean isExternal) { this.isExternal = isExternal; return this; } public DumbRule setIsAdHoc(boolean isAdHoc) { this.isAdHoc = isAdHoc; return this; } }
3,911
21.354286
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/EffortAggregatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import org.sonar.api.utils.Duration; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.measures.CoreMetrics.RELIABILITY_REMEDIATION_EFFORT; import static org.sonar.api.measures.CoreMetrics.RELIABILITY_REMEDIATION_EFFORT_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_REMEDIATION_EFFORT; import static org.sonar.api.measures.CoreMetrics.SECURITY_REMEDIATION_EFFORT_KEY; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_KEY; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.VULNERABILITY; public class EffortAggregatorTest { static final Component FILE = ReportComponent.builder(Component.Type.FILE, 1).build(); static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, 2).addChildren(FILE).build(); @org.junit.Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(TECHNICAL_DEBT) .add(RELIABILITY_REMEDIATION_EFFORT) .add(SECURITY_REMEDIATION_EFFORT); @org.junit.Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(PROJECT, metricRepository); EffortAggregator underTest = new EffortAggregator(metricRepository, measureRepository); @Test public void sum_maintainability_effort_of_unresolved_issues() { DefaultIssue unresolved1 = newCodeSmellIssue(10); DefaultIssue unresolved2 = newCodeSmellIssue(30); DefaultIssue unresolvedWithoutEffort = newCodeSmellIssueWithoutEffort(); DefaultIssue resolved = newCodeSmellIssue(50).setResolution(RESOLUTION_FIXED); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved1); underTest.onIssue(FILE, unresolved2); underTest.onIssue(FILE, unresolvedWithoutEffort); underTest.onIssue(FILE, resolved); underTest.afterComponent(FILE); // total maintainability effort assertMeasure(FILE, TECHNICAL_DEBT_KEY, 10L + 30L); } @Test public void maintainability_effort_is_only_computed_using_code_smell_issues() { DefaultIssue codeSmellIssue = newCodeSmellIssue(10); // Issues of type BUG and VULNERABILITY should be ignored DefaultIssue bugIssue = newBugIssue(15); DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(12); underTest.beforeComponent(FILE); underTest.onIssue(FILE, codeSmellIssue); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, vulnerabilityIssue); underTest.afterComponent(FILE); // Only effort of CODE SMELL issue is used assertMeasure(FILE, TECHNICAL_DEBT_KEY, 10L); } @Test public void sum_reliability_effort_of_unresolved_issues() { DefaultIssue unresolved1 = newBugIssue(10); DefaultIssue unresolved2 = newBugIssue(30); DefaultIssue unresolvedWithoutEffort = newBugIssueWithoutEffort(); DefaultIssue resolved = newBugIssue(50).setResolution(RESOLUTION_FIXED); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved1); underTest.onIssue(FILE, unresolved2); underTest.onIssue(FILE, unresolvedWithoutEffort); underTest.onIssue(FILE, resolved); underTest.afterComponent(FILE); assertMeasure(FILE, RELIABILITY_REMEDIATION_EFFORT_KEY, 10L + 30L); } @Test public void reliability_effort_is_only_computed_using_bug_issues() { DefaultIssue bugIssue = newBugIssue(10); // Issues of type CODE SMELL and VULNERABILITY should be ignored DefaultIssue codeSmellIssue = newCodeSmellIssue(15); DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(12); underTest.beforeComponent(FILE); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, codeSmellIssue); underTest.onIssue(FILE, vulnerabilityIssue); underTest.afterComponent(FILE); // Only effort of BUG issue is used assertMeasure(FILE, RELIABILITY_REMEDIATION_EFFORT_KEY, 10L); } @Test public void sum_security_effort_of_unresolved_issues() { DefaultIssue unresolved1 = newVulnerabilityIssue(10); DefaultIssue unresolved2 = newVulnerabilityIssue(30); DefaultIssue unresolvedWithoutEffort = newVulnerabilityIssueWithoutEffort(); DefaultIssue resolved = newVulnerabilityIssue(50).setResolution(RESOLUTION_FIXED); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved1); underTest.onIssue(FILE, unresolved2); underTest.onIssue(FILE, unresolvedWithoutEffort); underTest.onIssue(FILE, resolved); underTest.afterComponent(FILE); assertMeasure(FILE, SECURITY_REMEDIATION_EFFORT_KEY, 10L + 30L); } @Test public void security_effort_is_only_computed_using_code_smell_issues() { DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(10); // Issues of type BUG and CODE SMELL should be ignored DefaultIssue bugIssue = newBugIssue(15); DefaultIssue codeSmellIssue = newCodeSmellIssue(12); underTest.beforeComponent(FILE); underTest.onIssue(FILE, vulnerabilityIssue); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, codeSmellIssue); underTest.afterComponent(FILE); // Only effort of VULNERABILITY issue is used assertMeasure(FILE, SECURITY_REMEDIATION_EFFORT_KEY, 10L); } @Test public void aggregate_maintainability_measures_of_children() { underTest.beforeComponent(FILE); underTest.onIssue(FILE, newCodeSmellIssue(10)); underTest.onIssue(FILE, newBugIssue(8)); underTest.onIssue(FILE, newVulnerabilityIssue(12)); underTest.afterComponent(FILE); underTest.beforeComponent(PROJECT); underTest.onIssue(PROJECT, newCodeSmellIssue(30)); underTest.onIssue(PROJECT, newBugIssue(38)); underTest.onIssue(PROJECT, newVulnerabilityIssue(42)); underTest.afterComponent(PROJECT); assertMeasure(PROJECT, TECHNICAL_DEBT_KEY, 10L + 30L); assertMeasure(PROJECT, RELIABILITY_REMEDIATION_EFFORT_KEY, 8L + 38L); assertMeasure(PROJECT, SECURITY_REMEDIATION_EFFORT_KEY, 12L + 42L); } @Test public void sum_characteristic_measures_of_issues_without_effort() { underTest.beforeComponent(FILE); underTest.onIssue(FILE, newCodeSmellIssueWithoutEffort()); underTest.onIssue(FILE, newBugIssueWithoutEffort()); underTest.onIssue(FILE, newVulnerabilityIssueWithoutEffort()); underTest.afterComponent(FILE); underTest.beforeComponent(PROJECT); underTest.onIssue(PROJECT, newCodeSmellIssueWithoutEffort()); underTest.afterComponent(PROJECT); assertMeasure(PROJECT, TECHNICAL_DEBT_KEY, 0L); assertMeasure(PROJECT, RELIABILITY_REMEDIATION_EFFORT_KEY, 0L); assertMeasure(PROJECT, SECURITY_REMEDIATION_EFFORT_KEY, 0L); } private void assertMeasure(Component component, String metricKey, long expectedValue) { assertThat(measureRepository.getAddedRawMeasure(component, metricKey).get().getLongValue()).isEqualTo(expectedValue); } private static DefaultIssue newCodeSmellIssue(long effort) { return newCodeSmellIssueWithoutEffort().setEffort(Duration.create(effort)).setType(CODE_SMELL); } private static DefaultIssue newBugIssue(long effort) { return newCodeSmellIssueWithoutEffort().setEffort(Duration.create(effort)).setType(BUG); } private static DefaultIssue newVulnerabilityIssue(long effort) { return newCodeSmellIssueWithoutEffort().setEffort(Duration.create(effort)).setType(VULNERABILITY); } private static DefaultIssue newCodeSmellIssueWithoutEffort() { return new DefaultIssue().setType(CODE_SMELL); } private static DefaultIssue newBugIssueWithoutEffort() { return new DefaultIssue().setType(BUG); } private static DefaultIssue newVulnerabilityIssueWithoutEffort() { return new DefaultIssue().setType(VULNERABILITY); } }
9,074
39.513393
121
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/FillComponentIssuesVisitorRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.ListMultimap; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter; import org.sonar.core.issue.DefaultIssue; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Arrays.asList; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; /** * This rule can be used when testing a visitor that depends on {@link ComponentIssuesRepository}. */ public class FillComponentIssuesVisitorRule extends TypeAwareVisitorAdapter implements TestRule { private MutableComponentIssuesRepository issuesRepository = new ComponentIssuesRepositoryImpl(); private final TreeRootHolder treeRootHolder; private ListMultimap<Component, DefaultIssue> issues = ArrayListMultimap.create(); public FillComponentIssuesVisitorRule(MutableComponentIssuesRepository issuesRepository, TreeRootHolder treeRootHolder) { super(CrawlerDepthLimit.FILE, POST_ORDER); this.issuesRepository = issuesRepository; this.treeRootHolder = treeRootHolder; } @Override public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { issues = ArrayListMultimap.create(); } } }; } public void setIssues(int componentRef, DefaultIssue... issues) { Component component = treeRootHolder.getComponentByRef(componentRef); checkArgument(component != null, String.format("Component '%s' does not exists in the report ", componentRef)); this.issues.get(component).clear(); this.issues.putAll(component, asList(issues)); } @Override public void visitAny(Component component) { issuesRepository.setIssues(component, issues.get(component)); } }
3,136
38.2125
123
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueAssignerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Arrays; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.scm.Changeset; import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepositoryRule; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.user.UserIdDto; import org.sonar.server.issue.IssueFieldsSetter; import static java.util.stream.Collectors.joining; import static java.util.stream.IntStream.range; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class IssueAssignerTest { private static final int FILE_REF = 1; private static final Component FILE = builder(Component.Type.FILE, FILE_REF).setKey("FILE_KEY").setUuid("FILE_UUID").build(); @Rule public LogTester logTester = new LogTester(); @Rule public ScmInfoRepositoryRule scmInfoRepository = new ScmInfoRepositoryRule(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule().setAnalysisDate(123456789L); private final ScmAccountToUser scmAccountToUser = mock(ScmAccountToUser.class); private final DefaultAssignee defaultAssignee = mock(DefaultAssignee.class); private final IssueAssigner underTest = new IssueAssigner(analysisMetadataHolder, scmInfoRepository, scmAccountToUser, defaultAssignee, new IssueFieldsSetter()); @Before public void before() { logTester.setLevel(Level.DEBUG); } @Test public void do_not_set_author_if_no_changeset() { DefaultIssue issue = newIssueOnLines(1); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isNull(); } @Test public void set_author_of_new_issue_if_changeset() { setSingleChangeset("john", 123456789L, "rev-1"); DefaultIssue issue = newIssueOnLines(1); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isEqualTo("john"); } @Test public void do_not_reset_author_if_already_set() { setSingleChangeset("john", 123456789L, "rev-1"); DefaultIssue issue = newIssueOnLines(1) .setAuthorLogin("jane"); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isEqualTo("jane"); } @Test public void assign_but_do_not_set_author_if_too_long() { String scmAuthor = range(0, 256).mapToObj(i -> "s").collect(joining()); addScmUser(scmAuthor, buildUserId("u123", "John C")); setSingleChangeset(scmAuthor, 123456789L, "rev-1"); DefaultIssue issue = newIssueOnLines(1); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isNull(); assertThat(issue.assignee()).isEqualTo("u123"); assertThat(issue.assigneeLogin()).isEqualTo("John C"); assertThat(logTester.logs(Level.DEBUG)).contains("SCM account '" + scmAuthor + "' is too long to be stored as issue author"); } @Test public void assign_new_issue_to_author_of_change() { addScmUser("john", buildUserId("u123", "john")); setSingleChangeset("john", 123456789L, "rev-1"); DefaultIssue issue = newIssueOnLines(1); underTest.onIssue(FILE, issue); assertThat(issue.assignee()).isEqualTo("u123"); assertThat(issue.assigneeLogin()).isEqualTo("john"); } @Test public void assign_new_issue_to_default_assignee_if_author_not_found() { setSingleChangeset("john", 123456789L, "rev-1"); when(defaultAssignee.loadDefaultAssigneeUserId()).thenReturn(new UserIdDto("u1234", "john")); DefaultIssue issue = newIssueOnLines(1); underTest.onIssue(FILE, issue); assertThat(issue.assignee()).isEqualTo("u1234"); assertThat(issue.assigneeLogin()).isEqualTo("john"); } @Test public void do_not_assign_new_issue_if_no_author_in_changeset() { setSingleChangeset(null, 123456789L, "rev-1"); DefaultIssue issue = newIssueOnLines(1); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isNull(); assertThat(issue.assignee()).isNull(); } @Test public void do_not_assign_issue_if_unassigned_but_already_authored() { addScmUser("john", buildUserId("u1234", "john")); setSingleChangeset("john", 123456789L, "rev-1"); DefaultIssue issue = newIssueOnLines(1) .setAuthorLogin("john") .setAssigneeUuid(null); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isEqualTo("john"); assertThat(issue.assignee()).isNull(); } @Test public void assign_to_last_committer_of_file_if_issue_is_global_to_file() { addScmUser("henry", buildUserId("u123", "Henry V")); Changeset changeset1 = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(1_000L) .setRevision("rev-1") .build(); // Latest changeset Changeset changeset2 = Changeset.newChangesetBuilder() .setAuthor("henry") .setDate(2_000L) .setRevision("rev-2") .build(); scmInfoRepository.setScmInfo(FILE_REF, changeset1, changeset2, changeset1); DefaultIssue issue = newIssueOnLines(); underTest.onIssue(FILE, issue); assertThat(issue.assignee()).isEqualTo("u123"); assertThat(issue.assigneeLogin()).isEqualTo("Henry V"); } @Test public void assign_to_default_assignee_if_no_author() { DefaultIssue issue = newIssueOnLines(); when(defaultAssignee.loadDefaultAssigneeUserId()).thenReturn(new UserIdDto("u123", "john")); underTest.onIssue(FILE, issue); assertThat(issue.assignee()).isEqualTo("u123"); assertThat(issue.assigneeLogin()).isEqualTo("john"); } @Test public void assign_to_default_assignee_if_no_scm_on_issue_locations() { addScmUser("john", buildUserId("u123", "John C")); Changeset changeset = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build(); scmInfoRepository.setScmInfo(FILE_REF, changeset, changeset); DefaultIssue issue = newIssueOnLines(3); underTest.onIssue(FILE, issue); assertThat(issue.assignee()).isEqualTo("u123"); assertThat(issue.assigneeLogin()).isEqualTo("John C"); } @Test public void assign_to_author_of_the_most_recent_change_in_all_issue_locations() { addScmUser("john", buildUserId("u1", "John")); addScmUser("jane", buildUserId("u2", "Jane")); Changeset commit1 = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(1_000L) .setRevision("rev-1") .build(); Changeset commit2 = Changeset.newChangesetBuilder() .setAuthor("jane") .setDate(2_000L) .setRevision("rev-2") .build(); scmInfoRepository.setScmInfo(FILE_REF, commit1, commit1, commit2, commit1); DefaultIssue issue = newIssueOnLines(2, 3, 4); underTest.onIssue(FILE, issue); assertThat(issue.authorLogin()).isEqualTo("jane"); assertThat(issue.assignee()).isEqualTo("u2"); assertThat(issue.assigneeLogin()).isEqualTo("Jane"); } private void setSingleChangeset(@Nullable String author, Long date, String revision) { scmInfoRepository.setScmInfo(FILE_REF, Changeset.newChangesetBuilder() .setAuthor(author) .setDate(date) .setRevision(revision) .build()); } private void addScmUser(String scmAccount, UserIdDto userId) { when(scmAccountToUser.getNullable(scmAccount)).thenReturn(userId); } private static DefaultIssue newIssueOnLines(int... lines) { DefaultIssue issue = new DefaultIssue(); issue.setComponentUuid(FILE.getUuid()); DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); DbIssues.Flow.Builder flow = DbIssues.Flow.newBuilder(); Arrays.stream(lines).forEach(line -> flow.addLocation(newLocation(line))); locations.addFlow(flow.build()); issue.setLocations(locations.build()); return issue; } private static DbIssues.Location newLocation(int line) { return DbIssues.Location.newBuilder() .setComponentId(FILE.getUuid()) .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(line).setEndLine(line).build()).build(); } private UserIdDto buildUserId(String uuid, String login) { return new UserIdDto(uuid, login); } }
9,421
33.386861
163
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueChangesToDeleteRepositoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class IssueChangesToDeleteRepositoryTest { private final IssueChangesToDeleteRepository repository = new IssueChangesToDeleteRepository(); @Test public void get_returns_all_issues_added() { repository.add("a"); repository.add("b"); assertThat(repository.getUuids()).containsOnly("a", "b"); } }
1,298
35.083333
97
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueCounterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Arrays; import java.util.List; import java.util.Map; import javax.annotation.Nullable; import org.assertj.core.data.MapEntry; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rules.RuleType; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.rule.RuleTesting; import static java.util.Arrays.stream; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.issue.Issue.RESOLUTION_WONT_FIX; import static org.sonar.api.issue.Issue.STATUS_CLOSED; import static org.sonar.api.issue.Issue.STATUS_CONFIRMED; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.issue.Issue.STATUS_RESOLVED; import static org.sonar.api.measures.CoreMetrics.BLOCKER_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.BLOCKER_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.BUGS; import static org.sonar.api.measures.CoreMetrics.BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.CODE_SMELLS; import static org.sonar.api.measures.CoreMetrics.CODE_SMELLS_KEY; import static org.sonar.api.measures.CoreMetrics.CONFIRMED_ISSUES; import static org.sonar.api.measures.CoreMetrics.CONFIRMED_ISSUES_KEY; import static org.sonar.api.measures.CoreMetrics.CRITICAL_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.CRITICAL_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FALSE_POSITIVE_ISSUES; import static org.sonar.api.measures.CoreMetrics.FALSE_POSITIVE_ISSUES_KEY; import static org.sonar.api.measures.CoreMetrics.INFO_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.MAJOR_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.MAJOR_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.MINOR_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_BLOCKER_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_BLOCKER_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_BUGS; import static org.sonar.api.measures.CoreMetrics.NEW_BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_CODE_SMELLS; import static org.sonar.api.measures.CoreMetrics.NEW_CODE_SMELLS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_CRITICAL_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_CRITICAL_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_INFO_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_MAJOR_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_MAJOR_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_MINOR_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.NEW_VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_VULNERABILITIES; import static org.sonar.api.measures.CoreMetrics.NEW_VULNERABILITIES_KEY; import static org.sonar.api.measures.CoreMetrics.OPEN_ISSUES; import static org.sonar.api.measures.CoreMetrics.OPEN_ISSUES_KEY; import static org.sonar.api.measures.CoreMetrics.REOPENED_ISSUES; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_KEY; import static org.sonar.api.measures.CoreMetrics.VIOLATIONS; import static org.sonar.api.measures.CoreMetrics.VIOLATIONS_KEY; import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES; import static org.sonar.api.measures.CoreMetrics.VULNERABILITIES_KEY; import static org.sonar.api.measures.CoreMetrics.WONT_FIX_ISSUES; import static org.sonar.api.measures.CoreMetrics.WONT_FIX_ISSUES_KEY; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; public class IssueCounterTest { private static final Component FILE1 = builder(Component.Type.FILE, 1).build(); private static final Component FILE2 = builder(Component.Type.FILE, 2).build(); private static final Component FILE3 = builder(Component.Type.FILE, 3).build(); private static final Component PROJECT = builder(Component.Type.PROJECT, 4).addChildren(FILE1, FILE2, FILE3).build(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(VIOLATIONS) .add(OPEN_ISSUES) .add(REOPENED_ISSUES) .add(CONFIRMED_ISSUES) .add(BLOCKER_VIOLATIONS) .add(CRITICAL_VIOLATIONS) .add(MAJOR_VIOLATIONS) .add(MINOR_VIOLATIONS) .add(INFO_VIOLATIONS) .add(NEW_VIOLATIONS) .add(NEW_BLOCKER_VIOLATIONS) .add(NEW_CRITICAL_VIOLATIONS) .add(NEW_MAJOR_VIOLATIONS) .add(NEW_MINOR_VIOLATIONS) .add(NEW_INFO_VIOLATIONS) .add(FALSE_POSITIVE_ISSUES) .add(WONT_FIX_ISSUES) .add(CODE_SMELLS) .add(BUGS) .add(VULNERABILITIES) .add(SECURITY_HOTSPOTS) .add(NEW_CODE_SMELLS) .add(NEW_BUGS) .add(NEW_VULNERABILITIES) .add(NEW_SECURITY_HOTSPOTS); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private NewIssueClassifier newIssueClassifier = mock(NewIssueClassifier.class); private IssueCounter underTest = new IssueCounter(metricRepository, measureRepository, newIssueClassifier); @Test public void count_issues_by_status() { // bottom-up traversal -> from files to project underTest.beforeComponent(FILE1); underTest.onIssue(FILE1, createIssue(null, STATUS_OPEN, BLOCKER)); underTest.onIssue(FILE1, createIssue(RESOLUTION_FIXED, STATUS_CLOSED, MAJOR)); underTest.onIssue(FILE1, createIssue(RESOLUTION_FALSE_POSITIVE, STATUS_RESOLVED, MAJOR)); underTest.afterComponent(FILE1); underTest.beforeComponent(FILE2); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, BLOCKER)); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, MAJOR)); underTest.afterComponent(FILE2); underTest.beforeComponent(FILE3); // Security hotspot should be ignored underTest.onIssue(FILE3, createSecurityHotspot().setStatus(STATUS_OPEN)); underTest.afterComponent(FILE3); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertMeasures(FILE1, entry(VIOLATIONS_KEY, 1), entry(OPEN_ISSUES_KEY, 1), entry(CONFIRMED_ISSUES_KEY, 0)); assertMeasures(FILE2, entry(VIOLATIONS_KEY, 2), entry(OPEN_ISSUES_KEY, 0), entry(CONFIRMED_ISSUES_KEY, 2)); assertMeasures(FILE3, entry(VIOLATIONS_KEY, 0)); assertMeasures(PROJECT, entry(VIOLATIONS_KEY, 3), entry(OPEN_ISSUES_KEY, 1), entry(CONFIRMED_ISSUES_KEY, 2)); } @Test public void count_issues_by_resolution() { // bottom-up traversal -> from files to project underTest.beforeComponent(FILE1); underTest.onIssue(FILE1, createIssue(null, STATUS_OPEN, BLOCKER)); underTest.onIssue(FILE1, createIssue(RESOLUTION_FIXED, STATUS_CLOSED, MAJOR)); underTest.onIssue(FILE1, createIssue(RESOLUTION_FALSE_POSITIVE, STATUS_RESOLVED, MAJOR)); underTest.onIssue(FILE1, createIssue(RESOLUTION_WONT_FIX, STATUS_CLOSED, MAJOR)); underTest.afterComponent(FILE1); underTest.beforeComponent(FILE2); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, BLOCKER)); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, MAJOR)); underTest.onIssue(FILE2, createIssue(RESOLUTION_WONT_FIX, STATUS_CLOSED, MAJOR)); underTest.afterComponent(FILE2); underTest.beforeComponent(FILE3); // Security hotspot should be ignored underTest.onIssue(FILE3, createSecurityHotspot().setResolution(RESOLUTION_WONT_FIX)); underTest.afterComponent(FILE3); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertMeasures(FILE1, entry(VIOLATIONS_KEY, 1), entry(FALSE_POSITIVE_ISSUES_KEY, 1), entry(WONT_FIX_ISSUES_KEY, 1)); assertMeasures(FILE2, entry(VIOLATIONS_KEY, 2), entry(FALSE_POSITIVE_ISSUES_KEY, 0), entry(WONT_FIX_ISSUES_KEY, 1)); assertMeasures(FILE3, entry(VIOLATIONS_KEY, 0)); assertMeasures(PROJECT, entry(VIOLATIONS_KEY, 3), entry(FALSE_POSITIVE_ISSUES_KEY, 1), entry(WONT_FIX_ISSUES_KEY, 2)); } @Test public void count_unresolved_issues_by_severity() { // bottom-up traversal -> from files to project underTest.beforeComponent(FILE1); underTest.onIssue(FILE1, createIssue(null, STATUS_OPEN, BLOCKER)); // this resolved issue is ignored underTest.onIssue(FILE1, createIssue(RESOLUTION_FIXED, STATUS_CLOSED, MAJOR)); underTest.afterComponent(FILE1); underTest.beforeComponent(FILE2); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, BLOCKER)); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, MAJOR)); underTest.afterComponent(FILE2); underTest.beforeComponent(PROJECT); // Security hotspot should be ignored underTest.onIssue(FILE3, createSecurityHotspot().setSeverity(MAJOR)); underTest.afterComponent(PROJECT); assertMeasures(FILE1, entry(BLOCKER_VIOLATIONS_KEY, 1), entry(CRITICAL_VIOLATIONS_KEY, 0), entry(MAJOR_VIOLATIONS_KEY, 0)); assertMeasures(FILE2, entry(BLOCKER_VIOLATIONS_KEY, 1), entry(CRITICAL_VIOLATIONS_KEY, 0), entry(MAJOR_VIOLATIONS_KEY, 1)); assertMeasures(PROJECT, entry(BLOCKER_VIOLATIONS_KEY, 2), entry(CRITICAL_VIOLATIONS_KEY, 0), entry(MAJOR_VIOLATIONS_KEY, 1)); } @Test public void count_unresolved_issues_by_type() { // bottom-up traversal -> from files to project // file1 : one open code smell, one closed code smell (which will be excluded from metric) underTest.beforeComponent(FILE1); underTest.onIssue(FILE1, createIssue(null, STATUS_OPEN, BLOCKER).setType(RuleType.CODE_SMELL)); underTest.onIssue(FILE1, createIssue(RESOLUTION_FIXED, STATUS_CLOSED, MAJOR).setType(RuleType.CODE_SMELL)); underTest.afterComponent(FILE1); // file2 : one bug underTest.beforeComponent(FILE2); underTest.onIssue(FILE2, createIssue(null, STATUS_CONFIRMED, BLOCKER).setType(RuleType.BUG)); underTest.afterComponent(FILE2); // file3 : one unresolved security hotspot underTest.beforeComponent(FILE3); underTest.onIssue(FILE3, createSecurityHotspot()); underTest.onIssue(FILE3, createSecurityHotspot().setResolution(RESOLUTION_WONT_FIX).setStatus(STATUS_CLOSED)); underTest.afterComponent(FILE3); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertMeasures(FILE1, entry(CODE_SMELLS_KEY, 1), entry(BUGS_KEY, 0), entry(VULNERABILITIES_KEY, 0), entry(SECURITY_HOTSPOTS_KEY, 0)); assertMeasures(FILE2, entry(CODE_SMELLS_KEY, 0), entry(BUGS_KEY, 1), entry(VULNERABILITIES_KEY, 0), entry(SECURITY_HOTSPOTS_KEY, 0)); assertMeasures(FILE3, entry(CODE_SMELLS_KEY, 0), entry(BUGS_KEY, 0), entry(VULNERABILITIES_KEY, 0), entry(SECURITY_HOTSPOTS_KEY, 1)); assertMeasures(PROJECT, entry(CODE_SMELLS_KEY, 1), entry(BUGS_KEY, 1), entry(VULNERABILITIES_KEY, 0), entry(SECURITY_HOTSPOTS_KEY, 1)); } @Test public void count_new_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); underTest.beforeComponent(FILE1); // created before -> existing issues (so ignored) underTest.onIssue(FILE1, createIssue(null, STATUS_OPEN, BLOCKER).setType(RuleType.CODE_SMELL)); underTest.onIssue(FILE1, createIssue(null, STATUS_OPEN, BLOCKER).setType(RuleType.BUG)); // created after -> 4 new issues but 1 is closed underTest.onIssue(FILE1, createNewIssue(null, STATUS_OPEN, CRITICAL).setType(RuleType.CODE_SMELL)); underTest.onIssue(FILE1, createNewIssue(null, STATUS_OPEN, CRITICAL).setType(RuleType.BUG)); underTest.onIssue(FILE1, createNewIssue(RESOLUTION_FIXED, STATUS_CLOSED, MAJOR).setType(RuleType.BUG)); underTest.onIssue(FILE1, createNewSecurityHotspot()); underTest.onIssue(FILE1, createNewSecurityHotspot().setResolution(RESOLUTION_WONT_FIX).setStatus(STATUS_CLOSED)); underTest.afterComponent(FILE1); underTest.beforeComponent(FILE2); underTest.afterComponent(FILE2); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertValues(FILE1, entry(NEW_VIOLATIONS_KEY, 2), entry(NEW_CRITICAL_VIOLATIONS_KEY, 2), entry(NEW_BLOCKER_VIOLATIONS_KEY, 0), entry(NEW_MAJOR_VIOLATIONS_KEY, 0), entry(NEW_CODE_SMELLS_KEY, 1), entry(NEW_BUGS_KEY, 1), entry(NEW_VULNERABILITIES_KEY, 0), entry(NEW_SECURITY_HOTSPOTS_KEY, 1)); assertValues(PROJECT, entry(NEW_VIOLATIONS_KEY, 2), entry(NEW_CRITICAL_VIOLATIONS_KEY, 2), entry(NEW_BLOCKER_VIOLATIONS_KEY, 0), entry(NEW_MAJOR_VIOLATIONS_KEY, 0), entry(NEW_CODE_SMELLS_KEY, 1), entry(NEW_BUGS_KEY, 1), entry(NEW_VULNERABILITIES_KEY, 0), entry(NEW_SECURITY_HOTSPOTS_KEY, 1)); } @Test public void exclude_hotspots_from_issue_counts() { // bottom-up traversal -> from files to project underTest.beforeComponent(FILE1); underTest.onIssue(FILE1, createSecurityHotspot()); underTest.onIssue(FILE1, createSecurityHotspot()); underTest.afterComponent(FILE1); underTest.beforeComponent(FILE2); underTest.onIssue(FILE2, createSecurityHotspot()); underTest.afterComponent(FILE2); underTest.beforeComponent(FILE3); underTest.afterComponent(FILE3); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertMeasures(FILE1, entry(VIOLATIONS_KEY, 0), entry(OPEN_ISSUES_KEY, 0), entry(CONFIRMED_ISSUES_KEY, 0)); assertMeasures(FILE2, entry(VIOLATIONS_KEY, 0), entry(OPEN_ISSUES_KEY, 0), entry(CONFIRMED_ISSUES_KEY, 0)); assertMeasures(FILE3, entry(VIOLATIONS_KEY, 0)); assertMeasures(PROJECT, entry(VIOLATIONS_KEY, 0), entry(OPEN_ISSUES_KEY, 0), entry(CONFIRMED_ISSUES_KEY, 0)); } @Test public void exclude_new_hotspots_from_issue_counts() { when(newIssueClassifier.isEnabled()).thenReturn(true); underTest.beforeComponent(FILE1); // created before -> existing issues (so ignored) underTest.onIssue(FILE1, createSecurityHotspot()); underTest.onIssue(FILE1, createSecurityHotspot()); // created after, but closed underTest.onIssue(FILE1, createNewSecurityHotspot().setStatus(STATUS_RESOLVED).setResolution(RESOLUTION_WONT_FIX)); for (String severity : Arrays.asList(CRITICAL, BLOCKER, MAJOR)) { DefaultIssue issue = createNewSecurityHotspot(); issue.setSeverity(severity); underTest.onIssue(FILE1, issue); } underTest.afterComponent(FILE1); underTest.beforeComponent(FILE2); underTest.afterComponent(FILE2); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertValues(FILE1, entry(NEW_VIOLATIONS_KEY, 0), entry(NEW_CRITICAL_VIOLATIONS_KEY, 0), entry(NEW_BLOCKER_VIOLATIONS_KEY, 0), entry(NEW_MAJOR_VIOLATIONS_KEY, 0), entry(NEW_VULNERABILITIES_KEY, 0)); assertValues(PROJECT, entry(NEW_VIOLATIONS_KEY, 0), entry(NEW_CRITICAL_VIOLATIONS_KEY, 0), entry(NEW_BLOCKER_VIOLATIONS_KEY, 0), entry(NEW_MAJOR_VIOLATIONS_KEY, 0), entry(NEW_VULNERABILITIES_KEY, 0)); } @SafeVarargs private final void assertValues(Component componentRef, MapEntry<String, Integer>... entries) { assertThat(measureRepository.getRawMeasures(componentRef).entrySet() .stream() .map(e -> entry(e.getKey(), e.getValue().getIntValue()))) .contains(entries); } @SafeVarargs private final void assertMeasures(Component componentRef, Map.Entry<String, Integer>... entries) { List<MeasureRepoEntry> expected = stream(entries) .map(e -> entryOf(e.getKey(), newMeasureBuilder().create(e.getValue()))) .toList(); assertThat(measureRepository.getRawMeasures(componentRef).entrySet().stream().map(e -> entryOf(e.getKey(), e.getValue()))) .containsAll(expected); } private DefaultIssue createNewIssue(@Nullable String resolution, String status, String severity) { return createNewIssue(resolution, status, severity, RuleType.CODE_SMELL); } private DefaultIssue createNewIssue(@Nullable String resolution, String status, String severity, RuleType ruleType) { DefaultIssue issue = createIssue(resolution, status, severity, ruleType); when(newIssueClassifier.isNew(any(), eq(issue))).thenReturn(true); return issue; } private static DefaultIssue createIssue(@Nullable String resolution, String status, String severity) { return createIssue(resolution, status, severity, RuleType.CODE_SMELL); } private static DefaultIssue createIssue(@Nullable String resolution, String status, String severity, RuleType ruleType) { return new DefaultIssue() .setResolution(resolution).setStatus(status) .setSeverity(severity).setRuleKey(RuleTesting.XOO_X1) .setType(ruleType); } private static DefaultIssue createSecurityHotspot() { return createIssue(null, STATUS_OPEN, "MAJOR", RuleType.SECURITY_HOTSPOT); } private DefaultIssue createNewSecurityHotspot() { return createNewIssue(null, STATUS_OPEN, "MAJOR", RuleType.SECURITY_HOTSPOT); } }
19,137
47.697201
168
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueCreationDateCalculatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.BiConsumer; import java.util.stream.Stream; import org.apache.commons.lang.ArrayUtils; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.rule.RuleKey; import org.sonar.ce.task.projectanalysis.analysis.Analysis; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.ScannerPlugin; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.filemove.AddedFileRepository; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder; import org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository; import org.sonar.ce.task.projectanalysis.scm.Changeset; import org.sonar.ce.task.projectanalysis.scm.ScmInfo; import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.protobuf.DbCommons.TextRange; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.protobuf.DbIssues.Flow; import org.sonar.db.protobuf.DbIssues.Location; import org.sonar.db.protobuf.DbIssues.Locations.Builder; import org.sonar.server.issue.IssueFieldsSetter; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UNCHANGED; @RunWith(DataProviderRunner.class) public class IssueCreationDateCalculatorTest { private static final String COMPONENT_UUID = "ab12"; @org.junit.Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private ScmInfoRepository scmInfoRepository = mock(ScmInfoRepository.class); private IssueFieldsSetter issueUpdater = mock(IssueFieldsSetter.class); private ActiveRulesHolder activeRulesHolder = mock(ActiveRulesHolder.class); private Component component = mock(Component.class); private RuleKey ruleKey = RuleKey.of("reop", "rule"); private DefaultIssue issue = mock(DefaultIssue.class); private ActiveRule activeRule = mock(ActiveRule.class); private IssueCreationDateCalculator underTest; private Analysis baseAnalysis = mock(Analysis.class); private Map<String, ScannerPlugin> scannerPlugins = new HashMap<>(); private RuleRepository ruleRepository = mock(RuleRepository.class); private AddedFileRepository addedFileRepository = mock(AddedFileRepository.class); private QProfileStatusRepository qProfileStatusRepository = mock(QProfileStatusRepository.class); private ScmInfo scmInfo; private Rule rule = mock(Rule.class); @Before public void before() { analysisMetadataHolder.setScannerPluginsByKey(scannerPlugins); analysisMetadataHolder.setAnalysisDate(new Date()); when(component.getUuid()).thenReturn(COMPONENT_UUID); underTest = new IssueCreationDateCalculator(analysisMetadataHolder, scmInfoRepository, issueUpdater, activeRulesHolder, ruleRepository, addedFileRepository, qProfileStatusRepository); when(ruleRepository.findByKey(ruleKey)).thenReturn(Optional.of(rule)); when(activeRulesHolder.get(any(RuleKey.class))).thenReturn(Optional.empty()); when(activeRulesHolder.get(ruleKey)).thenReturn(Optional.of(activeRule)); when(activeRule.getQProfileKey()).thenReturn("qpKey"); when(issue.getRuleKey()).thenReturn(ruleKey); when(qProfileStatusRepository.get(any())).thenReturn(Optional.of(UNCHANGED)); } @Test public void should_not_backdate_if_no_scm_available() { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); noScm(); setRuleUpdatedAt(2800L); run(); assertNoChangeOfCreationDate(); } @Test @UseDataProvider("backdatingDateCases") public void should_not_backdate_if_rule_and_plugin_and_base_plugin_are_old(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(1500L); rulePlugin("customjava"); pluginUpdatedAt("customjava", "java", 1700L); pluginUpdatedAt("java", 1700L); run(); assertNoChangeOfCreationDate(); } @Test @UseDataProvider("backdatingDateCases") public void should_not_backdate_if_rule_and_plugin_are_old_and_no_base_plugin(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(1500L); rulePlugin("java"); pluginUpdatedAt("java", 1700L); run(); assertNoChangeOfCreationDate(); } @Test @UseDataProvider("backdatingDateCases") public void should_not_backdate_if_issue_existed_before(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNotNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(2800L); run(); assertNoChangeOfCreationDate(); } @Test public void should_not_fail_for_issue_about_to_be_closed() { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNotNew(); setIssueBelongToNonExistingRule(); run(); assertNoChangeOfCreationDate(); } @Test public void should_fail_if_rule_is_not_found() { previousAnalysisWas(2000L); currentAnalysisIs(3000L); when(ruleRepository.findByKey(ruleKey)).thenReturn(Optional.empty()); makeIssueNew(); assertThatThrownBy(this::run) .isInstanceOf(IllegalStateException.class) .hasMessage("The rule with key 'reop:rule' raised an issue, but no rule with that key was found"); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_date_if_scm_is_available_and_rule_is_new(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(2800L); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_date_if_scm_is_available_and_rule_has_changed(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(2800L); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_date_if_scm_is_available_and_first_analysis(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { currentAnalysisIsFirstAnalysis(); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_date_if_scm_is_available_and_current_component_is_new_file(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); currentComponentIsNewFile(); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateAndChangedQPStatusCases") public void should_backdate_if_qp_of_the_rule_which_raised_the_issue_has_changed(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate, QProfileStatusRepository.Status status) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); changeQualityProfile(status); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_if_scm_is_available_and_plugin_is_new(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(1500L); rulePlugin("java"); pluginUpdatedAt("java", 2500L); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_if_scm_is_available_and_base_plugin_is_new(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { previousAnalysisWas(2000L); currentAnalysisIs(3000L); makeIssueNew(); configure.accept(issue, createMockScmInfo()); setRuleUpdatedAt(1500L); rulePlugin("customjava"); pluginUpdatedAt("customjava", "java", 1000L); pluginUpdatedAt("java", 2500L); run(); assertChangeOfCreationDateTo(expectedDate); } @Test @UseDataProvider("backdatingDateCases") public void should_backdate_external_issues(BiConsumer<DefaultIssue, ScmInfo> configure, long expectedDate) { currentAnalysisIsFirstAnalysis(); currentAnalysisIs(3000L); makeIssueNew(); when(rule.isExternal()).thenReturn(true); configure.accept(issue, createMockScmInfo()); run(); assertChangeOfCreationDateTo(expectedDate); verifyNoInteractions(activeRulesHolder); } @DataProvider public static Object[][] backdatingDateAndChangedQPStatusCases() { return Stream.of(backdatingDateCases()) .flatMap(datesCases -> Stream.of(QProfileStatusRepository.Status.values()) .filter(s -> !UNCHANGED.equals(s)) .map(s -> ArrayUtils.add(datesCases, s))) .toArray(Object[][]::new); } @DataProvider public static Object[][] backdatingDateCases() { return new Object[][] { {new NoIssueLocation(), 1200L}, {new OnlyPrimaryLocation(), 1300L}, {new FlowOnCurrentFileOnly(), 1900L}, {new FlowOnMultipleFiles(), 1700L} }; } private static class NoIssueLocation implements BiConsumer<DefaultIssue, ScmInfo> { @Override public void accept(DefaultIssue issue, ScmInfo scmInfo) { setDateOfLatestScmChangeset(scmInfo, 1200L); } } private static class OnlyPrimaryLocation implements BiConsumer<DefaultIssue, ScmInfo> { @Override public void accept(DefaultIssue issue, ScmInfo scmInfo) { when(issue.getLocations()).thenReturn(DbIssues.Locations.newBuilder().setTextRange(range(2, 3)).build()); setDateOfChangetsetAtLine(scmInfo, 2, 1200L); setDateOfChangetsetAtLine(scmInfo, 3, 1300L); } } private static class FlowOnCurrentFileOnly implements BiConsumer<DefaultIssue, ScmInfo> { @Override public void accept(DefaultIssue issue, ScmInfo scmInfo) { Builder locations = DbIssues.Locations.newBuilder() .setTextRange(range(2, 3)) .addFlow(newFlow(newLocation(4, 5))) .addFlow(newFlow(newLocation(6, 7, COMPONENT_UUID), newLocation(8, 9, COMPONENT_UUID))); when(issue.getLocations()).thenReturn(locations.build()); setDateOfChangetsetAtLine(scmInfo, 2, 1200L); setDateOfChangetsetAtLine(scmInfo, 3, 1300L); setDateOfChangetsetAtLine(scmInfo, 4, 1400L); setDateOfChangetsetAtLine(scmInfo, 5, 1500L); // some lines missing should be ok setDateOfChangetsetAtLine(scmInfo, 9, 1900L); } } private static class FlowOnMultipleFiles implements BiConsumer<DefaultIssue, ScmInfo> { @Override public void accept(DefaultIssue issue, ScmInfo scmInfo) { Builder locations = DbIssues.Locations.newBuilder() .setTextRange(range(2, 3)) .addFlow(newFlow(newLocation(4, 5))) .addFlow(newFlow(newLocation(6, 7, COMPONENT_UUID), newLocation(8, 9, "another"))); when(issue.getLocations()).thenReturn(locations.build()); setDateOfChangetsetAtLine(scmInfo, 2, 1200L); setDateOfChangetsetAtLine(scmInfo, 3, 1300L); setDateOfChangetsetAtLine(scmInfo, 4, 1400L); setDateOfChangetsetAtLine(scmInfo, 5, 1500L); setDateOfChangetsetAtLine(scmInfo, 6, 1600L); setDateOfChangetsetAtLine(scmInfo, 7, 1700L); setDateOfChangetsetAtLine(scmInfo, 8, 1800L); setDateOfChangetsetAtLine(scmInfo, 9, 1900L); } } private void previousAnalysisWas(long analysisDate) { analysisMetadataHolder.setBaseAnalysis(baseAnalysis); when(baseAnalysis.getCreatedAt()) .thenReturn(analysisDate); } private void pluginUpdatedAt(String pluginKey, long updatedAt) { scannerPlugins.put(pluginKey, new ScannerPlugin(pluginKey, null, updatedAt)); } private void pluginUpdatedAt(String pluginKey, String basePluginKey, long updatedAt) { scannerPlugins.put(pluginKey, new ScannerPlugin(pluginKey, basePluginKey, updatedAt)); } private AnalysisMetadataHolderRule currentAnalysisIsFirstAnalysis() { return analysisMetadataHolder.setBaseAnalysis(null); } private void currentAnalysisIs(long analysisDate) { analysisMetadataHolder.setAnalysisDate(analysisDate); } private void currentComponentIsNewFile() { when(component.getType()).thenReturn(Component.Type.FILE); when(addedFileRepository.isAdded(component)).thenReturn(true); } private void makeIssueNew() { when(issue.isNew()) .thenReturn(true); } private void makeIssueNotNew() { when(issue.isNew()) .thenReturn(false); } private void changeQualityProfile(QProfileStatusRepository.Status status) { when(qProfileStatusRepository.get(any())).thenReturn(Optional.of(status)); } private void setIssueBelongToNonExistingRule() { when(issue.getRuleKey()) .thenReturn(RuleKey.of("repo", "disabled")); } private void noScm() { when(scmInfoRepository.getScmInfo(component)) .thenReturn(Optional.empty()); } private static void setDateOfLatestScmChangeset(ScmInfo scmInfo, long date) { Changeset changeset = Changeset.newChangesetBuilder().setDate(date).setRevision("1").build(); when(scmInfo.getLatestChangeset()).thenReturn(changeset); } private static void setDateOfChangetsetAtLine(ScmInfo scmInfo, int line, long date) { Changeset changeset = Changeset.newChangesetBuilder().setDate(date).setRevision("1").build(); when(scmInfo.hasChangesetForLine(line)).thenReturn(true); when(scmInfo.getChangesetForLine(line)).thenReturn(changeset); } private ScmInfo createMockScmInfo() { if (scmInfo == null) { scmInfo = mock(ScmInfo.class); when(scmInfoRepository.getScmInfo(component)) .thenReturn(Optional.of(scmInfo)); } return scmInfo; } private void setRuleUpdatedAt(long updateAt) { when(activeRule.getUpdatedAt()).thenReturn(updateAt); } private void rulePlugin(String pluginKey) { when(activeRule.getPluginKey()).thenReturn(pluginKey); } private static Location newLocation(int startLine, int endLine) { return Location.newBuilder().setTextRange(range(startLine, endLine)).build(); } private static Location newLocation(int startLine, int endLine, String componentUuid) { return Location.newBuilder().setTextRange(range(startLine, endLine)).setComponentId(componentUuid).build(); } private static org.sonar.db.protobuf.DbCommons.TextRange range(int startLine, int endLine) { return TextRange.newBuilder().setStartLine(startLine).setEndLine(endLine).build(); } private static Flow newFlow(Location... locations) { Flow.Builder builder = Flow.newBuilder(); Arrays.stream(locations).forEach(builder::addLocation); return builder.build(); } private void run() { underTest.beforeComponent(component); underTest.onIssue(component, issue); underTest.afterComponent(component); } private void assertNoChangeOfCreationDate() { verify(issueUpdater, never()) .setCreationDate(any(), any(), any()); } private void assertChangeOfCreationDateTo(long createdAt) { verify(issueUpdater, atLeastOnce()) .setCreationDate(same(issue), eq(new Date(createdAt)), any()); } }
17,715
33.874016
188
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueLifecycleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Date; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.DefaultIssueComment; import org.sonar.core.issue.FieldDiffs; import org.sonar.core.issue.IssueChangeContext; import org.sonar.db.component.BranchType; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.server.issue.IssueFieldsSetter; import org.sonar.server.issue.workflow.IssueWorkflow; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.entry; import static org.assertj.core.groups.Tuple.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.RESOLUTION_FALSE_POSITIVE; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.issue.Issue.STATUS_CLOSED; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.issue.Issue.STATUS_RESOLVED; import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.utils.DateUtils.parseDate; import static org.sonar.core.issue.IssueChangeContext.issueChangeContextByUserBuilder; import static org.sonar.db.rule.RuleTesting.XOO_X1; public class IssueLifecycleTest { private static final Date DEFAULT_DATE = new Date(); private static final Duration DEFAULT_DURATION = Duration.create(10); private static final String TEST_CONTEXT_KEY = "test_context_key"; private final DumbRule rule = new DumbRule(XOO_X1); @Rule public RuleRepositoryRule ruleRepository = new RuleRepositoryRule().add(rule); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private final IssueChangeContext issueChangeContext = issueChangeContextByUserBuilder(DEFAULT_DATE, "default_user_uuid").build(); private final IssueWorkflow workflow = mock(IssueWorkflow.class); private final IssueFieldsSetter updater = mock(IssueFieldsSetter.class); private final DebtCalculator debtCalculator = mock(DebtCalculator.class); private final IssueLifecycle underTest = new IssueLifecycle(analysisMetadataHolder, issueChangeContext, workflow, updater, debtCalculator, ruleRepository); @Test public void initNewOpenIssue() { DefaultIssue issue = new DefaultIssue() .setRuleKey(XOO_X1); when(debtCalculator.calculate(issue)).thenReturn(DEFAULT_DURATION); underTest.initNewOpenIssue(issue); assertThat(issue.key()).isNotNull(); assertThat(issue.creationDate()).isNotNull(); assertThat(issue.updateDate()).isNotNull(); assertThat(issue.status()).isEqualTo(STATUS_OPEN); assertThat(issue.effort()).isEqualTo(DEFAULT_DURATION); assertThat(issue.isNew()).isTrue(); assertThat(issue.isCopied()).isFalse(); } @Test public void initNewOpenHotspot() { rule.setType(RuleType.SECURITY_HOTSPOT); DefaultIssue issue = new DefaultIssue() .setRuleKey(XOO_X1); when(debtCalculator.calculate(issue)).thenReturn(DEFAULT_DURATION); underTest.initNewOpenIssue(issue); assertThat(issue.key()).isNotNull(); assertThat(issue.creationDate()).isNotNull(); assertThat(issue.updateDate()).isNotNull(); assertThat(issue.status()).isEqualTo(STATUS_TO_REVIEW); assertThat(issue.resolution()).isNull(); assertThat(issue.effort()).isEqualTo(DEFAULT_DURATION); assertThat(issue.isNew()).isTrue(); assertThat(issue.isCopied()).isFalse(); } @Test public void mergeIssueFromPRIntoBranch() { DefaultIssue raw = new DefaultIssue() .setKey("raw"); DefaultIssue fromShort = new DefaultIssue() .setKey("short") .setIsNewCodeReferenceIssue(true); fromShort.setResolution("resolution"); fromShort.setStatus("status"); Date commentDate = new Date(); fromShort.addComment(new DefaultIssueComment() .setIssueKey("short") .setCreatedAt(commentDate) .setUserUuid("user_uuid") .setMarkdownText("A comment")); Date diffDate = new Date(); // file diff alone fromShort.addChange(new FieldDiffs() .setCreationDate(diffDate) .setIssueKey("short") .setUserUuid("user_uuid") .setDiff("file", "uuidA1", "uuidB1")); // file diff with another field fromShort.addChange(new FieldDiffs() .setCreationDate(diffDate) .setIssueKey("short") .setUserUuid("user_uuid") .setDiff("severity", "MINOR", "MAJOR") .setDiff("file", "uuidA2", "uuidB2")); Branch branch = mock(Branch.class); when(branch.getName()).thenReturn("master"); analysisMetadataHolder.setBranch(branch); underTest.mergeConfirmedOrResolvedFromPrOrBranch(raw, fromShort, BranchType.PULL_REQUEST, "2"); assertThat(raw.resolution()).isEqualTo("resolution"); assertThat(raw.status()).isEqualTo("status"); assertThat(raw.defaultIssueComments()) .extracting(DefaultIssueComment::issueKey, DefaultIssueComment::createdAt, DefaultIssueComment::userUuid, DefaultIssueComment::markdownText) .containsOnly(tuple("raw", commentDate, "user_uuid", "A comment")); assertThat(raw.changes()).hasSize(2); assertThat(raw.changes().get(0).creationDate()).isEqualTo(diffDate); assertThat(raw.changes().get(0).userUuid()).contains("user_uuid"); assertThat(raw.changes().get(0).issueKey()).contains("raw"); assertThat(raw.changes().get(0).diffs()).containsOnlyKeys("severity"); assertThat(raw.changes().get(1).userUuid()).contains("default_user_uuid"); assertThat(raw.changes().get(1).diffs()).containsOnlyKeys(IssueFieldsSetter.FROM_BRANCH); assertThat(raw.changes().get(1).get(IssueFieldsSetter.FROM_BRANCH).oldValue()).isEqualTo("#2"); assertThat(raw.changes().get(1).get(IssueFieldsSetter.FROM_BRANCH).newValue()).isEqualTo("master"); assertThat(raw.isNewCodeReferenceIssue()).isTrue(); } @Test public void copyExistingIssuesFromSourceBranchOfPullRequest() { String pullRequestKey = "1"; Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn("sourceBranch-1"); when(branch.getPullRequestKey()).thenReturn(pullRequestKey); analysisMetadataHolder.setBranch(branch); analysisMetadataHolder.setPullRequestKey(pullRequestKey); DefaultIssue raw = new DefaultIssue() .setKey("raw"); DefaultIssue fromShort = new DefaultIssue() .setKey("short"); fromShort.setResolution("resolution"); fromShort.setStatus("status"); Date commentDate = new Date(); fromShort.addComment(new DefaultIssueComment() .setIssueKey("short") .setCreatedAt(commentDate) .setUserUuid("user_uuid") .setMarkdownText("A comment")); Date diffDate = new Date(); // file diff alone fromShort.addChange(new FieldDiffs() .setCreationDate(diffDate) .setIssueKey("short") .setUserUuid("user_uuid") .setDiff("file", "uuidA1", "uuidB1")); // file diff with another field fromShort.addChange(new FieldDiffs() .setCreationDate(diffDate) .setIssueKey("short") .setUserUuid("user_uuid") .setDiff("severity", "MINOR", "MAJOR") .setDiff("file", "uuidA2", "uuidB2")); underTest.copyExistingIssueFromSourceBranchToPullRequest(raw, fromShort); assertThat(raw.resolution()).isEqualTo("resolution"); assertThat(raw.status()).isEqualTo("status"); assertThat(raw.defaultIssueComments()) .extracting(DefaultIssueComment::issueKey, DefaultIssueComment::createdAt, DefaultIssueComment::userUuid, DefaultIssueComment::markdownText) .containsOnly(tuple("raw", commentDate, "user_uuid", "A comment")); assertThat(raw.changes()).hasSize(2); assertThat(raw.changes().get(0).creationDate()).isEqualTo(diffDate); assertThat(raw.changes().get(0).userUuid()).contains("user_uuid"); assertThat(raw.changes().get(0).issueKey()).contains("raw"); assertThat(raw.changes().get(0).diffs()).containsOnlyKeys("severity"); assertThat(raw.changes().get(1).userUuid()).contains("default_user_uuid"); assertThat(raw.changes().get(1).diffs()).containsOnlyKeys(IssueFieldsSetter.FROM_BRANCH); assertThat(raw.changes().get(1).get(IssueFieldsSetter.FROM_BRANCH).oldValue()).isEqualTo("sourceBranch-1"); assertThat(raw.changes().get(1).get(IssueFieldsSetter.FROM_BRANCH).newValue()).isEqualTo("#1"); } @Test public void copyExistingIssuesFromSourceBranchOfPullRequest_copyFieldDiffsCorrectly() { String pullRequestKey = "1"; Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(branch.getName()).thenReturn("sourceBranch-1"); when(branch.getPullRequestKey()).thenReturn(pullRequestKey); analysisMetadataHolder.setBranch(branch); analysisMetadataHolder.setPullRequestKey(pullRequestKey); DefaultIssue destIssue = new DefaultIssue() .setKey("raw"); DefaultIssue sourceIssue = new DefaultIssue() .setKey("issue"); sourceIssue.setResolution("resolution"); sourceIssue.setStatus("status"); FieldDiffs sourceFieldDiffs = new FieldDiffs(); sourceIssue.addChange(sourceFieldDiffs .setCreationDate(new Date()) .setIssueKey("short") .setUserUuid("user_uuid") .setExternalUser("toto") .setWebhookSource("github") .setDiff("severity", "MINOR", "MAJOR")); underTest.copyExistingIssueFromSourceBranchToPullRequest(destIssue, sourceIssue); FieldDiffs actualFieldDiffs = destIssue.changes().iterator().next(); assertThat(actualFieldDiffs.issueKey()).contains(destIssue.key()); assertThat(actualFieldDiffs).usingRecursiveComparison().ignoringFields("issueKey").isEqualTo(sourceFieldDiffs); } @Test public void copyExistingIssuesFromSourceBranchOfPullRequest_only_works_for_pull_requests() { DefaultIssue raw = new DefaultIssue() .setKey("raw"); DefaultIssue from = new DefaultIssue() .setKey("short"); from.setResolution("resolution"); from.setStatus("status"); Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); analysisMetadataHolder.setBranch(branch); assertThatThrownBy(() -> underTest.copyExistingIssueFromSourceBranchToPullRequest(raw, from)) .isInstanceOf(IllegalStateException.class) .hasMessage("This operation should be done only on pull request analysis"); } @Test public void copiedIssue() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setCreationDate(parseDate("2015-10-01")) .setUpdateDate(parseDate("2015-10-02")) .setCloseDate(parseDate("2015-10-03")) .setRuleDescriptionContextKey(TEST_CONTEXT_KEY); DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(10) .setEndLine(12) .build()) .build(); DefaultIssue base = new DefaultIssue() .setKey("BASE_KEY") .setCreationDate(parseDate("2015-01-01")) .setUpdateDate(parseDate("2015-01-02")) .setCloseDate(parseDate("2015-01-03")) .setResolution(RESOLUTION_FIXED) .setStatus(STATUS_CLOSED) .setSeverity(BLOCKER) .setAssigneeUuid("base assignee uuid") .setAssigneeLogin("base assignee login") .setAuthorLogin("base author") .setTags(newArrayList("base tag")) .setOnDisabledRule(true) .setSelectedAt(1000L) .setLine(10) .setMessage("message") .setGap(15d) .setEffort(Duration.create(15L)) .setManualSeverity(false) .setLocations(issueLocations); when(debtCalculator.calculate(raw)).thenReturn(DEFAULT_DURATION); Branch branch = mock(Branch.class); when(branch.getName()).thenReturn("release-2.x"); analysisMetadataHolder.setBranch(branch); underTest.copyExistingOpenIssueFromBranch(raw, base, "master"); assertThat(raw.isNew()).isFalse(); assertThat(raw.isCopied()).isTrue(); assertThat(raw.key()).isNotNull(); assertThat(raw.key()).isNotEqualTo(base.key()); assertThat(raw.creationDate()).isEqualTo(base.creationDate()); assertThat(raw.updateDate()).isEqualTo(base.updateDate()); assertThat(raw.closeDate()).isEqualTo(base.closeDate()); assertThat(raw.resolution()).isEqualTo(RESOLUTION_FIXED); assertThat(raw.status()).isEqualTo(STATUS_CLOSED); assertThat(raw.assignee()).isEqualTo("base assignee uuid"); assertThat(raw.assigneeLogin()).isEqualTo("base assignee login"); assertThat(raw.authorLogin()).isEqualTo("base author"); assertThat(raw.tags()).containsOnly("base tag"); assertThat(raw.effort()).isEqualTo(DEFAULT_DURATION); assertThat(raw.isOnDisabledRule()).isTrue(); assertThat(raw.selectedAt()).isEqualTo(1000L); assertThat(raw.changes().get(0).get(IssueFieldsSetter.FROM_BRANCH).oldValue()).isEqualTo("master"); assertThat(raw.changes().get(0).get(IssueFieldsSetter.FROM_BRANCH).newValue()).isEqualTo("release-2.x"); assertThat(raw.getRuleDescriptionContextKey()).contains(TEST_CONTEXT_KEY); verifyNoInteractions(updater); } @Test public void doAutomaticTransition() { DefaultIssue issue = new DefaultIssue(); underTest.doAutomaticTransition(issue); verify(workflow).doAutomaticTransition(issue, issueChangeContext); } @Test public void mergeExistingOpenIssue() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setRuleKey(XOO_X1) .setRuleDescriptionContextKey("spring") .setCodeVariants(Set.of("foo", "bar")) .setCreationDate(parseDate("2015-10-01")) .setUpdateDate(parseDate("2015-10-02")) .setCloseDate(parseDate("2015-10-03")); DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(10) .setEndLine(12) .build()) .build(); DbIssues.MessageFormattings messageFormattings = DbIssues.MessageFormattings.newBuilder() .addMessageFormatting(DbIssues.MessageFormatting .newBuilder() .setStart(13) .setEnd(17) .setType(DbIssues.MessageFormattingType.CODE) .build()) .build(); DefaultIssue base = new DefaultIssue() .setKey("BASE_KEY") .setCreationDate(parseDate("2015-01-01")) .setUpdateDate(parseDate("2015-01-02")) .setResolution(RESOLUTION_FALSE_POSITIVE) .setStatus(STATUS_RESOLVED) .setSeverity(BLOCKER) .setAssigneeUuid("base assignee uuid") .setAssigneeLogin("base assignee login") .setAuthorLogin("base author") .setTags(newArrayList("base tag")) .setOnDisabledRule(true) .setSelectedAt(1000L) .setLine(10) .setMessage("message with code") .setMessageFormattings(messageFormattings) .setGap(15d) .setRuleDescriptionContextKey("hibernate") .setCodeVariants(Set.of("donut")) .setEffort(Duration.create(15L)) .setManualSeverity(false) .setLocations(issueLocations) .addChange(new FieldDiffs().setDiff("foo", "bar", "donut")) .addChange(new FieldDiffs().setDiff("file", "A", "B")); when(debtCalculator.calculate(raw)).thenReturn(DEFAULT_DURATION); underTest.mergeExistingOpenIssue(raw, base); assertThat(raw.isNew()).isFalse(); assertThat(raw.key()).isEqualTo("BASE_KEY"); assertThat(raw.creationDate()).isEqualTo(base.creationDate()); assertThat(raw.updateDate()).isEqualTo(base.updateDate()); assertThat(raw.resolution()).isEqualTo(RESOLUTION_FALSE_POSITIVE); assertThat(raw.status()).isEqualTo(STATUS_RESOLVED); assertThat(raw.assignee()).isEqualTo("base assignee uuid"); assertThat(raw.assigneeLogin()).isEqualTo("base assignee login"); assertThat(raw.authorLogin()).isEqualTo("base author"); assertThat(raw.tags()).containsOnly("base tag"); assertThat(raw.codeVariants()).containsOnly("foo", "bar"); assertThat(raw.effort()).isEqualTo(DEFAULT_DURATION); assertThat(raw.isOnDisabledRule()).isTrue(); assertThat(raw.selectedAt()).isEqualTo(1000L); assertThat(raw.isChanged()).isFalse(); assertThat(raw.changes()).hasSize(2); assertThat(raw.changes().get(0).diffs()) .containsOnly(entry("foo", new FieldDiffs.Diff<>("bar", "donut"))); assertThat(raw.changes().get(1).diffs()) .containsOnly(entry("file", new FieldDiffs.Diff<>("A", "B"))); verify(updater).setPastSeverity(raw, BLOCKER, issueChangeContext); verify(updater).setPastLine(raw, 10); verify(updater).setRuleDescriptionContextKey(raw, "hibernate"); verify(updater).setCodeVariants(raw, Set.of("donut"), issueChangeContext); verify(updater).setPastMessage(raw, "message with code", messageFormattings, issueChangeContext); verify(updater).setPastEffort(raw, Duration.create(15L), issueChangeContext); verify(updater).setPastLocations(raw, issueLocations); } @Test public void mergeExistingOpenIssue_with_manual_severity() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setRuleKey(XOO_X1); DefaultIssue base = new DefaultIssue() .setKey("BASE_KEY") .setResolution(RESOLUTION_FIXED) .setStatus(STATUS_CLOSED) .setSeverity(BLOCKER) .setManualSeverity(true); underTest.mergeExistingOpenIssue(raw, base); assertThat(raw.manualSeverity()).isTrue(); assertThat(raw.severity()).isEqualTo(BLOCKER); verify(updater, never()).setPastSeverity(raw, BLOCKER, issueChangeContext); } @Test public void mergeExistingOpenIssue_with_base_changed() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setRuleKey(XOO_X1); DefaultIssue base = new DefaultIssue() .setChanged(true) .setKey("BASE_KEY") .setResolution(RESOLUTION_FALSE_POSITIVE) .setStatus(STATUS_RESOLVED); underTest.mergeExistingOpenIssue(raw, base); assertThat(raw.isChanged()).isTrue(); } @Test public void mergeExistingOpenIssue_with_rule_description_context_key_added() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setRuleKey(XOO_X1) .setRuleDescriptionContextKey(TEST_CONTEXT_KEY); DefaultIssue base = new DefaultIssue() .setChanged(true) .setKey("RAW_KEY") .setResolution(RESOLUTION_FALSE_POSITIVE) .setStatus(STATUS_RESOLVED) .setRuleDescriptionContextKey(null); underTest.mergeExistingOpenIssue(raw, base); assertThat(raw.isChanged()).isTrue(); assertThat(raw.getRuleDescriptionContextKey()).isEqualTo(raw.getRuleDescriptionContextKey()); } @Test public void mergeExistingOpenIssue_with_rule_description_context_key_removed() { DefaultIssue raw = new DefaultIssue() .setNew(true) .setKey("RAW_KEY") .setRuleKey(XOO_X1) .setRuleDescriptionContextKey(null); DefaultIssue base = new DefaultIssue() .setChanged(true) .setKey("RAW_KEY") .setResolution(RESOLUTION_FALSE_POSITIVE) .setStatus(STATUS_RESOLVED) .setRuleDescriptionContextKey(TEST_CONTEXT_KEY); underTest.mergeExistingOpenIssue(raw, base); assertThat(raw.isChanged()).isTrue(); assertThat(raw.getRuleDescriptionContextKey()).isEmpty(); } }
20,839
39.309478
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueLocationsTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import javax.annotation.Nullable; import org.junit.Test; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import static java.util.Optional.ofNullable; import static org.assertj.core.api.Assertions.assertThat; public class IssueLocationsTest { @Test public void allLinesFor_filters_lines_for_specified_component() { DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); locations.addFlowBuilder() .addLocation(newLocation("file1", 5, 5)) .addLocation(newLocation("file1", 10, 12)) .addLocation(newLocation("file1", 15, 15)) .addLocation(newLocation("file2", 10, 11)) .build(); DefaultIssue issue = new DefaultIssue().setLocations(locations.build()); assertThat(IssueLocations.allLinesFor(issue, "file1")).containsExactlyInAnyOrder(5, 10, 11, 12, 15); assertThat(IssueLocations.allLinesFor(issue, "file2")).containsExactlyInAnyOrder(10, 11); assertThat(IssueLocations.allLinesFor(issue, "file3")).isEmpty(); } @Test public void allLinesFor_traverses_all_flows() { DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); locations.addFlowBuilder() .addLocation(newLocation("file1", 5, 5)) .addLocation(newLocation("file2", 10, 11)) .build(); locations.addFlowBuilder() .addLocation(newLocation("file1", 7, 9)) .addLocation(newLocation("file2", 12, 12)) .build(); DefaultIssue issue = new DefaultIssue().setLocations(locations.build()); assertThat(IssueLocations.allLinesFor(issue, "file1")).containsExactlyInAnyOrder(5, 7, 8, 9); assertThat(IssueLocations.allLinesFor(issue, "file2")).containsExactlyInAnyOrder(10, 11, 12); } @Test public void allLinesFor_keeps_duplicated_lines() { DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); locations.addFlowBuilder() .addLocation(newLocation("file1", 5, 5)) .addLocation(newLocation("file1", 4, 6)) .build(); DefaultIssue issue = new DefaultIssue().setLocations(locations.build()); assertThat(IssueLocations.allLinesFor(issue, "file1")).containsExactlyInAnyOrder(4, 5, 5, 6); } @Test public void allLinesFor_returns_empty_if_no_locations_are_set() { DefaultIssue issue = new DefaultIssue().setLocations(null); assertThat(IssueLocations.allLinesFor(issue, "file1")).isEmpty(); } @Test public void allLinesFor_default_component_of_location_is_the_issue_component() { DbIssues.Locations.Builder locations = DbIssues.Locations.newBuilder(); locations.addFlowBuilder() .addLocation(newLocation("", 5, 5)) .addLocation(newLocation(null, 7, 7)) .addLocation(newLocation("file2", 9, 9)) .build(); DefaultIssue issue = new DefaultIssue() .setComponentUuid("file1") .setLocations(locations.build()); assertThat(IssueLocations.allLinesFor(issue, "file1")).containsExactlyInAnyOrder(5, 7); assertThat(IssueLocations.allLinesFor(issue, "file2")).containsExactlyInAnyOrder(9); assertThat(IssueLocations.allLinesFor(issue, "file3")).isEmpty(); } private static DbIssues.Location newLocation(@Nullable String componentId, int startLine, int endLine) { DbIssues.Location.Builder builder = DbIssues.Location.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(startLine).setEndLine(endLine).build()); ofNullable(componentId).ifPresent(builder::setComponentId); return builder.build(); } }
4,434
39.688073
106
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssueTrackingDelegatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.core.issue.tracking.Tracking; import org.sonar.db.component.BranchType; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class IssueTrackingDelegatorTest { @Mock private PullRequestTrackerExecution prBranchTracker; @Mock private ReferenceBranchTrackerExecution mergeBranchTracker; @Mock private TrackerExecution tracker; @Mock private AnalysisMetadataHolder analysisMetadataHolder; @Mock private Component component; @Mock private Tracking<DefaultIssue, DefaultIssue> trackingResult; @Mock private Input<DefaultIssue> rawInput; private IssueTrackingDelegator underTest; @Before public void setUp() { MockitoAnnotations.initMocks(this); underTest = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder); when(tracker.track(component, rawInput)).thenReturn(trackingResult); when(mergeBranchTracker.track(component, rawInput)).thenReturn(trackingResult); when(prBranchTracker.track(component, rawInput)).thenReturn(trackingResult); } @Test public void delegate_regular_tracker() { when(analysisMetadataHolder.getBranch()).thenReturn(mock(Branch.class)); underTest.track(component, rawInput); verify(tracker).track(component, rawInput); verifyNoInteractions(prBranchTracker); verifyNoInteractions(mergeBranchTracker); } @Test public void delegate_merge_tracker() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); when(branch.isMain()).thenReturn(false); when(analysisMetadataHolder.getBranch()).thenReturn(branch); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); underTest.track(component, rawInput); verify(mergeBranchTracker).track(component, rawInput); verifyNoInteractions(tracker); verifyNoInteractions(prBranchTracker); } @Test public void delegate_pull_request_tracker() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); when(analysisMetadataHolder.getBranch()).thenReturn(mock(Branch.class)); when(analysisMetadataHolder.isPullRequest()).thenReturn(true); underTest.track(component, rawInput); verify(prBranchTracker).track(component, rawInput); verifyNoInteractions(tracker); verifyNoInteractions(mergeBranchTracker); } }
3,791
34.439252
113
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssuesOnReferenceBranchVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class IssuesOnReferenceBranchVisitorTest { private final NewIssueClassifier newIssueClassifier = mock(NewIssueClassifier.class); private final Component component = mock(Component.class); private final DefaultIssue issue = mock(DefaultIssue.class); private final IssueOnReferenceBranchVisitor underTest = new IssueOnReferenceBranchVisitor(newIssueClassifier); @Test public void issue_is_not_changed_when_newIssueClassifier_is_not_enabled() { when(newIssueClassifier.isEnabled()).thenReturn(false); underTest.onIssue(component, issue); verifyNoInteractions(issue); } @Test public void handles_issue_not_on_branch_using_reference_branch() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isOnBranchUsingReferenceBranch()).thenReturn(false); underTest.onIssue(component, issue); verifyNoMoreInteractions(issue); } @Test public void handles_overall_code_issue_on_branch_using_reference_branch() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isOnBranchUsingReferenceBranch()).thenReturn(true); when(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(component, issue)).thenReturn(true); when(issue.isNewCodeReferenceIssue()).thenReturn(false); underTest.onIssue(component, issue); verify(issue).setIsOnChangedLine(true); verify(issue).isNewCodeReferenceIssue(); verifyNoMoreInteractions(issue); } @Test public void handles_new_code_issue_on_branch_using_reference_branch_which_is_still_new() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isOnBranchUsingReferenceBranch()).thenReturn(true); when(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(component, issue)).thenReturn(true); when(issue.isNewCodeReferenceIssue()).thenReturn(true); when(issue.isOnChangedLine()).thenReturn(true); underTest.onIssue(component, issue); verify(issue).setIsOnChangedLine(true); verify(issue).isNewCodeReferenceIssue(); verify(issue).isOnChangedLine(); verifyNoMoreInteractions(issue); } @Test public void handles_new_code_issue_on_branch_using_reference_branch_which_is_no_longer_new() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isOnBranchUsingReferenceBranch()).thenReturn(true); when(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(component, issue)).thenReturn(false); when(issue.isNewCodeReferenceIssue()).thenReturn(true); when(issue.isOnChangedLine()).thenReturn(false); underTest.onIssue(component, issue); verify(issue).setIsOnChangedLine(false); verify(issue).isNewCodeReferenceIssue(); verify(issue).setIsNoLongerNewCodeReferenceIssue(true); verify(issue).setIsNewCodeReferenceIssue(false); } }
4,098
39.99
112
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/IssuesRepositoryVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class IssuesRepositoryVisitorTest { static final String FILE_UUID = "FILE_UUID"; static final String FILE_KEY = "FILE_KEY"; static final int FILE_REF = 2; static final Component FILE = builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build(); static final String PROJECT_KEY = "PROJECT_KEY"; static final String PROJECT_UUID = "PROJECT_UUID"; static final int PROJECT_REF = 1; static final Component PROJECT = builder(Component.Type.PROJECT, PROJECT_REF) .setKey(PROJECT_KEY) .setUuid(PROJECT_UUID) .addChildren(FILE) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public ComponentIssuesRepositoryRule componentIssuesRepository = new ComponentIssuesRepositoryRule(treeRootHolder); IssuesRepositoryVisitor underTest = new IssuesRepositoryVisitor(componentIssuesRepository); @Before public void setUp() { treeRootHolder.setRoot(PROJECT); } @Test public void feed_component_issues_repo() { DefaultIssue i1 = mock(DefaultIssue.class); DefaultIssue i2 = mock(DefaultIssue.class); underTest.beforeComponent(FILE); underTest.onIssue(FILE, i1); underTest.onIssue(FILE, i2); underTest.afterComponent(FILE); assertThat(componentIssuesRepository.getIssues(FILE_REF)).hasSize(2); } @Test public void empty_component_issues_repo_when_no_issue() { DefaultIssue i1 = mock(DefaultIssue.class); DefaultIssue i2 = mock(DefaultIssue.class); underTest.beforeComponent(FILE); underTest.onIssue(FILE, i1); underTest.onIssue(FILE, i2); underTest.afterComponent(FILE); assertThat(componentIssuesRepository.getIssues(FILE)).hasSize(2); underTest.beforeComponent(PROJECT); underTest.afterComponent(PROJECT); assertThat(componentIssuesRepository.getIssues(PROJECT)).isEmpty(); } }
3,211
33.537634
117
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/LoadComponentUuidsHavingOpenIssuesVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Arrays; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import static com.google.common.collect.Sets.newHashSet; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; public class LoadComponentUuidsHavingOpenIssuesVisitorTest { BaseIssuesLoader baseIssuesLoader = mock(BaseIssuesLoader.class); ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues = mock(ComponentsWithUnprocessedIssues.class); VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(new LoadComponentUuidsHavingOpenIssuesVisitor(baseIssuesLoader, componentsWithUnprocessedIssues))); @Test public void set_issues_when_visiting_project() { when(baseIssuesLoader.loadUuidsOfComponentsWithOpenIssues()).thenReturn(newHashSet("FILE1", "FILE2")); underTest.visit(ReportComponent.builder(PROJECT, 1).build()); verify(componentsWithUnprocessedIssues).setUuids(newHashSet("FILE1", "FILE2")); } @Test public void do_nothing_on_not_project_level() { when(baseIssuesLoader.loadUuidsOfComponentsWithOpenIssues()).thenReturn(newHashSet("FILE1", "FILE2")); underTest.visit(ReportComponent.builder(DIRECTORY, 1).build()); underTest.visit(ReportComponent.builder(FILE, 1).build()); verifyNoInteractions(componentsWithUnprocessedIssues); } }
2,653
42.508197
163
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/MovedIssueVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Date; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.server.issue.IssueFieldsSetter; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class MovedIssueVisitorTest { private static final long ANALYSIS_DATE = 894521; private static final String FILE_UUID = "file uuid"; private static final Component FILE = ReportComponent.builder(Component.Type.FILE, 1) .setKey("key_1") .setUuid(FILE_UUID) .build(); @org.junit.Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private final MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class); private final MovedIssueVisitor underTest = new MovedIssueVisitor(analysisMetadataHolder, movedFilesRepository, new IssueFieldsSetter()); @Before public void setUp() { analysisMetadataHolder.setAnalysisDate(ANALYSIS_DATE); when(movedFilesRepository.getOriginalFile(any(Component.class))) .thenReturn(Optional.empty()); } @Test public void onIssue_does_not_alter_issue_if_component_is_not_a_file() { DefaultIssue issue = mock(DefaultIssue.class); underTest.onIssue(ReportComponent.builder(Component.Type.DIRECTORY, 1).build(), issue); verifyNoInteractions(issue); } @Test public void onIssue_does_not_alter_issue_if_component_file_but_issue_has_the_same_component_uuid() { DefaultIssue issue = mockIssue(FILE_UUID); underTest.onIssue(FILE, issue); verify(issue).componentUuid(); verifyNoMoreInteractions(issue); } @Test public void onIssue_throws_ISE_if_issue_has_different_component_uuid_but_component_has_no_original_file() { DefaultIssue issue = mockIssue("other component uuid"); when(issue.toString()).thenReturn("[bad issue, bad!]"); assertThatThrownBy(() -> underTest.onIssue(FILE, issue)) .isInstanceOf(IllegalStateException.class) .hasMessage("Issue [bad issue, bad!] for component ReportComponent{ref=1, key='key_1', type=FILE} " + "has a different component key but no original file exist in MovedFilesRepository"); } @Test public void onIssue_throws_ISE_if_issue_has_different_component_uuid_from_component_but_it_is_not_the_one_of_original_file() { DefaultIssue issue = mockIssue("other component uuid"); when(issue.toString()).thenReturn("[bad issue, bad!]"); when(movedFilesRepository.getOriginalFile(FILE)) .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile("original uuid", "original key"))); assertThatThrownBy(() -> underTest.onIssue(FILE, issue)) .isInstanceOf(IllegalStateException.class) .hasMessage("Issue [bad issue, bad!] doesn't belong to file original uuid registered as original " + "file of current file ReportComponent{ref=1, key='key_1', type=FILE}"); } @Test public void onIssue_update_component_and_module_fields_to_component_and_flag_issue_has_changed() { MovedFilesRepository.OriginalFile originalFile = new MovedFilesRepository.OriginalFile("original uuid", "original key"); DefaultIssue issue = mockIssue(originalFile.uuid()); when(movedFilesRepository.getOriginalFile(FILE)) .thenReturn(Optional.of(originalFile)); underTest.onIssue(FILE, issue); verify(issue).setComponentUuid(FILE.getUuid()); verify(issue).setComponentKey(FILE.getKey()); verify(issue).setUpdateDate(new Date(ANALYSIS_DATE)); verify(issue).setChanged(true); } private DefaultIssue mockIssue(String fileUuid) { DefaultIssue issue = mock(DefaultIssue.class); when(issue.componentUuid()).thenReturn(fileUuid); return issue; } }
5,179
40.774194
139
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewAdHocRuleTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class NewAdHocRuleTest { @Test public void fail_if_engine_id_is_not_set() { assertThatThrownBy(() -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("'engine id' not expected to be null for an ad hoc rule"); } @Test public void test_equals_and_hashcode() { NewAdHocRule adHocRule1 = new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build()); NewAdHocRule adHocRule2 = new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build()); NewAdHocRule anotherAdHocRule = new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("another").build()); assertThat(adHocRule1) .isEqualTo(adHocRule1) .isEqualTo(adHocRule2) .isNotNull() .isNotEqualTo(anotherAdHocRule) .hasSameHashCodeAs(adHocRule1) .hasSameHashCodeAs(adHocRule2); assertThat(adHocRule1.hashCode()).isNotEqualTo(anotherAdHocRule.hashCode()); } }
2,216
40.830189
147
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewEffortAggregatorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.util.UuidFactoryFast; import org.sonar.db.component.BranchType; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT; import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_REMEDIATION_EFFORT_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REMEDIATION_EFFORT_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT; import static org.sonar.api.measures.CoreMetrics.NEW_TECHNICAL_DEBT_KEY; import static org.sonar.api.rules.RuleType.BUG; import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.VULNERABILITY; public class NewEffortAggregatorTest { private static final Component FILE = ReportComponent.builder(Component.Type.FILE, 1).setUuid("FILE").build(); private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, 2).addChildren(FILE).build(); @org.junit.Rule public PeriodHolderRule periodsHolder = new PeriodHolderRule(); @org.junit.Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NEW_TECHNICAL_DEBT) .add(NEW_RELIABILITY_REMEDIATION_EFFORT) .add(NEW_SECURITY_REMEDIATION_EFFORT); @org.junit.Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(); private final NewIssueClassifier newIssueClassifier = mock(NewIssueClassifier.class); private final NewEffortAggregator underTest = new NewEffortAggregator(metricRepository, measureRepository, newIssueClassifier); @Test public void sum_new_maintainability_effort_of_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); DefaultIssue unresolved1 = newCodeSmellIssue(10L); DefaultIssue old1 = oldCodeSmellIssue(100L); DefaultIssue unresolved2 = newCodeSmellIssue(30L); DefaultIssue old2 = oldCodeSmellIssue(300L); DefaultIssue unresolvedWithoutDebt = newCodeSmellIssueWithoutEffort(); DefaultIssue resolved = newCodeSmellIssue(50L).setResolution(RESOLUTION_FIXED); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved1); underTest.onIssue(FILE, old1); underTest.onIssue(FILE, unresolved2); underTest.onIssue(FILE, old2); underTest.onIssue(FILE, unresolvedWithoutDebt); underTest.onIssue(FILE, resolved); underTest.afterComponent(FILE); assertValue(FILE, NEW_TECHNICAL_DEBT_KEY, 10 + 30); } @Test public void new_maintainability_effort_is_only_computed_using_code_smell_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); DefaultIssue codeSmellIssue = newCodeSmellIssue(10); DefaultIssue oldSmellIssue = oldCodeSmellIssue(100); // Issues of type BUG and VULNERABILITY should be ignored DefaultIssue bugIssue = newBugIssue(15); DefaultIssue oldBugIssue = oldBugIssue(150); DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(12); DefaultIssue oldVulnerabilityIssue = oldVulnerabilityIssue(120); underTest.beforeComponent(FILE); underTest.onIssue(FILE, codeSmellIssue); underTest.onIssue(FILE, oldSmellIssue); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, oldBugIssue); underTest.onIssue(FILE, vulnerabilityIssue); underTest.onIssue(FILE, oldVulnerabilityIssue); underTest.afterComponent(FILE); // Only effort of CODE SMELL issue is used assertValue(FILE, NEW_TECHNICAL_DEBT_KEY, 10); } @Test public void sum_new_reliability_effort_of_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); DefaultIssue unresolved1 = newBugIssue(10L); DefaultIssue old1 = oldBugIssue(100L); DefaultIssue unresolved2 = newBugIssue(30L); DefaultIssue old2 = oldBugIssue(300L); DefaultIssue unresolvedWithoutDebt = newBugIssueWithoutEffort(); DefaultIssue resolved = newBugIssue(50L).setResolution(RESOLUTION_FIXED); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved1); underTest.onIssue(FILE, old1); underTest.onIssue(FILE, unresolved2); underTest.onIssue(FILE, old2); underTest.onIssue(FILE, unresolvedWithoutDebt); underTest.onIssue(FILE, resolved); underTest.afterComponent(FILE); assertValue(FILE, NEW_RELIABILITY_REMEDIATION_EFFORT_KEY, 10 + 30); } @Test public void new_reliability_effort_is_only_computed_using_bug_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); DefaultIssue bugIssue = newBugIssue(15); DefaultIssue oldBugIssue = oldBugIssue(150); // Issues of type CODE SMELL and VULNERABILITY should be ignored DefaultIssue codeSmellIssue = newCodeSmellIssue(10); DefaultIssue oldCodeSmellIssue = oldCodeSmellIssue(100); DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(12); DefaultIssue oldVulnerabilityIssue = oldVulnerabilityIssue(120); underTest.beforeComponent(FILE); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, oldBugIssue); underTest.onIssue(FILE, codeSmellIssue); underTest.onIssue(FILE, oldCodeSmellIssue); underTest.onIssue(FILE, vulnerabilityIssue); underTest.onIssue(FILE, oldVulnerabilityIssue); underTest.afterComponent(FILE); // Only effort of BUG issue is used assertValue(FILE, NEW_RELIABILITY_REMEDIATION_EFFORT_KEY, 15); } @Test public void sum_new_vulnerability_effort_of_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); DefaultIssue unresolved1 = newVulnerabilityIssue(10L); DefaultIssue old1 = oldVulnerabilityIssue(100L); DefaultIssue unresolved2 = newVulnerabilityIssue(30L); DefaultIssue old2 = oldVulnerabilityIssue(300L); DefaultIssue unresolvedWithoutDebt = newVulnerabilityIssueWithoutEffort(); DefaultIssue resolved = newVulnerabilityIssue(50L).setResolution(RESOLUTION_FIXED); DefaultIssue oldResolved = oldVulnerabilityIssue(500L).setResolution(RESOLUTION_FIXED); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved1); underTest.onIssue(FILE, old1); underTest.onIssue(FILE, unresolved2); underTest.onIssue(FILE, old2); underTest.onIssue(FILE, unresolvedWithoutDebt); underTest.onIssue(FILE, resolved); underTest.onIssue(FILE, oldResolved); underTest.afterComponent(FILE); assertValue(FILE, NEW_SECURITY_REMEDIATION_EFFORT_KEY, 10 + 30); } @Test public void new_security_effort_is_only_computed_using_vulnerability_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(12); DefaultIssue oldVulnerabilityIssue = oldVulnerabilityIssue(120); // Issues of type CODE SMELL and BUG should be ignored DefaultIssue codeSmellIssue = newCodeSmellIssue(10); DefaultIssue oldCodeSmellIssue = oldCodeSmellIssue(100); DefaultIssue bugIssue = newBugIssue(15); DefaultIssue oldBugIssue = oldBugIssue(150); underTest.beforeComponent(FILE); underTest.onIssue(FILE, codeSmellIssue); underTest.onIssue(FILE, oldCodeSmellIssue); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, oldBugIssue); underTest.onIssue(FILE, vulnerabilityIssue); underTest.onIssue(FILE, oldVulnerabilityIssue); underTest.afterComponent(FILE); // Only effort of VULNERABILITY issue is used assertValue(FILE, NEW_SECURITY_REMEDIATION_EFFORT_KEY, 12); } @Test public void aggregate_new_characteristic_measures_of_children() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); DefaultIssue codeSmellIssue = newCodeSmellIssue(10); DefaultIssue oldCodeSmellIssue = oldCodeSmellIssue(100); DefaultIssue bugIssue = newBugIssue(8); DefaultIssue oldBugIssue = oldBugIssue(80); DefaultIssue vulnerabilityIssue = newVulnerabilityIssue(12); DefaultIssue oldVulnerabilityIssue = oldVulnerabilityIssue(120); DefaultIssue codeSmellProjectIssue = newCodeSmellIssue(30); DefaultIssue oldCodeSmellProjectIssue = oldCodeSmellIssue(300); DefaultIssue bugProjectIssue = newBugIssue(28); DefaultIssue oldBugProjectIssue = oldBugIssue(280); DefaultIssue vulnerabilityProjectIssue = newVulnerabilityIssue(32); DefaultIssue oldVulnerabilityProjectIssue = oldVulnerabilityIssue(320); underTest.beforeComponent(FILE); underTest.onIssue(FILE, codeSmellIssue); underTest.onIssue(FILE, oldCodeSmellIssue); underTest.onIssue(FILE, bugIssue); underTest.onIssue(FILE, oldBugIssue); underTest.onIssue(FILE, vulnerabilityIssue); underTest.onIssue(FILE, oldVulnerabilityIssue); underTest.afterComponent(FILE); underTest.beforeComponent(PROJECT); underTest.onIssue(PROJECT, codeSmellProjectIssue); underTest.onIssue(PROJECT, oldCodeSmellProjectIssue); underTest.onIssue(PROJECT, bugProjectIssue); underTest.onIssue(PROJECT, oldBugProjectIssue); underTest.onIssue(PROJECT, vulnerabilityProjectIssue); underTest.onIssue(PROJECT, oldVulnerabilityProjectIssue); underTest.afterComponent(PROJECT); assertValue(PROJECT, NEW_TECHNICAL_DEBT_KEY, 10 + 30); assertValue(PROJECT, NEW_RELIABILITY_REMEDIATION_EFFORT_KEY, 8 + 28); assertValue(PROJECT, NEW_SECURITY_REMEDIATION_EFFORT_KEY, 12 + 32); } @Test public void no_measures_if_no_periods() { when(newIssueClassifier.isEnabled()).thenReturn(false); Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.BRANCH); periodsHolder.setPeriod(null); DefaultIssue unresolved = newCodeSmellIssue(10); underTest.beforeComponent(FILE); underTest.onIssue(FILE, unresolved); underTest.afterComponent(FILE); assertThat(measureRepository.getRawMeasures(FILE)).isEmpty(); } @Test public void should_have_empty_measures_if_no_issues() { when(newIssueClassifier.isEnabled()).thenReturn(true); when(newIssueClassifier.isNew(any(), any())).thenReturn(true); underTest.beforeComponent(FILE); underTest.afterComponent(FILE); assertValue(FILE, NEW_TECHNICAL_DEBT_KEY, 0); assertValue(FILE, NEW_RELIABILITY_REMEDIATION_EFFORT_KEY, 0); assertValue(FILE, NEW_SECURITY_REMEDIATION_EFFORT_KEY, 0); } private void assertValue(Component component, String metricKey, int value) { Measure newMeasure = measureRepository.getRawMeasure(component, metricRepository.getByKey(metricKey)).get(); assertThat(newMeasure.getLongValue()).isEqualTo(value); } private DefaultIssue newCodeSmellIssue(long effort) { return createIssue(CODE_SMELL, effort, true); } private DefaultIssue oldCodeSmellIssue(long effort) { return createIssue(CODE_SMELL, effort, false); } private DefaultIssue newBugIssue(long effort) { return createIssue(BUG, effort, true); } private DefaultIssue oldBugIssue(long effort) { return createIssue(BUG, effort, false); } private DefaultIssue newVulnerabilityIssue(long effort) { return createIssue(VULNERABILITY, effort, true); } private DefaultIssue oldVulnerabilityIssue(long effort) { return createIssue(VULNERABILITY, effort, false); } private DefaultIssue newCodeSmellIssueWithoutEffort() { DefaultIssue defaultIssue = new DefaultIssue() .setKey(UuidFactoryFast.getInstance().create()) .setType(CODE_SMELL); when(newIssueClassifier.isNew(any(), eq(defaultIssue))).thenReturn(true); return defaultIssue; } private DefaultIssue createIssue(RuleType type, long effort, boolean isNew) { DefaultIssue defaultIssue = new DefaultIssue() .setKey(UuidFactoryFast.getInstance().create()) .setEffort(Duration.create(effort)) .setType(type); when(newIssueClassifier.isNew(any(), eq(defaultIssue))).thenReturn(isNew); return defaultIssue; } private static DefaultIssue newBugIssueWithoutEffort() { return new DefaultIssue().setType(BUG); } private static DefaultIssue newVulnerabilityIssueWithoutEffort() { return new DefaultIssue().setType(VULNERABILITY); } }
14,204
41.151335
129
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/NewIssueClassifierTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Date; import java.util.Optional; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.period.Period; import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule; import org.sonar.ce.task.projectanalysis.source.NewLinesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.component.BranchType; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class NewIssueClassifierTest { @Rule public PeriodHolderRule periodHolder = new PeriodHolderRule(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private final NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private final NewIssueClassifier newIssueClassifier = new NewIssueClassifier(newLinesRepository, periodHolder, analysisMetadataHolder); @Test public void isEnabled_returns_false() { periodHolder.setPeriod(null); assertThat(newIssueClassifier.isEnabled()).isFalse(); } @Test public void isEnabled_returns_true_when_pull_request() { periodHolder.setPeriod(null); analysisMetadataHolder.setBranch(newPr()); assertThat(newIssueClassifier.isEnabled()).isTrue(); } @Test public void isEnabled_returns_true_when_periodDate_present() { periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", 1000L)); assertThat(newIssueClassifier.isEnabled()).isTrue(); } @Test public void isEnabled_returns_true_when_reference_period_present() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null)); assertThat(newIssueClassifier.isEnabled()).isTrue(); } @Test public void isNew_returns_true_for_any_issue_if_pull_request() { periodHolder.setPeriod(null); analysisMetadataHolder.setBranch(newPr()); assertThat(newIssueClassifier.isNew(mock(Component.class), mock(DefaultIssue.class))).isTrue(); } @Test public void isNew_returns_true_if_issue_is_on_period() { periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", 1000L)); DefaultIssue issue = mock(DefaultIssue.class); when(issue.creationDate()).thenReturn(new Date(2000L)); assertThat(newIssueClassifier.isNew(mock(Component.class), issue)).isTrue(); verify(issue).creationDate(); verifyNoMoreInteractions(issue); } @Test public void isNew_returns_true_for_issue_located_on_changed_lines() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null)); Component file = mock(Component.class); DefaultIssue issue = mock(DefaultIssue.class); when(file.getType()).thenReturn(Component.Type.FILE); when(file.getUuid()).thenReturn("fileUuid"); when(newLinesRepository.getNewLines(file)).thenReturn(Optional.of(Set.of(2, 3))); when(issue.getLocations()).thenReturn(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(2) .setStartOffset(1) .setEndLine(2) .setEndOffset(2) .build()) .build()); assertThat(newIssueClassifier.isNew(file, issue)).isTrue(); assertThat(newIssueClassifier.isOnBranchUsingReferenceBranch()).isTrue(); assertThat(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(file, issue)).isTrue(); } @Test public void isNew_returns_false_for_issue_not_located_on_changed_lines() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null)); Component file = mock(Component.class); DefaultIssue issue = mock(DefaultIssue.class); when(file.getType()).thenReturn(Component.Type.FILE); when(file.getUuid()).thenReturn("fileUuid"); when(newLinesRepository.getNewLines(file)).thenReturn(Optional.of(Set.of(2, 3))); when(issue.getLocations()).thenReturn(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(10) .setStartOffset(1) .setEndLine(10) .setEndOffset(2) .build()) .build()); assertThat(newIssueClassifier.isNew(file, issue)).isFalse(); assertThat(newIssueClassifier.isOnBranchUsingReferenceBranch()).isTrue(); assertThat(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(file, issue)).isFalse(); } @Test public void isNew_returns_false_for_issue_which_was_new_but_it_is_not_located_on_changed_lines_anymore() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null)); Component file = mock(Component.class); DefaultIssue issue = mock(DefaultIssue.class); when(file.getType()).thenReturn(Component.Type.FILE); when(file.getUuid()).thenReturn("fileUuid"); when(newLinesRepository.getNewLines(file)).thenReturn(Optional.of(Set.of(2, 3))); when(issue.getLocations()).thenReturn(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(10) .setStartOffset(1) .setEndLine(10) .setEndOffset(2) .build()) .build()); when(issue.isNewCodeReferenceIssue()).thenReturn(true); assertThat(newIssueClassifier.isNew(file, issue)).isFalse(); assertThat(newIssueClassifier.isOnBranchUsingReferenceBranch()).isTrue(); assertThat(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(file, issue)).isFalse(); } @Test public void isNew_returns_true_for_issue_which_was_new_and_is_still_located_on_changed_lines() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null)); Component file = mock(Component.class); DefaultIssue issue = mock(DefaultIssue.class); when(file.getType()).thenReturn(Component.Type.FILE); when(file.getUuid()).thenReturn("fileUuid"); when(newLinesRepository.getNewLines(file)).thenReturn(Optional.of(Set.of(2, 3))); when(issue.getLocations()).thenReturn(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(2) .setStartOffset(1) .setEndLine(2) .setEndOffset(2) .build()) .build()); when(issue.isNewCodeReferenceIssue()).thenReturn(true); assertThat(newIssueClassifier.isNew(file, issue)).isTrue(); assertThat(newIssueClassifier.isOnBranchUsingReferenceBranch()).isTrue(); assertThat(newIssueClassifier.hasAtLeastOneLocationOnChangedLines(file, issue)).isTrue(); } @Test public void isNew_returns_false_if_issue_is_not_on_period() { periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", 1000L)); DefaultIssue issue = mock(DefaultIssue.class); when(issue.creationDate()).thenReturn(new Date(500L)); assertThat(newIssueClassifier.isNew(mock(Component.class), issue)).isFalse(); verify(issue).creationDate(); verifyNoMoreInteractions(issue); } @Test public void isNew_returns_false_if_period_without_date() { periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", null)); assertThat(newIssueClassifier.isNew(mock(Component.class), mock(DefaultIssue.class))).isFalse(); } private Branch newPr() { Branch nonMainBranch = mock(Branch.class); when(nonMainBranch.isMain()).thenReturn(false); when(nonMainBranch.getType()).thenReturn(BranchType.PULL_REQUEST); return nonMainBranch; } }
8,835
42.313725
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/PullRequestSourceBranchMergerTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Date; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.BlockHashSequence; import org.sonar.core.issue.tracking.Input; import org.sonar.core.issue.tracking.LineHashSequence; import org.sonar.core.issue.tracking.NonClosedTracking; import org.sonar.core.issue.tracking.Tracker; import org.sonar.db.DbTester; import org.sonar.db.component.BranchType; import org.sonar.db.component.ComponentDto; import org.sonar.db.rule.RuleDto; import static java.util.Collections.singletonList; import static java.util.Collections.singletonMap; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.db.component.ComponentTesting.newFileDto; public class PullRequestSourceBranchMergerTest { private static final String PROJECT_KEY = "project"; private static final String PROJECT_UUID = "projectUuid"; private static final int FILE_1_REF = 12341; private static final String FILE_1_KEY = "fileKey"; private static final String FILE_1_UUID = "fileUuid"; private static final org.sonar.ce.task.projectanalysis.component.Component FILE_1 = builder( org.sonar.ce.task.projectanalysis.component.Component.Type.FILE, FILE_1_REF) .setKey(FILE_1_KEY) .setUuid(FILE_1_UUID) .build(); @Mock private Tracker<DefaultIssue, DefaultIssue> tracker; @Mock private IssueLifecycle issueLifecycle; @Mock private TrackerSourceBranchInputFactory sourceBranchInputFactory; @Mock private NonClosedTracking<DefaultIssue, DefaultIssue> prTracking; @Rule public DbTester db = DbTester.create(); private PullRequestSourceBranchMerger underTest; private RuleDto rule; private DefaultIssue rawIssue; private Input<DefaultIssue> rawIssuesInput; @Before public void setUp() { MockitoAnnotations.initMocks(this); underTest = new PullRequestSourceBranchMerger( tracker, issueLifecycle, sourceBranchInputFactory); ComponentDto projectDto = db.components().insertPublicProject(p -> p.setKey(PROJECT_KEY).setUuid(PROJECT_UUID).setBranchUuid(PROJECT_UUID)).getMainBranchComponent(); ComponentDto branch1Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch1") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(projectDto.uuid())); ComponentDto branch2Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch2") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(projectDto.uuid())); ComponentDto branch3Dto = db.components().insertProjectBranch(projectDto, b -> b.setKey("myBranch3") .setBranchType(BranchType.PULL_REQUEST) .setMergeBranchUuid(projectDto.uuid())); db.components().insertComponent(newFileDto(branch1Dto, projectDto.uuid()).setKey(FILE_1_KEY + ":PULL_REQUEST:myBranch1")); db.components().insertComponent(newFileDto(branch2Dto, projectDto.uuid()).setKey(FILE_1_KEY + ":PULL_REQUEST:myBranch2")); db.components().insertComponent(newFileDto(branch3Dto, projectDto.uuid()).setKey(FILE_1_KEY + ":PULL_REQUEST:myBranch3")); rule = db.rules().insert(); rawIssue = createIssue("issue1", rule.getKey(), Issue.STATUS_OPEN, new Date()); rawIssuesInput = new DefaultTrackingInput(singletonList(rawIssue), mock(LineHashSequence.class), mock(BlockHashSequence.class)); } @Test public void tryMergeIssuesFromSourceBranchOfPullRequest_does_nothing_if_source_branch_was_not_analyzed() { when(sourceBranchInputFactory.hasSourceBranchAnalysis()).thenReturn(false); underTest.tryMergeIssuesFromSourceBranchOfPullRequest(FILE_1, rawIssuesInput.getIssues(), rawIssuesInput); verifyNoInteractions(issueLifecycle); } @Test public void tryMergeIssuesFromSourceBranchOfPullRequest_merges_issue_state_from_source_branch_into_pull_request() { DefaultIssue sourceBranchIssue = createIssue("issue2", rule.getKey(), Issue.STATUS_CONFIRMED, new Date()); Input<DefaultIssue> sourceBranchInput = new DefaultTrackingInput(singletonList(sourceBranchIssue), mock(LineHashSequence.class), mock(BlockHashSequence.class)); when(sourceBranchInputFactory.hasSourceBranchAnalysis()).thenReturn(true); when(sourceBranchInputFactory.createForSourceBranch(any())).thenReturn(sourceBranchInput); when(tracker.trackNonClosed(any(), any())).thenReturn(prTracking); when(prTracking.getMatchedRaws()).thenReturn(singletonMap(rawIssue, sourceBranchIssue)); underTest.tryMergeIssuesFromSourceBranchOfPullRequest(FILE_1, rawIssuesInput.getIssues(), rawIssuesInput); verify(issueLifecycle).copyExistingIssueFromSourceBranchToPullRequest(rawIssue, sourceBranchIssue); } private static DefaultIssue createIssue(String key, RuleKey ruleKey, String status, Date creationDate) { DefaultIssue issue = new DefaultIssue(); issue.setKey(key); issue.setRuleKey(ruleKey); issue.setMessage("msg"); issue.setLine(1); issue.setStatus(status); issue.setResolution(null); issue.setCreationDate(creationDate); issue.setChecksum("checksum"); return issue; } }
6,420
43.282759
169
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/PullRequestTrackerExecutionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.source.NewLinesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.BlockHashSequence; import org.sonar.core.issue.tracking.Input; import org.sonar.core.issue.tracking.LineHashSequence; import org.sonar.core.issue.tracking.Tracker; import org.sonar.core.issue.tracking.Tracking; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleTesting; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class PullRequestTrackerExecutionTest { private static final String FILE_UUID = "FILE_UUID"; private static final String FILE_KEY = "FILE_KEY"; private static final int FILE_REF = 2; private static final Component FILE = builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build(); private final TrackerBaseInputFactory baseFactory = mock(TrackerBaseInputFactory.class); private final NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private final List<DefaultIssue> rawIssues = new ArrayList<>(); private final List<DefaultIssue> baseIssues = new ArrayList<>(); private final List<DefaultIssue> targetIssues = new ArrayList<>(); private PullRequestTrackerExecution underTest; private TrackerTargetBranchInputFactory targetFactory = mock(TrackerTargetBranchInputFactory.class); @Before public void setUp() { when(baseFactory.create(FILE)).thenReturn(createInput(baseIssues)); when(targetFactory.createForTargetBranch(FILE)).thenReturn(createInput(targetIssues)); Tracker<DefaultIssue, DefaultIssue> tracker = new Tracker<>(); underTest = new PullRequestTrackerExecution(baseFactory, targetFactory, tracker, newLinesRepository); } @Test public void simple_tracking_keep_only_issues_having_location_on_changed_lines() { final DefaultIssue issue1 = createIssue(2, 3, RuleTesting.XOO_X1); rawIssues.add(issue1); rawIssues.add(createIssue(2, RuleTesting.XOO_X1)); when(newLinesRepository.getNewLines(FILE)).thenReturn(Optional.of(new HashSet<>(Arrays.asList(1, 3)))); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(FILE, createInput(rawIssues)); assertThat(tracking.getUnmatchedBases()).isEmpty(); assertThat(tracking.getMatchedRaws()).isEmpty(); assertThat(tracking.getUnmatchedRaws()).containsOnly(issue1); } @Test public void simple_tracking_keep_also_issues_having_secondary_locations_on_changed_lines() { final DefaultIssue issueWithSecondaryLocationOnAChangedLine = createIssue(2, RuleTesting.XOO_X1); issueWithSecondaryLocationOnAChangedLine.setLocations(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(2).setEndLine(3)) .addFlow(DbIssues.Flow.newBuilder().addLocation(DbIssues.Location.newBuilder() .setComponentId(FILE.getUuid()) .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(6).setEndLine(8)).build()).build()) .build()); rawIssues.add(issueWithSecondaryLocationOnAChangedLine); final DefaultIssue issueWithNoLocationsOnChangedLines = createIssue(2, RuleTesting.XOO_X1); issueWithNoLocationsOnChangedLines.setLocations(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(2).setEndLine(2)) .addFlow(DbIssues.Flow.newBuilder().addLocation(DbIssues.Location.newBuilder() .setComponentId(FILE.getUuid()) .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(11).setEndLine(12)).build()).build()) .build()); rawIssues.add(issueWithNoLocationsOnChangedLines); final DefaultIssue issueWithALocationOnADifferentFile = createIssue(2, RuleTesting.XOO_X1); issueWithALocationOnADifferentFile.setLocations(DbIssues.Locations.newBuilder() .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(2).setEndLine(3)) .addFlow(DbIssues.Flow.newBuilder().addLocation(DbIssues.Location.newBuilder() .setComponentId("anotherUuid") .setTextRange(DbCommons.TextRange.newBuilder().setStartLine(6).setEndLine(8)).build()).build()) .build()); rawIssues.add(issueWithALocationOnADifferentFile); when(newLinesRepository.getNewLines(FILE)).thenReturn(Optional.of(new HashSet<>(Arrays.asList(7, 10)))); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(FILE, createInput(rawIssues)); assertThat(tracking.getUnmatchedBases()).isEmpty(); assertThat(tracking.getMatchedRaws()).isEmpty(); assertThat(tracking.getUnmatchedRaws()).containsOnly(issueWithSecondaryLocationOnAChangedLine); } @Test public void track_and_ignore_resolved_issues_from_target_branch() { when(newLinesRepository.getNewLines(FILE)).thenReturn(Optional.of(new HashSet<>(Arrays.asList(1, 2, 3)))); rawIssues.add(createIssue(1, RuleTesting.XOO_X1)); rawIssues.add(createIssue(2, RuleTesting.XOO_X2)); rawIssues.add(createIssue(3, RuleTesting.XOO_X3)); when(targetFactory.hasTargetBranchAnalysis()).thenReturn(true); DefaultIssue resolvedIssue = createIssue(1, RuleTesting.XOO_X1).setStatus(Issue.STATUS_RESOLVED).setResolution(Issue.RESOLUTION_FALSE_POSITIVE); // will cause rawIssue0 to be ignored targetIssues.add(resolvedIssue); // not ignored since it's not resolved targetIssues.add(rawIssues.get(1)); baseIssues.add(rawIssues.get(0)); // should be matched baseIssues.add(rawIssues.get(1)); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(FILE, createInput(rawIssues)); assertThat(tracking.getMatchedRaws()).isEqualTo(Collections.singletonMap(rawIssues.get(1), rawIssues.get(1))); assertThat(tracking.getUnmatchedRaws()).containsOnly(rawIssues.get(2)); } @Test public void track_and_ignore_issues_from_previous_analysis() { when(newLinesRepository.getNewLines(FILE)).thenReturn(Optional.of(new HashSet<>(Arrays.asList(1, 2, 3)))); rawIssues.add(createIssue(1, RuleTesting.XOO_X1)); rawIssues.add(createIssue(2, RuleTesting.XOO_X2)); rawIssues.add(createIssue(3, RuleTesting.XOO_X3)); baseIssues.add(rawIssues.get(0)); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(FILE, createInput(rawIssues)); assertThat(tracking.getMatchedRaws()).isEqualTo(Collections.singletonMap(rawIssues.get(0), rawIssues.get(0))); assertThat(tracking.getUnmatchedRaws()).containsOnly(rawIssues.get(2)); } private DefaultIssue createIssue(int line, RuleKey ruleKey) { return createIssue(line, line, ruleKey); } private DefaultIssue createIssue(int startLine, int endLine, RuleKey ruleKey) { return new DefaultIssue() .setRuleKey(ruleKey) .setLine(startLine) .setLocations(DbIssues.Locations.newBuilder().setTextRange(DbCommons.TextRange.newBuilder().setStartLine(startLine).setEndLine(endLine)).build()) .setMessage("msg" + startLine); } private static Input<DefaultIssue> createInput(Collection<DefaultIssue> issues) { return new Input<DefaultIssue>() { @Override public LineHashSequence getLineHashSequence() { return LineHashSequence.createForLines(Arrays.asList("line1", "line2", "line3")); } @Override public BlockHashSequence getBlockHashSequence() { return BlockHashSequence.create(getLineHashSequence()); } @Override public Collection<DefaultIssue> getIssues() { return issues; } }; } }
8,924
43.849246
151
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/ReferenceBranchTrackerExecutionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Before; import org.junit.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.core.issue.tracking.NonClosedTracking; import org.sonar.core.issue.tracking.Tracker; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ReferenceBranchTrackerExecutionTest { @Mock private TrackerReferenceBranchInputFactory mergeInputFactory; @Mock private Tracker<DefaultIssue, DefaultIssue> tracker; @Mock private Component component; private ReferenceBranchTrackerExecution underTest; @Before public void before() { MockitoAnnotations.initMocks(this); underTest = new ReferenceBranchTrackerExecution(mergeInputFactory, tracker); } @Test public void testTracking() { Input<DefaultIssue> rawInput = mock(Input.class); Input<DefaultIssue> mergeInput = mock(Input.class); NonClosedTracking<DefaultIssue, DefaultIssue> result = mock(NonClosedTracking.class); when(mergeInputFactory.create(component)).thenReturn(mergeInput); when(tracker.trackNonClosed(rawInput, mergeInput)).thenReturn(result); assertThat(underTest.track(component, rawInput)).isEqualTo(result); } }
2,299
35.507937
89
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RemoveProcessedComponentsVisitorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository.OriginalFile; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class RemoveProcessedComponentsVisitorTest { private static final String UUID = "uuid"; private ComponentsWithUnprocessedIssues componentsWithUnprocessedIssues = mock(ComponentsWithUnprocessedIssues.class); private MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class); private Component component = mock(Component.class); private RemoveProcessedComponentsVisitor underTest = new RemoveProcessedComponentsVisitor(componentsWithUnprocessedIssues, movedFilesRepository); @Before public void setUp() { when(component.getUuid()).thenReturn(UUID); } @Test public void remove_processed_files() { when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty()); underTest.afterComponent(component); verify(movedFilesRepository).getOriginalFile(component); verify(componentsWithUnprocessedIssues).remove(UUID); verifyNoMoreInteractions(componentsWithUnprocessedIssues); } @Test public void also_remove_moved_files() { String uuid2 = "uuid2"; OriginalFile movedFile = new OriginalFile(uuid2, "key"); when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.of(movedFile)); underTest.afterComponent(component); verify(movedFilesRepository).getOriginalFile(component); verify(componentsWithUnprocessedIssues).remove(UUID); verify(componentsWithUnprocessedIssues).remove(uuid2); verifyNoMoreInteractions(componentsWithUnprocessedIssues); } }
2,928
39.680556
147
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Optional; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.rule.DeprecatedRuleKeyDto; import org.sonar.db.rule.RuleDao; import org.sonar.db.rule.RuleDto; import org.sonar.scanner.protocol.Constants; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.server.rule.index.RuleIndexer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.mockito.internal.verification.VerificationModeFactory.times; @RunWith(DataProviderRunner.class) public class RuleRepositoryImplTest { private static final RuleDto AB_RULE = createABRuleDto().setUuid("rule-uuid"); private static final RuleKey AB_RULE_DEPRECATED_KEY_1 = RuleKey.of("old_a", "old_b"); private static final RuleKey AB_RULE_DEPRECATED_KEY_2 = RuleKey.of(AB_RULE.getRepositoryKey(), "old_b"); private static final RuleKey DEPRECATED_KEY_OF_NON_EXITING_RULE = RuleKey.of("some_rep", "some_key"); private static final RuleKey AC_RULE_KEY = RuleKey.of("a", "c"); private static final String AC_RULE_UUID = "uuid-684"; @org.junit.Rule public DbTester db = DbTester.create(System2.INSTANCE); private DbClient dbClient = mock(DbClient.class); private DbSession dbSession = mock(DbSession.class); private RuleDao ruleDao = mock(RuleDao.class); private RuleIndexer ruleIndexer = mock(RuleIndexer.class); private AdHocRuleCreator adHocRuleCreator = new AdHocRuleCreator(db.getDbClient(), System2.INSTANCE, ruleIndexer, new SequenceUuidFactory()); private RuleRepositoryImpl underTest = new RuleRepositoryImpl(adHocRuleCreator, dbClient); @Before public void setUp() { when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); when(dbClient.ruleDao()).thenReturn(ruleDao); when(ruleDao.selectAll(any(DbSession.class))).thenReturn(ImmutableList.of(AB_RULE)); DeprecatedRuleKeyDto abDeprecatedRuleKey1 = deprecatedRuleKeyOf(AB_RULE, AB_RULE_DEPRECATED_KEY_1); DeprecatedRuleKeyDto abDeprecatedRuleKey2 = deprecatedRuleKeyOf(AB_RULE, AB_RULE_DEPRECATED_KEY_2); DeprecatedRuleKeyDto deprecatedRuleOfNonExistingRule = deprecatedRuleKeyOf("unknown-rule-uuid", DEPRECATED_KEY_OF_NON_EXITING_RULE); when(ruleDao.selectAllDeprecatedRuleKeys(any(DbSession.class))).thenReturn(ImmutableSet.of( abDeprecatedRuleKey1, abDeprecatedRuleKey2, deprecatedRuleOfNonExistingRule)); } private static DeprecatedRuleKeyDto deprecatedRuleKeyOf(RuleDto ruleDto, RuleKey deprecatedRuleKey) { return deprecatedRuleKeyOf(ruleDto.getUuid(), deprecatedRuleKey); } private static DeprecatedRuleKeyDto deprecatedRuleKeyOf(String ruleUuid, RuleKey deprecatedRuleKey) { return new DeprecatedRuleKeyDto().setRuleUuid(ruleUuid) .setOldRepositoryKey(deprecatedRuleKey.repository()) .setOldRuleKey(deprecatedRuleKey.rule()); } @Test public void constructor_does_not_query_DB_to_retrieve_rules() { verifyNoMoreInteractions(dbClient); } @Test public void first_call_to_getByKey_triggers_call_to_db_and_any_subsequent_get_or_find_call_does_not() { underTest.getByKey(AB_RULE.getKey()); verify(ruleDao, times(1)).selectAll(any(DbSession.class)); verifyNoMethodCallTriggersCallToDB(); } @Test public void first_call_to_findByKey_triggers_call_to_db_and_any_subsequent_get_or_find_call_does_not() { underTest.findByKey(AB_RULE.getKey()); verify(ruleDao, times(1)).selectAll(any(DbSession.class)); verifyNoMethodCallTriggersCallToDB(); } @Test public void first_call_to_getById_triggers_call_to_db_and_any_subsequent_get_or_find_call_does_not() { underTest.getByUuid(AB_RULE.getUuid()); verify(ruleDao, times(1)).selectAll(any(DbSession.class)); verifyNoMethodCallTriggersCallToDB(); } @Test public void first_call_to_findById_triggers_call_to_db_and_any_subsequent_get_or_find_call_does_not() { underTest.findByUuid(AB_RULE.getUuid()); verify(ruleDao, times(1)).selectAll(any(DbSession.class)); verifyNoMethodCallTriggersCallToDB(); } @Test public void getByKey_throws_NPE_if_key_argument_is_null() { expectNullRuleKeyNPE(() -> underTest.getByKey(null)); } @Test public void getByKey_does_not_call_DB_if_key_argument_is_null() { try { underTest.getByKey(null); } catch (NullPointerException e) { assertNoCallToDb(); } } @Test public void getByKey_returns_Rule_if_it_exists_in_DB() { Rule rule = underTest.getByKey(AB_RULE.getKey()); assertIsABRule(rule); } @Test public void getByKey_returns_Rule_if_argument_is_deprecated_key_in_DB_of_rule_in_DB() { Rule rule = underTest.getByKey(AB_RULE_DEPRECATED_KEY_1); assertIsABRule(rule); } @Test public void getByKey_throws_IAE_if_rules_does_not_exist_in_DB() { expectIAERuleNotFound(() -> underTest.getByKey(AC_RULE_KEY), AC_RULE_KEY); } @Test public void getByKey_throws_IAE_if_argument_is_deprecated_key_in_DB_of_non_existing_rule() { expectIAERuleNotFound(() -> underTest.getByKey(DEPRECATED_KEY_OF_NON_EXITING_RULE), DEPRECATED_KEY_OF_NON_EXITING_RULE); } private void expectIAERuleNotFound(ThrowingCallable callback, RuleKey ruleKey) { assertThatThrownBy(callback) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Can not find rule for key " + ruleKey.toString() + ". This rule does not exist in DB"); } @Test public void findByKey_throws_NPE_if_key_argument_is_null() { expectNullRuleKeyNPE(() -> underTest.findByKey(null)); } @Test public void findByKey_does_not_call_DB_if_key_argument_is_null() { try { underTest.findByKey(null); } catch (NullPointerException e) { assertNoCallToDb(); } } @Test public void findByKey_returns_absent_if_rule_does_not_exist_in_DB() { Optional<Rule> rule = underTest.findByKey(AC_RULE_KEY); assertThat(rule).isEmpty(); } @Test public void findByKey_returns_Rule_if_it_exists_in_DB() { Optional<Rule> rule = underTest.findByKey(AB_RULE.getKey()); assertIsABRule(rule.get()); } @Test public void findByKey_returns_Rule_if_argument_is_deprecated_key_in_DB_of_rule_in_DB() { Optional<Rule> rule = underTest.findByKey(AB_RULE_DEPRECATED_KEY_1); assertIsABRule(rule.get()); } @Test public void findByKey_returns_empty_if_argument_is_deprecated_key_in_DB_of_rule_in_DB() { Optional<Rule> rule = underTest.findByKey(DEPRECATED_KEY_OF_NON_EXITING_RULE); assertThat(rule).isEmpty(); } @Test public void getByUuid_returns_Rule_if_it_exists_in_DB() { Rule rule = underTest.getByUuid(AB_RULE.getUuid()); assertIsABRule(rule); } @Test public void getByUuid_throws_IAE_if_rules_does_not_exist_in_DB() { assertThatThrownBy(() -> underTest.getByUuid(AC_RULE_UUID)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Can not find rule for uuid " + AC_RULE_UUID + ". This rule does not exist in DB"); } @Test public void findByUuid_returns_absent_if_rule_does_not_exist_in_DB() { Optional<Rule> rule = underTest.findByUuid(AC_RULE_UUID); assertThat(rule).isEmpty(); } @Test public void findByUuid_returns_Rule_if_it_exists_in_DB() { Optional<Rule> rule = underTest.findByUuid(AB_RULE.getUuid()); assertIsABRule(rule.get()); } @Test public void accept_new_externally_defined_Rules() { RuleKey ruleKey = RuleKey.of("external_eslint", "no-cond-assign"); underTest.addOrUpdateAddHocRuleIfNeeded(ruleKey, () -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build())); assertThat(underTest.getByKey(ruleKey)).isNotNull(); assertThat(underTest.getByKey(ruleKey).getType()).isNull(); RuleDao ruleDao = dbClient.ruleDao(); Optional<RuleDto> ruleDefinitionDto = ruleDao.selectByKey(dbClient.openSession(false), ruleKey); assertThat(ruleDefinitionDto).isNotPresent(); } @Test public void persist_new_externally_defined_Rules() { underTest = new RuleRepositoryImpl(adHocRuleCreator, db.getDbClient()); RuleKey ruleKey = RuleKey.of("external_eslint", "no-cond-assign"); underTest.addOrUpdateAddHocRuleIfNeeded(ruleKey, () -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build())); underTest.saveOrUpdateAddHocRules(db.getSession()); db.commit(); Optional<RuleDto> ruleDefinitionDto = db.getDbClient().ruleDao().selectByKey(db.getSession(), ruleKey); assertThat(ruleDefinitionDto).isPresent(); Rule rule = underTest.getByKey(ruleKey); assertThat(rule).isNotNull(); assertThat(underTest.getByUuid(ruleDefinitionDto.get().getUuid())).isNotNull(); verify(ruleIndexer).commitAndIndex(db.getSession(), ruleDefinitionDto.get().getUuid()); } @DataProvider public static Object[][] typesMapping() { return new Object[][]{ {ScannerReport.IssueType.CODE_SMELL, RuleType.CODE_SMELL}, {ScannerReport.IssueType.BUG, RuleType.BUG}, {ScannerReport.IssueType.VULNERABILITY, RuleType.VULNERABILITY}, {ScannerReport.IssueType.SECURITY_HOTSPOT, RuleType.SECURITY_HOTSPOT} }; } @Test @UseDataProvider("typesMapping") public void addOrUpdateAddHocRuleIfNeeded_whenAdHocRule_shouldReturnRuleWithSameType(ScannerReport.IssueType type, RuleType expectedType) { RuleKey ruleKey = RuleKey.of("any_repo", "any_rule"); ScannerReport.AdHocRule adHocRule = ScannerReport.AdHocRule.newBuilder() .setEngineId("ANY_ENGINE") .setRuleId("any_rule") .setName("ANY_NAME") .setSeverity(Constants.Severity.MAJOR) .setType(type) .build(); underTest.addOrUpdateAddHocRuleIfNeeded(ruleKey, () -> new NewAdHocRule(adHocRule)); Rule rule = underTest.getByKey(ruleKey); assertThat(rule.getType()).isEqualTo(expectedType); } private void expectNullRuleKeyNPE(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(NullPointerException.class) .hasMessage("RuleKey can not be null"); } private void verifyNoMethodCallTriggersCallToDB() { reset(ruleDao); underTest.getByKey(AB_RULE.getKey()); assertNoCallToDb(); reset(ruleDao); underTest.findByKey(AB_RULE.getKey()); assertNoCallToDb(); reset(ruleDao); underTest.getByUuid(AB_RULE.getUuid()); assertNoCallToDb(); reset(ruleDao); underTest.findByUuid(AB_RULE.getUuid()); assertNoCallToDb(); } private void assertNoCallToDb() { verifyNoMoreInteractions(ruleDao); } private void assertIsABRule(Rule rule) { assertThat(rule).isNotNull(); assertThat(rule.getUuid()).isEqualTo(AB_RULE.getUuid()); assertThat(rule.getKey()).isEqualTo(AB_RULE.getKey()); assertThat(rule.getRemediationFunction()).isNull(); assertThat(rule.getStatus()).isEqualTo(RuleStatus.REMOVED); } private static RuleDto createABRuleDto() { RuleKey ruleKey = RuleKey.of("a", "b"); return new RuleDto() .setRepositoryKey(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setStatus(RuleStatus.REMOVED) .setType(RuleType.CODE_SMELL); } }
13,068
35.202216
177
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleRepositoryRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.function.Supplier; import org.junit.rules.ExternalResource; import org.sonar.api.rule.RuleKey; import org.sonar.db.DbSession; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; public class RuleRepositoryRule extends ExternalResource implements RuleRepository { private final Map<RuleKey, Rule> rulesByKey = new HashMap<>(); private final Map<String, Rule> rulesByUuid = new HashMap<>(); private final Map<RuleKey, NewAdHocRule> newExternalRulesById = new HashMap<>(); @Override protected void after() { rulesByKey.clear(); rulesByUuid.clear(); } @Override public Rule getByKey(RuleKey key) { Rule rule = rulesByKey.get(requireNonNull(key)); checkArgument(rule != null); return rule; } @Override public Rule getByUuid(String uuid) { Rule rule = rulesByUuid.get(uuid); checkArgument(rule != null); return rule; } @Override public Optional<Rule> findByKey(RuleKey key) { return Optional.ofNullable(rulesByKey.get(requireNonNull(key))); } @Override public Optional<Rule> findByUuid(String uuid) { return Optional.ofNullable(rulesByUuid.get(uuid)); } @Override public void saveOrUpdateAddHocRules(DbSession dbSession) { throw new UnsupportedOperationException(); } public DumbRule add(RuleKey key) { DumbRule rule = new DumbRule(key); rule.setUuid(key.rule()); rulesByKey.put(key, rule); rulesByUuid.put(rule.getUuid(), rule); return rule; } public RuleRepositoryRule add(DumbRule rule) { rulesByKey.put(requireNonNull(rule.getKey()), rule); rulesByUuid.put(rule.getUuid(), rule); return this; } @Override public void addOrUpdateAddHocRuleIfNeeded(RuleKey ruleKey, Supplier<NewAdHocRule> ruleSupplier) { newExternalRulesById.computeIfAbsent(ruleKey, k -> ruleSupplier.get()); } }
2,873
29.574468
99
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/RuleTagsCopierTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import com.google.common.collect.Sets; import java.util.Collections; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.sonar.db.rule.RuleTesting.XOO_X1; import static org.sonar.db.rule.RuleTesting.XOO_X2; public class RuleTagsCopierTest { DumbRule rule = new DumbRule(XOO_X1); DumbRule externalRule = new DumbRule(XOO_X2).setIsExternal(true); @org.junit.Rule public RuleRepositoryRule ruleRepository = new RuleRepositoryRule().add(rule).add(externalRule); DefaultIssue issue = new DefaultIssue().setRuleKey(rule.getKey()); DefaultIssue externalIssue = new DefaultIssue().setRuleKey(externalRule.getKey()); RuleTagsCopier underTest = new RuleTagsCopier(ruleRepository); @Test public void copy_tags_if_new_issue() { rule.setTags(Sets.newHashSet("bug", "performance")); issue.setNew(true); underTest.onIssue(mock(Component.class), issue); assertThat(issue.tags()).containsExactly("bug", "performance"); } @Test public void copy_tags_if_new_external_issue() { externalRule.setTags(Sets.newHashSet("es_lint", "java")); externalIssue.setNew(true); underTest.onIssue(mock(Component.class), externalIssue); assertThat(externalIssue.tags()).containsExactly("es_lint", "java"); } @Test public void do_not_copy_tags_if_existing_issue() { rule.setTags(Sets.newHashSet("bug", "performance")); issue.setNew(false).setTags(asList("misra")); underTest.onIssue(mock(Component.class), issue); assertThat(issue.tags()).containsExactly("misra"); } @Test public void do_not_copy_tags_if_existing_issue_without_tags() { rule.setTags(Sets.newHashSet("bug", "performance")); issue.setNew(false).setTags(Collections.emptyList()); underTest.onIssue(mock(Component.class), issue); assertThat(issue.tags()).isEmpty(); } }
2,938
33.174419
98
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerBaseInputFactoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.source.FileSourceDao; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class TrackerBaseInputFactoryTest { private static final String FILE_UUID = "uuid"; private static final String DIR_UUID = "dir"; private static final ReportComponent FILE = ReportComponent.builder(Component.Type.FILE, 1).setUuid(FILE_UUID).build(); private static final ReportComponent FOLDER = ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid(DIR_UUID).build(); @org.junit.Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private ComponentIssuesLoader issuesLoader = mock(ComponentIssuesLoader.class); private DbClient dbClient = mock(DbClient.class); private DbSession dbSession = mock(DbSession.class); private FileSourceDao fileSourceDao = mock(FileSourceDao.class); private MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class); private TrackerBaseInputFactory underTest = new TrackerBaseInputFactory(issuesLoader, dbClient, movedFilesRepository); @Before public void setUp() { when(dbClient.openSession(false)).thenReturn(dbSession); when(dbClient.fileSourceDao()).thenReturn(fileSourceDao); when(movedFilesRepository.getOriginalFile(any(Component.class))) .thenReturn(Optional.empty()); } @Test public void create_returns_Input_which_retrieves_lines_hashes_of_specified_file_component_when_it_has_no_original_file() { underTest.create(FILE).getLineHashSequence(); verify(fileSourceDao).selectLineHashes(dbSession, FILE_UUID); } @Test public void create_returns_empty_Input_for_folders() { Input<DefaultIssue> input = underTest.create(FOLDER); assertThat(input.getIssues()).isEmpty(); } @Test public void create_returns_Input_which_retrieves_lines_hashes_of_original_file_of_component_when_it_has_one() { String originalUuid = "original uuid"; when(movedFilesRepository.getOriginalFile(FILE)).thenReturn( Optional.of(new MovedFilesRepository.OriginalFile(originalUuid, "original key"))); underTest.create(FILE).getLineHashSequence(); verify(fileSourceDao).selectLineHashes(dbSession, originalUuid); verify(fileSourceDao, times(0)).selectLineHashes(dbSession, FILE_UUID); } @Test public void create_returns_Input_which_retrieves_issues_of_specified_file_component_when_it_has_no_original_file() { underTest.create(FILE).getIssues(); verify(issuesLoader).loadOpenIssues(FILE_UUID); } @Test public void create_returns_Input_which_retrieves_issues_of_original_file_of_component_when_it_has_one() { String originalUuid = "original uuid"; when(movedFilesRepository.getOriginalFile(FILE)).thenReturn( Optional.of(new MovedFilesRepository.OriginalFile(originalUuid, "original key"))); underTest.create(FILE).getIssues(); verify(issuesLoader).loadOpenIssues(originalUuid); verify(issuesLoader, times(0)).loadOpenIssues(FILE_UUID); } }
4,604
39.394737
127
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerExecutionTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.ArrayList; import java.util.Collections; import java.util.Random; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.sonar.api.issue.Issue; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.core.issue.tracking.NonClosedTracking; import org.sonar.core.issue.tracking.Tracker; import org.sonar.core.issue.tracking.Tracking; import static java.util.stream.Collectors.toSet; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class TrackerExecutionTest { private final TrackerBaseInputFactory baseInputFactory = mock(TrackerBaseInputFactory.class); private final ClosedIssuesInputFactory closedIssuesInputFactory = mock(ClosedIssuesInputFactory.class); private final Tracker<DefaultIssue, DefaultIssue> tracker = mock(Tracker.class); private final ComponentIssuesLoader componentIssuesLoader = mock(ComponentIssuesLoader.class); private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private final TrackerExecution underTest = new TrackerExecution(baseInputFactory, closedIssuesInputFactory, tracker, componentIssuesLoader, analysisMetadataHolder); private final Input<DefaultIssue> rawInput = mock(Input.class); private final Input<DefaultIssue> openIssuesInput = mock(Input.class); private final Input<DefaultIssue> closedIssuesInput = mock(Input.class); private final NonClosedTracking<DefaultIssue, DefaultIssue> nonClosedTracking = mock(NonClosedTracking.class); private final Tracking<DefaultIssue, DefaultIssue> closedTracking = mock(Tracking.class); @Test public void track_tracks_only_nonClosed_issues_if_tracking_returns_complete_from_Tracker() { ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).build(); when(baseInputFactory.create(component)).thenReturn(openIssuesInput); when(closedIssuesInputFactory.create(any())).thenThrow(new IllegalStateException("closedIssuesInputFactory should not be called")); when(nonClosedTracking.isComplete()).thenReturn(true); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false); when(tracker.trackNonClosed(rawInput, openIssuesInput)).thenReturn(nonClosedTracking); when(tracker.trackClosed(any(), any())).thenThrow(new IllegalStateException("trackClosed should not be called")); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(component, rawInput); assertThat(tracking).isSameAs(nonClosedTracking); verify(tracker).trackNonClosed(rawInput, openIssuesInput); verifyNoMoreInteractions(tracker); } @Test public void track_does_not_track_nonClosed_issues_if_tracking_returns_incomplete_but_this_is_first_analysis() { ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).build(); when(baseInputFactory.create(component)).thenReturn(openIssuesInput); when(closedIssuesInputFactory.create(any())).thenThrow(new IllegalStateException("closedIssuesInputFactory should not be called")); when(nonClosedTracking.isComplete()).thenReturn(false); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true); when(tracker.trackNonClosed(rawInput, openIssuesInput)).thenReturn(nonClosedTracking); when(tracker.trackClosed(any(), any())).thenThrow(new IllegalStateException("trackClosed should not be called")); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(component, rawInput); assertThat(tracking).isSameAs(nonClosedTracking); verify(tracker).trackNonClosed(rawInput, openIssuesInput); verifyNoMoreInteractions(tracker); } @Test public void track_tracks_nonClosed_issues_and_then_closedOnes_if_tracking_returns_incomplete() { ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).build(); when(baseInputFactory.create(component)).thenReturn(openIssuesInput); when(closedIssuesInputFactory.create(component)).thenReturn(closedIssuesInput); when(nonClosedTracking.isComplete()).thenReturn(false); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false); when(tracker.trackNonClosed(rawInput, openIssuesInput)).thenReturn(nonClosedTracking); when(tracker.trackClosed(nonClosedTracking, closedIssuesInput)).thenReturn(closedTracking); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(component, rawInput); assertThat(tracking).isSameAs(closedTracking); verify(tracker).trackNonClosed(rawInput, openIssuesInput); verify(tracker).trackClosed(nonClosedTracking, closedIssuesInput); verifyNoMoreInteractions(tracker); } @Test public void track_loadChanges_on_matched_closed_issues() { ReportComponent component = ReportComponent.builder(Component.Type.FILE, 1).build(); when(baseInputFactory.create(component)).thenReturn(openIssuesInput); when(closedIssuesInputFactory.create(component)).thenReturn(closedIssuesInput); when(nonClosedTracking.isComplete()).thenReturn(false); when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false); when(tracker.trackNonClosed(rawInput, openIssuesInput)).thenReturn(nonClosedTracking); when(tracker.trackClosed(nonClosedTracking, closedIssuesInput)).thenReturn(closedTracking); Set<DefaultIssue> mappedClosedIssues = IntStream.range(1, 2 + new Random().nextInt(2)) .mapToObj(i -> new DefaultIssue().setKey("closed" + i).setStatus(Issue.STATUS_CLOSED)) .collect(toSet()); ArrayList<DefaultIssue> mappedBaseIssues = new ArrayList<>(mappedClosedIssues); Issue.STATUSES.stream().filter(t -> !Issue.STATUS_CLOSED.equals(t)).forEach(s -> mappedBaseIssues.add(new DefaultIssue().setKey(s).setStatus(s))); Collections.shuffle(mappedBaseIssues); when(closedTracking.getMatchedRaws()).thenReturn(mappedBaseIssues.stream().collect(Collectors.toMap(i -> new DefaultIssue().setKey("raw_for_" + i.key()), Function.identity()))); Tracking<DefaultIssue, DefaultIssue> tracking = underTest.track(component, rawInput); assertThat(tracking).isSameAs(closedTracking); verify(tracker).trackNonClosed(rawInput, openIssuesInput); verify(tracker).trackClosed(nonClosedTracking, closedIssuesInput); verify(componentIssuesLoader).loadLatestDiffChangesForReopeningOfClosedIssues(mappedClosedIssues); verifyNoMoreInteractions(tracker); } }
7,776
53.384615
181
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/TrackerRawInputFactoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import com.google.common.collect.Iterators; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collection; import java.util.Collections; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.Duration; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.issue.filter.IssueFilter; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderRule; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.tracking.Input; import org.sonar.db.protobuf.DbIssues; import org.sonar.scanner.protocol.Constants; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.FlowType; import org.sonar.scanner.protocol.output.ScannerReport.IssueType; import org.sonar.server.rule.CommonRuleKeys; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW; import static org.sonar.scanner.protocol.output.ScannerReport.MessageFormattingType.CODE; @RunWith(DataProviderRunner.class) public class TrackerRawInputFactoryTest { private static final String FILE_UUID = "fake_uuid"; private static final String ANOTHER_FILE_UUID = "another_fake_uuid"; private static final String EXAMPLE_LINE_OF_CODE_FORMAT = "int example = line + of + code + %d; "; private static final int FILE_REF = 2; private static final int NOT_IN_REPORT_FILE_REF = 3; private static final int ANOTHER_FILE_REF = 4; private static final String TEST_CONTEXT_KEY = "test_context_key"; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public ActiveRulesHolderRule activeRulesHolder = new ActiveRulesHolderRule(); @Rule public RuleRepositoryRule ruleRepository = new RuleRepositoryRule(); private static final ReportComponent FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF).setUuid(FILE_UUID).build(); private static final ReportComponent ANOTHER_FILE = ReportComponent.builder(Component.Type.FILE, ANOTHER_FILE_REF).setUuid(ANOTHER_FILE_UUID).build(); private static final ReportComponent PROJECT = ReportComponent.builder(Component.Type.PROJECT, 1).addChildren(FILE, ANOTHER_FILE).build(); private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class); private final IssueFilter issueFilter = mock(IssueFilter.class); private final TrackerRawInputFactory underTest = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash, issueFilter, ruleRepository, activeRulesHolder); @Before public void before() { when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line")); when(issueFilter.accept(any(), eq(FILE))).thenReturn(true); } @Test public void load_source_hash_sequences() { Input<DefaultIssue> input = underTest.create(FILE); assertThat(input.getLineHashSequence()).isNotNull(); assertThat(input.getLineHashSequence().getHashForLine(1)).isEqualTo("line"); assertThat(input.getLineHashSequence().getHashForLine(2)).isEmpty(); assertThat(input.getLineHashSequence().getHashForLine(3)).isEmpty(); assertThat(input.getBlockHashSequence()).isNotNull(); } @Test public void load_source_hash_sequences_only_on_files() { Input<DefaultIssue> input = underTest.create(PROJECT); assertThat(input.getLineHashSequence()).isNotNull(); assertThat(input.getBlockHashSequence()).isNotNull(); } @Test public void load_issues_from_report() { RuleKey ruleKey = RuleKey.of("java", "S001"); markRuleAsActive(ruleKey); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .addMsgFormatting(ScannerReport.MessageFormatting.newBuilder().setStart(0).setEnd(3).setType(CODE).build()) .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setSeverity(Constants.Severity.BLOCKER) .setGap(3.14) .setQuickFixAvailable(true) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).hasSize(1); DefaultIssue issue = Iterators.getOnlyElement(issues.iterator()); // fields set by analysis report assertThat(issue.ruleKey()).isEqualTo(ruleKey); assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); assertThat(issue.line()).isEqualTo(2); assertThat(issue.gap()).isEqualTo(3.14); assertThat(issue.message()).isEqualTo("the message"); assertThat(issue.isQuickFixAvailable()).isTrue(); // Check message formatting DbIssues.MessageFormattings messageFormattings = Iterators.getOnlyElement(issues.iterator()).getMessageFormattings(); assertThat(messageFormattings.getMessageFormattingCount()).isEqualTo(1); assertThat(messageFormattings.getMessageFormatting(0).getStart()).isZero(); assertThat(messageFormattings.getMessageFormatting(0).getEnd()).isEqualTo(3); assertThat(messageFormattings.getMessageFormatting(0).getType()).isEqualTo(DbIssues.MessageFormattingType.CODE); // fields set by compute engine assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2)); assertThat(issue.tags()).isEmpty(); assertInitializedIssue(issue); assertThat(issue.effort()).isNull(); assertThat(issue.getRuleDescriptionContextKey()).isEmpty(); } @Test public void load_issues_from_report_with_locations() { RuleKey ruleKey = RuleKey.of("java", "S001"); markRuleAsActive(ruleKey); ScannerReport.MessageFormatting messageFormatting = ScannerReport.MessageFormatting.newBuilder().setStart(0).setEnd(4).setType(CODE).build(); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .addFlow(ScannerReport.Flow.newBuilder() .setType(FlowType.DATA) .setDescription("flow1") .addLocation(ScannerReport.IssueLocation.newBuilder().setMsg("loc1").addMsgFormatting(messageFormatting).setComponentRef(1).build()) .addLocation(ScannerReport.IssueLocation.newBuilder().setMsg("loc2").setComponentRef(1).build())) .addFlow(ScannerReport.Flow.newBuilder() .setType(FlowType.EXECUTION) .addLocation(ScannerReport.IssueLocation.newBuilder().setTextRange(newTextRange(2)).setComponentRef(1).build())) .addFlow(ScannerReport.Flow.newBuilder() .addLocation(ScannerReport.IssueLocation.newBuilder().setTextRange(newTextRange(2)).setComponentRef(1).build())) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); DbIssues.Locations locations = Iterators.getOnlyElement(issues.iterator()).getLocations(); assertThat(locations.getFlowCount()).isEqualTo(3); assertThat(locations.getFlow(0).getDescription()).isEqualTo("flow1"); assertThat(locations.getFlow(0).getType()).isEqualTo(DbIssues.FlowType.DATA); assertThat(locations.getFlow(0).getLocationList()).hasSize(2); assertThat(locations.getFlow(0).getLocation(0).getMsg()).isEqualTo("loc1"); assertThat(locations.getFlow(0).getLocation(0).getMsgFormattingCount()).isEqualTo(1); assertThat(locations.getFlow(0).getLocation(0).getMsgFormatting(0)).extracting(m -> m.getStart(), m -> m.getEnd(), m -> m.getType()) .containsExactly(0, 4, DbIssues.MessageFormattingType.CODE); assertThat(locations.getFlow(1).hasDescription()).isFalse(); assertThat(locations.getFlow(1).getType()).isEqualTo(DbIssues.FlowType.EXECUTION); assertThat(locations.getFlow(1).getLocationList()).hasSize(1); assertThat(locations.getFlow(2).hasDescription()).isFalse(); assertThat(locations.getFlow(2).hasType()).isFalse(); assertThat(locations.getFlow(2).getLocationList()).hasSize(1); } @Test public void load_issues_from_report_with_rule_description_context_key() { RuleKey ruleKey = RuleKey.of("java", "S001"); markRuleAsActive(ruleKey); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setRuleDescriptionContextKey(TEST_CONTEXT_KEY) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues) .hasSize(1) .extracting(DefaultIssue::getRuleDescriptionContextKey) .containsOnly(Optional.of(TEST_CONTEXT_KEY)); } @Test public void set_rule_name_as_message_when_issue_message_from_report_is_empty() { RuleKey ruleKey = RuleKey.of("java", "S001"); markRuleAsActive(ruleKey); registerRule(ruleKey, "Rule 1"); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setMsg("") .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).hasSize(1); DefaultIssue issue = Iterators.getOnlyElement(issues.iterator()); // fields set by analysis report assertThat(issue.ruleKey()).isEqualTo(ruleKey); // fields set by compute engine assertInitializedIssue(issue); assertThat(issue.message()).isEqualTo("Rule 1"); } // SONAR-10781 @Test public void load_issues_from_report_missing_secondary_location_component() { RuleKey ruleKey = RuleKey.of("java", "S001"); markRuleAsActive(ruleKey); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setSeverity(Constants.Severity.BLOCKER) .setGap(3.14) .addFlow(ScannerReport.Flow.newBuilder() .addLocation(ScannerReport.IssueLocation.newBuilder() .setComponentRef(FILE_REF) .setMsg("Secondary location in same file") .setTextRange(newTextRange(2))) .addLocation(ScannerReport.IssueLocation.newBuilder() .setComponentRef(NOT_IN_REPORT_FILE_REF) .setMsg("Secondary location in a missing file") .setTextRange(newTextRange(3))) .addLocation(ScannerReport.IssueLocation.newBuilder() .setComponentRef(ANOTHER_FILE_REF) .setMsg("Secondary location in another file") .setTextRange(newTextRange(3))) .build()) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).hasSize(1); DefaultIssue issue = Iterators.getOnlyElement(issues.iterator()); DbIssues.Locations locations = issue.getLocations(); // fields set by analysis report assertThat(locations.getFlowList()).hasSize(1); assertThat(locations.getFlow(0).getLocationList()).hasSize(2); // Not component id if location is in the same file assertThat(locations.getFlow(0).getLocation(0).getComponentId()).isEmpty(); assertThat(locations.getFlow(0).getLocation(1).getComponentId()).isEqualTo(ANOTHER_FILE_UUID); } @Test @UseDataProvider("ruleTypeAndStatusByIssueType") public void load_external_issues_from_report(IssueType issueType, RuleType expectedRuleType, String expectedStatus) { ScannerReport.ExternalIssue reportIssue = ScannerReport.ExternalIssue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .addMsgFormatting(ScannerReport.MessageFormatting.newBuilder().setStart(0).setEnd(3).build()) .setEngineId("eslint") .setRuleId("S001") .setSeverity(Constants.Severity.BLOCKER) .setEffort(20L) .setType(issueType) .addFlow(ScannerReport.Flow.newBuilder().setType(FlowType.DATA).addLocation(ScannerReport.IssueLocation.newBuilder().build()).build()) .build(); reportReader.putExternalIssues(FILE.getReportAttributes().getRef(), asList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).hasSize(1); DefaultIssue issue = Iterators.getOnlyElement(issues.iterator()); // fields set by analysis report assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("external_eslint", "S001")); assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); assertThat(issue.line()).isEqualTo(2); assertThat(issue.effort()).isEqualTo(Duration.create(20L)); assertThat(issue.message()).isEqualTo("the message"); // Check message formatting DbIssues.MessageFormattings messageFormattings = Iterators.getOnlyElement(issues.iterator()).getMessageFormattings(); assertThat(messageFormattings.getMessageFormattingCount()).isEqualTo(1); assertThat(messageFormattings.getMessageFormatting(0).getStart()).isZero(); assertThat(messageFormattings.getMessageFormatting(0).getEnd()).isEqualTo(3); assertThat(messageFormattings.getMessageFormatting(0).getType()).isEqualTo(DbIssues.MessageFormattingType.CODE); assertThat(issue.type()).isEqualTo(expectedRuleType); DbIssues.Locations locations = Iterators.getOnlyElement(issues.iterator()).getLocations(); assertThat(locations.getFlowCount()).isEqualTo(1); assertThat(locations.getFlow(0).getType()).isEqualTo(DbIssues.FlowType.DATA); assertThat(locations.getFlow(0).getLocationList()).hasSize(1); // fields set by compute engine assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2)); assertThat(issue.tags()).isEmpty(); assertInitializedExternalIssue(issue, expectedStatus); } @DataProvider public static Object[][] ruleTypeAndStatusByIssueType() { return new Object[][] { {IssueType.CODE_SMELL, RuleType.CODE_SMELL, STATUS_OPEN}, {IssueType.BUG, RuleType.BUG, STATUS_OPEN}, {IssueType.VULNERABILITY, RuleType.VULNERABILITY, STATUS_OPEN}, {IssueType.SECURITY_HOTSPOT, RuleType.SECURITY_HOTSPOT, STATUS_TO_REVIEW} }; } @Test @UseDataProvider("ruleTypeAndStatusByIssueType") public void load_external_issues_from_report_with_default_effort(IssueType issueType, RuleType expectedRuleType, String expectedStatus) { ScannerReport.ExternalIssue reportIssue = ScannerReport.ExternalIssue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .setEngineId("eslint") .setRuleId("S001") .setSeverity(Constants.Severity.BLOCKER) .setType(issueType) .build(); reportReader.putExternalIssues(FILE.getReportAttributes().getRef(), asList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).hasSize(1); DefaultIssue issue = Iterators.getOnlyElement(issues.iterator()); // fields set by analysis report assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("external_eslint", "S001")); assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); assertThat(issue.line()).isEqualTo(2); assertThat(issue.effort()).isEqualTo(Duration.create(0L)); assertThat(issue.message()).isEqualTo("the message"); assertThat(issue.type()).isEqualTo(expectedRuleType); // fields set by compute engine assertThat(issue.checksum()).isEqualTo(input.getLineHashSequence().getHashForLine(2)); assertThat(issue.tags()).isEmpty(); assertInitializedExternalIssue(issue, expectedStatus); } @Test public void excludes_issues_on_inactive_rules() { RuleKey ruleKey = RuleKey.of("java", "S001"); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setSeverity(Constants.Severity.BLOCKER) .setGap(3.14) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).isEmpty(); } @Test public void filter_excludes_issues_from_report() { RuleKey ruleKey = RuleKey.of("java", "S001"); markRuleAsActive(ruleKey); when(issueFilter.accept(any(), eq(FILE))).thenReturn(false); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setTextRange(newTextRange(2)) .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setSeverity(Constants.Severity.BLOCKER) .setGap(3.14) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); Collection<DefaultIssue> issues = input.getIssues(); assertThat(issues).isEmpty(); } @Test public void exclude_issues_on_common_rules() { RuleKey ruleKey = RuleKey.of(CommonRuleKeys.commonRepositoryForLang("java"), "S001"); markRuleAsActive(ruleKey); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setSeverity(Constants.Severity.BLOCKER) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); assertThat(input.getIssues()).isEmpty(); } private ScannerReport.TextRange newTextRange(int issueOnLine) { return ScannerReport.TextRange.newBuilder() .setStartLine(issueOnLine) .setEndLine(issueOnLine) .setStartOffset(0) .setEndOffset(EXAMPLE_LINE_OF_CODE_FORMAT.length() - 1) .build(); } private void assertInitializedIssue(DefaultIssue issue) { assertInitializedExternalIssue(issue, STATUS_OPEN); assertThat(issue.effort()).isNull(); assertThat(issue.effortInMinutes()).isNull(); } private void assertInitializedExternalIssue(DefaultIssue issue, String expectedStatus) { assertThat(issue.projectKey()).isEqualTo(PROJECT.getKey()); assertThat(issue.componentKey()).isEqualTo(FILE.getKey()); assertThat(issue.componentUuid()).isEqualTo(FILE.getUuid()); assertThat(issue.resolution()).isNull(); assertThat(issue.status()).isEqualTo(expectedStatus); assertThat(issue.key()).isNull(); assertThat(issue.authorLogin()).isNull(); } private void markRuleAsActive(RuleKey ruleKey) { activeRulesHolder.put(new ActiveRule(ruleKey, Severity.CRITICAL, emptyMap(), 1_000L, null, "qp1")); } private void registerRule(RuleKey ruleKey, String name) { DumbRule dumbRule = new DumbRule(ruleKey); dumbRule.setName(name); ruleRepository.add(dumbRule); } }
21,548
43.614907
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/UpdateConflictResolverTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import org.sonar.api.utils.DateUtils; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.issue.IssueDto; import org.sonar.db.issue.IssueMapper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.sonar.api.issue.Issue.STATUS_OPEN; import static org.sonar.api.rules.RuleType.CODE_SMELL; public class UpdateConflictResolverTest { @Test public void should_reload_issue_and_resolve_conflict() { DefaultIssue issue = new DefaultIssue() .setKey("ABCDE") .setType(CODE_SMELL) .setRuleKey(RuleKey.of("java", "AvoidCycles")) .setProjectUuid("U1") .setComponentUuid("U2") .setNew(false) .setStatus(STATUS_OPEN); // Issue as seen and changed by end-user IssueMapper mapper = mock(IssueMapper.class); IssueDto issueDto = new IssueDto() .setKee("ABCDE") .setType(CODE_SMELL) .setRuleUuid("uuid-10") .setRuleKey("java", "AvoidCycles") .setProjectUuid("U1") .setComponentUuid("U2") .setLine(10) .setStatus(STATUS_OPEN) // field changed by user .setAssigneeUuid("arthur-uuid"); new UpdateConflictResolver().resolve(issue, issueDto, mapper); ArgumentCaptor<IssueDto> argument = ArgumentCaptor.forClass(IssueDto.class); verify(mapper).update(argument.capture()); IssueDto updatedIssue = argument.getValue(); assertThat(updatedIssue.getKee()).isEqualTo("ABCDE"); assertThat(updatedIssue.getAssigneeUuid()).isEqualTo("arthur-uuid"); } @Test public void should_keep_changes_made_by_user() { DefaultIssue issue = new DefaultIssue() .setKey("ABCDE") .setRuleKey(RuleKey.of("java", "AvoidCycles")) .setComponentKey("struts:org.apache.struts.Action") .setNew(false); // Before starting scan issue.setAssigneeUuid(null); issue.setCreationDate(DateUtils.parseDate("2012-01-01")); issue.setUpdateDate(DateUtils.parseDate("2012-02-02")); // Changed by scan issue.setLine(200); issue.setSeverity(Severity.BLOCKER); issue.setManualSeverity(false); issue.setAuthorLogin("simon"); issue.setChecksum("CHECKSUM-ABCDE"); issue.setResolution(null); issue.setStatus(Issue.STATUS_REOPENED); // Issue as seen and changed by end-user IssueDto dbIssue = new IssueDto() .setKee("ABCDE") .setRuleUuid("uuid-10") .setRuleKey("java", "AvoidCycles") .setComponentUuid("100") .setComponentKey("struts:org.apache.struts.Action") .setLine(10) .setResolution(Issue.RESOLUTION_FALSE_POSITIVE) .setStatus(Issue.STATUS_RESOLVED) .setAssigneeUuid("arthur") .setSeverity(Severity.MAJOR) .setManualSeverity(false); new UpdateConflictResolver().mergeFields(dbIssue, issue); assertThat(issue.key()).isEqualTo("ABCDE"); assertThat(issue.componentKey()).isEqualTo("struts:org.apache.struts.Action"); // Scan wins on : assertThat(issue.line()).isEqualTo(200); assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); assertThat(issue.manualSeverity()).isFalse(); // User wins on : assertThat(issue.assignee()).isEqualTo("arthur"); assertThat(issue.resolution()).isEqualTo(Issue.RESOLUTION_FALSE_POSITIVE); assertThat(issue.status()).isEqualTo(Issue.STATUS_RESOLVED); } @Test public void severity_changed_by_user_should_be_kept() { DefaultIssue issue = new DefaultIssue() .setKey("ABCDE") .setRuleKey(RuleKey.of("java", "AvoidCycles")) .setComponentKey("struts:org.apache.struts.Action") .setNew(false) .setStatus(STATUS_OPEN); // Changed by scan issue.setSeverity(Severity.BLOCKER); issue.setManualSeverity(false); // Issue as seen and changed by end-user IssueDto dbIssue = new IssueDto() .setKee("ABCDE") .setStatus(STATUS_OPEN) .setSeverity(Severity.INFO) .setManualSeverity(true); new UpdateConflictResolver().mergeFields(dbIssue, issue); assertThat(issue.severity()).isEqualTo(Severity.INFO); assertThat(issue.manualSeverity()).isTrue(); } }
5,223
33.143791
82
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/filter/IssueFilterTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue.filter; import com.google.common.base.Joiner; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.config.internal.Settings; import org.sonar.api.rule.RuleKey; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.core.issue.DefaultIssue; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class IssueFilterTest { static final RuleKey XOO_X1 = RuleKey.of("xoo", "x1"); static final RuleKey XOO_X2 = RuleKey.of("xoo", "x2"); static final RuleKey XOO_X3 = RuleKey.of("xoo", "x3"); static final String PATH1 = "src/main/xoo/File1.xoo"; static final String PATH2 = "src/main/xoo/File2.xoo"; static final String PATH3 = "src/main/xoo/File3.xoo"; static final Component PROJECT = builder(Component.Type.PROJECT, 10).build(); static final Component COMPONENT_1 = builder(FILE, 1).setKey("File1").setName(PATH1).build(); static final Component COMPONENT_2 = builder(FILE, 2).setKey("File2").setName(PATH2).build(); static final Component COMPONENT_3 = builder(FILE, 3).setKey("File3").setName(PATH3).build(); static final DefaultIssue ISSUE_1 = new DefaultIssue().setRuleKey(XOO_X1); static final DefaultIssue ISSUE_2 = new DefaultIssue().setRuleKey(XOO_X2); static final DefaultIssue ISSUE_3 = new DefaultIssue().setRuleKey(XOO_X3); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT); ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class); @Test public void accept_everything_when_no_filter_properties() { IssueFilter underTest = newIssueFilter(new MapSettings()); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isTrue(); assertThat(underTest.accept(ISSUE_3, COMPONENT_3)).isTrue(); } @Test public void ignore_all() { IssueFilter underTest = newIssueFilter(newSettings(asList("*", "**"), Collections.emptyList())); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_3, COMPONENT_1)).isFalse(); } @Test public void ignore_some_rule_and_component() { IssueFilter underTest = newIssueFilter(newSettings(asList("xoo:x1", "**/xoo/File1*"), Collections.emptyList())); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isTrue(); } @Test public void ignore_many_rules() { IssueFilter underTest = newIssueFilter(newSettings( asList("xoo:x1", "**/xoo/File1*", "xoo:x2", "**/xoo/File1*"), Collections.emptyList())); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isTrue(); } @Test public void include_all() { IssueFilter underTest = newIssueFilter(newSettings(Collections.emptyList(), asList("*", "**"))); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_3, COMPONENT_1)).isTrue(); } @Test public void include_some_rule_and_component() { IssueFilter underTest = newIssueFilter(newSettings(Collections.emptyList(), asList("xoo:x1", "**/xoo/File1*"))); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isFalse(); // Issues on other rule are accepted assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isTrue(); } @Test public void ignore_and_include_same_rule_and_component() { IssueFilter underTest = newIssueFilter(newSettings( asList("xoo:x1", "**/xoo/File1*"), asList("xoo:x1", "**/xoo/File1*"))); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isFalse(); assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isFalse(); // Issues on other rule are accepted assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isTrue(); } @Test public void include_many_rules() { IssueFilter underTest = newIssueFilter(newSettings( Collections.emptyList(), asList("xoo:x1", "**/xoo/File1*", "xoo:x2", "**/xoo/File1*"))); assertThat(underTest.accept(ISSUE_1, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_1, COMPONENT_2)).isFalse(); assertThat(underTest.accept(ISSUE_2, COMPONENT_1)).isTrue(); assertThat(underTest.accept(ISSUE_2, COMPONENT_2)).isFalse(); } @Test public void accept_project_issues() { IssueFilter underTest = newIssueFilter(newSettings( asList("xoo:x1", "**/xoo/File1*"), asList("xoo:x1", "**/xoo/File1*"))); assertThat(underTest.accept(ISSUE_1, PROJECT)).isTrue(); assertThat(underTest.accept(ISSUE_2, PROJECT)).isTrue(); } @Test public void fail_when_only_rule_key_parameter() { assertThatThrownBy(() -> newIssueFilter(newSettings(asList("xoo:x1", ""), Collections.emptyList()))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("File path pattern cannot be empty. Please check 'sonar.issue.ignore.multicriteria' settings"); } @Test public void fail_when_only_path_parameter() { assertThatThrownBy(() -> newIssueFilter(newSettings(Collections.emptyList(), asList("", "**")))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Rule key pattern cannot be empty. Please check 'sonar.issue.enforce.multicriteria' settings"); } private IssueFilter newIssueFilter(MapSettings settings) { when(settingsRepository.getConfiguration()).thenReturn(settings.asConfig()); return new IssueFilter(settingsRepository); } private static MapSettings newSettings(List<String> exclusionsProperties, List<String> inclusionsProperties) { MapSettings settings = new MapSettings(); if (!exclusionsProperties.isEmpty()) { addProperties(exclusionsProperties, "ignore", settings); } if (!inclusionsProperties.isEmpty()) { addProperties(inclusionsProperties, "enforce", settings); } return settings; } private static void addProperties(List<String> properties, String property, Settings settings) { if (!properties.isEmpty()) { List<Integer> indexes = new ArrayList<>(); int index = 1; for (int i = 0; i < properties.size(); i += 2) { settings.setProperty("sonar.issue." + property + ".multicriteria." + index + ".ruleKey", properties.get(i)); settings.setProperty("sonar.issue." + property + ".multicriteria." + index + ".resourceKey", properties.get(i + 1)); indexes.add(index); index++; } settings.setProperty("sonar.issue." + property + ".multicriteria", Joiner.on(",").join(indexes)); } } }
8,665
40.266667
124
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/issue/filter/IssuePatternTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue.filter; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.Rule; import static org.assertj.core.api.Assertions.assertThat; public class IssuePatternTest { @Test public void match_file() { String javaFile = "org/foo/Bar.xoo"; assertThat(new IssuePattern("org/foo/Bar*", "*").matchComponent(javaFile)).isTrue(); assertThat(new IssuePattern("org/foo/*", "*").matchComponent(javaFile)).isTrue(); assertThat(new IssuePattern("**/*ar*", "*").matchComponent(javaFile)).isTrue(); assertThat(new IssuePattern("org/**/?ar.xoo", "*").matchComponent(javaFile)).isTrue(); assertThat(new IssuePattern("**", "*").matchComponent(javaFile)).isTrue(); assertThat(new IssuePattern("org/other/Hello", "*").matchComponent(javaFile)).isFalse(); assertThat(new IssuePattern("org/foo/Hello", "*").matchComponent(javaFile)).isFalse(); assertThat(new IssuePattern("org/**/??ar.xoo", "*").matchComponent(javaFile)).isFalse(); assertThat(new IssuePattern("org/**/??ar.xoo", "*").matchComponent(null)).isFalse(); assertThat(new IssuePattern("org/**/??ar.xoo", "*").matchComponent("plop")).isFalse(); } @Test public void match_rule() { RuleKey rule = Rule.create("checkstyle", "IllegalRegexp", "").ruleKey(); assertThat(new IssuePattern("*", "*").matchRule(rule)).isTrue(); assertThat(new IssuePattern("*", "checkstyle:*").matchRule(rule)).isTrue(); assertThat(new IssuePattern("*", "checkstyle:IllegalRegexp").matchRule(rule)).isTrue(); assertThat(new IssuePattern("*", "checkstyle:Illegal*").matchRule(rule)).isTrue(); assertThat(new IssuePattern("*", "*:*Illegal*").matchRule(rule)).isTrue(); assertThat(new IssuePattern("*", "pmd:IllegalRegexp").matchRule(rule)).isFalse(); assertThat(new IssuePattern("*", "pmd:*").matchRule(rule)).isFalse(); assertThat(new IssuePattern("*", "*:Foo*IllegalRegexp").matchRule(rule)).isFalse(); } @Test public void test_to_string() { IssuePattern pattern = new IssuePattern("*", "checkstyle:*"); assertThat(pattern).hasToString( "IssuePattern{componentPattern=*, rulePattern=checkstyle:*}"); } }
3,049
43.852941
92
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/language/HandleUnanalyzedLanguagesStepTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.language; import com.google.common.collect.ImmutableList; import java.util.List; import java.util.Optional; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.api.utils.System2; import org.sonar.ce.task.log.CeTaskMessages; import org.sonar.ce.task.log.CeTaskMessages.Message; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.platform.EditionProvider; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.db.ce.CeTaskMessageType; import org.sonar.scanner.protocol.output.ScannerReport; import static com.google.common.collect.ImmutableList.of; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT; import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_C; import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_CPP; import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_CPP_KEY; import static org.sonar.server.metric.UnanalyzedLanguageMetrics.UNANALYZED_C_KEY; @RunWith(MockitoJUnitRunner.class) public class HandleUnanalyzedLanguagesStepTest { private static final int PROJECT_REF = 1; private static final Component ROOT_PROJECT = ReportComponent.builder(PROJECT, PROJECT_REF).build(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(ROOT_PROJECT); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(UNANALYZED_C) .add(UNANALYZED_CPP); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Captor private ArgumentCaptor<Message> argumentCaptor; private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private final CeTaskMessages ceTaskMessages = mock(CeTaskMessages.class); private final HandleUnanalyzedLanguagesStep underTest = new HandleUnanalyzedLanguagesStep(reportReader, ceTaskMessages, editionProvider, System2.INSTANCE, treeRootHolder, metricRepository, measureRepository); @Test public void getDescription() { assertThat(underTest.getDescription()).isEqualTo(HandleUnanalyzedLanguagesStep.DESCRIPTION); } @Test public void add_warning_and_measures_in_SQ_community_edition_if_there_are_c_or_cpp_files() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.AnalysisWarning warning2 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 2").build(); ImmutableList<ScannerReport.AnalysisWarning> warnings = of(warning1, warning2); reportReader.setAnalysisWarnings(warnings); reportReader.setMetadata(ScannerReport.Metadata.newBuilder() .putNotAnalyzedFilesByLanguage("C++", 20) .putNotAnalyzedFilesByLanguage("C", 10) .putNotAnalyzedFilesByLanguage("SomeLang", 1000) .build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, times(1)).add(argumentCaptor.capture()); assertThat(argumentCaptor.getAllValues()) .extracting(Message::getText, Message::getType) .containsExactly(tuple( "10 unanalyzed C, 20 unanalyzed C++ and 1000 unanalyzed SomeLang files were detected in this project during the last analysis. C," + " C++ and SomeLang cannot be analyzed with your current SonarQube edition. Please consider" + " <a target=\"_blank\" href=\"https://www.sonarqube.org/trial-request/developer-edition/?referrer=sonarqube-cpp\">upgrading to Developer Edition</a> to find Bugs," + " Code Smells, Vulnerabilities and Security Hotspots in these files.", CeTaskMessageType.SUGGEST_DEVELOPER_EDITION_UPGRADE)); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY).get().getIntValue()).isEqualTo(10); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY).get().getIntValue()).isEqualTo(20); } @Test public void adds_warning_and_measures_in_SQ_community_edition_if_there_are_c_files() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); reportReader.setMetadata(ScannerReport.Metadata.newBuilder() .putNotAnalyzedFilesByLanguage("C", 10) .build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, times(1)).add(argumentCaptor.capture()); List<CeTaskMessages.Message> messages = argumentCaptor.getAllValues(); assertThat(messages).extracting(CeTaskMessages.Message::getText).containsExactly( "10 unanalyzed C files were detected in this project during the last analysis. C cannot be analyzed with your current SonarQube edition. Please" + " consider <a target=\"_blank\" href=\"https://www.sonarqube.org/trial-request/developer-edition/?referrer=sonarqube-cpp\">upgrading to Developer" + " Edition</a> to find Bugs, Code Smells, Vulnerabilities and Security Hotspots in this file."); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY).get().getIntValue()).isEqualTo(10); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY)).isEmpty(); } @Test public void adds_warning_in_SQ_community_edition_if_there_are_cpp_files() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); reportReader.setMetadata(ScannerReport.Metadata.newBuilder() .putNotAnalyzedFilesByLanguage("C++", 1) .build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, times(1)).add(argumentCaptor.capture()); List<CeTaskMessages.Message> messages = argumentCaptor.getAllValues(); assertThat(messages).extracting(CeTaskMessages.Message::getText).containsExactly( "1 unanalyzed C++ file was detected in this project during the last analysis. C++ cannot be analyzed with your current SonarQube edition. Please" + " consider <a target=\"_blank\" href=\"https://www.sonarqube.org/trial-request/developer-edition/?referrer=sonarqube-cpp\">upgrading to Developer" + " Edition</a> to find Bugs, Code Smells, Vulnerabilities and Security Hotspots in this file."); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY).get().getIntValue()).isOne(); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY)).isEmpty(); } @Test public void do_nothing_SQ_community_edition_if_cpp_files_in_report_is_zero() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.AnalysisWarning warning2 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 2").build(); ImmutableList<ScannerReport.AnalysisWarning> warnings = of(warning1, warning2); reportReader.setAnalysisWarnings(warnings); reportReader.setMetadata(ScannerReport.Metadata.newBuilder().putNotAnalyzedFilesByLanguage("C++", 0).build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, never()).add(any()); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY)).isEmpty(); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY)).isEmpty(); } @Test public void execute_does_not_add_a_warning_in_SQ_community_edition_if_no_c_or_cpp_files() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.COMMUNITY)); ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.AnalysisWarning warning2 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 2").build(); ImmutableList<ScannerReport.AnalysisWarning> warnings = of(warning1, warning2); reportReader.setAnalysisWarnings(warnings); reportReader.setMetadata(ScannerReport.Metadata.newBuilder().build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, never()).add(any()); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY)).isEmpty(); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY)).isEmpty(); } @Test public void execute_does_not_add_a_warning_in_SQ_non_community_edition() { when(editionProvider.get()).thenReturn(Optional.of(EditionProvider.Edition.ENTERPRISE)); ScannerReport.AnalysisWarning warning1 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 1").build(); ScannerReport.AnalysisWarning warning2 = ScannerReport.AnalysisWarning.newBuilder().setText("warning 2").build(); ImmutableList<ScannerReport.AnalysisWarning> warnings = of(warning1, warning2); reportReader.setAnalysisWarnings(warnings); reportReader.setMetadata(ScannerReport.Metadata.newBuilder().putNotAnalyzedFilesByLanguage("C++", 20).build()); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, never()).add(any()); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_C_KEY)).isEmpty(); assertThat(measureRepository.getAddedRawMeasure(PROJECT_REF, UNANALYZED_CPP_KEY)).isEmpty(); } }
11,285
53.521739
175
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/language/LanguageRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.language; import java.util.Optional; import org.junit.Test; import org.sonar.api.resources.Language; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class LanguageRepositoryImplTest { private static final String ANY_KEY = "Any_Key"; private static final String SOME_LANGUAGE_KEY = "SoMe language_Key"; private static final Language SOME_LANGUAGE = createLanguage(SOME_LANGUAGE_KEY, "_name"); @Test public void constructor_fails_is_language_have_the_same_key() { assertThatThrownBy(() -> new LanguageRepositoryImpl(createLanguage(SOME_LANGUAGE_KEY, " 1"), createLanguage(SOME_LANGUAGE_KEY, " 2"))) .isInstanceOf(IllegalStateException.class); } @Test public void find_on_empty_LanguageRepository_returns_absent() { assertThat(new LanguageRepositoryImpl().find(ANY_KEY)).isEmpty(); } @Test public void find_by_key_returns_the_same_object() { LanguageRepositoryImpl languageRepository = new LanguageRepositoryImpl(SOME_LANGUAGE); Optional<Language> language = languageRepository.find(SOME_LANGUAGE_KEY); assertThat(language) .isPresent() .containsSame(SOME_LANGUAGE); } @Test public void find_by_other_key_returns_absent() { LanguageRepositoryImpl languageRepository = new LanguageRepositoryImpl(SOME_LANGUAGE); Optional<Language> language = languageRepository.find(ANY_KEY); assertThat(language).isEmpty(); } private static Language createLanguage(final String key, final String nameSuffix) { return new Language() { @Override public String getKey() { return key; } @Override public String getName() { return key + nameSuffix; } @Override public String[] getFileSuffixes() { return new String[0]; } @Override public boolean publishAllFiles() { return true; } }; } }
2,839
32.023256
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/locations/flow/FlowGeneratorTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.locations.flow; import java.util.List; import java.util.Map; import org.apache.commons.lang.math.RandomUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import static java.util.function.Function.identity; import static java.util.stream.Collectors.toMap; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) public class FlowGeneratorTest { private static final String COMPONENT_NAME = "test_comp"; @Mock private TreeRootHolder treeRootHolder; @InjectMocks private FlowGenerator flowGenerator; @Test public void convertFlows_withNullDbLocations_returnsEmptyList() { assertThat(flowGenerator.convertFlows(COMPONENT_NAME, null)).isEmpty(); } @Test public void convertFlows_withEmptyDbLocations_returnsEmptyList() { DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder().build(); assertThat(flowGenerator.convertFlows(COMPONENT_NAME, issueLocations)).isEmpty(); } @Test public void convertFlows_withSingleDbLocations_returnsCorrectFlow() { DbIssues.Location location = createDbLocation("comp_id_1"); DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder() .addFlow(createFlow(location)) .build(); List<Flow> flows = flowGenerator.convertFlows(COMPONENT_NAME, issueLocations); assertThat(flows).hasSize(1); Flow singleFlow = flows.iterator().next(); assertThat(singleFlow.getLocations()).hasSize(1); Location singleLocation = singleFlow.getLocations().iterator().next(); assertLocationMatches(singleLocation, location); } @Test public void convertFlows_with2FlowsSingleDbLocations_returnsCorrectFlow() { DbIssues.Location location1 = createDbLocation("comp_id_1"); DbIssues.Location location2 = createDbLocation("comp_id_2"); DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder() .addFlow(createFlow(location1)) .addFlow(createFlow(location2)) .build(); List<Flow> flows = flowGenerator.convertFlows(COMPONENT_NAME, issueLocations); assertThat(flows).hasSize(2).extracting(f -> f.getLocations().size()).containsExactly(1, 1); Map<String, DbIssues.Location> toDbLocation = Map.of( "file_path_" + location1.getComponentId(), location1, "file_path_" + location2.getComponentId(), location2); flows.stream() .map(actualFlow -> actualFlow.getLocations().iterator().next()) .forEach(l -> assertLocationMatches(l, toDbLocation.get(l.getFilePath()))); } @Test public void convertFlows_with2DbLocations_returns() { DbIssues.Location location1 = createDbLocation("comp_id_1"); DbIssues.Location location2 = createDbLocation("comp_id_2"); DbIssues.Locations issueLocations = DbIssues.Locations.newBuilder() .addFlow(createFlow(location1, location2)) .build(); List<Flow> flows = flowGenerator.convertFlows(COMPONENT_NAME, issueLocations); assertThat(flows).hasSize(1); Flow singleFlow = flows.iterator().next(); assertThat(singleFlow.getLocations()).hasSize(2); Map<String, Location> pathToLocations = singleFlow.getLocations() .stream() .collect(toMap(Location::getFilePath, identity())); assertLocationMatches(pathToLocations.get("file_path_comp_id_1"), location1); assertLocationMatches(pathToLocations.get("file_path_comp_id_2"), location2); } private DbIssues.Location createDbLocation(String componentId) { org.sonar.db.protobuf.DbCommons.TextRange textRange = org.sonar.db.protobuf.DbCommons.TextRange.newBuilder() .setStartLine(RandomUtils.nextInt()) .setEndLine(RandomUtils.nextInt()) .setStartOffset(RandomUtils.nextInt()) .setEndOffset(RandomUtils.nextInt()) .build(); Component component = mock(Component.class); when(component.getName()).thenReturn("file_path_" + componentId); when(treeRootHolder.getComponentByUuid(componentId)).thenReturn(component); return DbIssues.Location.newBuilder() .setComponentId(componentId) .setChecksum("hash" + randomAlphanumeric(10)) .setTextRange(textRange) .setMsg("msg" + randomAlphanumeric(15)) .build(); } private static DbIssues.Flow createFlow(DbIssues.Location ... locations) { return DbIssues.Flow.newBuilder() .addAllLocation(List.of(locations)) .build(); } private static void assertLocationMatches(Location actualLocation, DbIssues.Location sourceLocation) { assertThat(actualLocation.getMessage()).isEqualTo(sourceLocation.getMsg()); DbCommons.TextRange textRange = sourceLocation.getTextRange(); assertThat(actualLocation.getTextRange().getStartLine()).isEqualTo(textRange.getStartLine()); assertThat(actualLocation.getTextRange().getEndLine()).isEqualTo(textRange.getEndLine()); assertThat(actualLocation.getTextRange().getStartLineOffset()).isEqualTo(textRange.getStartOffset()); assertThat(actualLocation.getTextRange().getEndLineOffset()).isEqualTo(textRange.getEndOffset()); assertThat(actualLocation.getTextRange().getHash()).isEqualTo(sourceLocation.getChecksum()); } }
6,457
39.111801
112
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/BatchMeasureToMeasureTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.util.Optional; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Measure.BoolValue; import org.sonar.scanner.protocol.output.ScannerReport.Measure.DoubleValue; import org.sonar.scanner.protocol.output.ScannerReport.Measure.IntValue; import org.sonar.scanner.protocol.output.ScannerReport.Measure.LongValue; import org.sonar.scanner.protocol.output.ScannerReport.Measure.StringValue; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class BatchMeasureToMeasureTest { private static final Metric SOME_INT_METRIC = new MetricImpl("42", "int", "name", Metric.MetricType.INT); private static final Metric SOME_LONG_METRIC = new MetricImpl("42", "long", "name", Metric.MetricType.WORK_DUR); private static final Metric SOME_DOUBLE_METRIC = new MetricImpl("42", "double", "name", Metric.MetricType.FLOAT); private static final Metric SOME_STRING_METRIC = new MetricImpl("42", "string", "name", Metric.MetricType.STRING); private static final Metric SOME_BOOLEAN_METRIC = new MetricImpl("42", "boolean", "name", Metric.MetricType.BOOL); private static final Metric SOME_LEVEL_METRIC = new MetricImpl("42", "level", "name", Metric.MetricType.LEVEL); private static final String SOME_DATA = "some_data man!"; private static final ScannerReport.Measure EMPTY_BATCH_MEASURE = ScannerReport.Measure.newBuilder().build(); private BatchMeasureToMeasure underTest = new BatchMeasureToMeasure(); @Test public void toMeasure_returns_absent_for_null_argument() { assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent(); } @Test public void toMeasure_throws_NPE_if_metric_argument_is_null() { assertThatThrownBy(() -> underTest.toMeasure(EMPTY_BATCH_MEASURE, null)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasure_throws_NPE_if_both_arguments_are_null() { assertThatThrownBy(() -> underTest.toMeasure(null, null)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasure_returns_no_value_if_dto_has_no_string_value_for_LEVEL_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dto_has_invalid_string_value_for_LEVEL_Metric() { Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setStringValue(StringValue.newBuilder().setValue("trololo")).build(), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dto_has_value_in_wrong_case_for_LEVEL_Metric() { Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setStringValue(StringValue.newBuilder().setValue("waRn")).build(), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_value_for_LEVEL_Metric() { for (Measure.Level alertStatus : Measure.Level.values()) { verify_toMeasure_returns_value_for_LEVEL_Metric(alertStatus); } } private void verify_toMeasure_returns_value_for_LEVEL_Metric(Measure.Level expectedQualityGateStatus) { Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setStringValue(StringValue.newBuilder().setValue(expectedQualityGateStatus.name())).build(), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LEVEL); assertThat(measure.get().getLevelValue()).isEqualTo(expectedQualityGateStatus); } @Test public void toMeasure_for_LEVEL_Metric_maps_QualityGateStatus() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setStringValue(StringValue.newBuilder().setValue(Measure.Level.OK.name())) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LEVEL); assertThat(measure.get().getLevelValue()).isEqualTo(Measure.Level.OK); } @Test public void toMeasure_for_LEVEL_Metric_parses_level_from_data() { for (Measure.Level level : Measure.Level.values()) { verify_toMeasure_for_LEVEL_Metric_parses_level_from_data(level); } } private void verify_toMeasure_for_LEVEL_Metric_parses_level_from_data(Measure.Level expectedLevel) { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setStringValue(StringValue.newBuilder().setValue(expectedLevel.name())) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getLevelValue()).isEqualTo(expectedLevel); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Int_Metric() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setIntValue(IntValue.newBuilder().setValue(10).setData(SOME_DATA)) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.INT); assertThat(measure.get().getIntValue()).isEqualTo(10); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Long_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_long_part_of_value_in_dto_for_Long_Metric() { Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setLongValue(LongValue.newBuilder().setValue(15L)).build(), SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LONG); assertThat(measure.get().getLongValue()).isEqualTo(15); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Long_Metric() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setLongValue(LongValue.newBuilder().setValue(10L).setData(SOME_DATA)) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LONG); assertThat(measure.get().getLongValue()).isEqualTo(10); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Double_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_DOUBLE_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Double_Metric() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setDoubleValue(DoubleValue.newBuilder().setValue(10.6395d).setData(SOME_DATA)) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_DOUBLE_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.DOUBLE); assertThat(measure.get().getDoubleValue()).isEqualTo(10.6395d); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric() { verify_toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric(true); verify_toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric(false); } private void verify_toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric(boolean expected) { Optional<Measure> measure = underTest.toMeasure(ScannerReport.Measure.newBuilder().setBooleanValue(BoolValue.newBuilder().setValue(expected)).build(), SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.BOOLEAN); assertThat(measure.get().getBooleanValue()).isEqualTo(expected); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Boolean_metric() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setBooleanValue(BoolValue.newBuilder().setValue(true).setData(SOME_DATA)).build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.BOOLEAN); assertThat(measure.get().getBooleanValue()).isTrue(); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_String_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_BATCH_MEASURE, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_maps_alert_properties_in_dto_for_String_Metric() { ScannerReport.Measure batchMeasure = ScannerReport.Measure.newBuilder() .setStringValue(StringValue.newBuilder().setValue(SOME_DATA)) .build(); Optional<Measure> measure = underTest.toMeasure(batchMeasure, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.STRING); assertThat(measure.get().getStringValue()).isEqualTo(SOME_DATA); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); } @DataProvider public static Object[][] all_types_batch_measure_builders() { return new Object[][] { {ScannerReport.Measure.newBuilder().setBooleanValue(BoolValue.newBuilder().setValue(true)), SOME_BOOLEAN_METRIC}, {ScannerReport.Measure.newBuilder().setIntValue(IntValue.newBuilder().setValue(1)), SOME_INT_METRIC}, {ScannerReport.Measure.newBuilder().setLongValue(LongValue.newBuilder().setValue(1)), SOME_LONG_METRIC}, {ScannerReport.Measure.newBuilder().setDoubleValue(DoubleValue.newBuilder().setValue(1)), SOME_DOUBLE_METRIC}, {ScannerReport.Measure.newBuilder().setStringValue(StringValue.newBuilder().setValue("1")), SOME_STRING_METRIC}, {ScannerReport.Measure.newBuilder().setStringValue(StringValue.newBuilder().setValue(Measure.Level.OK.name())), SOME_LEVEL_METRIC} }; } }
12,968
44.665493
179
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/BestValueOptimizationTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import java.util.function.Predicate; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.B; public class BestValueOptimizationTest { private static final ReportComponent FILE_COMPONENT = ReportComponent.builder(Component.Type.FILE, 1).build(); private static final ReportComponent SOME_NON_FILE_COMPONENT = ReportComponent.builder(Component.Type.DIRECTORY, 2).build(); private static final String SOME_DATA = "some_data"; private static final MetricImpl METRIC_BOOLEAN_FALSE = createMetric(Metric.MetricType.BOOL, 6d); private static final MetricImpl METRIC_BOOLEAN_TRUE = createMetric(Metric.MetricType.BOOL, 1d); @Test public void apply_returns_true_for_value_true_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(true))).isTrue(); assertThat(underTest.test(newMeasureBuilder().create(false))).isFalse(); } @Test public void apply_returns_false_if_component_is_not_a_FILE_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, SOME_NON_FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(true))).isFalse(); assertThat(underTest.test(newMeasureBuilder().create(false))).isFalse(); } @Test public void apply_returns_false_if_measure_has_anything_else_than_value_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, FILE_COMPONENT); Measure.NewMeasureBuilder builder = newMeasureBuilder().setQualityGateStatus(new QualityGateStatus(Measure.Level.ERROR, null)); assertThat(underTest.test(builder.create(true))).isFalse(); assertThat(underTest.test(builder.create(false))).isFalse(); } @Test public void apply_returns_false_if_measure_has_data_for_Boolean_Metric_and_best_value_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_TRUE, FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(true, SOME_DATA))).isFalse(); assertThat(underTest.test(newMeasureBuilder().create(false, SOME_DATA))).isFalse(); } @Test public void apply_returns_true_for_value_false_for_Boolean_Metric_and_best_value_not_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_FALSE, FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(true))).isFalse(); assertThat(underTest.test(newMeasureBuilder().create(false))).isTrue(); } @Test public void apply_returns_false_if_component_is_not_a_FILE_for_Boolean_Metric_and_best_value_not_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_FALSE, SOME_NON_FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(true))).isFalse(); assertThat(underTest.test(newMeasureBuilder().create(false))).isFalse(); } @Test public void apply_returns_false_if_measure_has_anything_else_than_value_for_Boolean_Metric_and_best_value_not_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_FALSE, FILE_COMPONENT); Measure.NewMeasureBuilder builder = newMeasureBuilder().setQualityGateStatus(new QualityGateStatus(Measure.Level.ERROR, null)); assertThat(underTest.test(builder.create(true))).isFalse(); assertThat(underTest.test(builder.create(false))).isFalse(); } @Test public void apply_returns_false_if_measure_has_data_for_Boolean_Metric_and_best_value_not_1() { Predicate<Measure> underTest = BestValueOptimization.from(METRIC_BOOLEAN_FALSE, FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(true, SOME_DATA))).isFalse(); assertThat(underTest.test(newMeasureBuilder().create(false, SOME_DATA))).isFalse(); } @Test public void verify_value_comparison_for_int_metric() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.INT, 10), FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(10))).isTrue(); assertThat(underTest.test(newMeasureBuilder().create(11))).isFalse(); } @Test public void verify_value_comparison_for_long_metric() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.WORK_DUR, 9511L), FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(9511L))).isTrue(); assertThat(underTest.test(newMeasureBuilder().create(963L))).isFalse(); } @Test public void verify_value_comparison_for_rating_metric() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.RATING, A.getIndex()), FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(A.getIndex()))).isTrue(); assertThat(underTest.test(newMeasureBuilder().create(B.getIndex()))).isFalse(); } @Test public void verify_value_comparison_for_double_metric() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.FLOAT, 36.5d), FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(36.5d, 1))).isTrue(); assertThat(underTest.test(newMeasureBuilder().create(36.6d, 1))).isFalse(); } @Test public void apply_returns_false_for_String_measure() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.FLOAT, 36.5d), FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create("aaa"))).isFalse(); } @Test public void apply_returns_false_for_LEVEL_measure() { Predicate<Measure> underTest = BestValueOptimization.from(createMetric(Metric.MetricType.STRING, 36.5d), FILE_COMPONENT); assertThat(underTest.test(newMeasureBuilder().create(Measure.Level.OK))).isFalse(); } private static MetricImpl createMetric(Metric.MetricType metricType, double bestValue) { return new MetricImpl(metricType.name() + bestValue, "key" + metricType + bestValue, "name" + metricType + bestValue, metricType, null, bestValue, true, false); } }
7,451
45.867925
139
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/LiveMeasureDtoToMeasureTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.util.Optional; import org.assertj.core.data.Offset; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure.Level; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.db.measure.LiveMeasureDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class LiveMeasureDtoToMeasureTest { private static final Metric SOME_INT_METRIC = new MetricImpl("42", "int", "name", Metric.MetricType.INT); private static final Metric SOME_LONG_METRIC = new MetricImpl("42", "long", "name", Metric.MetricType.WORK_DUR); private static final Metric SOME_DOUBLE_METRIC = new MetricImpl("42", "double", "name", Metric.MetricType.FLOAT); private static final Metric SOME_STRING_METRIC = new MetricImpl("42", "string", "name", Metric.MetricType.STRING); private static final Metric SOME_BOOLEAN_METRIC = new MetricImpl("42", "boolean", "name", Metric.MetricType.BOOL); private static final Metric SOME_LEVEL_METRIC = new MetricImpl("42", "level", "name", Metric.MetricType.LEVEL); private static final LiveMeasureDto EMPTY_MEASURE_DTO = new LiveMeasureDto(); private LiveMeasureDtoToMeasure underTest = new LiveMeasureDtoToMeasure(); @Test public void toMeasure_returns_absent_for_null_argument() { assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent(); } @Test public void toMeasure_throws_NPE_if_metric_argument_is_null() { assertThatThrownBy(() -> underTest.toMeasure(EMPTY_MEASURE_DTO, null)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasure_throws_NPE_if_both_arguments_are_null() { assertThatThrownBy(() -> underTest.toMeasure(null, null)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasure_returns_no_value_if_dto_has_no_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dto_has_invalid_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setData("trololo"), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dta_has_data_in_wrong_case_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setData("waRn"), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_QualityGateStatus_if_dto_has_no_alertStatus_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); } @Test public void toMeasure_returns_no_QualityGateStatus_if_alertStatus_has_invalid_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setData("trololo"), SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); } @Test public void toMeasure_returns_no_QualityGateStatus_if_alertStatus_has_data_in_wrong_case_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setData("waRn"), SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); } @Test public void toMeasure_returns_value_for_LEVEL_Metric() { for (Level level : Level.values()) { verify_toMeasure_returns_value_for_LEVEL_Metric(level); } } private void verify_toMeasure_returns_value_for_LEVEL_Metric(Level expectedLevel) { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setData(expectedLevel.name()), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LEVEL); assertThat(measure.get().getLevelValue()).isEqualTo(expectedLevel); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_int_part_of_value_in_dto_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setValue(1.5d), SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.INT); assertThat(measure.get().getIntValue()).isOne(); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Long_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_long_part_of_value_in_dto_for_Long_Metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setValue(1.5d), SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LONG); assertThat(measure.get().getLongValue()).isOne(); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Double_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_DOUBLE_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(new LiveMeasureDto().setValue(1.987d), SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.BOOLEAN); assertThat(measure.get().getBooleanValue()).isFalse(); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_String_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_should_not_loose_decimals_of_float_values() { MetricImpl metric = new MetricImpl("42", "double", "name", Metric.MetricType.FLOAT, 5, null, false, false); LiveMeasureDto LiveMeasureDto = new LiveMeasureDto() .setValue(0.12345); Optional<Measure> measure = underTest.toMeasure(LiveMeasureDto, metric); assertThat(measure.get().getDoubleValue()).isEqualTo(0.12345, Offset.offset(0.000001)); } }
8,559
42.232323
123
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MapBasedRawMeasureRepositoryTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.google.common.collect.ImmutableList; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.batch.BatchReportReader; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.metric.MetricRepository; import org.sonar.ce.task.projectanalysis.metric.ReportMetricValidator; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class MapBasedRawMeasureRepositoryTest { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private static final String FILE_COMPONENT_KEY = "file cpt key"; private static final ReportComponent FILE_COMPONENT = ReportComponent.builder(Component.Type.FILE, 1) .setKey(FILE_COMPONENT_KEY) .setUuid("1") .build(); private static final ReportComponent OTHER_COMPONENT = ReportComponent.builder(Component.Type.FILE, 2) .setKey("some other key") .setUuid("2") .build(); private static final String METRIC_KEY_1 = "metric 1"; private static final String METRIC_KEY_2 = "metric 2"; private final Metric metric1 = mock(Metric.class); private final Metric metric2 = mock(Metric.class); private static final Measure SOME_MEASURE = Measure.newMeasureBuilder().create("some value"); private ReportMetricValidator reportMetricValidator = mock(ReportMetricValidator.class); private MetricRepository metricRepository = mock(MetricRepository.class); private MapBasedRawMeasureRepository<Integer> underTest = new MapBasedRawMeasureRepository<>(component -> component.getReportAttributes().getRef()); private DbClient mockedDbClient = mock(DbClient.class); private BatchReportReader mockBatchReportReader = mock(BatchReportReader.class); private MeasureRepositoryImpl underTestWithMock = new MeasureRepositoryImpl(mockedDbClient, mockBatchReportReader, metricRepository, reportMetricValidator); @Before public void setUp() { when(metric1.getKey()).thenReturn(METRIC_KEY_1); when(metric1.getType()).thenReturn(Metric.MetricType.STRING); when(metric2.getKey()).thenReturn(METRIC_KEY_2); when(metric2.getType()).thenReturn(Metric.MetricType.STRING); // references to metrics are consistent with DB by design when(metricRepository.getByKey(METRIC_KEY_1)).thenReturn(metric1); when(metricRepository.getByKey(METRIC_KEY_2)).thenReturn(metric2); } @Test public void add_throws_NPE_if_Component_argument_is_null() { assertThatThrownBy(() -> underTest.add(null, metric1, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void add_throws_NPE_if_Component_metric_is_null() { assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, null, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void add_throws_NPE_if_Component_measure_is_null() { assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, metric1, null)) .isInstanceOf(NullPointerException.class); } @Test public void add_throws_UOE_if_measure_already_exists() { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); assertThatThrownBy(() -> underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE)) .isInstanceOf(UnsupportedOperationException.class); } @Test public void update_throws_NPE_if_Component_argument_is_null() { assertThatThrownBy(() -> underTest.update(null, metric1, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void update_throws_NPE_if_Component_metric_is_null() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, null, SOME_MEASURE)) .isInstanceOf(NullPointerException.class); } @Test public void update_throws_NPE_if_Component_measure_is_null() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, null)) .isInstanceOf(NullPointerException.class); } @Test public void update_throws_UOE_if_measure_does_not_exists() { assertThatThrownBy(() -> underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE)) .isInstanceOf(UnsupportedOperationException.class); } private static final List<Measure> MEASURES = ImmutableList.of( Measure.newMeasureBuilder().create(1), Measure.newMeasureBuilder().create(1L), Measure.newMeasureBuilder().create(1d, 1), Measure.newMeasureBuilder().create(true), Measure.newMeasureBuilder().create(false), Measure.newMeasureBuilder().create("sds"), Measure.newMeasureBuilder().create(Measure.Level.OK), Measure.newMeasureBuilder().createNoValue()); @DataProvider public static Object[][] measures() { return MEASURES.stream() .map(c -> new Measure[] {c}) .toArray(i -> new Object[i][]); } @Test public void add_accepts_NO_VALUE_as_measure_arg() { for (Metric.MetricType metricType : Metric.MetricType.values()) { underTest.add(FILE_COMPONENT, new MetricImpl("1", "key" + metricType, "name" + metricType, metricType), Measure.newMeasureBuilder().createNoValue()); } } @Test @UseDataProvider("measures") public void update_throws_IAE_if_valueType_of_Measure_is_not_the_same_as_the_Metric_valueType_unless_NO_VALUE(Measure measure) { for (Metric.MetricType metricType : Metric.MetricType.values()) { if (metricType.getValueType() == measure.getValueType() || measure.getValueType() == Measure.ValueType.NO_VALUE) { continue; } try { final MetricImpl metric = new MetricImpl("1", "key" + metricType, "name" + metricType, metricType); underTest.add(FILE_COMPONENT, metric, getSomeMeasureByValueType(metricType)); underTest.update(FILE_COMPONENT, metric, measure); fail("An IllegalArgumentException should have been raised"); } catch (IllegalArgumentException e) { assertThat(e).hasMessage(format( "Measure's ValueType (%s) is not consistent with the Metric's ValueType (%s)", measure.getValueType(), metricType.getValueType())); } } } @Test public void update_accepts_NO_VALUE_as_measure_arg() { for (Metric.MetricType metricType : Metric.MetricType.values()) { MetricImpl metric = new MetricImpl("1", "key" + metricType, "name" + metricType, metricType); underTest.add(FILE_COMPONENT, metric, getSomeMeasureByValueType(metricType)); underTest.update(FILE_COMPONENT, metric, Measure.newMeasureBuilder().createNoValue()); } } private Measure getSomeMeasureByValueType(final Metric.MetricType metricType) { return MEASURES.stream() .filter(measure -> measure.getValueType() == metricType.getValueType()) .findFirst().get(); } @Test public void update_supports_updating_to_the_same_value() { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); underTest.update(FILE_COMPONENT, metric1, SOME_MEASURE); } @Test public void update_updates_the_stored_value() { Measure newMeasure = Measure.updatedMeasureBuilder(SOME_MEASURE).create(); underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); underTest.update(FILE_COMPONENT, metric1, newMeasure); assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric1)).containsSame(newMeasure); } @Test public void getRawMeasure_throws_NPE_without_reading_batch_report_if_component_arg_is_null() { try { underTestWithMock.getRawMeasure(null, metric1); fail("an NPE should have been raised"); } catch (NullPointerException e) { verifyNoMoreInteractions(mockBatchReportReader); } } @Test public void getRawMeasure_throws_NPE_without_reading_batch_report_if_metric_arg_is_null() { try { underTestWithMock.getRawMeasure(FILE_COMPONENT, null); fail("an NPE should have been raised"); } catch (NullPointerException e) { verifyNoMoreInteractions(mockBatchReportReader); } } @Test public void getRawMeasure_returns_measure_added_through_add_method() { underTest.add(FILE_COMPONENT, metric1, SOME_MEASURE); Optional<Measure> res = underTest.getRawMeasure(FILE_COMPONENT, metric1); assertThat(res) .isPresent() .containsSame(SOME_MEASURE); // make sure we really match on the specified component and metric assertThat(underTest.getRawMeasure(OTHER_COMPONENT, metric1)).isNotPresent(); assertThat(underTest.getRawMeasure(FILE_COMPONENT, metric2)).isNotPresent(); } }
10,109
38.960474
158
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.google.common.collect.ImmutableList; import java.util.Collections; import org.junit.Test; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class MeasureComputersHolderImplTest { private MeasureComputersHolderImpl underTest = new MeasureComputersHolderImpl(); @Test public void get_measure_computers() { MeasureComputerWrapper measureComputer = mock(MeasureComputerWrapper.class); underTest.setMeasureComputers(Collections.singletonList(measureComputer)); assertThat(underTest.getMeasureComputers()).containsOnly(measureComputer); } @Test public void get_measure_computers_throws_ISE_if_not_initialized() { assertThatThrownBy(() -> underTest.getMeasureComputers()) .isInstanceOf(IllegalStateException.class) .hasMessage("Measure computers have not been initialized yet"); } @Test public void set_measure_computers_supports_empty_arg_is_empty() { underTest.setMeasureComputers(ImmutableList.of()); assertThat(underTest.getMeasureComputers()).isEmpty(); } @Test public void set_measure_computers_throws_ISE_if_already_initialized() { assertThatThrownBy(() -> { MeasureComputerWrapper measureComputer = mock(MeasureComputerWrapper.class); underTest.setMeasureComputers(Collections.singletonList(measureComputer)); underTest.setMeasureComputers(Collections.singletonList(measureComputer)); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Measure computers have already been initialized"); } }
2,623
36.485714
84
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureComputersHolderRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.rules.ExternalResource; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper; import static java.util.Objects.requireNonNull; public class MeasureComputersHolderRule extends ExternalResource implements MeasureComputersHolder { private final MeasureComputer.MeasureComputerDefinitionContext context; private List<MeasureComputerWrapper> measureComputers = new ArrayList<>(); public MeasureComputersHolderRule(MeasureComputer.MeasureComputerDefinitionContext context) { this.context = context; } @After public void tearDown() { measureComputers.clear(); } @Override public Iterable<MeasureComputerWrapper> getMeasureComputers() { return measureComputers; } public void addMeasureComputer(MeasureComputer measureComputer) { requireNonNull(measureComputer, "Measure computer cannot be null"); MeasureComputer.MeasureComputerDefinition definition = measureComputer.define(context); this.measureComputers.add(new MeasureComputerWrapper(measureComputer, definition)); } }
2,088
35.649123
100
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureDtoToMeasureTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.util.Optional; import org.assertj.core.data.Offset; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure.Level; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.db.measure.MeasureDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class MeasureDtoToMeasureTest { private static final Metric SOME_INT_METRIC = new MetricImpl("42", "int", "name", Metric.MetricType.INT); private static final Metric SOME_LONG_METRIC = new MetricImpl("42", "long", "name", Metric.MetricType.WORK_DUR); private static final Metric SOME_DOUBLE_METRIC = new MetricImpl("42", "double", "name", Metric.MetricType.FLOAT); private static final Metric SOME_STRING_METRIC = new MetricImpl("42", "string", "name", Metric.MetricType.STRING); private static final Metric SOME_BOOLEAN_METRIC = new MetricImpl("42", "boolean", "name", Metric.MetricType.BOOL); private static final Metric SOME_LEVEL_METRIC = new MetricImpl("42", "level", "name", Metric.MetricType.LEVEL); private static final String SOME_DATA = "some_data man!"; private static final String SOME_ALERT_TEXT = "some alert text_be_careFul!"; private static final MeasureDto EMPTY_MEASURE_DTO = new MeasureDto(); private MeasureDtoToMeasure underTest = new MeasureDtoToMeasure(); @Test public void toMeasure_returns_absent_for_null_argument() { assertThat(underTest.toMeasure(null, SOME_INT_METRIC)).isNotPresent(); } @Test public void toMeasure_throws_NPE_if_metric_argument_is_null() { assertThatThrownBy(() -> underTest.toMeasure(EMPTY_MEASURE_DTO, null)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasure_throws_NPE_if_both_arguments_are_null() { assertThatThrownBy(() -> underTest.toMeasure(null, null)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasure_returns_no_value_if_dto_has_no_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dto_has_invalid_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setData("trololo"), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_value_if_dta_has_data_in_wrong_case_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setData("waRn"), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_no_QualityGateStatus_if_dto_has_no_alertStatus_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); } @Test public void toMeasure_returns_no_QualityGateStatus_if_alertStatus_has_invalid_data_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setData("trololo"), SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); } @Test public void toMeasure_returns_no_QualityGateStatus_if_alertStatus_has_data_in_wrong_case_for_Level_Metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setData("waRn"), SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().hasQualityGateStatus()).isFalse(); } @Test public void toMeasure_returns_value_for_LEVEL_Metric() { for (Level level : Level.values()) { verify_toMeasure_returns_value_for_LEVEL_Metric(level); } } private void verify_toMeasure_returns_value_for_LEVEL_Metric(Level expectedLevel) { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setData(expectedLevel.name()), SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LEVEL); assertThat(measure.get().getLevelValue()).isEqualTo(expectedLevel); } @Test public void toMeasure_for_LEVEL_Metric_can_have_an_qualityGateStatus() { MeasureDto measureDto = new MeasureDto().setData(Level.OK.name()).setAlertStatus(Level.ERROR.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LEVEL); assertThat(measure.get().getLevelValue()).isEqualTo(Level.OK); assertThat(measure.get().getQualityGateStatus().getStatus()).isEqualTo(Level.ERROR); assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } @Test public void toMeasure_for_LEVEL_Metric_ignores_data() { MeasureDto measureDto = new MeasureDto().setAlertStatus(Level.ERROR.name()).setData(SOME_DATA); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_LEVEL_METRIC); assertThat(measure).isPresent(); assertThatThrownBy(() ->measure.get().getStringValue()) .isInstanceOf(IllegalStateException.class); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_int_part_of_value_in_dto_for_Int_Metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setValue(1.5d), SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.INT); assertThat(measure.get().getIntValue()).isOne(); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Int_Metric() { MeasureDto measureDto = new MeasureDto().setValue(10d).setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_INT_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.INT); assertThat(measure.get().getIntValue()).isEqualTo(10); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); assertThat(measure.get().getQualityGateStatus().getStatus()).isEqualTo(Level.OK); assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Long_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_long_part_of_value_in_dto_for_Long_Metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setValue(1.5d), SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LONG); assertThat(measure.get().getLongValue()).isOne(); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Long_Metric() { MeasureDto measureDto = new MeasureDto().setValue(10d).setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_LONG_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.LONG); assertThat(measure.get().getLongValue()).isEqualTo(10); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); assertThat(measure.get().getQualityGateStatus().getStatus()).isEqualTo(Level.OK); assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Double_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_DOUBLE_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Double_Metric() { MeasureDto measureDto = new MeasureDto().setValue(10.6395d).setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_DOUBLE_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.DOUBLE); assertThat(measure.get().getDoubleValue()).isEqualTo(10.6395d); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); assertThat(measure.get().getQualityGateStatus().getStatus()).isEqualTo(Level.OK); assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_returns_false_value_if_dto_has_invalid_value_for_Boolean_metric() { Optional<Measure> measure = underTest.toMeasure(new MeasureDto().setValue(1.987d), SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.BOOLEAN); assertThat(measure.get().getBooleanValue()).isFalse(); } @Test public void toMeasure_maps_data_and_alert_properties_in_dto_for_Boolean_metric() { MeasureDto measureDto = new MeasureDto().setValue(1d).setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_BOOLEAN_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.BOOLEAN); assertThat(measure.get().getBooleanValue()).isTrue(); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); assertThat(measure.get().getQualityGateStatus().getStatus()).isEqualTo(Level.OK); assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } @Test public void toMeasure_returns_no_value_if_dto_has_no_value_for_String_Metric() { Optional<Measure> measure = underTest.toMeasure(EMPTY_MEASURE_DTO, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.NO_VALUE); } @Test public void toMeasure_maps_alert_properties_in_dto_for_String_Metric() { MeasureDto measureDto = new MeasureDto().setData(SOME_DATA).setAlertStatus(Level.OK.name()).setAlertText(SOME_ALERT_TEXT); Optional<Measure> measure = underTest.toMeasure(measureDto, SOME_STRING_METRIC); assertThat(measure).isPresent(); assertThat(measure.get().getValueType()).isEqualTo(Measure.ValueType.STRING); assertThat(measure.get().getStringValue()).isEqualTo(SOME_DATA); assertThat(measure.get().getData()).isEqualTo(SOME_DATA); assertThat(measure.get().getQualityGateStatus().getStatus()).isEqualTo(Level.OK); assertThat(measure.get().getQualityGateStatus().getText()).isEqualTo(SOME_ALERT_TEXT); } @DataProvider public static Object[][] all_types_MeasureDtos() { return new Object[][] { {new MeasureDto().setValue(1d), SOME_BOOLEAN_METRIC}, {new MeasureDto().setValue(1d), SOME_INT_METRIC}, {new MeasureDto().setValue(1d), SOME_LONG_METRIC}, {new MeasureDto().setValue(1d), SOME_DOUBLE_METRIC}, {new MeasureDto().setData("1"), SOME_STRING_METRIC}, {new MeasureDto().setData(Measure.Level.OK.name()), SOME_LEVEL_METRIC} }; } @Test public void toMeasure_should_not_loose_decimals_of_float_values() { MetricImpl metric = new MetricImpl("42", "double", "name", Metric.MetricType.FLOAT, 5, null, false, false); MeasureDto measureDto = new MeasureDto() .setValue(0.12345); Optional<Measure> measure = underTest.toMeasure(measureDto, metric); assertThat(measure.get().getDoubleValue()).isEqualTo(0.12345, Offset.offset(0.000001)); } }
13,940
43.970968
145
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureLevelTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class MeasureLevelTest { @Test public void toLevel_return_absent_for_null_arg() { assertThat(Measure.Level.toLevel(null)).isNotPresent(); } @Test public void verify_toLevel_supports_all_Level_values() { for (Measure.Level level : Measure.Level.values()) { assertThat(Measure.Level.toLevel(level.name())).contains(level); } } @Test public void toLevel_is_case_sensitive_and_returns_absent() { for (Measure.Level level : Measure.Level.values()) { assertThat(Measure.Level.toLevel(level.name().toLowerCase())).isNotPresent(); } } @Test public void toLevel_returns_absent_when_value_is_unknown() { assertThat(Measure.Level.toLevel("trololo")).isNotPresent(); } }
1,707
32.490196
83
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.google.common.collect.ImmutableList; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure.ValueType; import org.sonar.ce.task.projectanalysis.util.WrapInSingleElementArray; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; @RunWith(DataProviderRunner.class) public class MeasureTest { private static final Measure INT_MEASURE = newMeasureBuilder().create(1); private static final Measure LONG_MEASURE = newMeasureBuilder().create(1L); private static final Measure DOUBLE_MEASURE = newMeasureBuilder().create(1d, 1); private static final Measure STRING_MEASURE = newMeasureBuilder().create("some_sT ring"); private static final Measure TRUE_MEASURE = newMeasureBuilder().create(true); private static final Measure FALSE_MEASURE = newMeasureBuilder().create(false); private static final Measure LEVEL_MEASURE = newMeasureBuilder().create(Measure.Level.OK); private static final Measure NO_VALUE_MEASURE = newMeasureBuilder().createNoValue(); private static final List<Measure> MEASURES = ImmutableList.of( INT_MEASURE, LONG_MEASURE, DOUBLE_MEASURE, STRING_MEASURE, TRUE_MEASURE, FALSE_MEASURE, NO_VALUE_MEASURE, LEVEL_MEASURE); @DataProvider public static Object[][] all_but_INT_MEASURE() { return getMeasuresExcept(ValueType.INT); } @DataProvider public static Object[][] all_but_LONG_MEASURE() { return getMeasuresExcept(ValueType.LONG); } @DataProvider public static Object[][] all_but_DOUBLE_MEASURE() { return getMeasuresExcept(ValueType.DOUBLE); } @DataProvider public static Object[][] all_but_BOOLEAN_MEASURE() { return getMeasuresExcept(ValueType.BOOLEAN); } @DataProvider public static Object[][] all_but_STRING_MEASURE() { return getMeasuresExcept(ValueType.STRING); } @DataProvider public static Object[][] all_but_LEVEL_MEASURE() { return getMeasuresExcept(ValueType.LEVEL); } @DataProvider public static Object[][] all() { return MEASURES.stream().map(WrapInSingleElementArray.INSTANCE).toArray(Object[][]::new); } private static Object[][] getMeasuresExcept(final ValueType valueType) { return MEASURES.stream() .filter(input -> input.getValueType() != valueType) .map(WrapInSingleElementArray.INSTANCE) .toArray(Object[][]::new); } @Test public void create_from_String_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> newMeasureBuilder().create((String) null)) .isInstanceOf(NullPointerException.class); } @Test public void create_from_int_has_INT_value_type() { assertThat(INT_MEASURE.getValueType()).isEqualTo(ValueType.INT); } @Test public void create_from_long_has_LONG_value_type() { assertThat(LONG_MEASURE.getValueType()).isEqualTo(ValueType.LONG); } @Test public void create_from_double_has_DOUBLE_value_type() { assertThat(DOUBLE_MEASURE.getValueType()).isEqualTo(ValueType.DOUBLE); } @Test public void create_from_boolean_has_BOOLEAN_value_type() { assertThat(TRUE_MEASURE.getValueType()).isEqualTo(ValueType.BOOLEAN); assertThat(FALSE_MEASURE.getValueType()).isEqualTo(ValueType.BOOLEAN); } @Test public void create_from_String_has_STRING_value_type() { assertThat(STRING_MEASURE.getValueType()).isEqualTo(ValueType.STRING); } @Test @UseDataProvider("all_but_INT_MEASURE") public void getIntValue_throws_ISE_for_all_value_types_except_INT(Measure measure) { assertThatThrownBy(measure::getIntValue) .isInstanceOf(IllegalStateException.class); } @Test public void getIntValue_returns_value_for_INT_value_type() { assertThat(INT_MEASURE.getIntValue()).isOne(); } @Test @UseDataProvider("all_but_LONG_MEASURE") public void getLongValue_throws_ISE_for_all_value_types_except_LONG(Measure measure) { assertThatThrownBy(measure::getLongValue) .isInstanceOf(IllegalStateException.class); } @Test public void getLongValue_returns_value_for_LONG_value_type() { assertThat(LONG_MEASURE.getLongValue()).isOne(); } @Test @UseDataProvider("all_but_DOUBLE_MEASURE") public void getDoubleValue_throws_ISE_for_all_value_types_except_DOUBLE(Measure measure) { assertThatThrownBy(measure::getDoubleValue) .isInstanceOf(IllegalStateException.class); } @Test public void getDoubleValue_returns_value_for_DOUBLE_value_type() { assertThat(DOUBLE_MEASURE.getDoubleValue()).isEqualTo(1d); } @Test @UseDataProvider("all_but_BOOLEAN_MEASURE") public void getBooleanValue_throws_ISE_for_all_value_types_except_BOOLEAN(Measure measure) { assertThatThrownBy(measure::getBooleanValue) .isInstanceOf(IllegalStateException.class); } @Test public void getBooleanValue_returns_value_for_BOOLEAN_value_type() { assertThat(TRUE_MEASURE.getBooleanValue()).isTrue(); assertThat(FALSE_MEASURE.getBooleanValue()).isFalse(); } @Test @UseDataProvider("all_but_STRING_MEASURE") public void getStringValue_throws_ISE_for_all_value_types_except_STRING(Measure measure) { assertThatThrownBy(measure::getStringValue) .isInstanceOf(IllegalStateException.class); } @Test @UseDataProvider("all_but_LEVEL_MEASURE") public void getLevelValue_throws_ISE_for_all_value_types_except_LEVEL(Measure measure) { assertThatThrownBy(measure::getLevelValue) .isInstanceOf(IllegalStateException.class); } @Test public void getData_returns_null_for_NO_VALUE_value_type() { assertThat(NO_VALUE_MEASURE.getData()).isNull(); } @Test @UseDataProvider("all_but_STRING_MEASURE") public void getData_returns_null_for_all_value_types_but_STRING_when_not_set(Measure measure) { assertThat(measure.getData()).isNull(); } @Test public void getData_returns_value_for_STRING_value_type() { assertThat(STRING_MEASURE.getData()).isEqualTo(STRING_MEASURE.getStringValue()); } @Test @UseDataProvider("all") public void hasAlertStatus_returns_false_for_all_value_types_when_not_set(Measure measure) { assertThat(measure.hasQualityGateStatus()).isFalse(); } @Test @UseDataProvider("all") public void getAlertStatus_throws_ISE_for_all_value_types_when_not_set(Measure measure) { assertThatThrownBy(measure::getQualityGateStatus) .isInstanceOf(IllegalStateException.class); } @Test public void getAlertStatus_returns_argument_from_setQualityGateStatus() { QualityGateStatus someStatus = new QualityGateStatus(Measure.Level.OK); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(true, null).getQualityGateStatus()).isEqualTo(someStatus); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(false, null).getQualityGateStatus()).isEqualTo(someStatus); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(1, null).getQualityGateStatus()).isEqualTo(someStatus); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create((long) 1, null).getQualityGateStatus()).isEqualTo(someStatus); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(1, 1, null).getQualityGateStatus()).isEqualTo(someStatus); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create("str").getQualityGateStatus()).isEqualTo(someStatus); assertThat(newMeasureBuilder().setQualityGateStatus(someStatus).create(Measure.Level.OK).getQualityGateStatus()).isEqualTo(someStatus); } @Test public void newMeasureBuilder_setQualityGateStatus_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> newMeasureBuilder().setQualityGateStatus(null)) .isInstanceOf(NullPointerException.class); } @Test public void updateMeasureBuilder_setQualityGateStatus_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> { Measure.updatedMeasureBuilder(newMeasureBuilder().createNoValue()).setQualityGateStatus(null); }) .isInstanceOf(NullPointerException.class); } @Test public void updateMeasureBuilder_setQualityGateStatus_throws_USO_if_measure_already_has_a_QualityGateStatus() { assertThatThrownBy(() -> { QualityGateStatus qualityGateStatus = new QualityGateStatus(Measure.Level.ERROR); Measure.updatedMeasureBuilder(newMeasureBuilder().setQualityGateStatus(qualityGateStatus).createNoValue()).setQualityGateStatus(qualityGateStatus); }) .isInstanceOf(UnsupportedOperationException.class); } @Test @UseDataProvider("all") public void updateMeasureBuilder_creates_Measure_with_same_immutable_properties(Measure measure) { Measure newMeasure = Measure.updatedMeasureBuilder(measure).create(); assertThat(newMeasure.getValueType()).isEqualTo(measure.getValueType()); assertThat(newMeasure.hasQualityGateStatus()).isEqualTo(measure.hasQualityGateStatus()); } @Test public void getData_returns_argument_from_factory_method() { String someData = "lololool"; assertThat(newMeasureBuilder().create(true, someData).getData()).isEqualTo(someData); assertThat(newMeasureBuilder().create(false, someData).getData()).isEqualTo(someData); assertThat(newMeasureBuilder().create(1, someData).getData()).isEqualTo(someData); assertThat(newMeasureBuilder().create((long) 1, someData).getData()).isEqualTo(someData); assertThat(newMeasureBuilder().create(1, 1, someData).getData()).isEqualTo(someData); } @Test public void measure_of_value_type_LEVEL_has_no_data() { assertThat(LEVEL_MEASURE.getData()).isNull(); } @Test public void double_values_are_scaled_to_1_digit_and_round() { assertThat(newMeasureBuilder().create(30.27777d, 1).getDoubleValue()).isEqualTo(30.3d); assertThat(newMeasureBuilder().create(30d, 1).getDoubleValue()).isEqualTo(30d); assertThat(newMeasureBuilder().create(30.01d, 1).getDoubleValue()).isEqualTo(30d); assertThat(newMeasureBuilder().create(30.1d, 1).getDoubleValue()).isEqualTo(30.1d); } @Test public void create_with_double_value_throws_IAE_if_value_is_NaN() { assertThatThrownBy(() -> newMeasureBuilder().create(Double.NaN, 1)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("NaN is not allowed as a Measure value"); } @Test public void create_with_double_value_data_throws_IAE_if_value_is_NaN() { assertThatThrownBy(() -> newMeasureBuilder().create(Double.NaN, 1, "some data")) .isInstanceOf(IllegalArgumentException.class) .hasMessage("NaN is not allowed as a Measure value"); } @Test public void valueMeasureImplEquals_instanceNotEqualToNull() { Measure.ValueMeasureImpl valueMeasureImpl = (Measure.ValueMeasureImpl) new Measure.NewMeasureBuilder().create(0, null); boolean equal = valueMeasureImpl.equals(null); assertThat(equal).isFalse(); } @Test public void valueMeasureImplEquals_sameInstance_returnTrue() { Measure.ValueMeasureImpl valueMeasureImpl = (Measure.ValueMeasureImpl) new Measure.NewMeasureBuilder().create(0, null); boolean equal = valueMeasureImpl.equals(valueMeasureImpl); assertThat(equal).isTrue(); } }
12,303
37.45
153
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/MeasureToMeasureDtoTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.MutableTreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.db.measure.LiveMeasureDto; import org.sonar.db.measure.MeasureDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class MeasureToMeasureDtoTest { private static final MetricImpl SOME_METRIC = new MetricImpl("42", "metric_key", "metric_name", Metric.MetricType.STRING); private static final String SOME_DATA = "some_data"; private static final String SOME_STRING = "some_string"; private static final MetricImpl SOME_BOOLEAN_METRIC = new MetricImpl("1", "1", "1", Metric.MetricType.BOOL); private static final MetricImpl SOME_INT_METRIC = new MetricImpl("2", "2", "2", Metric.MetricType.INT); private static final MetricImpl SOME_LONG_METRIC = new MetricImpl("3", "3", "3", Metric.MetricType.DISTRIB); private static final MetricImpl SOME_DOUBLE_METRIC = new MetricImpl("4", "4", "4", Metric.MetricType.FLOAT); private static final MetricImpl SOME_STRING_METRIC = new MetricImpl("5", "5", "5", Metric.MetricType.STRING); private static final MetricImpl SOME_LEVEL_METRIC = new MetricImpl("6", "6", "6", Metric.MetricType.LEVEL); private static final String ANALYSIS_UUID = "a1"; private static final Component SOME_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("uuid_1").build(); @Rule public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule(); @Rule public MutableTreeRootHolderRule treeRootHolder = new MutableTreeRootHolderRule(); private MeasureToMeasureDto underTest = new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder); @Before public void setUp() { analysisMetadataHolder.setUuid(ANALYSIS_UUID); } @Test public void toMeasureDto_throws_NPE_if_Measure_arg_is_null() { assertThatThrownBy(() -> underTest.toMeasureDto(null, SOME_METRIC, SOME_COMPONENT)) .isInstanceOf(NullPointerException.class); } @Test public void toMeasureDto_throws_NPE_if_Metric_arg_is_null() { assertThatThrownBy(() -> underTest.toMeasureDto(Measure.newMeasureBuilder().createNoValue(), null, SOME_COMPONENT)) .isInstanceOf(NullPointerException.class); } @DataProvider public static Object[][] all_types_Measures() { return new Object[][] { {Measure.newMeasureBuilder().create(true, SOME_DATA), SOME_BOOLEAN_METRIC}, {Measure.newMeasureBuilder().create(1, SOME_DATA), SOME_INT_METRIC}, {Measure.newMeasureBuilder().create((long) 1, SOME_DATA), SOME_LONG_METRIC}, {Measure.newMeasureBuilder().create(2, 1, SOME_DATA), SOME_DOUBLE_METRIC}, {Measure.newMeasureBuilder().create(SOME_STRING), SOME_STRING_METRIC}, {Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC} }; } @Test @UseDataProvider("all_types_Measures") public void toMeasureDto_returns_Dto_without_alertStatus_nor_alertText_if_Measure_has_no_QualityGateStatus(Measure measure, Metric metric) { MeasureDto measureDto = underTest.toMeasureDto(measure, metric, SOME_COMPONENT); assertThat(measureDto.getAlertStatus()).isNull(); assertThat(measureDto.getAlertText()).isNull(); } @Test public void toMeasureDto_returns_Dto_with_alertStatus_and_alertText_if_Measure_has_QualityGateStatus() { String alertText = "some error"; MeasureDto measureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().setQualityGateStatus(new QualityGateStatus(Measure.Level.ERROR, alertText)).create(SOME_STRING), SOME_STRING_METRIC, SOME_COMPONENT); assertThat(measureDto.getAlertStatus()).isEqualTo(Measure.Level.ERROR.name()); assertThat(measureDto.getAlertText()).isEqualTo(alertText); } @Test @UseDataProvider("all_types_Measures") public void toMeasureDto_set_componentId_and_snapshotId_from_method_arguments(Measure measure, Metric metric) { MeasureDto measureDto = underTest.toMeasureDto(measure, metric, SOME_COMPONENT); assertThat(measureDto.getComponentUuid()).isEqualTo(SOME_COMPONENT.getUuid()); } @Test public void toMeasureDto_maps_value_to_1_or_0_and_data_from_data_field_for_BOOLEAN_metric() { MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(true, SOME_DATA), SOME_BOOLEAN_METRIC, SOME_COMPONENT); assertThat(trueMeasureDto.getValue()).isEqualTo(1d); assertThat(trueMeasureDto.getData()).isEqualTo(SOME_DATA); MeasureDto falseMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(false, SOME_DATA), SOME_BOOLEAN_METRIC, SOME_COMPONENT); assertThat(falseMeasureDto.getValue()).isEqualTo(0d); assertThat(falseMeasureDto.getData()).isEqualTo(SOME_DATA); } @Test public void toMeasureDto_maps_value_and_data_from_data_field_for_INT_metric() { MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(123, SOME_DATA), SOME_INT_METRIC, SOME_COMPONENT); assertThat(trueMeasureDto.getValue()).isEqualTo(123); assertThat(trueMeasureDto.getData()).isEqualTo(SOME_DATA); } @Test public void toMeasureDto_maps_value_and_data_from_data_field_for_LONG_metric() { MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create((long) 456, SOME_DATA), SOME_LONG_METRIC, SOME_COMPONENT); assertThat(trueMeasureDto.getValue()).isEqualTo(456); assertThat(trueMeasureDto.getData()).isEqualTo(SOME_DATA); } @Test public void toMeasureDto_maps_value_and_data_from_data_field_for_DOUBLE_metric() { MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(789, 1, SOME_DATA), SOME_DOUBLE_METRIC, SOME_COMPONENT); assertThat(trueMeasureDto.getValue()).isEqualTo(789); assertThat(trueMeasureDto.getData()).isEqualTo(SOME_DATA); } @Test public void toMeasureDto_maps_to_only_data_for_STRING_metric() { MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(SOME_STRING), SOME_STRING_METRIC, SOME_COMPONENT); assertThat(trueMeasureDto.getValue()).isNull(); assertThat(trueMeasureDto.getData()).isEqualTo(SOME_STRING); } @Test public void toMeasureDto_maps_name_of_Level_to_data_and_has_no_value_for_LEVEL_metric() { MeasureDto trueMeasureDto = underTest.toMeasureDto(Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC, SOME_COMPONENT); assertThat(trueMeasureDto.getValue()).isNull(); assertThat(trueMeasureDto.getData()).isEqualTo(Measure.Level.OK.name()); } @Test public void toLiveMeasureDto() { treeRootHolder.setRoot(SOME_COMPONENT); LiveMeasureDto liveMeasureDto = underTest.toLiveMeasureDto( Measure.newMeasureBuilder().create(Measure.Level.OK), SOME_LEVEL_METRIC, SOME_COMPONENT); assertThat(liveMeasureDto.getTextValue()).isEqualTo(Measure.Level.OK.name()); } }
8,466
45.016304
175
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/PostMeasuresComputationChecksStepTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.PostMeasuresComputationCheck.Context; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.DUMB_PROJECT; import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto; public class PostMeasuresComputationChecksStepTest { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(DUMB_PROJECT); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule().add(NCLOC); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Test public void execute_extensions() { PostMeasuresComputationCheck check1 = mock(PostMeasuresComputationCheck.class); PostMeasuresComputationCheck check2 = mock(PostMeasuresComputationCheck.class); newStep(check1, check2).execute(new TestComputationStepContext()); InOrder inOrder = inOrder(check1, check2); inOrder.verify(check1).onCheck(any(Context.class)); inOrder.verify(check2).onCheck(any(Context.class)); } @Test public void context_contains_project_uuid_from_analysis_metada_holder() { Project project = Project.from(newPrivateProjectDto()); analysisMetadataHolder.setProject(project); PostMeasuresComputationCheck check = mock(PostMeasuresComputationCheck.class); newStep(check).execute(new TestComputationStepContext()); ArgumentCaptor<Context> contextArgumentCaptor = ArgumentCaptor.forClass(Context.class); verify(check).onCheck(contextArgumentCaptor.capture()); assertThat(contextArgumentCaptor.getValue().getProjectUuid()).isEqualTo(project.getUuid()); } @Test public void context_contains_ncloc_when_available() { PostMeasuresComputationCheck check = mock(PostMeasuresComputationCheck.class); measureRepository.addRawMeasure(DUMB_PROJECT.getReportAttributes().getRef(), CoreMetrics.NCLOC_KEY, Measure.newMeasureBuilder().create(10)); newStep(check).execute(new TestComputationStepContext()); ArgumentCaptor<Context> contextArgumentCaptor = ArgumentCaptor.forClass(Context.class); verify(check).onCheck(contextArgumentCaptor.capture()); assertThat(contextArgumentCaptor.getValue().getNcloc()).isEqualTo(10); } @Test public void ncloc_is_zero_in_context_when_not_available() { PostMeasuresComputationCheck check = mock(PostMeasuresComputationCheck.class); newStep(check).execute(new TestComputationStepContext()); ArgumentCaptor<Context> contextArgumentCaptor = ArgumentCaptor.forClass(Context.class); verify(check).onCheck(contextArgumentCaptor.capture()); assertThat(contextArgumentCaptor.getValue().getNcloc()).isZero(); } @Test public void do_nothing_if_no_extensions() { // no failure newStep().execute(new TestComputationStepContext()); } @Test public void fail_if_an_extension_throws_an_exception() { PostMeasuresComputationCheck check1 = mock(PostMeasuresComputationCheck.class); PostMeasuresComputationCheck check2 = mock(PostMeasuresComputationCheck.class); doThrow(new IllegalStateException("BOOM")).when(check2).onCheck(any(Context.class)); PostMeasuresComputationCheck check3 = mock(PostMeasuresComputationCheck.class); try { newStep(check1, check2, check3).execute(new TestComputationStepContext()); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("BOOM"); verify(check1).onCheck(any(Context.class)); verify(check3, never()).onCheck(any(Context.class)); } } @Test public void test_getDescription() { assertThat(newStep().getDescription()).isNotEmpty(); } private PostMeasuresComputationChecksStep newStep(PostMeasuresComputationCheck... postMeasuresComputationChecks) { if (postMeasuresComputationChecks.length == 0) { return new PostMeasuresComputationChecksStep(treeRootHolder, metricRepository, measureRepository, analysisMetadataHolder); } return new PostMeasuresComputationChecksStep(treeRootHolder, metricRepository, measureRepository, analysisMetadataHolder, postMeasuresComputationChecks); } }
6,003
41.885714
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/QualityGateStatusTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateStatusTest { private static final String SOME_TEXT = "some text"; @Test public void one_arg_constructor_throws_NPE_if_Level_arg_is_null() { assertThatThrownBy(() -> new QualityGateStatus(null)) .isInstanceOf(NullPointerException.class); } @Test public void two_args_constructor_throws_NPE_if_Level_arg_is_null() { assertThatThrownBy(() -> new QualityGateStatus(null, SOME_TEXT)) .isInstanceOf(NullPointerException.class); } @Test public void one_arg_constructor_sets_a_null_text() { QualityGateStatus qualityGateStatus = new QualityGateStatus(Measure.Level.OK); assertThat(qualityGateStatus.getStatus()).isEqualTo(Measure.Level.OK); assertThat(qualityGateStatus.getText()).isNull(); } @Test public void two_args_constructor_sets_text() { QualityGateStatus qualityGateStatus = new QualityGateStatus(Measure.Level.OK, SOME_TEXT); assertThat(qualityGateStatus.getStatus()).isEqualTo(Measure.Level.OK); assertThat(qualityGateStatus.getText()).isEqualTo(SOME_TEXT); assertThat(new QualityGateStatus(Measure.Level.OK, null).getText()).isNull(); } @Test public void two_args_constructor_supports_null_text_arg() { assertThat(new QualityGateStatus(Measure.Level.OK, null).getText()).isNull(); } @Test public void verify_equals() { for (Measure.Level level : Measure.Level.values()) { QualityGateStatus status = new QualityGateStatus(level, null); assertThat(status).isEqualTo(status); assertThat(status).isEqualTo(new QualityGateStatus(level, null)); assertThat(status).isNotEqualTo(new QualityGateStatus(level, "bar")); assertThat(status).isNotEqualTo(new QualityGateStatus(level, "")); assertThat(status).isNotNull(); } } @Test public void verify_toString() { assertThat(new QualityGateStatus(Measure.Level.OK, "foo")).hasToString("QualityGateStatus{status=OK, text=foo}"); } }
2,995
35.096386
117
java