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/measure/ReportMeasureComputersVisitorTest.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.Arrays; import java.util.Collections; import org.junit.Rule; import org.junit.Test; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerDefinitionImpl; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; 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.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_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; 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 ReportMeasureComputersVisitorTest { private static final String NEW_METRIC_KEY = "new_metric_key"; private static final String NEW_METRIC_NAME = "new metric name"; private static final org.sonar.api.measures.Metric<Integer> NEW_METRIC = new org.sonar.api.measures.Metric.Builder(NEW_METRIC_KEY, NEW_METRIC_NAME, org.sonar.api.measures.Metric.ValueType.INT) .create(); private static final int ROOT_REF = 1; private static final int DIRECTORY_REF = 123; private static final int FILE_1_REF = 1231; private static final int FILE_2_REF = 1232; private static final Component ROOT = builder(PROJECT, ROOT_REF).setKey("project") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setKey("file1").build(), builder(FILE, FILE_2_REF).setKey("file2").build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(ROOT); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC) .add(COMMENT_LINES) .add(NEW_METRIC); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(ROOT, metricRepository); ComponentIssuesRepository componentIssuesRepository = mock(ComponentIssuesRepository.class); MeasureComputersHolderImpl measureComputersHolder = new MeasureComputersHolderImpl(); @Test public void compute_plugin_measure() { addRawMeasure(FILE_1_REF, NCLOC_KEY, 10); addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, 2); addRawMeasure(FILE_2_REF, NCLOC_KEY, 40); addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, 5); addRawMeasure(DIRECTORY_REF, NCLOC_KEY, 50); addRawMeasure(DIRECTORY_REF, COMMENT_LINES_KEY, 7); addRawMeasure(ROOT_REF, NCLOC_KEY, 50); addRawMeasure(ROOT_REF, COMMENT_LINES_KEY, 7); final MeasureComputer.MeasureComputerDefinition definition = new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics(NCLOC_KEY, COMMENT_LINES_KEY) .setOutputMetrics(NEW_METRIC_KEY) .build(); measureComputersHolder.setMeasureComputers(newArrayList( new MeasureComputerWrapper( new MeasureComputer() { @Override public MeasureComputerDefinition define(MeasureComputerDefinitionContext defContext) { return definition; } @Override public void compute(MeasureComputerContext context) { org.sonar.api.ce.measure.Measure ncloc = context.getMeasure(NCLOC_KEY); org.sonar.api.ce.measure.Measure comment = context.getMeasure(COMMENT_LINES_KEY); if (ncloc != null && comment != null) { context.addMeasure(NEW_METRIC_KEY, ncloc.getIntValue() + comment.getIntValue()); } } }, definition))); VisitorsCrawler visitorsCrawler = new VisitorsCrawler(Arrays.asList(new MeasureComputersVisitor(metricRepository, measureRepository, null, measureComputersHolder, componentIssuesRepository))); visitorsCrawler.visit(ROOT); assertAddedRawMeasure(12, FILE_1_REF, NEW_METRIC_KEY); assertAddedRawMeasure(45, FILE_2_REF, NEW_METRIC_KEY); assertAddedRawMeasure(57, DIRECTORY_REF, NEW_METRIC_KEY); assertAddedRawMeasure(57, ROOT_REF, NEW_METRIC_KEY); } @Test public void nothing_to_compute() { addRawMeasure(FILE_1_REF, NCLOC_KEY, 10); addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, 2); addRawMeasure(FILE_2_REF, NCLOC_KEY, 40); addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, 5); addRawMeasure(DIRECTORY_REF, NCLOC_KEY, 50); addRawMeasure(DIRECTORY_REF, COMMENT_LINES_KEY, 7); addRawMeasure(ROOT_REF, NCLOC_KEY, 50); addRawMeasure(ROOT_REF, COMMENT_LINES_KEY, 7); measureComputersHolder.setMeasureComputers(Collections.emptyList()); VisitorsCrawler visitorsCrawler = new VisitorsCrawler(Arrays.asList(new MeasureComputersVisitor(metricRepository, measureRepository, null, measureComputersHolder, componentIssuesRepository))); visitorsCrawler.visit(ROOT); assertNoAddedRawMeasure(FILE_1_REF); assertNoAddedRawMeasure(FILE_2_REF); assertNoAddedRawMeasure(DIRECTORY_REF); assertNoAddedRawMeasure(ROOT_REF); } private void addRawMeasure(int componentRef, String metricKey, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertNoAddedRawMeasure(int componentRef) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).isEmpty(); } private void assertAddedRawMeasure(int value, int componentRef, String metricKey) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(value))); } }
7,418
43.160714
149
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/ViewsMeasureComputersVisitorTest.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.Arrays; import org.junit.Rule; import org.junit.Test; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.api.ce.measure.test.TestMeasureComputerDefinitionContext; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerDefinitionImpl; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; 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.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; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.entryOf; import static org.sonar.ce.task.projectanalysis.measure.MeasureRepoEntry.toEntries; public class ViewsMeasureComputersVisitorTest { private static final String NEW_METRIC_KEY = "new_metric_key"; private static final String NEW_METRIC_NAME = "new metric name"; private static final org.sonar.api.measures.Metric<Integer> NEW_METRIC = new org.sonar.api.measures.Metric.Builder(NEW_METRIC_KEY, NEW_METRIC_NAME, org.sonar.api.measures.Metric.ValueType.INT) .create(); private static final int ROOT_REF = 1; private static final int VIEW_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 Component TREE_WITH_SUB_VIEWS = builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, VIEW_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()) .build(); private static final Component TREE_WITH_DIRECT_PROJECT_VIEW = builder(VIEW, ROOT_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECT_VIEW_2_REF).build()) .build(); private static final MeasureComputer MEASURE_COMPUTER = new MeasureComputer() { @Override public MeasureComputer.MeasureComputerDefinition define(MeasureComputer.MeasureComputerDefinitionContext defContext) { return new MeasureComputerDefinitionImpl.BuilderImpl() .setInputMetrics(NCLOC_KEY, COMMENT_LINES_KEY) .setOutputMetrics(NEW_METRIC_KEY) .build(); } @Override public void compute(MeasureComputer.MeasureComputerContext context) { org.sonar.api.ce.measure.Measure ncloc = context.getMeasure(NCLOC_KEY); org.sonar.api.ce.measure.Measure comment = context.getMeasure(COMMENT_LINES_KEY); if (ncloc != null && comment != null) { context.addMeasure(NEW_METRIC_KEY, ncloc.getIntValue() + comment.getIntValue()); } } }; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC) .add(COMMENT_LINES) .add(NEW_METRIC); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(TREE_WITH_SUB_VIEWS, metricRepository); @Rule public MeasureComputersHolderRule measureComputersHolder = new MeasureComputersHolderRule(new TestMeasureComputerDefinitionContext()); ComponentIssuesRepository componentIssuesRepository = mock(ComponentIssuesRepository.class); @Test public void compute_plugin_measure() { treeRootHolder.setRoot(TREE_WITH_SUB_VIEWS); addRawMeasure(PROJECT_VIEW_1_REF, NCLOC_KEY, 10); addRawMeasure(PROJECT_VIEW_1_REF, COMMENT_LINES_KEY, 2); addRawMeasure(PROJECT_VIEW_2_REF, NCLOC_KEY, 40); addRawMeasure(PROJECT_VIEW_2_REF, COMMENT_LINES_KEY, 5); addRawMeasure(SUB_SUBVIEW_REF, NCLOC_KEY, 50); addRawMeasure(SUB_SUBVIEW_REF, COMMENT_LINES_KEY, 7); addRawMeasure(VIEW_REF, NCLOC_KEY, 50); addRawMeasure(VIEW_REF, COMMENT_LINES_KEY, 7); addRawMeasure(ROOT_REF, NCLOC_KEY, 50); addRawMeasure(ROOT_REF, COMMENT_LINES_KEY, 7); measureComputersHolder.addMeasureComputer(MEASURE_COMPUTER); VisitorsCrawler visitorsCrawler = new VisitorsCrawler(Arrays.asList(new MeasureComputersVisitor(metricRepository, measureRepository, null, measureComputersHolder, componentIssuesRepository))); visitorsCrawler.visit(treeRootHolder.getRoot()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasure(57, SUB_SUBVIEW_REF, NEW_METRIC_KEY); assertAddedRawMeasure(57, VIEW_REF, NEW_METRIC_KEY); assertAddedRawMeasure(57, ROOT_REF, NEW_METRIC_KEY); } @Test public void compute_plugin_measure_on_views_tree_having_only_one_view_with_a_project_view() { treeRootHolder.setRoot(TREE_WITH_DIRECT_PROJECT_VIEW); addRawMeasure(PROJECT_VIEW_1_REF, NCLOC_KEY, 10); addRawMeasure(PROJECT_VIEW_1_REF, COMMENT_LINES_KEY, 2); addRawMeasure(PROJECT_VIEW_2_REF, NCLOC_KEY, 40); addRawMeasure(PROJECT_VIEW_2_REF, COMMENT_LINES_KEY, 5); addRawMeasure(ROOT_REF, NCLOC_KEY, 50); addRawMeasure(ROOT_REF, COMMENT_LINES_KEY, 7); measureComputersHolder.addMeasureComputer(MEASURE_COMPUTER); VisitorsCrawler visitorsCrawler = new VisitorsCrawler(Arrays.asList(new MeasureComputersVisitor(metricRepository, measureRepository, null, measureComputersHolder, componentIssuesRepository))); visitorsCrawler.visit(treeRootHolder.getRoot()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasure(57, ROOT_REF, NEW_METRIC_KEY); } @Test public void nothing_to_compute_when_no_project_view() { treeRootHolder.setRoot(builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, VIEW_REF) .addChildren( builder(SUBVIEW, SUB_SUBVIEW_REF) .build()) .build()) .build()); measureComputersHolder.addMeasureComputer(MEASURE_COMPUTER); VisitorsCrawler visitorsCrawler = new VisitorsCrawler(Arrays.asList(new MeasureComputersVisitor(metricRepository, measureRepository, null, measureComputersHolder, componentIssuesRepository))); visitorsCrawler.visit(treeRootHolder.getRoot()); assertNoAddedRawMeasureOnProjectViews(); assertNoAddedRawMeasure(SUB_SUBVIEW_REF); assertNoAddedRawMeasure(VIEW_REF); assertNoAddedRawMeasure(ROOT_REF); } @Test public void nothing_to_compute_when_no_measure_computers() { treeRootHolder.setRoot(TREE_WITH_SUB_VIEWS); addRawMeasure(PROJECT_VIEW_1_REF, NCLOC_KEY, 10); addRawMeasure(PROJECT_VIEW_1_REF, COMMENT_LINES_KEY, 2); addRawMeasure(PROJECT_VIEW_2_REF, NCLOC_KEY, 40); addRawMeasure(PROJECT_VIEW_2_REF, COMMENT_LINES_KEY, 5); addRawMeasure(SUB_SUBVIEW_REF, NCLOC_KEY, 50); addRawMeasure(SUB_SUBVIEW_REF, COMMENT_LINES_KEY, 7); addRawMeasure(VIEW_REF, NCLOC_KEY, 50); addRawMeasure(VIEW_REF, COMMENT_LINES_KEY, 7); addRawMeasure(ROOT_REF, NCLOC_KEY, 50); addRawMeasure(ROOT_REF, COMMENT_LINES_KEY, 7); VisitorsCrawler visitorsCrawler = new VisitorsCrawler(Arrays.asList(new MeasureComputersVisitor(metricRepository, measureRepository, null, measureComputersHolder, componentIssuesRepository))); visitorsCrawler.visit(treeRootHolder.getRoot()); assertNoAddedRawMeasureOnProjectViews(); assertNoAddedRawMeasure(SUB_SUBVIEW_REF); assertNoAddedRawMeasure(VIEW_REF); assertNoAddedRawMeasure(ROOT_REF); } private void assertNoAddedRawMeasureOnProjectViews() { assertNoAddedRawMeasure(PROJECT_VIEW_1_REF); assertNoAddedRawMeasure(PROJECT_VIEW_2_REF); } private void addRawMeasure(int componentRef, String metricKey, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertNoAddedRawMeasure(int componentRef) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).isEmpty(); } private void assertAddedRawMeasure(int value, int componentRef, String metricKey) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(value))); } }
9,865
41.709957
149
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/EvaluatedConditionTest.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.qualitygatedetails; import org.junit.Test; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; 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 EvaluatedConditionTest { private static final Metric SOME_METRIC = mock(Metric.class); static { when(SOME_METRIC.getKey()).thenReturn("dummy key"); } private static final Condition SOME_CONDITION = new Condition(SOME_METRIC, Condition.Operator.LESS_THAN.getDbValue(), "1"); private static final Measure.Level SOME_LEVEL = Measure.Level.OK; private static final String SOME_VALUE = "some value"; @Test public void constructor_throws_NPE_if_Condition_arg_is_null() { assertThatThrownBy(() -> new EvaluatedCondition(null, SOME_LEVEL, SOME_VALUE)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_NPE_if_Level_arg_is_null() { assertThatThrownBy(() -> new EvaluatedCondition(SOME_CONDITION, null, SOME_VALUE)) .isInstanceOf(NullPointerException.class); } @Test public void getCondition_returns_object_passed_in_constructor() { assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, SOME_VALUE).getCondition()).isSameAs(SOME_CONDITION); } @Test public void getLevel_returns_object_passed_in_constructor() { assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, SOME_VALUE).getLevel()).isSameAs(SOME_LEVEL); } @Test public void getValue_returns_empty_string_if_null_was_passed_in_constructor() { assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, null).getActualValue()).isEmpty(); } @Test public void getValue_returns_toString_of_Object_passed_in_constructor() { assertThat(new EvaluatedCondition(SOME_CONDITION, SOME_LEVEL, new A()).getActualValue()).isEqualTo("A string"); } private static class A { @Override public String toString() { return "A string"; } } }
3,069
36.901235
125
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/measure/qualitygatedetails/QualityGateDetailsDataTest.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.qualitygatedetails; import com.google.common.collect.ImmutableList; import java.util.Collections; import org.junit.Test; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.test.JsonAssert; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class QualityGateDetailsDataTest { @Test public void constructor_throws_NPE_if_Level_arg_is_null() { assertThatThrownBy(() -> new QualityGateDetailsData(null, Collections.emptyList(), false)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_NPE_if_Iterable_arg_is_null() { assertThatThrownBy(() -> new QualityGateDetailsData(Measure.Level.OK, null, false)) .isInstanceOf(NullPointerException.class); } @Test public void verify_json_when_there_is_no_condition() { String actualJson = new QualityGateDetailsData(Measure.Level.OK, Collections.emptyList(), false).toJson(); JsonAssert.assertJson(actualJson).isSimilarTo("{" + "\"level\":\"OK\"," + "\"conditions\":[]" + "}"); } @Test public void verify_json_for_each_type_of_condition() { String value = "actualValue"; Condition condition = new Condition(new MetricImpl("1", "key1", "name1", Metric.MetricType.STRING), Condition.Operator.GREATER_THAN.getDbValue(), "errorTh"); ImmutableList<EvaluatedCondition> evaluatedConditions = ImmutableList.of( new EvaluatedCondition(condition, Measure.Level.OK, value), new EvaluatedCondition(condition, Measure.Level.ERROR, value)); String actualJson = new QualityGateDetailsData(Measure.Level.OK, evaluatedConditions, false).toJson(); JsonAssert.assertJson(actualJson).isSimilarTo("{" + "\"level\":\"OK\"," + "\"conditions\":[" + " {" + " \"metric\":\"key1\"," + " \"op\":\"GT\"," + " \"error\":\"errorTh\"," + " \"actual\":\"actualValue\"," + " \"level\":\"OK\"" + " }," + " {" + " \"metric\":\"key1\"," + " \"op\":\"GT\"," + " \"error\":\"errorTh\"," + " \"actual\":\"actualValue\"," + " \"level\":\"ERROR\"" + " }" + "]" + "}"); } @Test public void verify_json_for_condition_on_leak_metric() { String value = "actualValue"; Condition condition = new Condition(new MetricImpl("1", "new_key1", "name1", Metric.MetricType.STRING), Condition.Operator.GREATER_THAN.getDbValue(), "errorTh"); ImmutableList<EvaluatedCondition> evaluatedConditions = ImmutableList.of( new EvaluatedCondition(condition, Measure.Level.OK, value), new EvaluatedCondition(condition, Measure.Level.ERROR, value)); String actualJson = new QualityGateDetailsData(Measure.Level.OK, evaluatedConditions, false).toJson(); JsonAssert.assertJson(actualJson).isSimilarTo("{" + "\"level\":\"OK\"," + "\"conditions\":[" + " {" + " \"metric\":\"new_key1\"," + " \"op\":\"GT\"," + " \"error\":\"errorTh\"," + " \"actual\":\"actualValue\"," + " \"period\":1," + " \"level\":\"OK\"" + " }," + " {" + " \"metric\":\"new_key1\"," + " \"op\":\"GT\"," + " \"error\":\"errorTh\"," + " \"actual\":\"actualValue\"," + " \"period\":1," + " \"level\":\"ERROR\"" + " }" + "]" + "}"); } @Test public void verify_json_for_small_leak() { String actualJson = new QualityGateDetailsData(Measure.Level.OK, Collections.emptyList(), false).toJson(); JsonAssert.assertJson(actualJson).isSimilarTo("{\"ignoredConditions\": false}"); String actualJson2 = new QualityGateDetailsData(Measure.Level.OK, Collections.emptyList(), true).toJson(); JsonAssert.assertJson(actualJson2).isSimilarTo("{\"ignoredConditions\": true}"); } }
4,922
37.460938
165
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricDtoToMetricTest.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.metric; import org.junit.Test; import org.sonar.db.metric.MetricDto; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricDtoToMetricTest { private static final double SOME_BEST_VALUE = 951; private MetricDtoToMetric underTest = MetricDtoToMetric.INSTANCE; @Test public void apply_throws_NPE_if_arg_is_null() { assertThatThrownBy(() -> underTest.apply(null)) .isInstanceOf(NullPointerException.class); } @Test public void verify_mapping_from_dto() { for (Metric.MetricType metricType : Metric.MetricType.values()) { MetricDto metricDto = createMetricDto(metricType); Metric metric = underTest.apply(metricDto); assertThat(metric.getUuid()).isEqualTo(metricDto.getUuid()); assertThat(metric.getKey()).isEqualTo(metricDto.getKey()); assertThat(metric.getName()).isEqualTo(metricDto.getShortName()); assertThat(metric.getType()).isEqualTo(metricType); assertThat(metric.isBestValueOptimized()).isFalse(); assertThat(metric.getBestValue()).isEqualTo(SOME_BEST_VALUE); assertThat(metric.isDeleteHistoricalData()).isTrue(); } } @Test public void verify_mapping_of_isBestValueOptimized() { assertThat(underTest.apply(createMetricDto(Metric.MetricType.INT).setOptimizedBestValue(true)).isBestValueOptimized()).isTrue(); } @Test public void apply_throws_IAE_if_valueType_can_not_be_parsed() { assertThatThrownBy(() -> underTest.apply(new MetricDto().setUuid("1").setKey("key").setValueType("trololo"))) .isInstanceOf(IllegalArgumentException.class); } private static MetricDto createMetricDto(Metric.MetricType metricType) { return new MetricDto() .setUuid(metricType.name()) .setKey(metricType.name() + "_key") .setShortName(metricType.name() + "_name") .setValueType(metricType.name()) .setBestValue(SOME_BEST_VALUE) .setDeleteHistoricalData(true) .setEnabled(true); } }
2,915
35.911392
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/MetricImplTest.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.metric; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class MetricImplTest { private static final String SOME_UUID = "uuid"; private static final String SOME_KEY = "key"; private static final String SOME_NAME = "name"; @Test public void constructor_throws_NPE_if_key_arg_is_null() { assertThatThrownBy(() -> new MetricImpl(SOME_UUID, null, SOME_NAME, Metric.MetricType.BOOL)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_NPE_if_name_arg_is_null() { assertThatThrownBy(() -> new MetricImpl(SOME_UUID, SOME_KEY, null, Metric.MetricType.BOOL)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_NPE_if_valueType_arg_is_null() { assertThatThrownBy(() -> new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, null)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_IAE_if_bestValueOptimized_is_true_but_bestValue_is_null() { assertThatThrownBy(() -> new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.INT, 1, null, true, false)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("A BestValue must be specified if Metric is bestValueOptimized"); } @Test public void verify_getters() { MetricImpl metric = new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT); assertThat(metric.getUuid()).isEqualTo(SOME_UUID); assertThat(metric.getKey()).isEqualTo(SOME_KEY); assertThat(metric.getName()).isEqualTo(SOME_NAME); assertThat(metric.getType()).isEqualTo(Metric.MetricType.FLOAT); } @Test public void equals_uses_only_key() { MetricImpl expected = new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT)).isEqualTo(expected); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.STRING)).isEqualTo(expected); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.STRING, null, 0d, true, true)).isEqualTo(expected); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.STRING, null, null, false, false)).isEqualTo(expected); assertThat(new MetricImpl(SOME_UUID, "some other key", SOME_NAME, Metric.MetricType.FLOAT)).isNotEqualTo(expected); } @Test public void hashcode_uses_only_key() { int expected = new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT).hashCode(); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, "some other name", Metric.MetricType.FLOAT).hashCode()).isEqualTo(expected); assertThat(new MetricImpl(SOME_UUID, SOME_KEY, "some other name", Metric.MetricType.BOOL).hashCode()).isEqualTo(expected); } @Test public void all_fields_are_displayed_in_toString() { assertThat(new MetricImpl(SOME_UUID, SOME_KEY, SOME_NAME, Metric.MetricType.FLOAT, 1, 951d, true, false)) .hasToString("MetricImpl{uuid=uuid, key=key, name=name, type=FLOAT, bestValue=951.0, bestValueOptimized=true, deleteHistoricalData=false}"); } }
4,111
42.744681
146
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/metric/ReportMetricValidatorImplTest.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.metric; import com.google.common.collect.ImmutableSet; import java.util.Collections; 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.api.utils.log.LoggerLevel; import org.sonar.core.metric.ScannerMetrics; 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.Metric.Builder; import static org.sonar.api.measures.Metric.ValueType; public class ReportMetricValidatorImplTest { @Rule public LogTester logTester = new LogTester().setLevel(LoggerLevel.DEBUG); static final String METRIC_KEY = "metric_key"; ScannerMetrics scannerMetrics = mock(ScannerMetrics.class); @Before public void before() { logTester.setLevel(Level.DEBUG); } @Test public void validate_metric() { when(scannerMetrics.getMetrics()).thenReturn(ImmutableSet.of(new Builder(METRIC_KEY, "name", ValueType.INT).create())); ReportMetricValidator validator = new ReportMetricValidatorImpl(scannerMetrics); assertThat(validator.validate(METRIC_KEY)).isTrue(); assertThat(logTester.logs()).isEmpty(); } @Test public void not_validate_metric() { when(scannerMetrics.getMetrics()).thenReturn(Collections.emptySet()); ReportMetricValidator validator = new ReportMetricValidatorImpl(scannerMetrics); assertThat(validator.validate(METRIC_KEY)).isFalse(); assertThat(logTester.logs()).containsOnly("The metric 'metric_key' is ignored and should not be send in the batch report"); } @Test public void not_generate_new_log_when_validating_twice_the_same_metric() { when(scannerMetrics.getMetrics()).thenReturn(Collections.emptySet()); ReportMetricValidator validator = new ReportMetricValidatorImpl(scannerMetrics); assertThat(validator.validate(METRIC_KEY)).isFalse(); assertThat(logTester.logs()).hasSize(1); assertThat(validator.validate(METRIC_KEY)).isFalse(); assertThat(logTester.logs()).hasSize(1); } }
2,991
35.938272
127
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/NotificationFactoryTest.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.notification; import com.google.common.collect.ImmutableMap; 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.lang.reflect.Field; import java.util.Collections; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.Durations; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.Branch; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.issue.DumbRule; import org.sonar.ce.task.projectanalysis.issue.RuleRepositoryRule; import org.sonar.core.issue.DefaultIssue; import org.sonar.db.component.BranchType; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; import org.sonar.server.issue.notification.IssuesChangesNotification; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.AnalysisChange; import org.sonar.server.issue.notification.IssuesChangesNotificationBuilder.ChangedIssue; import org.sonar.server.issue.notification.IssuesChangesNotificationSerializer; import org.sonar.server.issue.notification.MyNewIssuesNotification; import org.sonar.server.issue.notification.NewIssuesNotification; import org.sonar.server.issue.notification.NewIssuesNotification.DetailsSupplier; import org.sonar.server.issue.notification.NewIssuesNotification.RuleDefinition; import static java.util.Collections.emptyMap; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; 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.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.issue.Issue.STATUS_OPEN; 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; @RunWith(DataProviderRunner.class) public class NotificationFactoryTest { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public RuleRepositoryRule ruleRepository = new RuleRepositoryRule(); @Rule public AnalysisMetadataHolderRule analysisMetadata = new AnalysisMetadataHolderRule(); private Durations durations = new Durations(); private IssuesChangesNotificationSerializer issuesChangesSerializer = mock(IssuesChangesNotificationSerializer.class); private NotificationFactory underTest = new NotificationFactory(treeRootHolder, analysisMetadata, ruleRepository, durations, issuesChangesSerializer); @Test public void newMyNewIssuesNotification_throws_NPE_if_assigneesByUuid_is_null() { assertThatThrownBy(() -> underTest.newMyNewIssuesNotification(null)) .isInstanceOf(NullPointerException.class) .hasMessage("assigneesByUuid can't be null"); } @Test public void newNewIssuesNotification_throws_NPE_if_assigneesByUuid_is_null() { assertThatThrownBy(() -> underTest.newNewIssuesNotification(null)) .isInstanceOf(NullPointerException.class) .hasMessage("assigneesByUuid can't be null"); } @Test public void newMyNewIssuesNotification_returns_MyNewIssuesNotification_object_with_the_constructor_Durations() { MyNewIssuesNotification notification = underTest.newMyNewIssuesNotification(emptyMap()); assertThat(readDurationsField(notification)).isSameAs(durations); } @Test public void newNewIssuesNotification_returns_NewIssuesNotification_object_with_the_constructor_Durations() { NewIssuesNotification notification = underTest.newNewIssuesNotification(emptyMap()); assertThat(readDurationsField(notification)).isSameAs(durations); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getUserNameByUuid_fails_with_NPE_if_uuid_is_null() { MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getUserNameByUuid(null)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can't be null"); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getUserNameByUuid_always_returns_empty_if_map_argument_is_empty() { MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getUserNameByUuid("foo")).isEmpty(); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getUserNameByUuid_returns_name_of_user_from_map_argument() { Set<UserDto> users = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> UserTesting.newUserDto().setLogin("user" + i)) .collect(Collectors.toSet()); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification( users.stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity()))); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getUserNameByUuid("foo")).isEmpty(); users .forEach(user -> assertThat(detailsSupplier.getUserNameByUuid(user.getUuid())).contains(user.getName())); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getUserNameByUuid_returns_empty_if_user_has_null_name() { UserDto user = UserTesting.newUserDto().setLogin("user_noname").setName(null); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(ImmutableMap.of(user.getUuid(), user)); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getUserNameByUuid(user.getUuid())).isEmpty(); } @Test public void newNewIssuesNotification_DetailsSupplier_getUserNameByUuid_fails_with_NPE_if_uuid_is_null() { NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getUserNameByUuid(null)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can't be null"); } @Test public void newNewIssuesNotification_DetailsSupplier_getUserNameByUuid_always_returns_empty_if_map_argument_is_empty() { NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getUserNameByUuid("foo")).isEmpty(); } @Test public void newNewIssuesNotification_DetailsSupplier_getUserNameByUuid_returns_name_of_user_from_map_argument() { Set<UserDto> users = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> UserTesting.newUserDto().setLogin("user" + i)) .collect(Collectors.toSet()); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification( users.stream().collect(Collectors.toMap(UserDto::getUuid, Function.identity()))); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getUserNameByUuid("foo")).isEmpty(); users .forEach(user -> assertThat(detailsSupplier.getUserNameByUuid(user.getUuid())).contains(user.getName())); } @Test public void newNewIssuesNotification_DetailsSupplier_getUserNameByUuid_returns_empty_if_user_has_null_name() { UserDto user = UserTesting.newUserDto().setLogin("user_noname").setName(null); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(ImmutableMap.of(user.getUuid(), user)); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getUserNameByUuid(user.getUuid())).isEmpty(); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_fails_with_ISE_if_TreeRootHolder_is_not_initialized() { MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid("foo")) .isInstanceOf(IllegalStateException.class) .hasMessage("Holder has not been initialized yet"); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_fails_with_NPE_if_uuid_is_null() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root").build()); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid(null)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can't be null"); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_name_of_project_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root").build()); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getComponentNameByUuid("rootUuid")).contains("root"); assertThat(detailsSupplier.getComponentNameByUuid("foo")).isEmpty(); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_shortName_of_dir_and_file_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root") .addChildren(ReportComponent.builder(DIRECTORY, 2).setUuid("dir1Uuid").setName("dir1").setShortName("dir1_short") .addChildren(ReportComponent.builder(FILE, 21).setUuid("file21Uuid").setName("file21").setShortName("file21_short").build()) .build()) .addChildren(ReportComponent.builder(DIRECTORY, 3).setUuid("dir2Uuid").setName("dir2").setShortName("dir2_short") .addChildren(ReportComponent.builder(FILE, 31).setUuid("file31Uuid").setName("file31").setShortName("file31_short").build()) .addChildren(ReportComponent.builder(FILE, 32).setUuid("file32Uuid").setName("file32").setShortName("file32_short").build()) .build()) .addChildren(ReportComponent.builder(FILE, 11).setUuid("file11Uuid").setName("file11").setShortName("file11_short").build()) .build()); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); Stream.of("dir1", "dir2", "file11", "file21", "file31", "file32") .forEach(name -> { assertThat(detailsSupplier.getComponentNameByUuid(name + "Uuid")).contains(name + "_short"); assertThat(detailsSupplier.getComponentNameByUuid(name)).isEmpty(); }); } @Test public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_fails_with_ISE_if_TreeRootHolder_is_not_initialized() { NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid("foo")) .isInstanceOf(IllegalStateException.class) .hasMessage("Holder has not been initialized yet"); } @Test public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_fails_with_NPE_if_uuid_is_null() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root").build()); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getComponentNameByUuid(null)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can't be null"); } @Test public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_name_of_project_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root").build()); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getComponentNameByUuid("rootUuid")).contains("root"); assertThat(detailsSupplier.getComponentNameByUuid("foo")).isEmpty(); } @Test public void newNewIssuesNotification_DetailsSupplier_getComponentNameByUuid_returns_shortName_of_dir_and_file_in_TreeRootHolder() { treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).setUuid("rootUuid").setName("root") .addChildren(ReportComponent.builder(DIRECTORY, 2).setUuid("dir1Uuid").setName("dir1").setShortName("dir1_short") .addChildren(ReportComponent.builder(FILE, 21).setUuid("file21Uuid").setName("file21").setShortName("file21_short").build()) .build()) .addChildren(ReportComponent.builder(DIRECTORY, 3).setUuid("dir2Uuid").setName("dir2").setShortName("dir2_short") .addChildren(ReportComponent.builder(FILE, 31).setUuid("file31Uuid").setName("file31").setShortName("file31_short").build()) .addChildren(ReportComponent.builder(FILE, 32).setUuid("file32Uuid").setName("file32").setShortName("file32_short").build()) .build()) .addChildren(ReportComponent.builder(FILE, 11).setUuid("file11Uuid").setName("file11").setShortName("file11_short").build()) .build()); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); Stream.of("dir1", "dir2", "file11", "file21", "file31", "file32") .forEach(name -> { assertThat(detailsSupplier.getComponentNameByUuid(name + "Uuid")).contains(name + "_short"); assertThat(detailsSupplier.getComponentNameByUuid(name)).isEmpty(); }); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_fails_with_NPE_if_ruleKey_is_null() { MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getRuleDefinitionByRuleKey(null)) .isInstanceOf(NullPointerException.class) .hasMessage("ruleKey can't be null"); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_always_returns_empty_if_RuleRepository_is_empty() { MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.of("foo", "bar"))).isEmpty(); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.of("bar", "foo"))).isEmpty(); } @Test public void newMyNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_returns_name_and_language_from_RuleRepository() { RuleKey rulekey1 = RuleKey.of("foo", "bar"); RuleKey rulekey2 = RuleKey.of("foo", "donut"); RuleKey rulekey3 = RuleKey.of("no", "language"); DumbRule rule1 = ruleRepository.add(rulekey1).setName("rule1").setLanguage("lang1"); DumbRule rule2 = ruleRepository.add(rulekey2).setName("rule2").setLanguage("lang2"); DumbRule rule3 = ruleRepository.add(rulekey3).setName("rule3"); MyNewIssuesNotification underTest = this.underTest.newMyNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(rulekey1)) .contains(new RuleDefinition(rule1.getName(), rule1.getLanguage())); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(rulekey2)) .contains(new RuleDefinition(rule2.getName(), rule2.getLanguage())); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(rulekey3)) .contains(new RuleDefinition(rule3.getName(), null)); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.of("donut", "foo"))) .isEmpty(); } @Test public void newNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_fails_with_NPE_if_ruleKey_is_null() { NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThatThrownBy(() -> detailsSupplier.getRuleDefinitionByRuleKey(null)) .isInstanceOf(NullPointerException.class) .hasMessage("ruleKey can't be null"); } @Test public void newNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_always_returns_empty_if_RuleRepository_is_empty() { NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.of("foo", "bar"))).isEmpty(); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.of("bar", "foo"))).isEmpty(); } @Test public void newNewIssuesNotification_DetailsSupplier_getRuleDefinitionByRuleKey_returns_name_and_language_from_RuleRepository() { RuleKey rulekey1 = RuleKey.of("foo", "bar"); RuleKey rulekey2 = RuleKey.of("foo", "donut"); RuleKey rulekey3 = RuleKey.of("no", "language"); DumbRule rule1 = ruleRepository.add(rulekey1).setName("rule1").setLanguage("lang1"); DumbRule rule2 = ruleRepository.add(rulekey2).setName("rule2").setLanguage("lang2"); DumbRule rule3 = ruleRepository.add(rulekey3).setName("rule3"); NewIssuesNotification underTest = this.underTest.newNewIssuesNotification(emptyMap()); DetailsSupplier detailsSupplier = readDetailsSupplier(underTest); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(rulekey1)) .contains(new RuleDefinition(rule1.getName(), rule1.getLanguage())); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(rulekey2)) .contains(new RuleDefinition(rule2.getName(), rule2.getLanguage())); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(rulekey3)) .contains(new RuleDefinition(rule3.getName(), null)); assertThat(detailsSupplier.getRuleDefinitionByRuleKey(RuleKey.of("donut", "foo"))) .isEmpty(); } @Test public void newIssuesChangesNotification_fails_with_ISE_if_analysis_date_has_not_been_set() { Set<DefaultIssue> issues = IntStream.range(0, 1 + new Random().nextInt(2)) .mapToObj(i -> new DefaultIssue()) .collect(Collectors.toSet()); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(issues, assigneesByUuid)) .isInstanceOf(IllegalStateException.class) .hasMessage("Analysis date has not been set"); } @Test public void newIssuesChangesNotification_fails_with_IAE_if_issues_is_empty() { analysisMetadata.setAnalysisDate(new Random().nextLong()); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(Collections.emptySet(), assigneesByUuid)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("issues can't be empty"); } @Test public void newIssuesChangesNotification_fails_with_NPE_if_issue_has_no_rule() { DefaultIssue issue = new DefaultIssue(); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); analysisMetadata.setAnalysisDate(new Random().nextLong()); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(NullPointerException.class); } @Test public void newIssuesChangesNotification_fails_with_ISE_if_rule_of_issue_does_not_exist_in_repository() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); analysisMetadata.setAnalysisDate(new Random().nextLong()); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not find rule " + ruleKey + " in RuleRepository"); } @Test public void newIssuesChangesNotification_fails_with_ISE_if_treeRootHolder_is_empty() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ruleRepository.add(ruleKey); analysisMetadata.setAnalysisDate(new Random().nextLong()); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(IllegalStateException.class) .hasMessage("Holder has not been initialized yet"); } @Test public void newIssuesChangesNotification_fails_with_ISE_if_branch_has_not_been_set() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ruleRepository.add(ruleKey); analysisMetadata.setAnalysisDate(new Random().nextLong()); treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).build()); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(IllegalStateException.class) .hasMessage("Branch has not been set"); } @Test public void newIssuesChangesNotification_fails_with_NPE_if_issue_has_no_key() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ruleRepository.add(ruleKey); treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).build()); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(mock(Branch.class)); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(NullPointerException.class) .hasMessage("key can't be null"); } @Test public void newIssuesChangesNotification_fails_with_NPE_if_issue_has_no_status() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey"); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ruleRepository.add(ruleKey); treeRootHolder.setRoot(ReportComponent.builder(PROJECT, 1).build()); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(mock(Branch.class)); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(NullPointerException.class) .hasMessage("newStatus can't be null"); } @Test @UseDataProvider("noBranchNameBranches") public void newIssuesChangesNotification_creates_project_from_TreeRootHolder_and_branch_name_only_on_non_main_branches(Branch branch) { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStatus(STATUS_OPEN); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(branch); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); IssuesChangesNotification notification = underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); assertThat(notification).isSameAs(expected); IssuesChangesNotificationBuilder builder = verifyAndCaptureIssueChangeNotificationBuilder(); assertThat(builder.getIssues()).hasSize(1); ChangedIssue changeIssue = builder.getIssues().iterator().next(); assertThat(changeIssue.getProject().getUuid()).isEqualTo(project.getUuid()); assertThat(changeIssue.getProject().getKey()).isEqualTo(project.getKey()); assertThat(changeIssue.getProject().getProjectName()).isEqualTo(project.getName()); assertThat(changeIssue.getProject().getBranchName()).isEmpty(); } @DataProvider public static Object[][] noBranchNameBranches() { Branch mainBranch = mock(Branch.class); when(mainBranch.isMain()).thenReturn(true); when(mainBranch.getType()).thenReturn(BranchType.BRANCH); Branch pr = mock(Branch.class); when(pr.isMain()).thenReturn(false); when(pr.getType()).thenReturn(BranchType.PULL_REQUEST); return new Object[][] { {mainBranch}, {pr} }; } @Test public void newIssuesChangesNotification_creates_project_from_TreeRootHolder_and_branch_name_from_branch() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStatus(STATUS_OPEN); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); String branchName = randomAlphabetic(12); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, branchName)); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); IssuesChangesNotification notification = underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); assertThat(notification).isSameAs(expected); IssuesChangesNotificationBuilder builder = verifyAndCaptureIssueChangeNotificationBuilder(); assertThat(builder.getIssues()).hasSize(1); ChangedIssue changeIssue = builder.getIssues().iterator().next(); assertThat(changeIssue.getProject().getUuid()).isEqualTo(project.getUuid()); assertThat(changeIssue.getProject().getKey()).isEqualTo(project.getKey()); assertThat(changeIssue.getProject().getProjectName()).isEqualTo(project.getName()); assertThat(changeIssue.getProject().getBranchName()).contains(branchName); } @Test public void newIssuesChangesNotification_creates_rule_from_RuleRepository() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStatus(STATUS_OPEN); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); String branchName = randomAlphabetic(12); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, branchName)); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); IssuesChangesNotification notification = underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); assertThat(notification).isSameAs(expected); IssuesChangesNotificationBuilder builder = verifyAndCaptureIssueChangeNotificationBuilder(); assertThat(builder.getIssues()).hasSize(1); ChangedIssue changeIssue = builder.getIssues().iterator().next(); assertThat(changeIssue.getRule().getKey()).isEqualTo(ruleKey); assertThat(changeIssue.getRule().getName()).isEqualTo(ruleRepository.getByKey(ruleKey).getName()); } @Test public void newIssuesChangesNotification_fails_with_ISE_if_issue_has_assignee_not_in_assigneesByUuid() { RuleKey ruleKey = RuleKey.of("foo", "bar"); String assigneeUuid = randomAlphabetic(40); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStatus(STATUS_OPEN) .setAssigneeUuid(assigneeUuid); Map<String, UserDto> assigneesByUuid = Collections.emptyMap(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); assertThatThrownBy(() -> underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not find DTO for assignee uuid " + assigneeUuid); } @Test public void newIssuesChangesNotification_creates_assignee_from_UserDto() { RuleKey ruleKey = RuleKey.of("foo", "bar"); String assigneeUuid = randomAlphabetic(40); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStatus(STATUS_OPEN) .setAssigneeUuid(assigneeUuid); UserDto userDto = UserTesting.newUserDto(); Map<String, UserDto> assigneesByUuid = ImmutableMap.of(assigneeUuid, userDto); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(new Random().nextLong()); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); IssuesChangesNotification notification = underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); assertThat(notification).isSameAs(expected); IssuesChangesNotificationBuilder builder = verifyAndCaptureIssueChangeNotificationBuilder(); assertThat(builder.getIssues()).hasSize(1); ChangedIssue changeIssue = builder.getIssues().iterator().next(); assertThat(changeIssue.getAssignee()).isPresent(); IssuesChangesNotificationBuilder.User assignee = changeIssue.getAssignee().get(); assertThat(assignee.getUuid()).isEqualTo(userDto.getUuid()); assertThat(assignee.getName()).contains(userDto.getName()); assertThat(assignee.getLogin()).isEqualTo(userDto.getLogin()); } @Test public void newIssuesChangesNotification_creates_AnalysisChange_with_analysis_date() { RuleKey ruleKey = RuleKey.of("foo", "bar"); DefaultIssue issue = new DefaultIssue() .setRuleKey(ruleKey) .setKey("issueKey") .setStatus(STATUS_OPEN); Map<String, UserDto> assigneesByUuid = nonEmptyAssigneesByUuid(); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); long analysisDate = new Random().nextLong(); ruleRepository.add(ruleKey); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(analysisDate); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); IssuesChangesNotification notification = underTest.newIssuesChangesNotification(ImmutableSet.of(issue), assigneesByUuid); assertThat(notification).isSameAs(expected); IssuesChangesNotificationBuilder builder = verifyAndCaptureIssueChangeNotificationBuilder(); assertThat(builder.getIssues()).hasSize(1); assertThat(builder.getChange()) .isInstanceOf(AnalysisChange.class) .extracting(IssuesChangesNotificationBuilder.Change::getDate) .isEqualTo(analysisDate); } @Test public void newIssuesChangesNotification_maps_all_issues() { Set<DefaultIssue> issues = IntStream.range(0, 3 + new Random().nextInt(5)) .mapToObj(i -> new DefaultIssue() .setRuleKey(RuleKey.of("repo_" + i, "rule_" + i)) .setKey("issue_key_" + i) .setStatus("status_" + i)) .collect(Collectors.toSet()); ReportComponent project = ReportComponent.builder(PROJECT, 1).build(); long analysisDate = new Random().nextLong(); issues.stream() .map(DefaultIssue::ruleKey) .forEach(ruleKey -> ruleRepository.add(ruleKey)); treeRootHolder.setRoot(project); analysisMetadata.setAnalysisDate(analysisDate); analysisMetadata.setBranch(newNonMainBranch(BranchType.BRANCH, randomAlphabetic(12))); IssuesChangesNotification expected = mock(IssuesChangesNotification.class); when(issuesChangesSerializer.serialize(any(IssuesChangesNotificationBuilder.class))).thenReturn(expected); IssuesChangesNotification notification = underTest.newIssuesChangesNotification(issues, emptyMap()); assertThat(notification).isSameAs(expected); IssuesChangesNotificationBuilder builder = verifyAndCaptureIssueChangeNotificationBuilder(); assertThat(builder.getIssues()).hasSize(issues.size()); Map<String, ChangedIssue> changedIssuesByKey = builder.getIssues().stream() .collect(Collectors.toMap(ChangedIssue::getKey, Function.identity())); issues.forEach( issue -> { ChangedIssue changedIssue = changedIssuesByKey.get(issue.key()); assertThat(changedIssue.getNewStatus()).isEqualTo(issue.status()); assertThat(changedIssue.getNewResolution()).isEmpty(); assertThat(changedIssue.getAssignee()).isEmpty(); assertThat(changedIssue.getRule().getKey()).isEqualTo(issue.ruleKey()); assertThat(changedIssue.getRule().getName()).isEqualTo(ruleRepository.getByKey(issue.ruleKey()).getName()); }); } private static Map<String, UserDto> nonEmptyAssigneesByUuid() { return IntStream.range(0, 1 + new Random().nextInt(3)) .boxed() .collect(Collectors.toMap(i -> "uuid_" + i, i1 -> new UserDto())); } private IssuesChangesNotificationBuilder verifyAndCaptureIssueChangeNotificationBuilder() { ArgumentCaptor<IssuesChangesNotificationBuilder> builderCaptor = ArgumentCaptor.forClass(IssuesChangesNotificationBuilder.class); verify(issuesChangesSerializer).serialize(builderCaptor.capture()); verifyNoMoreInteractions(issuesChangesSerializer); return builderCaptor.getValue(); } private static Branch newNonMainBranch(BranchType branchType, String branchName) { Branch nonMainBranch = mock(Branch.class); when(nonMainBranch.isMain()).thenReturn(false); when(nonMainBranch.getType()).thenReturn(branchType); when(nonMainBranch.getName()).thenReturn(branchName); return nonMainBranch; } private static Durations readDurationsField(NewIssuesNotification notification) { return readField(notification, "durations"); } private static Durations readField(NewIssuesNotification notification, String fieldName) { try { Field durationsField = NewIssuesNotification.class.getDeclaredField(fieldName); durationsField.setAccessible(true); Object o = durationsField.get(notification); return (Durations) o; } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); } } private static DetailsSupplier readDetailsSupplier(NewIssuesNotification notification) { try { Field durationsField = NewIssuesNotification.class.getDeclaredField("detailsSupplier"); durationsField.setAccessible(true); return (DetailsSupplier) durationsField.get(notification); } catch (IllegalAccessException | NoSuchFieldException e) { throw new RuntimeException(e); } } }
37,925
47.375
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationEmailTemplateTest.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.notification; import org.junit.Test; import org.sonar.api.config.EmailSettings; import org.sonar.server.qualitygate.notification.QGChangeNotification; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ReportAnalysisFailureNotificationEmailTemplateTest { ReportAnalysisFailureNotificationSerializer serializer = new ReportAnalysisFailureNotificationSerializerImpl(); EmailSettings settings = mock(EmailSettings.class); ReportAnalysisFailureNotificationEmailTemplate underTest = new ReportAnalysisFailureNotificationEmailTemplate(serializer, settings); @Test public void should_not_format_other_than_analysis_failure() { assertThat(underTest.format(new QGChangeNotification())).isNull(); } @Test public void check_formatting() { ReportAnalysisFailureNotification notification = mock(ReportAnalysisFailureNotification.class); when(notification.getFieldValue("project.uuid")).thenReturn("uuid"); when(notification.getFieldValue("project.name")).thenReturn("name"); when(notification.getFieldValue("project.key")).thenReturn("key"); when(notification.getFieldValue("project.branch")).thenReturn("branch"); when(notification.getFieldValue("task.uuid")).thenReturn("task_uuid"); when(notification.getFieldValue("task.createdAt")).thenReturn("1673449576159"); when(notification.getFieldValue("task.failedAt")).thenReturn("1673449576159"); when(notification.getFieldValue("error.message")).thenReturn("error"); when(settings.getServerBaseURL()).thenReturn("sonarsource.com"); var result = underTest.format(notification); assertThat(result.getSubject()).isEqualTo("name: Background task in failure"); assertThat(result.getMessage()) .contains(""" Project: name Background task: task_uuid""") .contains(""" Error message: error More details at: sonarsource.com/project/background_tasks?id=key"""); } }
2,920
41.333333
134
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/notification/ReportAnalysisFailureNotificationHandlerTest.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.notification; import java.util.Collections; import java.util.Random; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; import javax.annotation.Nullable; import org.junit.Test; import org.mockito.Mockito; import org.sonar.api.web.UserRole; import org.sonar.server.notification.NotificationDispatcherMetadata; import org.sonar.server.notification.NotificationManager; import org.sonar.server.notification.NotificationManager.EmailRecipient; import org.sonar.server.notification.NotificationManager.SubscriberPermissionsOnProject; import org.sonar.server.notification.email.EmailNotificationChannel; import org.sonar.server.notification.email.EmailNotificationChannel.EmailDeliveryRequest; import static java.util.Collections.emptySet; import static java.util.stream.Collectors.toSet; 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.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.server.notification.NotificationDispatcherMetadata.GLOBAL_NOTIFICATION; import static org.sonar.server.notification.NotificationDispatcherMetadata.PER_PROJECT_NOTIFICATION; public class ReportAnalysisFailureNotificationHandlerTest { private static final String REPORT_FAILURE_DISPATCHER_KEY = "CeReportTaskFailure"; private static final SubscriberPermissionsOnProject REQUIRED_SUBSCRIBER_PERMISSIONS = new SubscriberPermissionsOnProject(UserRole.ADMIN, UserRole.USER); private NotificationManager notificationManager = mock(NotificationManager.class); private EmailNotificationChannel emailNotificationChannel = mock(EmailNotificationChannel.class); private ReportAnalysisFailureNotificationHandler underTest = new ReportAnalysisFailureNotificationHandler(notificationManager, emailNotificationChannel); @Test public void getMetadata_returns_same_instance_as_static_method() { assertThat(underTest.getMetadata()).containsSame(ReportAnalysisFailureNotificationHandler.newMetadata()); } @Test public void verify_reportFailures_notification_dispatcher_key() { NotificationDispatcherMetadata metadata = ReportAnalysisFailureNotificationHandler.newMetadata(); assertThat(metadata.getDispatcherKey()).isEqualTo(REPORT_FAILURE_DISPATCHER_KEY); } @Test public void reportFailures_notification_is_enable_at_global_level() { NotificationDispatcherMetadata metadata = ReportAnalysisFailureNotificationHandler.newMetadata(); assertThat(metadata.getProperty(GLOBAL_NOTIFICATION)).isEqualTo("true"); } @Test public void reportFailures_notification_is_enable_at_project_level() { NotificationDispatcherMetadata metadata = ReportAnalysisFailureNotificationHandler.newMetadata(); assertThat(metadata.getProperty(PER_PROJECT_NOTIFICATION)).isEqualTo("true"); } @Test public void getNotificationClass_is_ReportAnalysisFailureNotification() { assertThat(underTest.getNotificationClass()).isEqualTo(ReportAnalysisFailureNotification.class); } @Test public void deliver_has_no_effect_if_notifications_is_empty() { when(emailNotificationChannel.isActivated()).thenReturn(true); int deliver = underTest.deliver(Collections.emptyList()); assertThat(deliver).isZero(); verifyNoInteractions(notificationManager, emailNotificationChannel); } @Test public void deliver_has_no_effect_if_emailNotificationChannel_is_disabled() { when(emailNotificationChannel.isActivated()).thenReturn(false); Set<ReportAnalysisFailureNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> mock(ReportAnalysisFailureNotification.class)) .collect(toSet()); int deliver = underTest.deliver(notifications); assertThat(deliver).isZero(); verifyNoInteractions(notificationManager); verify(emailNotificationChannel).isActivated(); verifyNoMoreInteractions(emailNotificationChannel); notifications.forEach(Mockito::verifyNoInteractions); } @Test public void deliver_has_no_effect_if_no_notification_has_projectKey() { when(emailNotificationChannel.isActivated()).thenReturn(true); Set<ReportAnalysisFailureNotification> notifications = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> newNotification(null)) .collect(toSet()); int deliver = underTest.deliver(notifications); assertThat(deliver).isZero(); verifyNoInteractions(notificationManager); verify(emailNotificationChannel).isActivated(); verifyNoMoreInteractions(emailNotificationChannel); notifications.forEach(notification -> { verify(notification).getProjectKey(); verifyNoMoreInteractions(notification); }); } @Test public void deliver_has_no_effect_if_no_notification_has_subscribed_recipients_to_ReportFailure_notifications() { String projectKey = randomAlphabetic(12); ReportAnalysisFailureNotification notification = newNotification(projectKey); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS)) .thenReturn(emptySet()); int deliver = underTest.deliver(Collections.singleton(notification)); assertThat(deliver).isZero(); verify(notificationManager).findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS); verifyNoMoreInteractions(notificationManager); verify(emailNotificationChannel).isActivated(); verifyNoMoreInteractions(emailNotificationChannel); } @Test public void deliver_ignores_notification_without_projectKey() { String projectKey = randomAlphabetic(10); Set<ReportAnalysisFailureNotification> withProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newNotification(projectKey)) .collect(toSet()); Set<ReportAnalysisFailureNotification> noProjectKey = IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newNotification(null)) .collect(toSet()); Set<EmailRecipient> emailRecipients = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> "user_" + i) .map(login -> new EmailRecipient(login, emailOf(login))) .collect(toSet()); Set<EmailDeliveryRequest> expectedRequests = emailRecipients.stream() .flatMap(emailRecipient -> withProjectKey.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))) .collect(toSet()); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS)) .thenReturn(emailRecipients); Set<ReportAnalysisFailureNotification> notifications = Stream.of(withProjectKey.stream(), noProjectKey.stream()) .flatMap(t -> t) .collect(toSet()); int deliver = underTest.deliver(notifications); assertThat(deliver).isZero(); verify(notificationManager).findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey, REQUIRED_SUBSCRIBER_PERMISSIONS); verifyNoMoreInteractions(notificationManager); verify(emailNotificationChannel).isActivated(); verify(emailNotificationChannel).deliverAll(expectedRequests); verifyNoMoreInteractions(emailNotificationChannel); } @Test public void deliver_checks_by_projectKey_if_notifications_have_subscribed_assignee_to_ReportFailure_notifications() { String projectKey1 = randomAlphabetic(10); String projectKey2 = randomAlphabetic(11); Set<ReportAnalysisFailureNotification> notifications1 = randomSetOfNotifications(projectKey1); Set<ReportAnalysisFailureNotification> notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); Set<EmailRecipient> emailRecipients1 = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> "user1_" + i) .map(login -> new EmailRecipient(login, emailOf(login))) .collect(toSet()); Set<EmailRecipient> emailRecipients2 = IntStream.range(0, 1 + new Random().nextInt(10)) .mapToObj(i -> "user2_" + i) .map(login -> new EmailRecipient(login, emailOf(login))) .collect(toSet()); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey1, REQUIRED_SUBSCRIBER_PERMISSIONS)) .thenReturn(emailRecipients1); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey2, REQUIRED_SUBSCRIBER_PERMISSIONS)) .thenReturn(emailRecipients2); Set<EmailDeliveryRequest> expectedRequests = Stream.concat( emailRecipients1.stream() .flatMap(emailRecipient -> notifications1.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif))), emailRecipients2.stream() .flatMap(emailRecipient -> notifications2.stream().map(notif -> new EmailDeliveryRequest(emailRecipient.email(), notif)))) .collect(toSet()); int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet())); assertThat(deliver).isZero(); verify(notificationManager).findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey1, REQUIRED_SUBSCRIBER_PERMISSIONS); verify(notificationManager).findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey2, REQUIRED_SUBSCRIBER_PERMISSIONS); verifyNoMoreInteractions(notificationManager); verify(emailNotificationChannel).isActivated(); verify(emailNotificationChannel).deliverAll(expectedRequests); verifyNoMoreInteractions(emailNotificationChannel); } @Test public void deliver_send_notifications_to_all_subscribers_of_all_projects() { String projectKey1 = randomAlphabetic(10); String projectKey2 = randomAlphabetic(11); Set<ReportAnalysisFailureNotification> notifications1 = randomSetOfNotifications(projectKey1); Set<ReportAnalysisFailureNotification> notifications2 = randomSetOfNotifications(projectKey2); when(emailNotificationChannel.isActivated()).thenReturn(true); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey1, REQUIRED_SUBSCRIBER_PERMISSIONS)) .thenReturn(emptySet()); when(notificationManager.findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey2, REQUIRED_SUBSCRIBER_PERMISSIONS)) .thenReturn(emptySet()); int deliver = underTest.deliver(Stream.concat(notifications1.stream(), notifications2.stream()).collect(toSet())); assertThat(deliver).isZero(); verify(notificationManager).findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey1, REQUIRED_SUBSCRIBER_PERMISSIONS); verify(notificationManager).findSubscribedEmailRecipients(REPORT_FAILURE_DISPATCHER_KEY, projectKey2, REQUIRED_SUBSCRIBER_PERMISSIONS); verifyNoMoreInteractions(notificationManager); verify(emailNotificationChannel).isActivated(); verifyNoMoreInteractions(emailNotificationChannel); } private static Set<ReportAnalysisFailureNotification> randomSetOfNotifications(@Nullable String projectKey) { return IntStream.range(0, 1 + new Random().nextInt(5)) .mapToObj(i -> newNotification(projectKey)) .collect(Collectors.toSet()); } private static ReportAnalysisFailureNotification newNotification(@Nullable String projectKey) { ReportAnalysisFailureNotification notification = mock(ReportAnalysisFailureNotification.class); when(notification.getProjectKey()).thenReturn(projectKey); return notification; } private static String emailOf(String assignee1) { return assignee1 + "@house"; } }
12,889
48.76834
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderImplTest.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.period; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class PeriodHolderImplTest { private PeriodHolderImpl underTest = new PeriodHolderImpl(); @Test public void get_period() { Period period = createPeriod(); underTest.setPeriod(period); assertThat(underTest.getPeriod()).isEqualTo(period); } @Test public void get_period_throws_illegal_state_exception_if_not_initialized() { assertThatThrownBy(() -> new PeriodHolderImpl().getPeriod()) .isInstanceOf(IllegalStateException.class) .hasMessage("Period have not been initialized yet"); } @Test public void setPeriod_throws_ISE_if_already_initialized() { assertThatThrownBy(() -> { underTest.setPeriod(createPeriod()); underTest.setPeriod(createPeriod()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Period have already been initialized"); } @Test public void hasPeriod_returns_false_if_holder_is_empty() { underTest.setPeriod(null); assertThat(underTest.hasPeriod()).isFalse(); } @Test public void hasPeriodDate_returns_false_if_date_is_null() { underTest.setPeriod(createPeriodWithoutDate()); assertThat(underTest.hasPeriod()).isTrue(); assertThat(underTest.hasPeriodDate()).isFalse(); } @Test public void hasPeriod_returns_true_only_if_period_exists_in_holder() { underTest.setPeriod(createPeriod()); assertThat(underTest.hasPeriod()).isTrue(); assertThat(underTest.hasPeriodDate()).isTrue(); } @Test public void hasPeriod_throws_ISE_if_not_initialized() { assertThatThrownBy(() -> underTest.hasPeriod()) .isInstanceOf(IllegalStateException.class) .hasMessage("Period have not been initialized yet"); } private static Period createPeriod() { return new Period(1 + "mode", null, 1000L); } private static Period createPeriodWithoutDate() { return new Period(1 + "mode", null, null); } }
2,926
30.815217
78
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodHolderRule.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.period; import javax.annotation.Nullable; import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class PeriodHolderRule implements TestRule, PeriodHolder { private PeriodHolderImpl delegate = new PeriodHolderImpl(); @Override public Statement apply(final Statement statement, Description description) { return new Statement() { @Override public void evaluate() throws Throwable { try { statement.evaluate(); } finally { clear(); } } }; } private void clear() { this.delegate = new PeriodHolderImpl(); } public PeriodHolderRule setPeriod(@Nullable Period period) { delegate = new PeriodHolderImpl(); delegate.setPeriod(period); return this; } @Override public boolean hasPeriod() { return delegate.hasPeriod(); } @Override public boolean hasPeriodDate() { return delegate.hasPeriodDate(); } @Override public Period getPeriod() { return delegate.getPeriod(); } }
1,950
27.275362
78
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/period/PeriodTest.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.period; import org.junit.Test; import org.sonar.db.newcodeperiod.NewCodePeriodType; import static org.assertj.core.api.Assertions.assertThat; public class PeriodTest { private static final String SOME_MODE_PARAM = "mode_para"; private static final long SOME_SNAPSHOT_DATE = 1000L; @Test public void test_some_setters_and_getters() { Period period = new Period(NewCodePeriodType.PREVIOUS_VERSION.name(), SOME_MODE_PARAM, SOME_SNAPSHOT_DATE); assertThat(period.getMode()).isEqualTo(NewCodePeriodType.PREVIOUS_VERSION.name()); assertThat(period.getModeParameter()).isEqualTo(SOME_MODE_PARAM); assertThat(period.getDate()).isEqualTo(SOME_SNAPSHOT_DATE); } @Test public void verify_to_string() { assertThat(new Period(NewCodePeriodType.PREVIOUS_VERSION.name(), "2.3", 1420034400000L)) .hasToString("Period{mode=PREVIOUS_VERSION, modeParameter=2.3, date=1420034400000}"); } @Test public void equals_is_done_on_all_fields() { Period period = new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "2.3", 1420034400000L); assertThat(period) .isEqualTo(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "2.3", 1420034400000L)) .isNotNull() .isNotEqualTo("sdsd") .isNotEqualTo(new Period(NewCodePeriodType.PREVIOUS_VERSION.name(), "2.3", 1420034400000L)) .isNotEqualTo(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "2.4", 1420034400000L)) .isNotEqualTo(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "2.3", 1420034410000L)); } }
2,417
38
111
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/purge/IndexPurgeListenerTest.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.purge; import org.junit.Test; import org.sonar.server.issue.index.IssueIndexer; import static java.util.Arrays.asList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class IndexPurgeListenerTest { private IssueIndexer issueIndexer = mock(IssueIndexer.class); private IndexPurgeListener underTest = new IndexPurgeListener(issueIndexer); @Test public void test_onIssuesRemoval() { underTest.onIssuesRemoval("P1", asList("ISSUE1", "ISSUE2")); verify(issueIndexer).deleteByKeys("P1", asList("ISSUE1", "ISSUE2")); } }
1,465
33.904762
78
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/purge/ProjectCleanerTest.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.purge; import java.util.List; import java.util.stream.Collectors; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.CoreProperties; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.System2; import org.sonar.core.config.PurgeConstants; import org.sonar.core.config.PurgeProperties; import org.sonar.db.DbSession; import org.sonar.db.purge.PurgeDao; import org.sonar.db.purge.PurgeListener; import org.sonar.db.purge.PurgeProfiler; import org.sonar.db.purge.period.DefaultPeriodCleaner; import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class ProjectCleanerTest { public static final String DUMMY_PROFILE_CONTENT = "DUMMY PROFILE CONTENT"; private ProjectCleaner underTest; private PurgeDao dao = mock(PurgeDao.class); private PurgeProfiler profiler = mock(PurgeProfiler.class); private DefaultPeriodCleaner periodCleaner = mock(DefaultPeriodCleaner.class); private PurgeListener purgeListener = mock(PurgeListener.class); private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, PurgeProperties.all())); @Rule public LogTester logTester = new LogTester(); @Before public void before() { this.underTest = new ProjectCleaner(dao, periodCleaner, profiler, purgeListener); } @Test public void call_period_cleaner_index_client_and_purge_dao() { settings.setProperty(PurgeConstants.DAYS_BEFORE_DELETING_CLOSED_ISSUES, 5); underTest.purge(mock(DbSession.class), "root", "project", settings.asConfig(), emptySet()); verify(periodCleaner).clean(any(), any(), any()); verify(dao).purge(any(), any(), any(), any()); } @Test public void no_profiling_when_property_is_false() { settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, false); underTest.purge(mock(DbSession.class), "root", "project", settings.asConfig(), emptySet()); verify(profiler, never()).getProfilingResult(anyLong()); assertThat(logTester.getLogs().stream() .map(LogAndArguments::getFormattedMsg) .collect(Collectors.joining())) .doesNotContain("Profiling for purge"); } @Test public void profiling_when_property_is_true() { settings.setProperty(CoreProperties.PROFILING_LOG_PROPERTY, true); when(profiler.getProfilingResult(anyLong())).thenReturn(List.of(DUMMY_PROFILE_CONTENT)); underTest.purge(mock(DbSession.class), "root", "project", settings.asConfig(), emptySet()); verify(profiler).getProfilingResult(anyLong()); assertThat(logTester.getLogs(Level.INFO).stream() .map(LogAndArguments::getFormattedMsg) .collect(Collectors.joining())) .contains("Profiling for purge") .contains(DUMMY_PROFILE_CONTENT); } }
4,125
37.560748
115
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/purge/PurgeDatastoresStepTest.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.purge; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import java.util.Arrays; import java.util.Collections; import java.util.function.Predicate; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.sonar.api.config.internal.MapSettings; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; import org.sonar.ce.task.projectanalysis.component.MutableDisabledComponentsHolder; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import org.sonar.ce.task.projectanalysis.step.BaseStepTest; import org.sonar.ce.task.projectanalysis.util.WrapInSingleElementArray; import org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.db.DbClient; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class PurgeDatastoresStepTest extends BaseStepTest { private static final String PROJECT_KEY = "PROJECT_KEY"; private static final String PROJECT_UUID = "UUID-1234"; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private ProjectCleaner projectCleaner = mock(ProjectCleaner.class); private ConfigurationRepository settingsRepository = mock(ConfigurationRepository.class); private MutableDisabledComponentsHolder disabledComponentsHolder = mock(MutableDisabledComponentsHolder.class, RETURNS_DEEP_STUBS); private PurgeDatastoresStep underTest = new PurgeDatastoresStep(mock(DbClient.class, Mockito.RETURNS_DEEP_STUBS), projectCleaner, treeRootHolder, settingsRepository, disabledComponentsHolder, analysisMetadataHolder); @Before public void before() { analysisMetadataHolder.setProject(new Project("uuid", "key", "name", null, Collections.emptyList())); } @Test public void call_purge_method_of_the_purge_task_for_project() { Component project = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(PROJECT_UUID).setKey(PROJECT_KEY).build(); verify_call_purge_method_of_the_purge_task(project); } @Test public void call_purge_method_of_the_purge_task_for_view() { Component project = ViewsComponent.builder(Component.Type.VIEW, PROJECT_KEY).setUuid(PROJECT_UUID).build(); verify_call_purge_method_of_the_purge_task(project); } private void verify_call_purge_method_of_the_purge_task(Component project) { treeRootHolder.setRoot(project); when(settingsRepository.getConfiguration()).thenReturn(new MapSettings().asConfig()); underTest.execute(new TestComputationStepContext()); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(projectCleaner).purge(any(), argumentCaptor.capture(), anyString(), any(), any()); assertThat(argumentCaptor.getValue()).isEqualTo(PROJECT_UUID); } private static Object[][] dataproviderFromComponentTypeValues(Predicate<Component.Type> predicate) { return Arrays.stream(Component.Type.values()) .filter(predicate) .map(WrapInSingleElementArray.INSTANCE) .toArray(Object[][]::new); } @Override protected ComputationStep step() { return underTest; } }
4,846
40.784483
147
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/pushevent/PushEventFactoryTest.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.pushevent; import com.google.gson.Gson; import java.nio.charset.StandardCharsets; import java.util.Date; import java.util.Set; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.issue.Issue; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.api.utils.DateUtils; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.analysis.TestBranch; import org.sonar.ce.task.projectanalysis.component.Component.Type; import org.sonar.ce.task.projectanalysis.component.MutableTreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.issue.RuleRepository; import org.sonar.ce.task.projectanalysis.locations.flow.FlowGenerator; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.issue.FieldDiffs; import org.sonar.db.protobuf.DbCommons; import org.sonar.db.protobuf.DbIssues; import org.sonar.db.rule.RuleDto; import org.sonar.server.issue.TaintChecker; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class PushEventFactoryTest { private static final Gson gson = new Gson(); private static final String BRANCH_NAME = "develop"; private final TaintChecker taintChecker = mock(TaintChecker.class); @Rule public MutableTreeRootHolderRule treeRootHolder = new MutableTreeRootHolderRule(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule() .setBranch(new TestBranch(BRANCH_NAME)); private final FlowGenerator flowGenerator = new FlowGenerator(treeRootHolder); private final RuleRepository ruleRepository = mock(RuleRepository.class); private final PushEventFactory underTest = new PushEventFactory(treeRootHolder, analysisMetadataHolder, taintChecker, flowGenerator, ruleRepository); @Before public void setUp() { when(ruleRepository.getByKey(RuleKey.of("javasecurity", "S123"))).thenReturn(buildRule()); buildComponentTree(); } @Test public void raiseEventOnIssue_whenNewTaintVulnerability_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setNew(true) .setRuleDescriptionContextKey(randomAlphabetic(6)); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo("TaintVulnerabilityRaised"); verifyPayload(pushEventDto.getPayload(), defaultIssue); assertThat(pushEventDto.getLanguage()).isEqualTo("java"); assertThat(pushEventDto.getProjectUuid()).isEqualTo("some-project-uuid"); }); } private static void verifyPayload(byte[] payload, DefaultIssue defaultIssue) { assertThat(payload).isNotNull(); TaintVulnerabilityRaised taintVulnerabilityRaised = gson.fromJson(new String(payload, StandardCharsets.UTF_8), TaintVulnerabilityRaised.class); assertThat(taintVulnerabilityRaised.getProjectKey()).isEqualTo(defaultIssue.projectKey()); assertThat(taintVulnerabilityRaised.getCreationDate()).isEqualTo(defaultIssue.creationDate().getTime()); assertThat(taintVulnerabilityRaised.getKey()).isEqualTo(defaultIssue.key()); assertThat(taintVulnerabilityRaised.getSeverity()).isEqualTo(defaultIssue.severity()); assertThat(taintVulnerabilityRaised.getRuleKey()).isEqualTo(defaultIssue.ruleKey().toString()); assertThat(taintVulnerabilityRaised.getType()).isEqualTo(defaultIssue.type().name()); assertThat(taintVulnerabilityRaised.getBranch()).isEqualTo(BRANCH_NAME); String ruleDescriptionContextKey = taintVulnerabilityRaised.getRuleDescriptionContextKey().orElseGet(() -> fail("No rule description " + "context key")); assertThat(ruleDescriptionContextKey).isEqualTo(defaultIssue.getRuleDescriptionContextKey().orElse(null)); } @Test public void raiseEventOnIssue_whenReopenedTaintVulnerability_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setChanged(true) .setNew(false) .setCopied(false) .setCurrentChange(new FieldDiffs().setDiff("status", "CLOSED", "OPEN")); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo("TaintVulnerabilityRaised"); assertThat(pushEventDto.getPayload()).isNotNull(); }); } @Test public void raiseEventOnIssue_whenTaintVulnerabilityStatusChange_shouldSkipEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setChanged(true) .setNew(false) .setCopied(false) .setCurrentChange(new FieldDiffs().setDiff("status", "OPEN", "FIXED")); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); } @Test public void raiseEventOnIssue_whenCopiedTaintVulnerability_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setCopied(true); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo("TaintVulnerabilityRaised"); assertThat(pushEventDto.getPayload()).isNotNull(); }); } @Test public void raiseEventOnIssue_whenClosedTaintVulnerability_shouldCreateClosedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setNew(false) .setCopied(false) .setBeingClosed(true); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo("TaintVulnerabilityClosed"); assertThat(pushEventDto.getPayload()).isNotNull(); }); } @Test public void raiseEventOnIssue_whenChangedTaintVulnerability_shouldSkipEvent() { DefaultIssue defaultIssue = new DefaultIssue() .setComponentUuid("issue-component-uuid") .setNew(false) .setCopied(false) .setChanged(true) .setType(RuleType.VULNERABILITY) .setCreationDate(DateUtils.parseDate("2022-01-01")) .setRuleKey(RuleKey.of("javasecurity", "S123")); when(taintChecker.isTaintVulnerability(any())).thenReturn(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); } @Test public void raiseEventOnIssue_whenIssueNotFromTaintVulnerabilityRepository_shouldSkipEvent() { DefaultIssue defaultIssue = new DefaultIssue() .setComponentUuid("issue-component-uuid") .setChanged(true) .setType(RuleType.VULNERABILITY) .setRuleKey(RuleKey.of("weirdrepo", "S123")); when(taintChecker.isTaintVulnerability(any())).thenReturn(false); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); defaultIssue = new DefaultIssue() .setComponentUuid("issue-component-uuid") .setChanged(false) .setNew(false) .setBeingClosed(true) .setType(RuleType.VULNERABILITY) .setRuleKey(RuleKey.of("weirdrepo", "S123")); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); } @Test public void raiseEventOnIssue_whenIssueDoesNotHaveLocations_shouldSkipEvent() { DefaultIssue defaultIssue = new DefaultIssue() .setComponentUuid("issue-component-uuid") .setChanged(true) .setType(RuleType.VULNERABILITY) .setRuleKey(RuleKey.of("javasecurity", "S123")); when(taintChecker.isTaintVulnerability(any())).thenReturn(false); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); } @Test public void raiseEventOnIssue_whenNewHotspot_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setStatus(Issue.STATUS_TO_REVIEW) .setNew(true) .setRuleDescriptionContextKey(randomAlphabetic(6)); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo(SecurityHotspotRaised.EVENT_NAME); verifyHotspotRaisedEventPayload(pushEventDto.getPayload(), defaultIssue); assertThat(pushEventDto.getLanguage()).isEqualTo("java"); assertThat(pushEventDto.getProjectUuid()).isEqualTo("some-project-uuid"); }); } private static void verifyHotspotRaisedEventPayload(byte[] payload, DefaultIssue defaultIssue) { assertThat(payload).isNotNull(); SecurityHotspotRaised event = gson.fromJson(new String(payload, StandardCharsets.UTF_8), SecurityHotspotRaised.class); assertThat(event.getProjectKey()).isEqualTo(defaultIssue.projectKey()); assertThat(event.getCreationDate()).isEqualTo(defaultIssue.creationDate().getTime()); assertThat(event.getKey()).isEqualTo(defaultIssue.key()); assertThat(event.getRuleKey()).isEqualTo(defaultIssue.ruleKey().toString()); assertThat(event.getStatus()).isEqualTo(Issue.STATUS_TO_REVIEW); assertThat(event.getVulnerabilityProbability()).isEqualTo("LOW"); assertThat(event.getMainLocation()).isNotNull(); assertThat(event.getBranch()).isEqualTo(BRANCH_NAME); assertThat(event.getAssignee()).isEqualTo("some-user-login"); } @Test public void raiseEventOnIssue_whenReopenedHotspot_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setChanged(true) .setNew(false) .setCopied(false) .setCurrentChange(new FieldDiffs().setDiff("status", "CLOSED", "TO_REVIEW")); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo(SecurityHotspotRaised.EVENT_NAME); assertThat(pushEventDto.getPayload()).isNotNull(); }); } @Test public void raiseEventOnIssue_whenCopiedHotspot_shouldCreateRaisedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setCopied(true); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo(SecurityHotspotRaised.EVENT_NAME); assertThat(pushEventDto.getPayload()).isNotNull(); }); } @Test public void raiseEventOnIssue_whenClosedHotspot_shouldCreateClosedEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setNew(false) .setCopied(false) .setBeingClosed(true) .setStatus(Issue.STATUS_CLOSED) .setResolution(Issue.RESOLUTION_FIXED); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)) .isNotEmpty() .hasValueSatisfying(pushEventDto -> { assertThat(pushEventDto.getName()).isEqualTo(SecurityHotspotClosed.EVENT_NAME); verifyHotspotClosedEventPayload(pushEventDto.getPayload(), defaultIssue); assertThat(pushEventDto.getLanguage()).isEqualTo("java"); assertThat(pushEventDto.getProjectUuid()).isEqualTo("some-project-uuid"); }); } private static void verifyHotspotClosedEventPayload(byte[] payload, DefaultIssue defaultIssue) { assertThat(payload).isNotNull(); SecurityHotspotClosed event = gson.fromJson(new String(payload, StandardCharsets.UTF_8), SecurityHotspotClosed.class); assertThat(event.getProjectKey()).isEqualTo(defaultIssue.projectKey()); assertThat(event.getKey()).isEqualTo(defaultIssue.key()); assertThat(event.getStatus()).isEqualTo(Issue.STATUS_CLOSED); assertThat(event.getResolution()).isEqualTo(Issue.RESOLUTION_FIXED); assertThat(event.getFilePath()).isEqualTo("component-name"); } @Test public void raiseEventOnIssue_whenChangedHotspot_shouldSkipEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setType(RuleType.SECURITY_HOTSPOT) .setChanged(true) .setNew(false) .setCopied(false); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); } @Test public void raiseEventOnIssue_whenComponentUuidNull_shouldSkipEvent() { DefaultIssue defaultIssue = createDefaultIssue() .setComponentUuid(null); assertThat(underTest.raiseEventOnIssue("some-project-uuid", defaultIssue)).isEmpty(); } private void buildComponentTree() { treeRootHolder.setRoot(ReportComponent.builder(Type.PROJECT, 1) .setUuid("uuid_1") .addChildren(ReportComponent.builder(Type.FILE, 2) .setName("component-name") .setUuid("issue-component-uuid") .build()) .addChildren(ReportComponent.builder(Type.FILE, 3) .setUuid("location-component-uuid") .build()) .build()); } private DefaultIssue createDefaultIssue() { return new DefaultIssue() .setKey("issue-key") .setProjectKey("project-key") .setComponentUuid("issue-component-uuid") .setAssigneeUuid("some-user-uuid") .setAssigneeLogin("some-user-login") .setType(RuleType.VULNERABILITY) .setLanguage("java") .setCreationDate(new Date()) .setLocations(DbIssues.Locations.newBuilder() .addFlow(DbIssues.Flow.newBuilder() .addLocation(DbIssues.Location.newBuilder() .setChecksum("checksum") .setComponentId("location-component-uuid") .build()) .build()) .setTextRange(DbCommons.TextRange.newBuilder() .setStartLine(1) .build()) .build()) .setRuleKey(RuleKey.of("javasecurity", "S123")); } private org.sonar.ce.task.projectanalysis.issue.Rule buildRule() { RuleDto ruleDto = new RuleDto(); ruleDto.setRuleKey(RuleKey.of("javasecurity", "S123")); ruleDto.setSecurityStandards(Set.of("owasp-a1")); return new org.sonar.ce.task.projectanalysis.issue.RuleImpl(ruleDto); } }
15,685
39.742857
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/pushevent/TaintVulnerabilityClosedTest.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.pushevent; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class TaintVulnerabilityClosedTest { @Test public void testConstructor_Getters_Setters() { TaintVulnerabilityClosed underTest = new TaintVulnerabilityClosed(); assertThat(underTest.getKey()).isNull(); assertThat(underTest.getProjectKey()).isNull(); underTest = new TaintVulnerabilityClosed("issue-key", "project-key"); assertThat(underTest.getKey()).isEqualTo("issue-key"); assertThat(underTest.getProjectKey()).isEqualTo("project-key"); underTest.setKey("another-issue-key"); assertThat(underTest.getKey()).isEqualTo("another-issue-key"); underTest.setProjectKey("another-project-key"); assertThat(underTest.getProjectKey()).isEqualTo("another-project-key"); } }
1,701
36.822222
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionEvaluatorTest.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.qualitygate; 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 org.junit.Test; import org.junit.runner.RunWith; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.FluentIterable.from; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.ERROR; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.BOOL; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.DATA; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.DISTRIB; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.FLOAT; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.INT; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.PERCENT; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.RATING; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.STRING; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.WORK_DUR; import static org.sonar.ce.task.projectanalysis.metric.Metric.MetricType.values; import static org.sonar.ce.task.projectanalysis.qualitygate.Condition.Operator.GREATER_THAN; import static org.sonar.ce.task.projectanalysis.qualitygate.Condition.Operator.LESS_THAN; import static org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResultAssert.assertThat; @RunWith(DataProviderRunner.class) public class ConditionEvaluatorTest { private ConditionEvaluator underTest = new ConditionEvaluator(); @Test public void test_input_numbers() { try { Metric metric = createMetric(FLOAT); Measure measure = newMeasureBuilder().create(10.2d, 1, null); underTest.evaluate(createCondition(metric, LESS_THAN, "20"), measure); } catch (NumberFormatException ex) { fail(); } try { Metric metric = createMetric(INT); Measure measure = newMeasureBuilder().create(5, null); underTest.evaluate(createCondition(metric, LESS_THAN, "20.1"), measure); } catch (NumberFormatException ex) { fail(); } try { Metric metric = createMetric(PERCENT); Measure measure = newMeasureBuilder().create(10.2d, 1, null); underTest.evaluate(createCondition(metric, LESS_THAN, "20.1"), measure); } catch (NumberFormatException ex) { fail(); } } @Test public void testGreater() { Metric metric = createMetric(FLOAT); Measure measure = newMeasureBuilder().create(10.2d, 1, null); assertThat(underTest.evaluate(createCondition(metric, GREATER_THAN, "10.1"), measure)).hasLevel(ERROR).hasValue(10.2d); assertThat(underTest.evaluate(createCondition(metric, GREATER_THAN, "10.2"), measure)).hasLevel(OK).hasValue(10.2d); assertThat(underTest.evaluate(createCondition(metric, GREATER_THAN, "10.3"), measure)).hasLevel(OK).hasValue(10.2d); } @Test public void testSmaller() { Metric metric = createMetric(FLOAT); Measure measure = newMeasureBuilder().create(10.2d, 1, null); assertThat(underTest.evaluate(createCondition(metric, LESS_THAN, "10.1"), measure)).hasLevel(OK).hasValue(10.2d); assertThat(underTest.evaluate(createCondition(metric, LESS_THAN, "10.2"), measure)).hasLevel(OK).hasValue(10.2d); assertThat(underTest.evaluate(createCondition(metric, LESS_THAN, "10.3"), measure)).hasLevel(ERROR).hasValue(10.2d); } @Test public void getLevel_throws_IEA_if_error_threshold_is_not_parsable_long() { Metric metric = createMetric(WORK_DUR); Measure measure = newMeasureBuilder().create(60L, null); assertThatThrownBy(() -> underTest.evaluate(createCondition(metric, LESS_THAN, "polop"), measure)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Quality Gate: Unable to parse value 'polop' to compare against name"); } @Test public void testErrorLevel() { Metric metric = createMetric(FLOAT); Measure measure = newMeasureBuilder().create(10.2d, 1, null); assertThat(underTest.evaluate(createCondition(metric, LESS_THAN, "10.3"), measure)).hasLevel(ERROR); assertThat(underTest.evaluate(createCondition(metric, LESS_THAN, "10.1"), measure)).hasLevel(OK); assertThat(underTest.evaluate(new Condition(metric, LESS_THAN.getDbValue(), "10.3"), measure)).hasLevel(Measure.Level.ERROR); } @Test public void condition_is_always_ok_when_measure_is_noValue() { for (MetricType metricType : from(asList(values())).filter(not(in(ImmutableSet.of(BOOL, DATA, DISTRIB, STRING))))) { Metric metric = createMetric(metricType); Measure measure = newMeasureBuilder().createNoValue(); assertThat(underTest.evaluate(createCondition(metric, LESS_THAN, "10.2"), measure)).hasLevel(OK); } } @Test @UseDataProvider("unsupportedMetricTypes") public void fail_when_metric_is_not_supported(MetricType metricType) { Metric metric = createMetric(metricType); Measure measure = newMeasureBuilder().create("3.14159265358"); assertThatThrownBy(() -> underTest.evaluate(createCondition(metric, LESS_THAN, "1.60217657"), measure)) .isInstanceOf(IllegalArgumentException.class) .hasMessage(String.format("Conditions on MetricType %s are not supported", metricType)); } @DataProvider public static Object[][] unsupportedMetricTypes() { return new Object[][] { {BOOL}, {STRING}, {DATA}, {DISTRIB} }; } @Test public void test_condition_on_rating() { Metric metric = createMetric(RATING); Measure measure = newMeasureBuilder().create(4, "D"); assertThat(underTest.evaluate(new Condition(metric, GREATER_THAN.getDbValue(), "4"), measure)).hasLevel(OK).hasValue(4); assertThat(underTest.evaluate(new Condition(metric, GREATER_THAN.getDbValue(), "2"), measure)).hasLevel(ERROR).hasValue(4); } private static Condition createCondition(Metric metric, Condition.Operator operator, String errorThreshold) { return new Condition(metric, operator.getDbValue(), errorThreshold); } private static MetricImpl createMetric(MetricType metricType) { return new MetricImpl("1", "key", "name", metricType); } }
7,805
43.101695
129
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionStatusTest.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.qualitygate; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.EvaluationStatus.NO_VALUE; import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.EvaluationStatus.OK; import static org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus.EvaluationStatus.values; @RunWith(DataProviderRunner.class) public class ConditionStatusTest { private static final String SOME_VALUE = "value"; @Test public void create_throws_NPE_if_status_argument_is_null() { assertThatThrownBy(() -> ConditionStatus.create(null, SOME_VALUE)) .isInstanceOf(NullPointerException.class) .hasMessage("status can not be null"); } @Test public void create_throws_IAE_if_status_argument_is_NO_VALUE() { assertThatThrownBy(() -> ConditionStatus.create(NO_VALUE, SOME_VALUE)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("EvaluationStatus 'NO_VALUE' can not be used with this method, use constant ConditionStatus.NO_VALUE_STATUS instead."); } @Test @UseDataProvider("allStatusesButNO_VALUE") public void create_throws_NPE_if_value_is_null_and_status_argument_is_not_NO_VALUE(ConditionStatus.EvaluationStatus status) { assertThatThrownBy(() -> ConditionStatus.create(status, null)) .isInstanceOf(NullPointerException.class) .hasMessage("value can not be null"); } @Test public void verify_getters() { ConditionStatus underTest = ConditionStatus.create(OK, SOME_VALUE); assertThat(underTest.getStatus()).isEqualTo(OK); assertThat(underTest.getValue()).isEqualTo(SOME_VALUE); } @Test public void verify_toString() { assertThat(ConditionStatus.create(OK, SOME_VALUE)).hasToString("ConditionStatus{status=OK, value='value'}"); assertThat(ConditionStatus.NO_VALUE_STATUS).hasToString("ConditionStatus{status=NO_VALUE, value='null'}"); } @Test public void constant_NO_VALUE_STATUS_has_status_NO_VALUE_and_null_value() { assertThat(ConditionStatus.NO_VALUE_STATUS.getStatus()).isEqualTo(NO_VALUE); assertThat(ConditionStatus.NO_VALUE_STATUS.getValue()).isNull(); } @DataProvider public static Object[][] allStatusesButNO_VALUE() { Object[][] res = new Object[values().length - 1][1]; int i = 0; for (ConditionStatus.EvaluationStatus status : values()) { if (status != NO_VALUE) { res[i][0] = status; i++; } } return res; } }
3,674
38.095745
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/ConditionTest.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.qualitygate; import org.junit.Before; import org.junit.Test; 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; public class ConditionTest { private static final Metric SOME_METRIC = mock(Metric.class); private static final String SOME_OPERATOR = "LT"; @Before public void setUp() { when(SOME_METRIC.getKey()).thenReturn("dummy key"); } @Test public void constructor_throws_NPE_for_null_metric_argument() { assertThatThrownBy(() -> new Condition(null, SOME_OPERATOR, null)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_NPE_for_null_operator_argument() { assertThatThrownBy(() -> new Condition(SOME_METRIC, null, null)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_throws_IAE_if_operator_is_not_valid() { assertThatThrownBy(() -> new Condition(SOME_METRIC, "troloto", null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Unsupported operator value: 'troloto'"); } @Test public void verify_getters() { String error = "error threshold"; Condition condition = new Condition(SOME_METRIC, SOME_OPERATOR, error); assertThat(condition.getMetric()).isSameAs(SOME_METRIC); assertThat(condition.getOperator()).isSameAs(Condition.Operator.LESS_THAN); assertThat(condition.getErrorThreshold()).isEqualTo(error); } @Test public void all_fields_are_displayed_in_toString() { when(SOME_METRIC.toString()).thenReturn("metric1"); assertThat(new Condition(SOME_METRIC, SOME_OPERATOR, "error_l")) .hasToString("Condition{metric=metric1, operator=LESS_THAN, errorThreshold=error_l}"); } }
2,773
32.829268
92
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultAssert.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.qualitygate; import java.util.Objects; import org.assertj.core.api.AbstractAssert; import org.sonar.ce.task.projectanalysis.measure.Measure; class EvaluationResultAssert extends AbstractAssert<EvaluationResultAssert, EvaluationResult> { protected EvaluationResultAssert(EvaluationResult actual) { super(actual, EvaluationResultAssert.class); } public static EvaluationResultAssert assertThat(EvaluationResult actual) { return new EvaluationResultAssert(actual); } public EvaluationResultAssert hasLevel(Measure.Level expected) { isNotNull(); // check condition if (actual.level() != expected) { failWithMessage("Expected Level to be <%s> but was <%s>", expected, actual.level()); } return this; } public EvaluationResultAssert hasValue(Comparable<?> expected) { isNotNull(); if (!Objects.equals(actual.value(), expected)) { failWithMessage("Expected Value to be <%s> but was <%s>", expected, actual.value()); } return this; } }
1,895
32.263158
95
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTest.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.qualitygate; import org.junit.Test; import org.sonar.ce.task.projectanalysis.measure.Measure; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class EvaluationResultTest { @Test public void constructor_throws_NPE_if_Level_arg_is_null() { assertThatThrownBy(() -> new EvaluationResult(null, 11)) .isInstanceOf(NullPointerException.class); } @Test public void verify_getters() { String value = "toto"; Measure.Level level = Measure.Level.OK; EvaluationResult evaluationResult = new EvaluationResult(level, value); assertThat(evaluationResult.level()).isEqualTo(level); assertThat(evaluationResult.value()).isEqualTo(value); } @Test public void toString_is_defined() { assertThat(new EvaluationResult(Measure.Level.OK, "toto")) .hasToString("EvaluationResult{level=OK, value=toto}"); } }
1,816
34.627451
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/EvaluationResultTextConverterTest.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.qualitygate; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.ArrayList; import java.util.List; import java.util.Locale; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.utils.Durations; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.core.i18n.I18n; 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.measure.Measure.Level.ERROR; @RunWith(DataProviderRunner.class) public class EvaluationResultTextConverterTest { private static final Metric INT_METRIC = new MetricImpl("1", "key", "int_metric_name", Metric.MetricType.INT); private static final Metric SOME_VARIATION_METRIC = new MetricImpl("2", "new_variation_of_trololo", "variation_of_trololo_name", Metric.MetricType.INT); private static final Condition LT_10_CONDITION = new Condition(INT_METRIC, Condition.Operator.LESS_THAN.getDbValue(), "10"); private static final EvaluationResult OK_EVALUATION_RESULT = new EvaluationResult(Measure.Level.OK, null); private static final String ERROR_THRESHOLD = "error_threshold"; private I18n i18n = mock(I18n.class); private Durations durations = mock(Durations.class); private EvaluationResultTextConverter underTest = new EvaluationResultTextConverterImpl(i18n, durations); @Test public void evaluate_throws_NPE_if_Condition_arg_is_null() { assertThatThrownBy(() -> underTest.asText(null, OK_EVALUATION_RESULT)) .isInstanceOf(NullPointerException.class); } @Test public void evaluate_throws_NPE_if_EvaluationResult_arg_is_null() { assertThatThrownBy(() -> underTest.asText(LT_10_CONDITION, null)) .isInstanceOf(NullPointerException.class); } @Test public void evaluate_returns_null_if_EvaluationResult_has_level_OK() { assertThat(underTest.asText(LT_10_CONDITION, OK_EVALUATION_RESULT)).isNull(); } @DataProvider public static Object[][] all_operators_for_error_levels() { List<Object[]> res = new ArrayList<>(); for (Condition.Operator operator : Condition.Operator.values()) { res.add(new Object[] {operator, ERROR}); } return res.toArray(new Object[res.size()][2]); } @Test @UseDataProvider("all_operators_for_error_levels") public void evaluate_returns_msg_of_metric_plus_operator_plus_threshold_for_level_argument(Condition.Operator operator, Measure.Level level) { String metricMsg = "int_metric_msg"; when(i18n.message(Locale.ENGLISH, "metric." + INT_METRIC.getKey() + ".name", INT_METRIC.getName())) .thenReturn(metricMsg); Condition condition = new Condition(INT_METRIC, operator.getDbValue(), ERROR_THRESHOLD); assertThat(underTest.asText(condition, new EvaluationResult(level, null))) .isEqualTo(metricMsg + " " + toSign(operator) + " " + ERROR_THRESHOLD); } @Test @UseDataProvider("all_operators_for_error_levels") public void evaluate_does_not_add_variation_if_metric_starts_with_variation_prefix_but_period_is_null(Condition.Operator operator, Measure.Level level) { String metricMsg = "trololo_metric_msg"; when(i18n.message(Locale.ENGLISH, "metric." + SOME_VARIATION_METRIC.getKey() + ".name", SOME_VARIATION_METRIC.getName())) .thenReturn(metricMsg); Condition condition = new Condition(SOME_VARIATION_METRIC, operator.getDbValue(), ERROR_THRESHOLD); assertThat(underTest.asText(condition, new EvaluationResult(level, null))) .isEqualTo(metricMsg + " " + toSign(operator) + " " + ERROR_THRESHOLD); } private static String toSign(Condition.Operator operator) { switch (operator) { case GREATER_THAN: return ">"; case LESS_THAN: return "<"; default: throw new IllegalArgumentException("Unsupported operator"); } } }
5,065
41.571429
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/MutableQualityGateHolderRule.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.qualitygate; import java.util.Optional; import org.junit.rules.ExternalResource; import org.sonar.server.qualitygate.EvaluatedQualityGate; public class MutableQualityGateHolderRule extends ExternalResource implements MutableQualityGateHolder { private MutableQualityGateHolder delegate = new QualityGateHolderImpl(); @Override public void setQualityGate(QualityGate qualityGate) { delegate.setQualityGate(qualityGate); } @Override public Optional<QualityGate> getQualityGate() { return delegate.getQualityGate(); } @Override public void setEvaluation(EvaluatedQualityGate evaluation) { delegate.setEvaluation(evaluation); } @Override public Optional<EvaluatedQualityGate> getEvaluation() { return delegate.getEvaluation(); } @Override protected void after() { reset(); } public void reset() { this.delegate = new QualityGateHolderImpl(); } }
1,795
29.965517
104
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/MutableQualityGateStatusHolderRule.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.qualitygate; import java.util.Map; import org.junit.rules.ExternalResource; public class MutableQualityGateStatusHolderRule extends ExternalResource implements MutableQualityGateStatusHolder { private MutableQualityGateStatusHolder delegate = new QualityGateStatusHolderImpl(); @Override public void setStatus(QualityGateStatus globalStatus, Map<Condition, ConditionStatus> statusPerCondition) { delegate.setStatus(globalStatus, statusPerCondition); } @Override public QualityGateStatus getStatus() { return delegate.getStatus(); } @Override public Map<Condition, ConditionStatus> getStatusPerConditions() { return delegate.getStatusPerConditions(); } @Override protected void after() { reset(); } public void reset() { this.delegate = new QualityGateStatusHolderImpl(); } }
1,717
32.038462
116
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderImplTest.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.qualitygate; import org.junit.Test; import org.sonar.server.qualitygate.EvaluatedQualityGate; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class QualityGateHolderImplTest { private static final QualityGate QUALITY_GATE = new QualityGate("4612", "name", emptyList()); @Test public void getQualityGate_throws_ISE_if_QualityGate_not_set() { assertThatThrownBy(() -> new QualityGateHolderImpl().getQualityGate()) .isInstanceOf(IllegalStateException.class); } @Test public void setQualityGate_throws_NPE_if_argument_is_null() { assertThatThrownBy(() -> new QualityGateHolderImpl().setQualityGate(null)) .isInstanceOf(NullPointerException.class); } @Test public void setQualityGate_throws_ISE_if_called_twice() { assertThatThrownBy(() -> { QualityGateHolderImpl holder = new QualityGateHolderImpl(); holder.setQualityGate(QUALITY_GATE); holder.setQualityGate(QUALITY_GATE); }) .isInstanceOf(IllegalStateException.class); } @Test public void getQualityGate_returns_QualityGate_set_by_setQualityGate() { QualityGateHolderImpl holder = new QualityGateHolderImpl(); holder.setQualityGate(QUALITY_GATE); assertThat(holder.getQualityGate()).containsSame(QUALITY_GATE); } @Test public void getEvaluation_throws_ISE_if_QualityGate_not_set() { assertThatThrownBy(() -> new QualityGateHolderImpl().getEvaluation()) .isInstanceOf(IllegalStateException.class); } @Test public void setEvaluation_throws_NPE_if_argument_is_null() { assertThatThrownBy(() -> new QualityGateHolderImpl().setEvaluation(null)) .isInstanceOf(NullPointerException.class); } @Test public void setEvaluation_throws_ISE_if_called_twice() { assertThatThrownBy(() -> { QualityGateHolderImpl holder = new QualityGateHolderImpl(); EvaluatedQualityGate evaluation = mock(EvaluatedQualityGate.class); holder.setEvaluation(evaluation); holder.setEvaluation(evaluation); }) .isInstanceOf(IllegalStateException.class); } @Test public void getEvaluation_returns_QualityGate_set_by_setQualityGate() { QualityGateHolderImpl holder = new QualityGateHolderImpl(); EvaluatedQualityGate evaluation = mock(EvaluatedQualityGate.class); holder.setEvaluation(evaluation); assertThat(holder.getEvaluation()).containsSame(evaluation); } }
3,436
33.029703
95
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateHolderRule.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.qualitygate; import java.util.Optional; import javax.annotation.Nullable; import org.junit.rules.ExternalResource; import org.sonar.server.qualitygate.EvaluatedQualityGate; import static com.google.common.base.Preconditions.checkState; public class QualityGateHolderRule extends ExternalResource implements QualityGateHolder { @Nullable private Optional<QualityGate> qualityGate; @Nullable private Optional<EvaluatedQualityGate> evaluation; public void setQualityGate(@Nullable QualityGate qualityGate) { this.qualityGate = Optional.ofNullable(qualityGate); } @Override public Optional<QualityGate> getQualityGate() { checkState(qualityGate != null, "Holder has not been initialized"); return qualityGate; } public void setEvaluation(@Nullable EvaluatedQualityGate e) { this.evaluation = Optional.ofNullable(e); } @Override public Optional<EvaluatedQualityGate> getEvaluation() { checkState(evaluation != null, "EvaluatedQualityGate has not been initialized"); return evaluation; } @Override protected void after() { reset(); } public void reset() { this.qualityGate = null; this.evaluation = null; } }
2,071
30.876923
90
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateServiceImplTest.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.qualitygate; import com.google.common.collect.ImmutableList; import java.util.Optional; import org.junit.Before; import org.junit.Test; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepository; import org.sonar.db.DbClient; import org.sonar.db.qualitygate.QualityGateConditionDao; import org.sonar.db.qualitygate.QualityGateConditionDto; import org.sonar.db.qualitygate.QualityGateDao; import org.sonar.db.qualitygate.QualityGateDto; import org.sonar.server.project.Project; 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.mock; import static org.mockito.Mockito.when; public class QualityGateServiceImplTest { private static final String SOME_UUID = "123"; private static final String SOME_NAME = "some name"; private static final QualityGateDto QUALITY_GATE_DTO = new QualityGateDto().setUuid(SOME_UUID).setName(SOME_NAME); private static final String METRIC_UUID_1 = "uuid1"; private static final String METRIC_UUID_2 = "uuid2"; private static final Metric METRIC_1 = mock(Metric.class); private static final Metric METRIC_2 = mock(Metric.class); private static final QualityGateConditionDto CONDITION_1 = new QualityGateConditionDto().setUuid("321").setMetricUuid(METRIC_UUID_1).setOperator("LT") .setErrorThreshold("error_th"); private static final QualityGateConditionDto CONDITION_2 = new QualityGateConditionDto().setUuid("456").setMetricUuid(METRIC_UUID_2).setOperator("GT") .setErrorThreshold("error_th"); private final QualityGateDao qualityGateDao = mock(QualityGateDao.class); private final QualityGateConditionDao qualityGateConditionDao = mock(QualityGateConditionDao.class); private final MetricRepository metricRepository = mock(MetricRepository.class); private final DbClient dbClient = mock(DbClient.class); private final QualityGateService underTest = new QualityGateServiceImpl(dbClient, metricRepository); @Before public void setUp() { when(dbClient.qualityGateDao()).thenReturn(qualityGateDao); when(dbClient.gateConditionDao()).thenReturn(qualityGateConditionDao); when(METRIC_1.getKey()).thenReturn("metric"); when(METRIC_2.getKey()).thenReturn("new_metric"); } @Test public void findDefaultQualityGate_by_property_not_found() { assertThatThrownBy(() -> underTest.findEffectiveQualityGate(mock(Project.class))).isInstanceOf(IllegalStateException.class); } @Test public void findDefaultQualityGate_by_property_found() { QualityGateDto qualityGateDto = new QualityGateDto(); qualityGateDto.setUuid(QUALITY_GATE_DTO.getUuid()); qualityGateDto.setName(QUALITY_GATE_DTO.getName()); when(qualityGateDao.selectDefault(any())).thenReturn(qualityGateDto); when(qualityGateConditionDao.selectForQualityGate(any(), eq(SOME_UUID))).thenReturn(ImmutableList.of(CONDITION_1, CONDITION_2)); when(metricRepository.getOptionalByUuid(METRIC_UUID_1)).thenReturn(Optional.empty()); when(metricRepository.getOptionalByUuid(METRIC_UUID_2)).thenReturn(Optional.of(METRIC_2)); QualityGate result = underTest.findEffectiveQualityGate(mock(Project.class)); assertThat(result).isNotNull(); assertThat(result.getUuid()).isEqualTo(QUALITY_GATE_DTO.getUuid()); assertThat(result.getName()).isEqualTo(QUALITY_GATE_DTO.getName()); } @Test public void findQualityGate_by_project_found() { QualityGateDto qualityGateDto = new QualityGateDto(); qualityGateDto.setUuid(QUALITY_GATE_DTO.getUuid()); qualityGateDto.setName(QUALITY_GATE_DTO.getName()); when(qualityGateDao.selectByProjectUuid(any(), any())).thenReturn(qualityGateDto); when(qualityGateConditionDao.selectForQualityGate(any(), eq(SOME_UUID))).thenReturn(ImmutableList.of(CONDITION_1, CONDITION_2)); when(metricRepository.getOptionalByUuid(METRIC_UUID_1)).thenReturn(Optional.empty()); when(metricRepository.getOptionalByUuid(METRIC_UUID_2)).thenReturn(Optional.of(METRIC_2)); QualityGate result = underTest.findEffectiveQualityGate(mock(Project.class)); assertThat(result.getUuid()).isEqualTo(QUALITY_GATE_DTO.getUuid()); assertThat(result.getName()).isEqualTo(QUALITY_GATE_DTO.getName()); } }
5,279
47
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitygate/QualityGateStatusHolderImplTest.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.qualitygate; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; import java.util.Collections; import java.util.Map; import org.assertj.core.api.ThrowableAssert.ThrowingCallable; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; @RunWith(DataProviderRunner.class) public class QualityGateStatusHolderImplTest { private static final Map<Condition, ConditionStatus> SOME_STATUS_PER_CONDITION = Collections.singletonMap( mock(Condition.class), ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, "val")); private QualityGateStatusHolderImpl underTest = new QualityGateStatusHolderImpl(); @Test public void setStatus_throws_NPE_if_globalStatus_is_null() { assertThatThrownBy(() -> underTest.setStatus(null, SOME_STATUS_PER_CONDITION)) .isInstanceOf(NullPointerException.class) .hasMessage("global status can not be null"); } @Test public void setStatus_throws_NPE_if_statusPerCondition_is_null() { assertThatThrownBy(() -> underTest.setStatus(QualityGateStatus.OK, null)) .isInstanceOf(NullPointerException.class) .hasMessage("status per condition can not be null"); } @Test public void setStatus_throws_ISE_if_called_twice() { underTest.setStatus(QualityGateStatus.OK, SOME_STATUS_PER_CONDITION); assertThatThrownBy(() -> underTest.setStatus(null, null)) .isInstanceOf(IllegalStateException.class) .hasMessage("Quality gate status has already been set in the holder"); } @Test public void getStatus_throws_ISE_if_setStatus_not_called_yet() { expectQGNotSetYetISE(() -> underTest.getStatus()); } @Test @UseDataProvider("qualityGateStatusValue") public void getStatus_returns_status_argument_from_setStatus(QualityGateStatus status) { underTest.setStatus(status, SOME_STATUS_PER_CONDITION); assertThat(underTest.getStatus()).isEqualTo(status); } @Test public void getStatusPerConditions_throws_ISE_if_setStatus_not_called_yet() { expectQGNotSetYetISE(() -> underTest.getStatusPerConditions()); } @Test public void getStatusPerConditions_returns_statusPerCondition_argument_from_setStatus() { underTest.setStatus(QualityGateStatus.ERROR, SOME_STATUS_PER_CONDITION); assertThat(underTest.getStatusPerConditions()).isEqualTo(SOME_STATUS_PER_CONDITION); // a copy is made to be immutable assertThat(underTest.getStatusPerConditions()).isNotSameAs(SOME_STATUS_PER_CONDITION); } private void expectQGNotSetYetISE(ThrowingCallable callback) { assertThatThrownBy(callback) .isInstanceOf(IllegalStateException.class) .hasMessage("Quality gate status has not been set yet"); } @DataProvider public static Object[][] qualityGateStatusValue() { Object[][] res = new Object[QualityGateStatus.values().length][1]; int i = 0; for (QualityGateStatus status : QualityGateStatus.values()) { res[i][0] = status; i++; } return res; } }
4,114
36.409091
108
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/MaintainabilityMeasuresVisitorTest.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.qualitymodel; 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.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryRule; 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.server.measure.DebtRatingGrid; import org.sonar.server.measure.Rating; import static java.util.Collections.singletonList; 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.DEVELOPMENT_COST; import static org.sonar.api.measures.CoreMetrics.DEVELOPMENT_COST_KEY; import static org.sonar.api.measures.CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A; import static org.sonar.api.measures.CoreMetrics.EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.SQALE_DEBT_RATIO; import static org.sonar.api.measures.CoreMetrics.SQALE_DEBT_RATIO_KEY; import static org.sonar.api.measures.CoreMetrics.SQALE_RATING; import static org.sonar.api.measures.CoreMetrics.SQALE_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT; import static org.sonar.api.measures.CoreMetrics.TECHNICAL_DEBT_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; 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; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.C; import static org.sonar.server.measure.Rating.E; public class MaintainabilityMeasuresVisitorTest { static final String LANGUAGE_KEY_1 = "lKey1"; static final String LANGUAGE_KEY_2 = "lKey2"; static final double[] RATING_GRID = new double[] {0.1, 0.2, 0.5, 1}; static final long DEV_COST_LANGUAGE_1 = 30; static final long DEV_COST_LANGUAGE_2 = 42; static final int PROJECT_REF = 1; static final int DIRECTORY_REF = 123; static final int FILE_1_REF = 1231; static final int FILE_2_REF = 1232; static final Component ROOT_PROJECT = builder(Component.Type.PROJECT, PROJECT_REF).setKey("project") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file1").build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file2").build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC) .add(DEVELOPMENT_COST) .add(TECHNICAL_DEBT) .add(SQALE_DEBT_RATIO) .add(SQALE_RATING) .add(EFFORT_TO_REACH_MAINTAINABILITY_RATING_A); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public ComponentIssuesRepositoryRule componentIssuesRepositoryRule = new ComponentIssuesRepositoryRule(treeRootHolder); private RatingSettings ratingSettings = mock(RatingSettings.class); private VisitorsCrawler underTest; @Before public void setUp() { // assumes rating configuration is consistent when(ratingSettings.getDebtRatingGrid()).thenReturn(new DebtRatingGrid(RATING_GRID)); when(ratingSettings.getDevCost(LANGUAGE_KEY_1)).thenReturn(DEV_COST_LANGUAGE_1); when(ratingSettings.getDevCost(LANGUAGE_KEY_2)).thenReturn(DEV_COST_LANGUAGE_2); underTest = new VisitorsCrawler(singletonList(new MaintainabilityMeasuresVisitor(metricRepository, measureRepository, ratingSettings))); } @Test public void measures_created_for_project_are_all_zero_when_they_have_no_FILE_child() { ReportComponent root = builder(PROJECT, 1).build(); treeRootHolder.setRoot(root); underTest.visit(root); assertThat(measureRepository.getRawMeasures(root).entrySet().stream().map(e -> entryOf(e.getKey(), e.getValue()))) .containsOnly( entryOf(DEVELOPMENT_COST_KEY, newMeasureBuilder().create("0")), entryOf(SQALE_DEBT_RATIO_KEY, newMeasureBuilder().create(0d, 1)), entryOf(SQALE_RATING_KEY, createMaintainabilityRatingMeasure(A)), entryOf(EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, newMeasureBuilder().create(0L))); } @Test public void compute_development_cost() { ReportComponent root = builder(PROJECT, 1).addChildren( builder(DIRECTORY, 111).addChildren( createFileComponent(LANGUAGE_KEY_1, 1111), createFileComponent(LANGUAGE_KEY_2, 1112), // Unit test should not be ignored builder(FILE, 1113).setFileAttributes(new FileAttributes(true, LANGUAGE_KEY_1, 1)).build()) .build(), builder(DIRECTORY, 112).addChildren( createFileComponent(LANGUAGE_KEY_2, 1121)) .build(), builder(DIRECTORY, 121).addChildren( createFileComponent(LANGUAGE_KEY_1, 1211)) .build(), builder(DIRECTORY, 122).build()) .build(); treeRootHolder.setRoot(root); int ncloc1112 = 12; addRawMeasure(NCLOC_KEY, 1112, ncloc1112); int ncloc1113 = 15; addRawMeasure(NCLOC_KEY, 1113, ncloc1113); int nclocValue1121 = 30; addRawMeasure(NCLOC_KEY, 1121, nclocValue1121); int ncloc1211 = 20; addRawMeasure(NCLOC_KEY, 1211, ncloc1211); underTest.visit(root); // verify measures on files verifyAddedRawMeasure(1112, DEVELOPMENT_COST_KEY, Long.toString(ncloc1112 * DEV_COST_LANGUAGE_2)); verifyAddedRawMeasure(1113, DEVELOPMENT_COST_KEY, Long.toString(ncloc1113 * DEV_COST_LANGUAGE_1)); verifyAddedRawMeasure(1121, DEVELOPMENT_COST_KEY, Long.toString(nclocValue1121 * DEV_COST_LANGUAGE_2)); verifyAddedRawMeasure(1211, DEVELOPMENT_COST_KEY, Long.toString(ncloc1211 * DEV_COST_LANGUAGE_1)); // directory has no children => no file => 0 everywhere and A rating verifyAddedRawMeasure(122, DEVELOPMENT_COST_KEY, "0"); // directory has children => dev cost is aggregated verifyAddedRawMeasure(111, DEVELOPMENT_COST_KEY, Long.toString( ncloc1112 * DEV_COST_LANGUAGE_2 + ncloc1113 * DEV_COST_LANGUAGE_1)); verifyAddedRawMeasure(112, DEVELOPMENT_COST_KEY, Long.toString(nclocValue1121 * DEV_COST_LANGUAGE_2)); verifyAddedRawMeasure(121, DEVELOPMENT_COST_KEY, Long.toString(ncloc1211 * DEV_COST_LANGUAGE_1)); verifyAddedRawMeasure(1, DEVELOPMENT_COST_KEY, Long.toString( ncloc1112 * DEV_COST_LANGUAGE_2 + ncloc1113 * DEV_COST_LANGUAGE_1 + nclocValue1121 * DEV_COST_LANGUAGE_2 + ncloc1211 * DEV_COST_LANGUAGE_1)); } @Test public void compute_maintainability_debt_ratio_measure() { treeRootHolder.setRoot(ROOT_PROJECT); int file1Ncloc = 10; addRawMeasure(NCLOC_KEY, FILE_1_REF, file1Ncloc); long file1MaintainabilityCost = 100L; addRawMeasure(TECHNICAL_DEBT_KEY, FILE_1_REF, file1MaintainabilityCost); int file2Ncloc = 5; addRawMeasure(NCLOC_KEY, FILE_2_REF, file2Ncloc); long file2MaintainabilityCost = 1L; addRawMeasure(TECHNICAL_DEBT_KEY, FILE_2_REF, file2MaintainabilityCost); long directoryMaintainabilityCost = 100L; addRawMeasure(TECHNICAL_DEBT_KEY, DIRECTORY_REF, directoryMaintainabilityCost); long projectMaintainabilityCost = 1000L; addRawMeasure(TECHNICAL_DEBT_KEY, PROJECT_REF, projectMaintainabilityCost); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, SQALE_DEBT_RATIO_KEY, file1MaintainabilityCost * 1d / (file1Ncloc * DEV_COST_LANGUAGE_1) * 100); verifyAddedRawMeasure(FILE_2_REF, SQALE_DEBT_RATIO_KEY, file2MaintainabilityCost * 1d / (file2Ncloc * DEV_COST_LANGUAGE_1) * 100); verifyAddedRawMeasure(DIRECTORY_REF, SQALE_DEBT_RATIO_KEY, directoryMaintainabilityCost * 1d / ((file1Ncloc + file2Ncloc) * DEV_COST_LANGUAGE_1) * 100); verifyAddedRawMeasure(PROJECT_REF, SQALE_DEBT_RATIO_KEY, projectMaintainabilityCost * 1d / ((file1Ncloc + file2Ncloc) * DEV_COST_LANGUAGE_1) * 100); } @Test public void compute_maintainability_rating_measure() { treeRootHolder.setRoot(ROOT_PROJECT); addRawMeasure(NCLOC_KEY, FILE_1_REF, 10); addRawMeasure(TECHNICAL_DEBT_KEY, FILE_1_REF, 100L); addRawMeasure(NCLOC_KEY, FILE_2_REF, 5); addRawMeasure(TECHNICAL_DEBT_KEY, FILE_2_REF, 1L); addRawMeasure(TECHNICAL_DEBT_KEY, DIRECTORY_REF, 100L); addRawMeasure(TECHNICAL_DEBT_KEY, PROJECT_REF, 1000L); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, SQALE_RATING_KEY, C); verifyAddedRawMeasure(FILE_2_REF, SQALE_RATING_KEY, A); verifyAddedRawMeasure(DIRECTORY_REF, SQALE_RATING_KEY, C); verifyAddedRawMeasure(PROJECT_REF, SQALE_RATING_KEY, E); } @Test public void compute_effort_to_maintainability_rating_A_measure() { treeRootHolder.setRoot(ROOT_PROJECT); int file1Ncloc = 10; long file1Effort = 100L; addRawMeasure(NCLOC_KEY, FILE_1_REF, file1Ncloc); addRawMeasure(TECHNICAL_DEBT_KEY, FILE_1_REF, file1Effort); int file2Ncloc = 5; long file2Effort = 20L; addRawMeasure(NCLOC_KEY, FILE_2_REF, file2Ncloc); addRawMeasure(TECHNICAL_DEBT_KEY, FILE_2_REF, file2Effort); long dirEffort = 120L; addRawMeasure(TECHNICAL_DEBT_KEY, DIRECTORY_REF, dirEffort); long projectEffort = 150L; addRawMeasure(TECHNICAL_DEBT_KEY, PROJECT_REF, projectEffort); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, (long) (file1Effort - RATING_GRID[0] * file1Ncloc * DEV_COST_LANGUAGE_1)); verifyAddedRawMeasure(FILE_2_REF, EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, (long) (file2Effort - RATING_GRID[0] * file2Ncloc * DEV_COST_LANGUAGE_1)); verifyAddedRawMeasure(DIRECTORY_REF, EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, (long) (dirEffort - RATING_GRID[0] * (file1Ncloc + file2Ncloc) * DEV_COST_LANGUAGE_1)); verifyAddedRawMeasure(PROJECT_REF, EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, (long) (projectEffort - RATING_GRID[0] * (file1Ncloc + file2Ncloc) * DEV_COST_LANGUAGE_1)); } @Test public void compute_0_effort_to_maintainability_rating_A_when_effort_is_lower_than_dev_cost() { treeRootHolder.setRoot(ROOT_PROJECT); addRawMeasure(NCLOC_KEY, FILE_1_REF, 10); addRawMeasure(TECHNICAL_DEBT_KEY, FILE_1_REF, 2L); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, 0L); } @Test public void effort_to_maintainability_rating_A_is_same_as_effort_when_no_dev_cost() { treeRootHolder.setRoot(ROOT_PROJECT); addRawMeasure(TECHNICAL_DEBT_KEY, FILE_1_REF, 100L); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, EFFORT_TO_REACH_MAINTAINABILITY_RATING_A_KEY, 100); } private void addRawMeasure(String metricKey, int componentRef, long value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void addRawMeasure(String metricKey, int componentRef, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void verifyAddedRawMeasure(int componentRef, String metricKey, long value) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(value))); } private void verifyAddedRawMeasure(int componentRef, String metricKey, double value) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(value, 1))); } private void verifyAddedRawMeasure(int componentRef, String metricKey, Rating rating) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(rating.getIndex(), rating.name()))); } private void verifyAddedRawMeasure(int componentRef, String metricKey, String value) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(value))); } private static ReportComponent createFileComponent(String languageKey1, int fileRef) { return builder(FILE, fileRef).setFileAttributes(new FileAttributes(false, languageKey1, 1)).build(); } private static Measure createMaintainabilityRatingMeasure(Rating rating) { return newMeasureBuilder().create(rating.getIndex(), rating.name()); } }
14,451
42.927052
170
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewMaintainabilityMeasuresVisitorTest.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.qualitymodel; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Ordering; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.assertj.core.data.Offset; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.KeyValueFormat; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; 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.source.NewLinesRepository; import org.sonar.server.measure.DebtRatingGrid; import org.sonar.server.measure.Rating; import static com.google.common.base.Preconditions.checkArgument; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA; import static org.sonar.api.measures.CoreMetrics.NCLOC_DATA_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_DEVELOPMENT_COST; import static org.sonar.api.measures.CoreMetrics.NEW_DEVELOPMENT_COST_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING; import static org.sonar.api.measures.CoreMetrics.NEW_MAINTAINABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SQALE_DEBT_RATIO; import static org.sonar.api.measures.CoreMetrics.NEW_SQALE_DEBT_RATIO_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.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.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.MeasureAssert.assertThat; import static org.sonar.server.measure.Rating.A; import static org.sonar.server.measure.Rating.D; public class NewMaintainabilityMeasuresVisitorTest { private static final double[] RATING_GRID = new double[] {0.1, 0.2, 0.5, 1}; private static final String LANGUAGE_1_KEY = "language 1 key"; private static final long LANGUAGE_1_DEV_COST = 30L; private static final int ROOT_REF = 1; private static final int LANGUAGE_1_FILE_REF = 11111; private static final Offset<Double> VALUE_COMPARISON_OFFSET = Offset.offset(0.01); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NEW_TECHNICAL_DEBT) .add(NCLOC_DATA) .add(NEW_SQALE_DEBT_RATIO) .add(NEW_MAINTAINABILITY_RATING) .add(NEW_DEVELOPMENT_COST); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private RatingSettings ratingSettings = mock(RatingSettings.class); private VisitorsCrawler underTest; @Before public void setUp() { when(ratingSettings.getDebtRatingGrid()).thenReturn(new DebtRatingGrid(RATING_GRID)); underTest = new VisitorsCrawler(Arrays.asList(new NewMaintainabilityMeasuresVisitor(metricRepository, measureRepository, newLinesRepository, ratingSettings))); } @Test public void project_has_new_measures() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); treeRootHolder.setRoot(builder(PROJECT, ROOT_REF).build()); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(ROOT_REF, 0); assertNewMaintainability(ROOT_REF, A); } @Test public void project_has_no_measure_if_new_lines_not_available() { when(newLinesRepository.newLinesAvailable()).thenReturn(false); treeRootHolder.setRoot(builder(PROJECT, ROOT_REF).build()); underTest.visit(treeRootHolder.getRoot()); assertNoNewDebtRatioMeasure(ROOT_REF); assertNoNewMaintainability(ROOT_REF); } @Test public void file_has_no_new_debt_ratio_variation_if_new_lines_not_available() { when(newLinesRepository.newLinesAvailable()).thenReturn(false); when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.NO_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); underTest.visit(treeRootHolder.getRoot()); assertNoNewDebtRatioMeasure(LANGUAGE_1_FILE_REF); assertNoNewDebtRatioMeasure(ROOT_REF); } @Test public void file_has_0_new_debt_ratio_if_no_line_is_new() { ReportComponent file = builder(FILE, LANGUAGE_1_FILE_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_1_KEY, 1)).build(); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren(file) .build()); measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NCLOC_DATA_KEY, createNclocDataMeasure(2, 3, 4)); setNewLines(file); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 0); assertNewDebtRatioValues(ROOT_REF, 0); } @Test public void file_has_new_debt_ratio_if_some_lines_are_new() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 83.33); assertNewDebtRatioValues(ROOT_REF, 83.33); } @Test public void new_debt_ratio_changes_with_language_cost() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST * 10); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 8.33); assertNewDebtRatioValues(ROOT_REF, 8.33); } @Test public void new_debt_ratio_changes_with_new_technical_debt() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(500, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(500)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 833.33); assertNewDebtRatioValues(ROOT_REF, 833.33); } @Test public void new_debt_ratio_on_non_file_level_is_based_on_new_technical_debt_of_that_level() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(500, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(1200)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 833.33); assertNewDebtRatioValues(ROOT_REF, 833.33); } @Test public void new_debt_ratio_when_file_is_unit_test() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(500, Flag.UT_FILE, Flag.WITH_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(1200)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 833.33); assertNewDebtRatioValues(ROOT_REF, 833.33); } @Test public void new_debt_ratio_is_0_when_file_has_no_new_lines() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.NO_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 0); assertNewDebtRatioValues(ROOT_REF, 0); } @Test public void new_debt_ratio_is_0_on_non_file_level_when_no_file_has_new_lines() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.WITH_NCLOC, Flag.NO_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(200)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 0); assertNewDebtRatioValues(ROOT_REF, 0); } @Test public void new_debt_ratio_is_0_when_there_is_no_ncloc_in_file() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.NO_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 0); assertNewDebtRatioValues(ROOT_REF, 0); } @Test public void new_debt_ratio_is_0_on_non_file_level_when_one_file_has_zero_new_debt_because_of_no_changeset() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.NO_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(200)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 0); assertNewDebtRatioValues(ROOT_REF, 0); } @Test public void new_debt_ratio_is_0_when_ncloc_measure_is_missing() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); setupOneFileAloneInAProject(50, Flag.SRC_FILE, Flag.MISSING_MEASURE_NCLOC, Flag.WITH_NEW_LINES); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(50)); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 0); assertNewDebtRatioValues(ROOT_REF, 0); } @Test public void leaf_components_always_have_a_measure_when_at_least_one_period_exist_and_ratio_is_computed_from_current_level_new_debt() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); Component file = builder(FILE, LANGUAGE_1_FILE_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_1_KEY, 1)).build(); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, 111) .addChildren(file) .build()) .build()); Measure newDebtMeasure = createNewDebtMeasure(50); measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NEW_TECHNICAL_DEBT_KEY, newDebtMeasure); measureRepository.addRawMeasure(111, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(150)); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(250)); // 4 lines file, only first one is not ncloc measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NCLOC_DATA_KEY, createNclocDataMeasure(2, 3, 4)); // first 2 lines are before all snapshots, 2 last lines are after PERIOD 2's snapshot date setNewLines(file, 3, 4); underTest.visit(treeRootHolder.getRoot()); assertNewDebtRatioValues(LANGUAGE_1_FILE_REF, 83.33); assertNewDebtRatioValues(111, 83.33); assertNewDebtRatioValues(ROOT_REF, 83.33); } @Test public void compute_new_maintainability_rating() { when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); ReportComponent file = builder(FILE, LANGUAGE_1_FILE_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_1_KEY, 1)).build(); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, 111) .addChildren(file) .build()) .build()); Measure newDebtMeasure = createNewDebtMeasure(50); measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NEW_TECHNICAL_DEBT_KEY, newDebtMeasure); measureRepository.addRawMeasure(111, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(150)); measureRepository.addRawMeasure(ROOT_REF, NEW_TECHNICAL_DEBT_KEY, createNewDebtMeasure(250)); // 4 lines file, only first one is not ncloc measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NCLOC_DATA_KEY, createNclocDataMeasure(2, 3, 4)); // first 2 lines are before all snapshots, 2 last lines are after PERIOD 2's snapshot date setNewLines(file, 3, 4); underTest.visit(treeRootHolder.getRoot()); assertNewMaintainability(LANGUAGE_1_FILE_REF, D); assertNewMaintainability(111, D); assertNewMaintainability(ROOT_REF, D); } @Test public void compute_new_development_cost() { ReportComponent file1 = builder(FILE, LANGUAGE_1_FILE_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_1_KEY, 4)).build(); ReportComponent file2 = builder(FILE, 22_222).setFileAttributes(new FileAttributes(false, LANGUAGE_1_KEY, 6)).build(); when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, 111) .addChildren(file1, file2) .build()) .build()); // 4 lines file, only first one is not ncloc measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NCLOC_DATA_KEY, createNclocDataMeasure(2, 3, 4)); // first 2 lines are before all snapshots, 2 last lines are after PERIOD 2's snapshot date setNewLines(file1, 3, 4); // 6 lines file, only last one is not ncloc measureRepository.addRawMeasure(22_222, NCLOC_DATA_KEY, createNclocDataMeasure(1, 2, 3, 4, 5)); // first 2 lines are before all snapshots, 4 last lines are after PERIOD 2's snapshot date setNewLines(file2, 3, 4, 5, 6); underTest.visit(treeRootHolder.getRoot()); assertNewDevelopmentCostValues(ROOT_REF, 5 * LANGUAGE_1_DEV_COST); assertNewDevelopmentCostValues(LANGUAGE_1_FILE_REF, 2 * LANGUAGE_1_DEV_COST); assertNewDevelopmentCostValues(22_222, 3 * LANGUAGE_1_DEV_COST); } @Test public void compute_new_maintainability_rating_to_A_when_no_debt() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(ratingSettings.getDevCost(LANGUAGE_1_KEY)).thenReturn(LANGUAGE_1_DEV_COST); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, 111) .addChildren( builder(FILE, LANGUAGE_1_FILE_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_1_KEY, 1)).build()) .build()) .build()); underTest.visit(treeRootHolder.getRoot()); assertNewMaintainability(LANGUAGE_1_FILE_REF, A); assertNewMaintainability(111, A); assertNewMaintainability(ROOT_REF, A); } private void setupOneFileAloneInAProject(int newDebt, Flag isUnitTest, Flag withNclocLines, Flag withNewLines) { checkArgument(isUnitTest == Flag.UT_FILE || isUnitTest == Flag.SRC_FILE); checkArgument(withNclocLines == Flag.WITH_NCLOC || withNclocLines == Flag.NO_NCLOC || withNclocLines == Flag.MISSING_MEASURE_NCLOC); checkArgument(withNewLines == Flag.WITH_NEW_LINES || withNewLines == Flag.NO_NEW_LINES); Component file = builder(FILE, LANGUAGE_1_FILE_REF).setFileAttributes(new FileAttributes(isUnitTest == Flag.UT_FILE, LANGUAGE_1_KEY, 1)).build(); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren(file) .build()); Measure newDebtMeasure = createNewDebtMeasure(newDebt); measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NEW_TECHNICAL_DEBT_KEY, newDebtMeasure); if (withNclocLines == Flag.WITH_NCLOC) { // 4 lines file, only first one is not ncloc measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NCLOC_DATA_KEY, createNclocDataMeasure(2, 3, 4)); } else if (withNclocLines == Flag.NO_NCLOC) { // 4 lines file, none of which is ncloc measureRepository.addRawMeasure(LANGUAGE_1_FILE_REF, NCLOC_DATA_KEY, createNoNclocDataMeasure(4)); } if (withNewLines == Flag.WITH_NEW_LINES) { // 2 last lines are new setNewLines(file, 3, 4); } } private void setNewLines(Component component, int... lineNumbers) { HashSet<Integer> newLines = new HashSet<>(); for (int i : lineNumbers) { newLines.add(i); } when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(newLinesRepository.getNewLines(component)).thenReturn(Optional.of(newLines)); } private enum Flag { UT_FILE, SRC_FILE, NO_NEW_LINES, WITH_NEW_LINES, WITH_NCLOC, NO_NCLOC, MISSING_MEASURE_NCLOC } public static ReportComponent.Builder builder(Component.Type type, int ref) { return ReportComponent.builder(type, ref).setKey(String.valueOf(ref)); } private Measure createNewDebtMeasure(long value) { return newMeasureBuilder().create(value); } private static Measure createNclocDataMeasure(Integer... nclocLines) { Set<Integer> nclocLinesSet = ImmutableSet.copyOf(nclocLines); int max = Ordering.<Integer>natural().max(nclocLinesSet); ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builder(); for (int i = 1; i <= max; i++) { builder.put(i, nclocLinesSet.contains(i) ? 1 : 0); } return newMeasureBuilder().create(KeyValueFormat.format(builder.build(), KeyValueFormat.newIntegerConverter(), KeyValueFormat.newIntegerConverter())); } private static Measure createNoNclocDataMeasure(int lineCount) { ImmutableMap.Builder<Integer, Integer> builder = ImmutableMap.builder(); for (int i = 1; i <= lineCount; i++) { builder.put(i, 0); } return newMeasureBuilder().create(KeyValueFormat.format(builder.build(), KeyValueFormat.newIntegerConverter(), KeyValueFormat.newIntegerConverter())); } private void assertNoNewDebtRatioMeasure(int componentRef) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SQALE_DEBT_RATIO_KEY)) .isAbsent(); } private void assertNewDebtRatioValues(int componentRef, double expectedValue) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SQALE_DEBT_RATIO_KEY)).hasValue(expectedValue, VALUE_COMPARISON_OFFSET); } private void assertNewDevelopmentCostValues(int componentRef, float expectedValue) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_DEVELOPMENT_COST_KEY)).hasValue(expectedValue, VALUE_COMPARISON_OFFSET); } private void assertNewMaintainability(int componentRef, Rating expectedValue) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_MAINTAINABILITY_RATING_KEY)).hasValue(expectedValue.getIndex()); } private void assertNoNewMaintainability(int componentRef) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_MAINTAINABILITY_RATING_KEY)) .isAbsent(); } }
20,858
43.47548
163
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewReliabilityAndSecurityRatingMeasuresVisitorTest.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.qualitymodel; import java.util.Arrays; import java.util.Date; import org.junit.Before; 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.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryRule; import org.sonar.ce.task.projectanalysis.issue.FillComponentIssuesVisitorRule; import org.sonar.ce.task.projectanalysis.issue.NewIssueClassifier; import org.sonar.ce.task.projectanalysis.measure.MeasureAssert; 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.core.util.UuidFactoryFast; import org.sonar.server.measure.Rating; 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_RATING; import static org.sonar.api.measures.CoreMetrics.NEW_RELIABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_RATING_KEY; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.api.rule.Severity.INFO; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; 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; 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; 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; import static org.sonar.server.measure.Rating.E; public class NewReliabilityAndSecurityRatingMeasuresVisitorTest { private static final long LEAK_PERIOD_SNAPSHOT_IN_MILLISEC = 12323L; private static final Date DEFAULT_ISSUE_CREATION_DATE = new Date(1000L); private static final Date AFTER_LEAK_PERIOD_DATE = new Date(LEAK_PERIOD_SNAPSHOT_IN_MILLISEC + 5000L); static final String LANGUAGE_KEY_1 = "lKey1"; static final int PROJECT_REF = 1; static final int ROOT_DIR_REF = 12; static final int DIRECTORY_REF = 123; static final int FILE_1_REF = 1231; static final int FILE_2_REF = 1232; static final Component ROOT_PROJECT = builder(Component.Type.PROJECT, PROJECT_REF).setKey("project") .addChildren( builder(DIRECTORY, ROOT_DIR_REF).setKey("dir") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file1").build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file2").build()) .build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NEW_SECURITY_RATING) .add(NEW_RELIABILITY_RATING); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public ComponentIssuesRepositoryRule componentIssuesRepositoryRule = new ComponentIssuesRepositoryRule(treeRootHolder); @Rule public FillComponentIssuesVisitorRule fillComponentIssuesVisitorRule = new FillComponentIssuesVisitorRule(componentIssuesRepositoryRule, treeRootHolder); private final NewIssueClassifier newIssueClassifier = mock(NewIssueClassifier.class); private final VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(fillComponentIssuesVisitorRule, new NewReliabilityAndSecurityRatingMeasuresVisitor(metricRepository, measureRepository, componentIssuesRepositoryRule, newIssueClassifier))); @Before public void before() { when(newIssueClassifier.isEnabled()).thenReturn(true); } @Test public void measures_created_for_project_are_all_A_when_they_have_no_FILE_child() { ReportComponent root = builder(PROJECT, 1).build(); treeRootHolder.setRoot(root); underTest.visit(root); verifyAddedRawMeasureOnLeakPeriod(1, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(1, NEW_RELIABILITY_RATING_KEY, A); } @Test public void no_measure_if_there_is_no_period() { when(newIssueClassifier.isEnabled()).thenReturn(false); treeRootHolder.setRoot(builder(PROJECT, 1).build()); underTest.visit(treeRootHolder.getRoot()); assertThat(measureRepository.getAddedRawMeasures(1).values()).isEmpty(); } @Test public void compute_new_security_rating() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newVulnerabilityIssue(10L, MAJOR), // Should not be taken into account oldVulnerabilityIssue(1L, MAJOR), newBugIssue(1L, MAJOR)); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newVulnerabilityIssue(2L, CRITICAL), newVulnerabilityIssue(3L, MINOR), // Should not be taken into account newVulnerabilityIssue(10L, BLOCKER).setResolution(RESOLUTION_FIXED)); fillComponentIssuesVisitorRule.setIssues(ROOT_DIR_REF, newVulnerabilityIssue(7L, BLOCKER)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(FILE_1_REF, NEW_SECURITY_RATING_KEY, C); verifyAddedRawMeasureOnLeakPeriod(FILE_2_REF, NEW_SECURITY_RATING_KEY, D); verifyAddedRawMeasureOnLeakPeriod(DIRECTORY_REF, NEW_SECURITY_RATING_KEY, D); verifyAddedRawMeasureOnLeakPeriod(ROOT_DIR_REF, NEW_SECURITY_RATING_KEY, E); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, E); } @Test public void compute_new_security_rating_to_A_when_no_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(FILE_1_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(FILE_2_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(DIRECTORY_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(ROOT_DIR_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, A); } @Test public void compute_new_security_rating_to_A_when_no_new_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, oldVulnerabilityIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(FILE_1_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(FILE_2_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(DIRECTORY_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(ROOT_DIR_REF, NEW_SECURITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, A); } @Test public void compute_new_reliability_rating() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, MAJOR), // Should not be taken into account oldBugIssue(1L, MAJOR), newVulnerabilityIssue(1L, MAJOR)); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newBugIssue(2L, CRITICAL), newBugIssue(3L, MINOR), // Should not be taken into account newBugIssue(10L, BLOCKER).setResolution(RESOLUTION_FIXED)); fillComponentIssuesVisitorRule.setIssues(ROOT_DIR_REF, newBugIssue(7L, BLOCKER)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(FILE_1_REF, NEW_RELIABILITY_RATING_KEY, C); verifyAddedRawMeasureOnLeakPeriod(FILE_2_REF, NEW_RELIABILITY_RATING_KEY, D); verifyAddedRawMeasureOnLeakPeriod(DIRECTORY_REF, NEW_RELIABILITY_RATING_KEY, D); verifyAddedRawMeasureOnLeakPeriod(ROOT_DIR_REF, NEW_RELIABILITY_RATING_KEY, E); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, E); } @Test public void compute_new_reliability_rating_to_A_when_no_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(FILE_1_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(FILE_2_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(DIRECTORY_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(ROOT_DIR_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, A); } @Test public void compute_new_reliability_rating_to_A_when_no_new_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, oldBugIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(FILE_1_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(FILE_2_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(DIRECTORY_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(ROOT_DIR_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, A); } @Test public void compute_E_reliability_and_security_rating_on_blocker_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, BLOCKER), newVulnerabilityIssue(1L, BLOCKER), // Should not be taken into account newBugIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, E); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, E); } @Test public void compute_D_reliability_and_security_rating_on_critical_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, CRITICAL), newVulnerabilityIssue(15L, CRITICAL), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, D); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, D); } @Test public void compute_C_reliability_and_security_rating_on_major_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, MAJOR), newVulnerabilityIssue(15L, MAJOR), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, C); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, C); } @Test public void compute_B_reliability_and_security_rating_on_minor_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, MINOR), newVulnerabilityIssue(15L, MINOR), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, B); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, B); } @Test public void compute_A_reliability_and_security_rating_on_info_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, INFO).setCreationDate(AFTER_LEAK_PERIOD_DATE), newVulnerabilityIssue(15L, INFO).setCreationDate(AFTER_LEAK_PERIOD_DATE), // Should not be taken into account newCodeSmellIssue(1L, MAJOR).setCreationDate(AFTER_LEAK_PERIOD_DATE)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_RELIABILITY_RATING_KEY, A); verifyAddedRawMeasureOnLeakPeriod(PROJECT_REF, NEW_SECURITY_RATING_KEY, A); } private void verifyAddedRawMeasureOnLeakPeriod(int componentRef, String metricKey, Rating rating) { MeasureAssert.assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey)).hasValue(rating.getIndex()); } private DefaultIssue newBugIssue(long effort, String severity) { return createIssue(effort, severity, BUG, true); } private DefaultIssue oldBugIssue(long effort, String severity) { return createIssue(effort, severity, BUG, false); } private DefaultIssue newVulnerabilityIssue(long effort, String severity) { return createIssue(effort, severity, VULNERABILITY, true); } private DefaultIssue oldVulnerabilityIssue(long effort, String severity) { return createIssue(effort, severity, VULNERABILITY, false); } private DefaultIssue newCodeSmellIssue(long effort, String severity) { return createIssue(effort, severity, CODE_SMELL, true); } private DefaultIssue createIssue(long effort, String severity, RuleType type, boolean isNew) { DefaultIssue issue = createIssue(severity, type) .setEffort(Duration.create(effort)); when(newIssueClassifier.isNew(any(), eq(issue))).thenReturn(isNew); return issue; } private static DefaultIssue createIssue(String severity, RuleType type) { return new DefaultIssue() .setKey(UuidFactoryFast.getInstance().create()) .setSeverity(severity) .setType(type) .setCreationDate(DEFAULT_ISSUE_CREATION_DATE); } }
15,502
41.590659
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/NewSecurityReviewMeasuresVisitorTest.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.qualitymodel; import java.util.Arrays; import javax.annotation.Nullable; import org.assertj.core.api.Assertions; import org.assertj.core.data.Offset; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rules.RuleType; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryRule; import org.sonar.ce.task.projectanalysis.issue.FillComponentIssuesVisitorRule; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.projectanalysis.issue.NewIssueClassifier; import org.sonar.core.issue.DefaultIssue; import org.sonar.core.util.UuidFactoryFast; import org.sonar.core.util.Uuids; import org.sonar.server.measure.Rating; 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.issue.Issue.STATUS_REVIEWED; import static org.sonar.api.issue.Issue.STATUS_TO_REVIEW; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REVIEW_RATING; import static org.sonar.api.measures.CoreMetrics.NEW_SECURITY_REVIEW_RATING_KEY; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; 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.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.measure.MeasureAssert.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; import static org.sonar.server.measure.Rating.E; public class NewSecurityReviewMeasuresVisitorTest { private static final Offset<Double> VALUE_COMPARISON_OFFSET = Offset.offset(0.01); private static final String LANGUAGE_KEY_1 = "lKey1"; private static final int PROJECT_REF = 1; private static final int ROOT_DIR_REF = 12; private static final int DIRECTORY_REF = 123; private static final int FILE_1_REF = 1231; private static final int FILE_2_REF = 1232; private static final Component ROOT_PROJECT = builder(Component.Type.PROJECT, PROJECT_REF).setKey("project") .addChildren( builder(DIRECTORY, ROOT_DIR_REF).setKey("dir") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file1").build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file2").build()) .build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NEW_SECURITY_REVIEW_RATING) .add(NEW_SECURITY_HOTSPOTS_REVIEWED) .add(NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS) .add(NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public ComponentIssuesRepositoryRule componentIssuesRepositoryRule = new ComponentIssuesRepositoryRule(treeRootHolder); @Rule public FillComponentIssuesVisitorRule fillComponentIssuesVisitorRule = new FillComponentIssuesVisitorRule(componentIssuesRepositoryRule, treeRootHolder); private final NewIssueClassifier newIssueClassifier = mock(NewIssueClassifier.class); private final VisitorsCrawler underTest = new VisitorsCrawler(Arrays.asList(fillComponentIssuesVisitorRule, new NewSecurityReviewMeasuresVisitor(componentIssuesRepositoryRule, measureRepository, metricRepository, newIssueClassifier))); @Before public void setup() { when(newIssueClassifier.isEnabled()).thenReturn(true); } @Test public void compute_measures_when_100_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED)); fillComponentIssuesVisitorRule.setIssues(ROOT_DIR_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED)); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, A, 100.0); verifyRatingAndReviewedMeasures(FILE_2_REF, A, 100.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, A, 100.0); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, A, 100.0); verifyRatingAndReviewedMeasures(PROJECT_REF, A, 100.0); } @Test public void compute_measures_when_more_than_80_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, A, 100.0); verifyRatingAndReviewedMeasures(FILE_2_REF, A, 80.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, A, 87.5); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, A, 87.5); verifyRatingAndReviewedMeasures(PROJECT_REF, A, 87.5); } @Test public void compute_measures_when_more_than_70_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, A, 100.0); verifyRatingAndReviewedMeasures(FILE_2_REF, B, 71.42); verifyRatingAndReviewedMeasures(DIRECTORY_REF, B, 75.0); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, B, 75.0); verifyRatingAndReviewedMeasures(PROJECT_REF, B, 75.0); } @Test public void compute_measures_when_more_than_50_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, C, 50.0); verifyRatingAndReviewedMeasures(FILE_2_REF, C, 60.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, C, 57.14); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, C, 57.14); verifyRatingAndReviewedMeasures(PROJECT_REF, C, 57.14); } @Test public void compute_measures_when_more_30_than_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, D, 33.33); verifyRatingAndReviewedMeasures(FILE_2_REF, D, 40.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, D, 37.5); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, D, 37.5); verifyRatingAndReviewedMeasures(PROJECT_REF, D, 37.5); } @Test public void compute_measures_when_less_than_30_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), // Should not be taken into account oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, D, 33.33); verifyRatingAndReviewedMeasures(FILE_2_REF, E, 0.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, E, 16.66); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, E, 16.66); verifyRatingAndReviewedMeasures(PROJECT_REF, E, 16.66); } @Test public void compute_A_rating_and_no_percent_when_no_new_hotspot_on_new_code() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, oldHotspot(STATUS_TO_REVIEW, null), oldHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(PROJECT_REF, A, null); } @Test public void compute_status_related_measures() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyHotspotStatusMeasures(FILE_1_REF, null, null); verifyHotspotStatusMeasures(FILE_2_REF, null, null); verifyHotspotStatusMeasures(DIRECTORY_REF, null, null); verifyHotspotStatusMeasures(ROOT_DIR_REF, null, null); verifyHotspotStatusMeasures(PROJECT_REF, 4, 3); } @Test public void compute_0_status_related_measures_when_no_hotspot() { treeRootHolder.setRoot(ROOT_PROJECT); underTest.visit(ROOT_PROJECT); verifyHotspotStatusMeasures(PROJECT_REF, 0, 0); } @Test public void no_measure_if_there_is_no_period() { when(newIssueClassifier.isEnabled()).thenReturn(false); treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED)); underTest.visit(ROOT_PROJECT); assertThat(measureRepository.getAddedRawMeasures(PROJECT_REF).values()).isEmpty(); } private void verifyRatingAndReviewedMeasures(int componentRef, Rating expectedReviewRating, @Nullable Double expectedHotspotsReviewed) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_REVIEW_RATING_KEY)).hasValue(expectedReviewRating.getIndex()); if (expectedHotspotsReviewed != null) { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY)).hasValue(expectedHotspotsReviewed, VALUE_COMPARISON_OFFSET); } else { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_HOTSPOTS_REVIEWED_KEY)).isAbsent(); } } private void verifyHotspotStatusMeasures(int componentRef, @Nullable Integer hotspotsReviewed, @Nullable Integer hotspotsToReview) { if (hotspotsReviewed == null) { Assertions.assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY)).isEmpty(); } else { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY)).hasValue(hotspotsReviewed); } if (hotspotsReviewed == null) { Assertions.assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY)).isEmpty(); } else { assertThat(measureRepository.getAddedRawMeasure(componentRef, NEW_SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY)).hasValue(hotspotsToReview); } } private DefaultIssue newHotspot(String status, @Nullable String resolution) { return createHotspot(status, resolution, true); } private DefaultIssue oldHotspot(String status, @Nullable String resolution) { return createHotspot(status, resolution, false); } private DefaultIssue createHotspot(String status, @Nullable String resolution, boolean isNew) { DefaultIssue issue = new DefaultIssue() .setKey(UuidFactoryFast.getInstance().create()) .setSeverity(MINOR) .setStatus(status) .setResolution(resolution) .setType(RuleType.SECURITY_HOTSPOT); when(newIssueClassifier.isNew(any(), eq(issue))).thenReturn(isNew); return issue; } private DefaultIssue newIssue() { DefaultIssue issue = new DefaultIssue() .setKey(Uuids.create()) .setSeverity(MAJOR) .setType(RuleType.BUG); when(newIssueClassifier.isNew(any(), eq(issue))).thenReturn(false); return issue; } }
17,126
42.25
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/RatingSettingsTest.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.qualitymodel; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.config.PropertyDefinitions; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.System2; import org.sonar.core.config.CorePropertyDefinitions; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.api.CoreProperties.DEVELOPMENT_COST; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY; import static org.sonar.api.CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY; public class RatingSettingsTest { private MapSettings settings = new MapSettings(new PropertyDefinitions(System2.INSTANCE, CorePropertyDefinitions.all())); @Test public void load_rating_grid() { settings.setProperty(CoreProperties.RATING_GRID, "1,3.4,8,50"); RatingSettings configurationLoader = new RatingSettings(settings.asConfig()); double[] grid = configurationLoader.getDebtRatingGrid().getGridValues(); assertThat(grid).hasSize(4); assertThat(grid[0]).isEqualTo(1.0); assertThat(grid[1]).isEqualTo(3.4); assertThat(grid[2]).isEqualTo(8.0); assertThat(grid[3]).isEqualTo(50.0); } @Test public void load_work_units_for_language() { settings.setProperty(DEVELOPMENT_COST, "50"); RatingSettings configurationLoader = new RatingSettings(settings.asConfig()); assertThat(configurationLoader.getDevCost("defaultLanguage")).isEqualTo(50L); } @Test public void load_overridden_values_for_language() { String aLanguage = "aLanguage"; String anotherLanguage = "anotherLanguage"; settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS, "0,1"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY, aLanguage); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "30"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY, CoreMetrics.NCLOC_KEY); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY, anotherLanguage); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "1" + "." + CoreProperties.LANGUAGE_SPECIFIC_PARAMETERS_SIZE_METRIC_KEY, CoreMetrics.COMPLEXITY_KEY); RatingSettings configurationLoader = new RatingSettings(settings.asConfig()); assertThat(configurationLoader.getDevCost(aLanguage)).isEqualTo(30L); assertThat(configurationLoader.getDevCost(anotherLanguage)).isEqualTo(40L); } @Test public void fail_on_invalid_rating_grid_configuration() { assertThatThrownBy(() -> { settings.setProperty(CoreProperties.RATING_GRID, "a b c"); new RatingSettings(settings.asConfig()); }) .isInstanceOf(IllegalArgumentException.class); } @Test public void use_generic_value_when_specific_setting_is_missing() { String aLanguage = "aLanguage"; settings.setProperty(DEVELOPMENT_COST, "30"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS, "0"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_LANGUAGE_KEY, aLanguage); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40"); RatingSettings configurationLoader = new RatingSettings(settings.asConfig()); assertThat(configurationLoader.getDevCost(aLanguage)).isEqualTo(40L); } @Test public void constructor_fails_with_ME_if_language_specific_parameter_language_is_missing() { settings.setProperty(DEVELOPMENT_COST, "30"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS, "0"); settings.setProperty(LANGUAGE_SPECIFIC_PARAMETERS + "." + "0" + "." + LANGUAGE_SPECIFIC_PARAMETERS_MAN_DAYS_KEY, "40"); assertThatThrownBy(() -> new RatingSettings(settings.asConfig())) .isInstanceOf(MessageException.class) .hasMessage("Technical debt configuration is corrupted. At least one language specific parameter has no Language key. " + "Contact your administrator to update this configuration in the global administration section of SonarQube."); } }
5,488
44.741667
163
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/ReliabilityAndSecurityRatingMeasuresVisitorTest.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.qualitymodel; import java.util.Arrays; import java.util.Date; 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.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryRule; import org.sonar.ce.task.projectanalysis.issue.FillComponentIssuesVisitorRule; 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.core.issue.DefaultIssue; import org.sonar.core.util.Uuids; import org.sonar.server.measure.Rating; 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_RATING; import static org.sonar.api.measures.CoreMetrics.RELIABILITY_RATING_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING; import static org.sonar.api.measures.CoreMetrics.SECURITY_RATING_KEY; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.api.rule.Severity.INFO; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; 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; 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; 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; 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; import static org.sonar.server.measure.Rating.E; public class ReliabilityAndSecurityRatingMeasuresVisitorTest { static final String LANGUAGE_KEY_1 = "lKey1"; static final int PROJECT_REF = 1; static final int DIRECTORY_REF = 123; static final int FILE_1_REF = 1231; static final int FILE_2_REF = 1232; static final Component ROOT_PROJECT = builder(Component.Type.PROJECT, PROJECT_REF).setKey("project") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file1").build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_KEY_1, 1)).setKey("file2").build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(RELIABILITY_RATING) .add(SECURITY_RATING); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public ComponentIssuesRepositoryRule componentIssuesRepositoryRule = new ComponentIssuesRepositoryRule(treeRootHolder); @Rule public FillComponentIssuesVisitorRule fillComponentIssuesVisitorRule = new FillComponentIssuesVisitorRule(componentIssuesRepositoryRule, treeRootHolder); VisitorsCrawler underTest = new VisitorsCrawler( Arrays.asList(fillComponentIssuesVisitorRule, new ReliabilityAndSecurityRatingMeasuresVisitor(metricRepository, measureRepository, componentIssuesRepositoryRule))); @Test public void measures_created_for_project_are_all_A_when_they_have_no_FILE_child() { ReportComponent root = builder(PROJECT, 1).build(); treeRootHolder.setRoot(root); underTest.visit(root); assertThat(measureRepository.getRawMeasures(root) .entrySet().stream().map(e -> entryOf(e.getKey(), e.getValue()))) .containsOnly( entryOf(RELIABILITY_RATING_KEY, createRatingMeasure(A)), entryOf(SECURITY_RATING_KEY, createRatingMeasure(A))); } @Test public void compute_reliability_rating() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, MAJOR), newBugIssue(1L, MAJOR), // Should not be taken into account newVulnerabilityIssue(5L, MINOR)); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newBugIssue(2L, CRITICAL), newBugIssue(3L, MINOR), // Should not be taken into account newBugIssue(10L, BLOCKER).setResolution(RESOLUTION_FIXED)); fillComponentIssuesVisitorRule.setIssues(PROJECT_REF, newBugIssue(7L, BLOCKER)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, RELIABILITY_RATING_KEY, C); verifyAddedRawMeasure(FILE_2_REF, RELIABILITY_RATING_KEY, D); verifyAddedRawMeasure(DIRECTORY_REF, RELIABILITY_RATING_KEY, D); verifyAddedRawMeasure(PROJECT_REF, RELIABILITY_RATING_KEY, E); } @Test public void compute_security_rating() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newVulnerabilityIssue(10L, MAJOR), newVulnerabilityIssue(1L, MAJOR), // Should not be taken into account newBugIssue(1L, MAJOR)); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newVulnerabilityIssue(2L, CRITICAL), newVulnerabilityIssue(3L, MINOR), // Should not be taken into account newVulnerabilityIssue(10L, BLOCKER).setResolution(RESOLUTION_FIXED)); fillComponentIssuesVisitorRule.setIssues(PROJECT_REF, newVulnerabilityIssue(7L, BLOCKER)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(FILE_1_REF, SECURITY_RATING_KEY, C); verifyAddedRawMeasure(FILE_2_REF, SECURITY_RATING_KEY, D); verifyAddedRawMeasure(DIRECTORY_REF, SECURITY_RATING_KEY, D); verifyAddedRawMeasure(PROJECT_REF, SECURITY_RATING_KEY, E); } @Test public void compute_E_reliability_and_security_rating_on_blocker_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, BLOCKER), newVulnerabilityIssue(1L, BLOCKER), // Should not be taken into account newBugIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(PROJECT_REF, RELIABILITY_RATING_KEY, E); verifyAddedRawMeasure(PROJECT_REF, SECURITY_RATING_KEY, E); } @Test public void compute_D_reliability_and_security_rating_on_critical_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, CRITICAL), newVulnerabilityIssue(15L, CRITICAL), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(PROJECT_REF, RELIABILITY_RATING_KEY, D); verifyAddedRawMeasure(PROJECT_REF, SECURITY_RATING_KEY, D); } @Test public void compute_C_reliability_and_security_rating_on_major_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, MAJOR), newVulnerabilityIssue(15L, MAJOR), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(PROJECT_REF, RELIABILITY_RATING_KEY, C); verifyAddedRawMeasure(PROJECT_REF, SECURITY_RATING_KEY, C); } @Test public void compute_B_reliability_and_security_rating_on_minor_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, MINOR), newVulnerabilityIssue(15L, MINOR), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(PROJECT_REF, RELIABILITY_RATING_KEY, B); verifyAddedRawMeasure(PROJECT_REF, SECURITY_RATING_KEY, B); } @Test public void compute_A_reliability_and_security_rating_on_info_issue() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newBugIssue(10L, INFO), newVulnerabilityIssue(15L, INFO), // Should not be taken into account newCodeSmellIssue(1L, MAJOR)); underTest.visit(ROOT_PROJECT); verifyAddedRawMeasure(PROJECT_REF, RELIABILITY_RATING_KEY, A); verifyAddedRawMeasure(PROJECT_REF, SECURITY_RATING_KEY, A); } private void verifyAddedRawMeasure(int componentRef, String metricKey, Rating rating) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(rating.getIndex(), rating.name()))); } private static Measure createRatingMeasure(Rating rating) { return newMeasureBuilder().create(rating.getIndex(), rating.name()); } private static DefaultIssue newBugIssue(long effort, String severity) { return newIssue(effort, severity, BUG); } private static DefaultIssue newVulnerabilityIssue(long effort, String severity) { return newIssue(effort, severity, VULNERABILITY); } private static DefaultIssue newCodeSmellIssue(long effort, String severity) { return newIssue(effort, severity, CODE_SMELL); } private static DefaultIssue newIssue(long effort, String severity, RuleType type) { return newIssue(severity, type) .setEffort(Duration.create(effort)); } private static DefaultIssue newIssue(String severity, RuleType type) { return new DefaultIssue() .setKey(Uuids.create()) .setSeverity(severity) .setType(type) .setCreationDate(new Date(1000L)); } }
11,121
42.108527
170
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualitymodel/SecurityReviewMeasuresVisitorTest.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.qualitymodel; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rules.RuleType; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepositoryRule; import org.sonar.ce.task.projectanalysis.issue.FillComponentIssuesVisitorRule; 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.core.issue.DefaultIssue; import org.sonar.core.util.Uuids; import org.sonar.server.measure.Rating; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.issue.Issue.RESOLUTION_FIXED; import static org.sonar.api.issue.Issue.RESOLUTION_SAFE; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS; import static org.sonar.api.measures.CoreMetrics.SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY; import static org.sonar.api.measures.CoreMetrics.SECURITY_REVIEW_RATING; import static org.sonar.api.measures.CoreMetrics.SECURITY_REVIEW_RATING_KEY; import static org.sonar.api.rule.Severity.MAJOR; import static org.sonar.api.rule.Severity.MINOR; 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.ReportComponent.builder; import static org.sonar.core.issue.DefaultIssue.STATUS_REVIEWED; import static org.sonar.core.issue.DefaultIssue.STATUS_TO_REVIEW; 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; import static org.sonar.server.measure.Rating.E; public class SecurityReviewMeasuresVisitorTest { private static final int PROJECT_REF = 1; private static final int ROOT_DIR_REF = 12; private static final int DIRECTORY_REF = 123; private static final int FILE_1_REF = 1231; private static final int FILE_2_REF = 1232; static final Component ROOT_PROJECT = builder(Component.Type.PROJECT, PROJECT_REF).setKey("project") .addChildren( builder(DIRECTORY, ROOT_DIR_REF).setKey("dir") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setKey("file1").build(), builder(FILE, FILE_2_REF).setKey("file2").build()) .build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(SECURITY_REVIEW_RATING) .add(SECURITY_HOTSPOTS_REVIEWED) .add(SECURITY_HOTSPOTS_REVIEWED_STATUS) .add(SECURITY_HOTSPOTS_TO_REVIEW_STATUS); @Rule public ComponentIssuesRepositoryRule componentIssuesRepositoryRule = new ComponentIssuesRepositoryRule(treeRootHolder); @Rule public FillComponentIssuesVisitorRule fillComponentIssuesVisitorRule = new FillComponentIssuesVisitorRule(componentIssuesRepositoryRule, treeRootHolder); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private VisitorsCrawler underTest = new VisitorsCrawler(asList(fillComponentIssuesVisitorRule, new SecurityReviewMeasuresVisitor(componentIssuesRepositoryRule, measureRepository, metricRepository))); @Test public void compute_rating_and_reviewed_measures_when_100_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_SAFE), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, A, 100.0); verifyRatingAndReviewedMeasures(FILE_2_REF, A, 100.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, A, 100.0); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, A, 100.0); verifyRatingAndReviewedMeasures(PROJECT_REF, A, 100.0); } @Test public void compute_rating_and_reviewed__measures_when_more_than_80_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, A, 100.0); verifyRatingAndReviewedMeasures(FILE_2_REF, A, 80.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, A, 87.5); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, A, 87.5); verifyRatingAndReviewedMeasures(PROJECT_REF, A, 87.5); } @Test public void compute_rating_and_reviewed__measures_when_more_than_70_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, A, 100.0); verifyRatingAndReviewedMeasures(FILE_2_REF, B, 71.4); verifyRatingAndReviewedMeasures(DIRECTORY_REF, B, 75.0); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, B, 75.0); verifyRatingAndReviewedMeasures(PROJECT_REF, B, 75.0); } @Test public void compute_rating_and_reviewed__measures_when_more_than_50_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, C, 50.0); verifyRatingAndReviewedMeasures(FILE_2_REF, C, 60.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, C, 57.1); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, C, 57.1); verifyRatingAndReviewedMeasures(PROJECT_REF, C, 57.1); } @Test public void compute_rating_and_reviewed__measures_when_more_30_than_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, D, 33.3); verifyRatingAndReviewedMeasures(FILE_2_REF, D, 40.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, D, 37.5); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, D, 37.5); verifyRatingAndReviewedMeasures(PROJECT_REF, D, 37.5); } @Test public void compute_rating_and_reviewed__measures_when_less_than_30_percent_hotspots_reviewed() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newIssue()); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(FILE_1_REF, D, 33.3); verifyRatingAndReviewedMeasures(FILE_2_REF, E, 0.0); verifyRatingAndReviewedMeasures(DIRECTORY_REF, E, 16.7); verifyRatingAndReviewedMeasures(ROOT_DIR_REF, E, 16.7); verifyRatingAndReviewedMeasures(PROJECT_REF, E, 16.7); } @Test public void compute_A_rating_and_no_reviewed_when_no_hotspot() { treeRootHolder.setRoot(ROOT_PROJECT); underTest.visit(ROOT_PROJECT); verifyRatingAndReviewedMeasures(PROJECT_REF, A, null); } @Test public void compute_status_related_measures() { treeRootHolder.setRoot(ROOT_PROJECT); fillComponentIssuesVisitorRule.setIssues(FILE_1_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), // Should not be taken into account newIssue()); fillComponentIssuesVisitorRule.setIssues(FILE_2_REF, newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_TO_REVIEW, null), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newHotspot(STATUS_REVIEWED, RESOLUTION_FIXED), newIssue()); underTest.visit(ROOT_PROJECT); verifyHotspotStatusMeasures(FILE_1_REF, 1, 1); verifyHotspotStatusMeasures(FILE_2_REF, 3, 2); verifyHotspotStatusMeasures(DIRECTORY_REF, 4, 3); verifyHotspotStatusMeasures(ROOT_DIR_REF, 4, 3); verifyHotspotStatusMeasures(PROJECT_REF, 4, 3); } @Test public void compute_0_status_related_measures_when_no_hotspot() { treeRootHolder.setRoot(ROOT_PROJECT); underTest.visit(ROOT_PROJECT); verifyHotspotStatusMeasures(PROJECT_REF, 0, 0); } private void verifyRatingAndReviewedMeasures(int componentRef, Rating expectedReviewRating, @Nullable Double expectedHotspotsReviewed) { verifySecurityReviewRating(componentRef, expectedReviewRating); if (expectedHotspotsReviewed != null) { verifySecurityHotspotsReviewed(componentRef, expectedHotspotsReviewed); } else { assertThat(measureRepository.getAddedRawMeasure(componentRef, SECURITY_HOTSPOTS_REVIEWED_KEY)).isEmpty(); } } private void verifySecurityReviewRating(int componentRef, Rating rating) { Measure measure = measureRepository.getAddedRawMeasure(componentRef, SECURITY_REVIEW_RATING_KEY).get(); assertThat(measure.getIntValue()).isEqualTo(rating.getIndex()); assertThat(measure.getData()).isEqualTo(rating.name()); } private void verifySecurityHotspotsReviewed(int componentRef, double percent) { assertThat(measureRepository.getAddedRawMeasure(componentRef, SECURITY_HOTSPOTS_REVIEWED_KEY).get().getDoubleValue()).isEqualTo(percent); } private void verifyHotspotStatusMeasures(int componentRef, @Nullable Integer hotspotsReviewed, @Nullable Integer hotspotsToReview) { if (hotspotsReviewed == null){ assertThat(measureRepository.getAddedRawMeasure(componentRef, SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY)).isEmpty(); } else { assertThat(measureRepository.getAddedRawMeasure(componentRef, SECURITY_HOTSPOTS_REVIEWED_STATUS_KEY).get().getIntValue()).isEqualTo(hotspotsReviewed); } if (hotspotsReviewed == null){ assertThat(measureRepository.getAddedRawMeasure(componentRef, SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY)).isEmpty(); } else { assertThat(measureRepository.getAddedRawMeasure(componentRef, SECURITY_HOTSPOTS_TO_REVIEW_STATUS_KEY).get().getIntValue()).isEqualTo(hotspotsToReview); } } private static DefaultIssue newHotspot(String status, @Nullable String resolution) { return new DefaultIssue() .setKey(Uuids.create()) .setSeverity(MINOR) .setStatus(status) .setResolution(resolution) .setType(RuleType.SECURITY_HOTSPOT); } private static DefaultIssue newIssue() { return new DefaultIssue() .setKey(Uuids.create()) .setSeverity(MAJOR) .setType(RuleType.BUG); } }
14,634
41.917889
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderImplTest.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.qualityprofile; import java.util.Collections; import java.util.Optional; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ActiveRulesHolderImplTest { private static final String PLUGIN_KEY = "java"; private static final long SOME_DATE = 1_000L; static final RuleKey RULE_KEY = RuleKey.of("java", "S001"); private static final String QP_KEY = "qp1"; ActiveRulesHolderImpl underTest = new ActiveRulesHolderImpl(); @Test public void get_inactive_rule() { underTest.set(Collections.emptyList()); Optional<ActiveRule> activeRule = underTest.get(RULE_KEY); assertThat(activeRule).isEmpty(); } @Test public void get_active_rule() { underTest.set(asList(new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); Optional<ActiveRule> activeRule = underTest.get(RULE_KEY); assertThat(activeRule).isPresent(); assertThat(activeRule.get().getRuleKey()).isEqualTo(RULE_KEY); assertThat(activeRule.get().getSeverity()).isEqualTo(Severity.BLOCKER); } @Test public void can_not_set_twice() { assertThatThrownBy(() -> { underTest.set(asList(new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); underTest.set(Collections.emptyList()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Active rules have already been initialized"); } @Test public void can_not_get_if_not_initialized() { assertThatThrownBy(() -> underTest.get(RULE_KEY)) .isInstanceOf(IllegalStateException.class) .hasMessage("Active rules have not been initialized yet"); } @Test public void can_not_set_duplicated_rules() { assertThatThrownBy(() -> { underTest.set(asList( new ActiveRule(RULE_KEY, Severity.BLOCKER, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY), new ActiveRule(RULE_KEY, Severity.MAJOR, Collections.emptyMap(), SOME_DATE, PLUGIN_KEY, QP_KEY))); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Active rule must not be declared multiple times: java:S001"); } }
3,230
35.303371
127
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/ActiveRulesHolderRule.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.qualityprofile; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.rules.ExternalResource; import org.sonar.api.rule.RuleKey; public class ActiveRulesHolderRule extends ExternalResource implements ActiveRulesHolder { private final Map<RuleKey, ActiveRule> activeRulesByKey = new HashMap<>(); @Override public Optional<ActiveRule> get(RuleKey ruleKey) { return Optional.ofNullable(activeRulesByKey.get(ruleKey)); } public ActiveRulesHolderRule put(ActiveRule activeRule) { activeRulesByKey.put(activeRule.getRuleKey(), activeRule); return this; } @Override protected void after() { activeRulesByKey.clear(); } }
1,577
32.574468
90
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/AlwaysActiveRulesHolderImpl.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.qualityprofile; import java.util.Optional; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.Severity; import static java.util.Collections.emptyMap; public class AlwaysActiveRulesHolderImpl implements ActiveRulesHolder { @Override public Optional<ActiveRule> get(RuleKey ruleKey) { return Optional.of(new ActiveRule(ruleKey, Severity.MAJOR, emptyMap(), 1_000L, null, "qp1")); } }
1,290
35.885714
97
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/qualityprofile/QProfileStatusRepositoryImplTest.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.qualityprofile; 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 java.util.stream.Stream; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class QProfileStatusRepositoryImplTest { private QProfileStatusRepositoryImpl underTest; @Before public void setUp() { underTest = new QProfileStatusRepositoryImpl(); } @Test @UseDataProvider("qualityProfileStatuses") public void get_return_optional_of_status(QProfileStatusRepository.Status status) { underTest.register("key", status); assertThat(underTest.get("key")).isEqualTo(Optional.of(status)); } @Test @UseDataProvider("qualityProfileStatuses") public void get_return_empty_for_qp_not_registered(QProfileStatusRepository.Status status) { underTest.register("key", status); assertThat(underTest.get("other_key")).isEmpty(); } @Test public void get_return_empty_for_null_qp_key() { assertThat(underTest.get(null)).isEmpty(); } @Test @UseDataProvider("qualityProfileStatuses") public void register_fails_with_NPE_if_qpKey_is_null(QProfileStatusRepository.Status status) { assertThatThrownBy(() -> underTest.register(null, status)) .isInstanceOf(NullPointerException.class) .hasMessage("qpKey can't be null"); } @Test public void register_fails_with_NPE_if_status_is_null() { assertThatThrownBy(() -> underTest.register("key", null)) .isInstanceOf(NullPointerException.class) .hasMessage("status can't be null"); } @Test @UseDataProvider("qualityProfileStatuses") public void register_fails_with_ISE_if_qp_is_already_registered(QProfileStatusRepository.Status status) { underTest.register("key", status); assertThatThrownBy(() -> underTest.register("key", status)) .isInstanceOf(IllegalStateException.class) .hasMessage("Quality Profile 'key' is already registered"); } @DataProvider public static Object[][] qualityProfileStatuses() { return Stream.of(QProfileStatusRepository.Status.values()) .map(s -> new Object[] {s}) .toArray(Object[][]::new); } }
3,310
33.134021
107
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ChangesetTest.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.scm; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ChangesetTest { @Test public void create_changeset() { Changeset underTest = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build(); assertThat(underTest.getAuthor()).isEqualTo("john"); assertThat(underTest.getDate()).isEqualTo(123456789L); assertThat(underTest.getRevision()).isEqualTo("rev-1"); } @Test public void create_changeset_with_minimum_fields() { Changeset underTest = Changeset.newChangesetBuilder() .setDate(123456789L) .build(); assertThat(underTest.getAuthor()).isNull(); assertThat(underTest.getDate()).isEqualTo(123456789L); assertThat(underTest.getRevision()).isNull(); } @Test public void fail_with_NPE_when_setting_null_date() { assertThatThrownBy(() -> Changeset.newChangesetBuilder().setDate(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Date cannot be null"); } @Test public void fail_with_NPE_when_building_without_date() { assertThatThrownBy(() -> { Changeset.newChangesetBuilder() .setAuthor("john") .setRevision("rev-1") .build(); }) .isInstanceOf(NullPointerException.class) .hasMessage("Date cannot be null"); } @Test public void test_to_string() { Changeset underTest = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build(); assertThat(underTest).hasToString("Changeset{revision='rev-1', author='john', date=123456789}"); } @Test public void equals_and_hashcode_are_based_on_all_fields() { Changeset.Builder changesetBuilder = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1"); Changeset changeset = changesetBuilder.build(); Changeset sameChangeset = changesetBuilder.build(); Changeset anotherChangesetWithSameRevision = Changeset.newChangesetBuilder() .setAuthor("henry") .setDate(1234567810L) .setRevision("rev-1") .build(); Changeset anotherChangeset = Changeset.newChangesetBuilder() .setAuthor("henry") .setDate(996L) .setRevision("rev-2") .build(); assertThat(changeset) .isEqualTo(changeset) .isEqualTo(sameChangeset) .isNotEqualTo(anotherChangesetWithSameRevision) .isNotEqualTo(anotherChangeset) .hasSameHashCodeAs(changeset) .hasSameHashCodeAs(sameChangeset); assertThat(changeset.hashCode()) .isNotEqualTo(anotherChangesetWithSameRevision.hashCode()) .isNotEqualTo(anotherChangeset.hashCode()); } }
3,709
30.709402
100
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/DbScmInfoTest.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.scm; import org.junit.Test; import org.sonar.db.protobuf.DbFileSources; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.server.source.index.FileSourceTesting.newFakeData; public class DbScmInfoTest { @Test public void create_scm_info_with_some_changesets() { ScmInfo scmInfo = DbScmInfo.create(newFakeData(10).build().getLinesList(), 10, "hash").get(); assertThat(scmInfo.getAllChangesets()).hasSize(10); } @Test public void return_changeset_for_a_given_line() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); addLine(fileDataBuilder, 1, "john", 123456789L, "rev-1"); addLine(fileDataBuilder, 2, "henry", 1234567810L, "rev-2"); addLine(fileDataBuilder, 3, "henry", 1234567810L, "rev-2"); addLine(fileDataBuilder, 4, "john", 123456789L, "rev-1"); fileDataBuilder.build(); ScmInfo scmInfo = DbScmInfo.create(fileDataBuilder.getLinesList(), 4, "hash").get(); assertThat(scmInfo.getAllChangesets()).hasSize(4); Changeset changeset = scmInfo.getChangesetForLine(4); assertThat(changeset.getAuthor()).isEqualTo("john"); assertThat(changeset.getDate()).isEqualTo(123456789L); assertThat(changeset.getRevision()).isEqualTo("rev-1"); } @Test public void return_same_changeset_objects_for_lines_with_same_fields() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(65L).setLine(1); fileDataBuilder.addLinesBuilder().setScmRevision("rev2").setScmDate(6541L).setLine(2); fileDataBuilder.addLinesBuilder().setScmRevision("rev1").setScmDate(6541L).setLine(3); fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(65L).setLine(4); ScmInfo scmInfo = DbScmInfo.create(fileDataBuilder.getLinesList(), 4, "hash").get(); assertThat(scmInfo.getAllChangesets()).hasSize(4); assertThat(scmInfo.getChangesetForLine(1)).isSameAs(scmInfo.getChangesetForLine(4)); } @Test public void return_latest_changeset() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); addLine(fileDataBuilder, 1, "john", 123456789L, "rev-1"); // Older changeset addLine(fileDataBuilder, 2, "henry", 1234567810L, "rev-2"); addLine(fileDataBuilder, 3, "john", 123456789L, "rev-1"); fileDataBuilder.build(); ScmInfo scmInfo = DbScmInfo.create(fileDataBuilder.getLinesList(), 3, "hash").get(); Changeset latestChangeset = scmInfo.getLatestChangeset(); assertThat(latestChangeset.getAuthor()).isEqualTo("henry"); assertThat(latestChangeset.getDate()).isEqualTo(1234567810L); assertThat(latestChangeset.getRevision()).isEqualTo("rev-2"); } @Test public void return_absent_dsm_info_when_no_changeset() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); fileDataBuilder.addLinesBuilder().setLine(1); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 1, "hash")).isNotPresent(); } @Test public void should_support_some_lines_not_having_scm_info() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(543L).setLine(1); fileDataBuilder.addLinesBuilder().setLine(2); fileDataBuilder.build(); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getAllChangesets()).hasSize(2); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().hasChangesetForLine(1)).isTrue(); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().hasChangesetForLine(2)).isFalse(); } @Test public void filter_out_entries_without_date() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(555L).setLine(1); fileDataBuilder.addLinesBuilder().setScmRevision("rev-1").setLine(2); fileDataBuilder.build(); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getAllChangesets()).hasSize(2); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getChangesetForLine(1).getRevision()).isEqualTo("rev"); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().hasChangesetForLine(2)).isFalse(); } @Test public void should_support_having_no_author() { DbFileSources.Data.Builder fileDataBuilder = DbFileSources.Data.newBuilder(); // gets filtered out fileDataBuilder.addLinesBuilder().setScmAuthor("John").setLine(1); fileDataBuilder.addLinesBuilder().setScmRevision("rev").setScmDate(555L).setLine(2); fileDataBuilder.build(); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getAllChangesets()).hasSize(2); assertThat(DbScmInfo.create(fileDataBuilder.getLinesList(), 2, "hash").get().getChangesetForLine(2).getAuthor()).isNull(); } private static void addLine(DbFileSources.Data.Builder dataBuilder, Integer line, String author, Long date, String revision) { dataBuilder.addLinesBuilder() .setLine(line) .setScmAuthor(author) .setScmDate(date) .setScmRevision(revision); } }
6,196
42.335664
136
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ReportScmInfoTest.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.scm; 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 ReportScmInfoTest { static final int FILE_REF = 1; @Test public void create_scm_info_with_some_changesets() { ScmInfo scmInfo = ReportScmInfo.create(ScannerReport.Changesets.newBuilder() .setComponentRef(FILE_REF) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build()) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("henry") .setDate(1234567810L) .setRevision("rev-2") .build()) .addChangesetIndexByLine(0) .addChangesetIndexByLine(1) .addChangesetIndexByLine(0) .addChangesetIndexByLine(0) .build()); assertThat(scmInfo.getAllChangesets()).hasSize(4); } @Test public void return_changeset_for_a_given_line() { ScmInfo scmInfo = ReportScmInfo.create(ScannerReport.Changesets.newBuilder() .setComponentRef(FILE_REF) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build()) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("henry") .setDate(1234567810L) .setRevision("rev-2") .build()) .addChangesetIndexByLine(0) .addChangesetIndexByLine(1) .addChangesetIndexByLine(1) .addChangesetIndexByLine(0) .build()); assertThat(scmInfo.getAllChangesets()).hasSize(4); Changeset changeset = scmInfo.getChangesetForLine(4); assertThat(changeset.getAuthor()).isEqualTo("john"); assertThat(changeset.getDate()).isEqualTo(123456789L); assertThat(changeset.getRevision()).isEqualTo("rev-1"); } @Test public void return_latest_changeset() { ScmInfo scmInfo = ReportScmInfo.create(ScannerReport.Changesets.newBuilder() .setComponentRef(FILE_REF) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build()) // Older changeset .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("henry") .setDate(1234567810L) .setRevision("rev-2") .build()) .addChangesetIndexByLine(0) .addChangesetIndexByLine(1) .addChangesetIndexByLine(0) .build()); Changeset latestChangeset = scmInfo.getLatestChangeset(); assertThat(latestChangeset.getAuthor()).isEqualTo("henry"); assertThat(latestChangeset.getDate()).isEqualTo(1234567810L); assertThat(latestChangeset.getRevision()).isEqualTo("rev-2"); } @Test public void fail_with_ISE_when_no_changeset() { assertThatThrownBy(() -> ReportScmInfo.create(ScannerReport.Changesets.newBuilder().build())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("ScmInfo cannot be empty"); } @Test public void fail_with_NPE_when_report_is_null() { assertThatThrownBy(() -> ReportScmInfo.create(null)) .isInstanceOf(NullPointerException.class); } @Test public void fail_with_ISE_when_changeset_has_no_revision() { assertThatThrownBy(() -> { ReportScmInfo.create(ScannerReport.Changesets.newBuilder() .setComponentRef(FILE_REF) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("john") .setDate(123456789L) .build()) .addChangesetIndexByLine(0) .build()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Changeset on line 1 must have a revision"); } @Test public void fail_with_ISE_when_changeset_has_no_date() { assertThatThrownBy(() -> { ReportScmInfo.create(ScannerReport.Changesets.newBuilder() .setComponentRef(FILE_REF) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor("john") .setRevision("rev-1") .build()) .addChangesetIndexByLine(0) .build()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Changeset on line 1 must have a date"); } }
5,282
33.083871
97
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoImplTest.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.scm; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ScmInfoImplTest { static final Changeset CHANGESET_1 = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build(); static final Changeset CHANGESET_2 = Changeset.newChangesetBuilder() .setAuthor("henry") .setDate(1234567810L) .setRevision("rev-2") .build(); @Test public void get_all_changesets() { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); assertThat(scmInfo.getAllChangesets()).contains(CHANGESET_1, CHANGESET_2, CHANGESET_1, CHANGESET_1); } @Test public void get_latest_changeset() { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); assertThat(scmInfo.getLatestChangeset()).isEqualTo(CHANGESET_2); } @Test public void get_changeset_for_given_line() { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); assertThat(scmInfo.getChangesetForLine(1)).isEqualTo(CHANGESET_1); assertThat(scmInfo.getChangesetForLine(2)).isEqualTo(CHANGESET_2); assertThat(scmInfo.getChangesetForLine(3)).isEqualTo(CHANGESET_1); assertThat(scmInfo.getChangesetForLine(4)).isEqualTo(CHANGESET_1); } @Test public void exists_for_given_line() { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); assertThat(scmInfo.hasChangesetForLine(1)).isTrue(); assertThat(scmInfo.hasChangesetForLine(5)).isFalse(); } @Test public void fail_with_ISE_on_empty_changeset() { assertThatThrownBy(() -> new ScmInfoImpl(new Changeset[0])) .isInstanceOf(IllegalStateException.class) .hasMessage("ScmInfo cannot be empty"); } @Test public void fail_with_IAE_when_line_is_smaller_than_one() { assertThatThrownBy(() -> { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); scmInfo.getChangesetForLine(0); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("There's no changeset on line 0"); } @Test public void fail_with_IAE_when_line_is_bigger_than_changetset_size() { assertThatThrownBy(() -> { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); scmInfo.getChangesetForLine(5); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("There's no changeset on line 5"); } @Test public void test_to_string() { ScmInfo scmInfo = createScmInfoWithTwoChangestOnFourLines(); assertThat(scmInfo).hasToString("ScmInfoImpl{" + "latestChangeset=Changeset{revision='rev-2', author='henry', date=1234567810}, " + "lineChangesets={" + "1=Changeset{revision='rev-1', author='john', date=123456789}, " + "2=Changeset{revision='rev-2', author='henry', date=1234567810}, " + "3=Changeset{revision='rev-1', author='john', date=123456789}, " + "4=Changeset{revision='rev-1', author='john', date=123456789}" + "}}"); } private static ScmInfo createScmInfoWithTwoChangestOnFourLines() { Changeset changeset1 = Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123456789L) .setRevision("rev-1") .build(); // Latest changeset Changeset changeset2 = Changeset.newChangesetBuilder() .setAuthor("henry") .setDate(1234567810L) .setRevision("rev-2") .build(); return new ScmInfoImpl(new Changeset[] {changeset1, changeset2, changeset1, changeset1}); } }
4,419
32.740458
104
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryImplTest.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.scm; 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.Collections; import java.util.Date; import java.util.EnumSet; 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.testfixtures.log.LogTester; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule; import org.sonar.ce.task.projectanalysis.batch.BatchReportReader; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.Component.Status; import org.sonar.ce.task.projectanalysis.component.Component.Type; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.FileStatuses; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import org.sonar.ce.task.projectanalysis.source.SourceLinesDiff; import org.sonar.db.protobuf.DbFileSources.Line; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.Changesets; 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.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.slf4j.event.Level.TRACE; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; @RunWith(DataProviderRunner.class) public class ScmInfoRepositoryImplTest { static final int FILE_REF = 1; static final FileAttributes attributes = new FileAttributes(false, "java", 3); static final Component FILE = builder(Component.Type.FILE, FILE_REF).setKey("FILE_KEY").setUuid("FILE_UUID").setFileAttributes(attributes).build(); static final Component FILE_SAME = builder(Component.Type.FILE, FILE_REF).setStatus(Status.SAME).setKey("FILE_KEY").setUuid("FILE_UUID").setFileAttributes(attributes).build(); static final long DATE_1 = 123456789L; static final long DATE_2 = 1234567810L; @Rule public LogTester logTester = new LogTester(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public AnalysisMetadataHolderRule analysisMetadata = new AnalysisMetadataHolderRule(); private final FileStatuses fileStatuses = mock(FileStatuses.class); private final SourceLinesDiff diff = mock(SourceLinesDiff.class); private final ScmInfoDbLoader dbLoader = mock(ScmInfoDbLoader.class); private final Date analysisDate = new Date(); private final ScmInfoRepositoryImpl underTest = new ScmInfoRepositoryImpl(reportReader, analysisMetadata, dbLoader, diff, fileStatuses); @Before public void setUp() { logTester.setLevel(TRACE); analysisMetadata.setAnalysisDate(analysisDate); } @Test public void return_empty_if_component_is_not_file() { Component c = mock(Component.class); when(c.getType()).thenReturn(Type.DIRECTORY); assertThat(underTest.getScmInfo(c)).isEmpty(); } @Test public void load_scm_info_from_cache_when_already_loaded() { addChangesetInReport("john", DATE_1, "rev-1"); ScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertThat(logTester.logs(TRACE)).hasSize(1); logTester.clear(); underTest.getScmInfo(FILE); assertThat(logTester.logs(TRACE)).isEmpty(); verifyNoInteractions(dbLoader); verifyNoInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void read_from_report() { addChangesetInReport("john", DATE_1, "rev-1"); ScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); Changeset changeset = scmInfo.getChangesetForLine(1); assertThat(changeset.getAuthor()).isEqualTo("john"); assertThat(changeset.getDate()).isEqualTo(DATE_1); assertThat(changeset.getRevision()).isEqualTo("rev-1"); assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from report for file 'FILE_KEY'"); verifyNoInteractions(dbLoader); verifyNoInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void read_from_DB_if_no_report_and_file_unchanged() { createDbScmInfoWithOneLine(); when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true); // should clear revision and author ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertChangeset(scmInfo.getChangesetForLine(1), null, null, 10L); verify(fileStatuses).isUnchanged(FILE_SAME); verify(dbLoader).getScmInfo(FILE_SAME); verifyNoMoreInteractions(dbLoader); verifyNoMoreInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void read_from_DB_with_missing_lines_if_no_report_and_file_unchanged() { createDbScmInfoWithMissingLine(); when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true); // should clear revision and author ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get(); assertThat(scmInfo.getAllChangesets()).hasSize(2); assertChangeset(scmInfo.getChangesetForLine(1), null, null, 10L); assertThat(scmInfo.hasChangesetForLine(2)).isFalse(); verify(fileStatuses).isUnchanged(FILE_SAME); verify(dbLoader).getScmInfo(FILE_SAME); verifyNoMoreInteractions(dbLoader); verifyNoMoreInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void read_from_DB_if_no_report_and_file_unchanged_and_copyFromPrevious_is_true() { createDbScmInfoWithOneLine(); when(fileStatuses.isUnchanged(FILE_SAME)).thenReturn(true); addFileSourceInReport(1); addCopyFromPrevious(); ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get(); assertThat(scmInfo.getAllChangesets()).hasSize(1); assertChangeset(scmInfo.getChangesetForLine(1), "rev1", "author1", 10L); verify(fileStatuses).isUnchanged(FILE_SAME); verify(dbLoader).getScmInfo(FILE_SAME); verifyNoMoreInteractions(dbLoader); verifyNoMoreInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void generate_scm_info_when_nothing_in_report_nor_db() { when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.empty()); ScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(3); for (int i = 1; i <= 3; i++) { assertChangeset(scmInfo.getChangesetForLine(i), null, null, analysisDate.getTime()); } verify(dbLoader).getScmInfo(FILE); verifyNoMoreInteractions(dbLoader); verifyNoInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void generate_scm_info_when_nothing_in_db_and_report_is_has_no_changesets() { when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.empty()); addFileSourceInReport(3); ScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(3); for (int i = 1; i <= 3; i++) { assertChangeset(scmInfo.getChangesetForLine(i), null, null, analysisDate.getTime()); } verify(dbLoader).getScmInfo(FILE); verifyNoMoreInteractions(dbLoader); verifyNoInteractions(fileStatuses); verifyNoInteractions(diff); } @Test public void generate_scm_info_for_new_and_changed_lines_when_report_is_empty() { createDbScmInfoWithOneLine(); when(diff.computeMatchingLines(FILE)).thenReturn(new int[] {1, 0, 0}); addFileSourceInReport(3); ScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(3); assertChangeset(scmInfo.getChangesetForLine(1), null, null, 10L); assertChangeset(scmInfo.getChangesetForLine(2), null, null, analysisDate.getTime()); assertChangeset(scmInfo.getChangesetForLine(3), null, null, analysisDate.getTime()); verify(dbLoader).getScmInfo(FILE); verify(diff).computeMatchingLines(FILE); verifyNoMoreInteractions(dbLoader); verifyNoMoreInteractions(diff); } @Test public void generate_scm_info_for_db_changesets_without_date_when_report_is_empty() { // changeset for line 1 will have no date, so won't be loaded createDbScmInfoWithOneLineWithoutDate(); when(diff.computeMatchingLines(FILE)).thenReturn(new int[] {1, 0, 0}); addFileSourceInReport(3); ScmInfo scmInfo = underTest.getScmInfo(FILE).get(); assertThat(scmInfo.getAllChangesets()).hasSize(3); // a date will be generated for line 1 assertChangeset(scmInfo.getChangesetForLine(1), null, null, analysisDate.getTime()); assertChangeset(scmInfo.getChangesetForLine(2), null, null, analysisDate.getTime()); assertChangeset(scmInfo.getChangesetForLine(3), null, null, analysisDate.getTime()); } @Test public void fail_with_NPE_when_component_is_null() { assertThatThrownBy(() -> underTest.getScmInfo(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Component cannot be null"); } @Test @UseDataProvider("allTypeComponentButFile") public void do_not_query_db_nor_report_if_component_type_is_not_FILE(Component component) { BatchReportReader batchReportReader = mock(BatchReportReader.class); ScmInfoRepositoryImpl underTest = new ScmInfoRepositoryImpl(batchReportReader, analysisMetadata, dbLoader, diff, fileStatuses); assertThat(underTest.getScmInfo(component)).isEmpty(); verifyNoInteractions(batchReportReader, dbLoader); } @DataProvider public static Object[][] allTypeComponentButFile() { Object[][] res = new Object[Component.Type.values().length - 1][1]; int i = 0; for (Component.Type type : EnumSet.complementOf(EnumSet.of(Component.Type.FILE))) { if (type.isReportType()) { res[i][0] = ReportComponent.builder(type, i).build(); } else { res[i][0] = ViewsComponent.builder(type, i).build(); } i++; } return res; } private void assertChangeset(Changeset changeset, String revision, String author, long date) { assertThat(changeset.getAuthor()).isEqualTo(author); assertThat(changeset.getRevision()).isEqualTo(revision); assertThat(changeset.getDate()).isEqualTo(date); } private void addChangesetInReport(String author, Long date, String revision) { addChangesetInReport(author, date, revision, false); } private void addChangesetInReport(String author, Long date, String revision, boolean copyFromPrevious) { reportReader.putChangesets(ScannerReport.Changesets.newBuilder() .setComponentRef(FILE_REF) .setCopyFromPrevious(copyFromPrevious) .addChangeset(ScannerReport.Changesets.Changeset.newBuilder() .setAuthor(author) .setDate(date) .setRevision(revision) .build()) .addChangesetIndexByLine(0) .build()); } private void addCopyFromPrevious() { reportReader.putChangesets(Changesets.newBuilder().setComponentRef(FILE_REF).setCopyFromPrevious(true).build()); } private DbScmInfo createDbScmInfoWithOneLine() { Line line1 = Line.newBuilder().setLine(1) .setScmRevision("rev1") .setScmAuthor("author1") .setScmDate(10L) .build(); DbScmInfo scmInfo = DbScmInfo.create(Collections.singletonList(line1), 1, "hash1").get(); when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.of(scmInfo)); return scmInfo; } private DbScmInfo createDbScmInfoWithOneLineWithoutDate() { Line line1 = Line.newBuilder().setLine(1) .setScmRevision("rev1") .setScmAuthor("author1") .build(); Line line2 = Line.newBuilder().setLine(2) .setScmRevision("rev1") .setScmAuthor("author1") .setScmDate(10L) .build(); DbScmInfo scmInfo = DbScmInfo.create(List.of(line1, line2), 2, "hash1").get(); when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.of(scmInfo)); return scmInfo; } private DbScmInfo createDbScmInfoWithMissingLine() { Line line1 = Line.newBuilder().setLine(1) .setScmRevision("rev1") .setScmAuthor("author1") .setScmDate(10L) .build(); DbScmInfo scmInfo = DbScmInfo.create(Collections.singletonList(line1), 2, "hash1").get(); when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.of(scmInfo)); return scmInfo; } private void addFileSourceInReport(int lineCount) { reportReader.putFileSourceLines(FILE_REF, generateLines(lineCount)); reportReader.putComponent(ScannerReport.Component.newBuilder() .setRef(FILE_REF) .setLines(lineCount) .build()); } private static List<String> generateLines(int lineCount) { ImmutableList.Builder<String> builder = ImmutableList.builder(); for (int i = 0; i < lineCount; i++) { builder.add("line " + i); } return builder.build(); } }
14,142
37.432065
177
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/scm/ScmInfoRepositoryRule.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.scm; import java.util.HashMap; import java.util.Map; import java.util.Optional; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import static com.google.common.base.Preconditions.checkNotNull; public class ScmInfoRepositoryRule extends ExternalResource implements ScmInfoRepository { private Map<Integer, ScmInfo> scmInfoByFileRef = new HashMap<>(); @Override protected void after() { scmInfoByFileRef.clear(); } @Override public Optional<ScmInfo> getScmInfo(Component component) { checkNotNull(component, "Component cannot be bull"); ScmInfo scmInfo = scmInfoByFileRef.get(component.getReportAttributes().getRef()); return Optional.ofNullable(scmInfo); } public ScmInfoRepositoryRule setScmInfo(int fileRef, Changeset... changesetList) { scmInfoByFileRef.put(fileRef, new ScmInfoImpl(changesetList)); return this; } public ScmInfoRepositoryRule setScmInfo(int fileRef, Map<Integer, Changeset> changesets) { scmInfoByFileRef.put(fileRef, new ScmInfoImpl(changesets.values().toArray(new Changeset[0]))); return this; } }
2,022
35.125
98
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataComputerTest.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.source; import java.util.Iterator; import java.util.List; import java.util.Random; import java.util.function.Consumer; import java.util.stream.IntStream; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.scm.Changeset; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepositoryImpl.LineHashesComputer; import org.sonar.ce.task.projectanalysis.source.linereader.LineReader; import org.sonar.core.hash.SourceHashComputer; import org.sonar.core.util.CloseableIterator; import org.sonar.db.protobuf.DbFileSources; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class FileSourceDataComputerTest { private static final Component FILE = ReportComponent.builder(Component.Type.FILE, 1).build(); private SourceLinesRepository sourceLinesRepository = mock(SourceLinesRepository.class); private LineHashesComputer lineHashesComputer = mock(LineHashesComputer.class); private SourceLineReadersFactory sourceLineReadersFactory = mock(SourceLineReadersFactory.class); private SourceLinesHashRepository sourceLinesHashRepository = mock(SourceLinesHashRepository.class); private FileSourceDataComputer underTest = new FileSourceDataComputer(sourceLinesRepository, sourceLineReadersFactory, sourceLinesHashRepository); private FileSourceDataWarnings fileSourceDataWarnings = mock(FileSourceDataWarnings.class); private SourceLineReadersFactory.LineReaders lineReaders = mock(SourceLineReadersFactory.LineReaders.class); @Before public void before() { when(sourceLinesHashRepository.getLineHashesComputerToPersist(FILE)).thenReturn(lineHashesComputer); when(sourceLineReadersFactory.getLineReaders(FILE)).thenReturn(mock(SourceLineReadersFactory.LineReaders.class)); } @Test public void compute_calls_read_for_each_line_and_passe_read_error_to_fileSourceDataWarnings() { int lineCount = 1 + new Random().nextInt(10); List<String> lines = IntStream.range(0, lineCount).mapToObj(i -> "line" + i).collect(toList()); when(sourceLinesRepository.readLines(FILE)).thenReturn(CloseableIterator.from(lines.iterator())); when(sourceLineReadersFactory.getLineReaders(FILE)).thenReturn(lineReaders); when(sourceLinesHashRepository.getLineHashesComputerToPersist(FILE)).thenReturn(lineHashesComputer); // mock an implementation that will call the ReadErrorConsumer in order to verify that the provided consumer is // doing what we expect: pass readError to fileSourceDataWarnings int randomStartPoint = new Random().nextInt(500); doAnswer(new Answer() { int i = randomStartPoint; @Override public Object answer(InvocationOnMock invocation) { Consumer<LineReader.ReadError> readErrorConsumer = invocation.getArgument(1); readErrorConsumer.accept(new LineReader.ReadError(LineReader.Data.SYMBOLS, i++)); return null; } }).when(lineReaders).read(any(), any()); underTest.compute(FILE, fileSourceDataWarnings); ArgumentCaptor<DbFileSources.Line.Builder> lineBuilderCaptor = ArgumentCaptor.forClass(DbFileSources.Line.Builder.class); verify(lineReaders, times(lineCount)).read(lineBuilderCaptor.capture(), any()); assertThat(lineBuilderCaptor.getAllValues()) .extracting(DbFileSources.Line.Builder::getSource) .containsOnlyElementsOf(lines); assertThat(lineBuilderCaptor.getAllValues()) .extracting(DbFileSources.Line.Builder::getLine) .containsExactly(IntStream.range(1, lineCount + 1).boxed().toArray(Integer[]::new)); ArgumentCaptor<LineReader.ReadError> readErrorCaptor = ArgumentCaptor.forClass(LineReader.ReadError.class); verify(fileSourceDataWarnings, times(lineCount)).addWarning(same(FILE), readErrorCaptor.capture()); assertThat(readErrorCaptor.getAllValues()) .extracting(LineReader.ReadError::line) .containsExactly(IntStream.range(randomStartPoint, randomStartPoint + lineCount).boxed().toArray(Integer[]::new)); } @Test public void compute_builds_data_object_from_lines() { int lineCount = 1 + new Random().nextInt(10); int randomStartPoint = new Random().nextInt(500); List<String> lines = IntStream.range(0, lineCount).mapToObj(i -> "line" + i).collect(toList()); List<String> expectedLineHashes = IntStream.range(0, 1 + new Random().nextInt(12)).mapToObj(i -> "str_" + i).collect(toList()); Changeset expectedChangeset = Changeset.newChangesetBuilder().setDate((long) new Random().nextInt(9_999)).build(); String expectedSrcHash = computeSrcHash(lines); CloseableIterator<String> lineIterator = spy(CloseableIterator.from(lines.iterator())); DbFileSources.Data.Builder expectedLineDataBuilder = DbFileSources.Data.newBuilder(); for (int i = 0; i < lines.size(); i++) { expectedLineDataBuilder.addLinesBuilder() .setSource(lines.get(i)) .setLine(i + 1) // scmAuthor will be set with specific value by our mock implementation of LinesReaders.read() .setScmAuthor("reader_called_" + (randomStartPoint + i)); } when(sourceLinesRepository.readLines(FILE)).thenReturn(lineIterator); when(sourceLineReadersFactory.getLineReaders(FILE)).thenReturn(lineReaders); when(sourceLinesHashRepository.getLineHashesComputerToPersist(FILE)).thenReturn(lineHashesComputer); when(lineHashesComputer.getResult()).thenReturn(expectedLineHashes); when(lineReaders.getLatestChangeWithRevision()).thenReturn(expectedChangeset); // mocked implementation of LineReader.read to ensure changes done by it to the lineBuilder argument actually end // up in the FileSourceDataComputer.Data object returned doAnswer(new Answer() { int i = 0; @Override public Object answer(InvocationOnMock invocation) { DbFileSources.Line.Builder lineBuilder = invocation.getArgument(0); lineBuilder.setScmAuthor("reader_called_" + (randomStartPoint + i++)); return null; } }).when(lineReaders).read(any(), any()); FileSourceDataComputer.Data data = underTest.compute(FILE, fileSourceDataWarnings); assertThat(data.getLineHashes()).isEqualTo(expectedLineHashes); assertThat(data.getSrcHash()).isEqualTo(expectedSrcHash); assertThat(data.getLatestChangeWithRevision()).isSameAs(expectedChangeset); assertThat(data.getLineData()).isEqualTo(expectedLineDataBuilder.build()); verify(lineIterator).close(); verify(lineReaders).close(); } private static String computeSrcHash(List<String> lines) { SourceHashComputer computer = new SourceHashComputer(); Iterator<String> iterator = lines.iterator(); while (iterator.hasNext()) { computer.addLine(iterator.next(), iterator.hasNext()); } return computer.getHash(); } }
8,279
49.181818
148
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/FileSourceDataWarningsTest.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.source; 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.Random; import java.util.stream.Collectors; import java.util.stream.IntStream; import org.junit.Test; import org.junit.runner.RunWith; import org.sonar.api.utils.System2; import org.sonar.ce.task.log.CeTaskMessages; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.source.linereader.LineReader; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; 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.source.linereader.LineReader.Data.HIGHLIGHTING; import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.SYMBOLS; @RunWith(DataProviderRunner.class) public class FileSourceDataWarningsTest { private CeTaskMessages taskMessages = mock(CeTaskMessages.class); private System2 system2 = mock(System2.class); private Random random = new Random(); private int line = 1 + new Random().nextInt(200); private long timeStamp = 9_887L + new Random().nextInt(300); private String path = randomAlphabetic(50); private FileSourceDataWarnings underTest = new FileSourceDataWarnings(taskMessages, system2); @Test public void addWarning_fails_with_NPE_if_file_is_null() { LineReader.ReadError readError = new LineReader.ReadError(HIGHLIGHTING, 2); assertThatThrownBy(() -> underTest.addWarning(null, readError)) .isInstanceOf(NullPointerException.class) .hasMessage("file can't be null"); } @Test public void addWarning_fails_with_NPE_if_readError_is_null() { Component component = mock(Component.class); assertThatThrownBy(() -> underTest.addWarning(component, null)) .isInstanceOf(NullPointerException.class) .hasMessage("readError can't be null"); } @Test public void addWarnings_fails_with_ISE_if_called_after_commitWarnings() { underTest.commitWarnings(); assertThatThrownBy(() -> underTest.addWarning(null /*doesn't matter*/, null /*doesn't matter*/)) .isInstanceOf(IllegalStateException.class) .hasMessage("warnings already commit"); } @Test public void commitWarnings_fails_with_ISE_if_called_after_commitWarnings() { underTest.commitWarnings(); assertThatThrownBy(() -> underTest.commitWarnings()) .isInstanceOf(IllegalStateException.class) .hasMessage("warnings already commit"); } @Test public void create_highlighting_warning_when_one_file_HIGHLIGHT_read_error() { ReportComponent file = ReportComponent.builder(Component.Type.FILE, 1) .setUuid("uuid") .setName(path) .build(); LineReader.ReadError readError = new LineReader.ReadError(HIGHLIGHTING, line); when(system2.now()).thenReturn(timeStamp); underTest.addWarning(file, readError); verifyNoInteractions(taskMessages); underTest.commitWarnings(); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message("Inconsistent highlighting data detected on file '" + path + "'. " + "File source may have been modified while analysis was running.", timeStamp)); } @Test public void create_highlighting_warning_when_any_number_of_read_error_for_one_file() { ReportComponent file = ReportComponent.builder(Component.Type.FILE, 1) .setUuid("uuid") .setName(path) .build(); LineReader.ReadError[] readErrors = IntStream.range(0, 1 + random.nextInt(10)) .mapToObj(i -> new LineReader.ReadError(HIGHLIGHTING, line + i)) .toArray(LineReader.ReadError[]::new); when(system2.now()).thenReturn(timeStamp); Arrays.stream(readErrors).forEach(readError -> underTest.addWarning(file, readError)); verifyNoInteractions(taskMessages); underTest.commitWarnings(); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message("Inconsistent highlighting data detected on file '" + path + "'. " + "File source may have been modified while analysis was running.", timeStamp)); } @Test public void create_highlighting_warning_when_any_number_of_read_error_for_less_than_5_files() { int fileCount = 2 + random.nextInt(3); Component[] files = IntStream.range(0, fileCount) .mapToObj(i -> ReportComponent.builder(Component.Type.FILE, i) .setUuid("uuid_" + i) .setName(path + "_" + i) .build()) .toArray(Component[]::new); when(system2.now()).thenReturn(timeStamp); Arrays.stream(files).forEach(file -> IntStream.range(0, 1 + random.nextInt(10)) .forEach(i -> underTest.addWarning(file, new LineReader.ReadError(HIGHLIGHTING, line + i)))); verifyNoInteractions(taskMessages); underTest.commitWarnings(); String expectedMessage = "Inconsistent highlighting data detected on some files (" + fileCount + " in total). " + "File source may have been modified while analysis was running." + Arrays.stream(files).map(Component::getName).collect(Collectors.joining("\n ° ", "\n ° ", "")); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message(expectedMessage, timeStamp)); } @Test public void create_highlighting_warning_when_any_number_of_read_error_for_more_than_5_files_only_the_5_first_by_ref() { int fileCount = 6 + random.nextInt(4); Component[] files = IntStream.range(0, fileCount) .mapToObj(i -> ReportComponent.builder(Component.Type.FILE, i) .setUuid("uuid_" + i) .setName(path + "_" + i) .build()) .toArray(Component[]::new); when(system2.now()).thenReturn(timeStamp); Arrays.stream(files).forEach(file -> IntStream.range(0, 1 + random.nextInt(10)) .forEach(i -> underTest.addWarning(file, new LineReader.ReadError(HIGHLIGHTING, line + i)))); verifyNoInteractions(taskMessages); underTest.commitWarnings(); String expectedMessage = "Inconsistent highlighting data detected on some files (" + fileCount + " in total). " + "File source may have been modified while analysis was running." + Arrays.stream(files).limit(5).map(Component::getName).collect(Collectors.joining("\n ° ", "\n ° ", "")); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message(expectedMessage, timeStamp)); } @Test public void create_symbol_warning_when_one_file_HIGHLIGHT_read_error() { ReportComponent file = ReportComponent.builder(Component.Type.FILE, 1) .setUuid("uuid") .setName(path) .build(); LineReader.ReadError readError = new LineReader.ReadError(SYMBOLS, line); when(system2.now()).thenReturn(timeStamp); underTest.addWarning(file, readError); verifyNoInteractions(taskMessages); underTest.commitWarnings(); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message("Inconsistent symbol data detected on file '" + path + "'. " + "File source may have been modified while analysis was running.", timeStamp)); } @Test public void create_symbol_warning_when_any_number_of_read_error_for_one_file() { ReportComponent file = ReportComponent.builder(Component.Type.FILE, 1) .setUuid("uuid") .setName(path) .build(); LineReader.ReadError[] readErrors = IntStream.range(0, 1 + random.nextInt(10)) .mapToObj(i -> new LineReader.ReadError(SYMBOLS, line + i)) .toArray(LineReader.ReadError[]::new); when(system2.now()).thenReturn(timeStamp); Arrays.stream(readErrors).forEach(readError -> underTest.addWarning(file, readError)); verifyNoInteractions(taskMessages); underTest.commitWarnings(); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message("Inconsistent symbol data detected on file '" + path + "'. " + "File source may have been modified while analysis was running.", timeStamp)); } @Test public void create_symbol_warning_when_any_number_of_read_error_for_less_than_5_files() { int fileCount = 2 + random.nextInt(3); Component[] files = IntStream.range(0, fileCount) .mapToObj(i -> ReportComponent.builder(Component.Type.FILE, i) .setUuid("uuid_" + i) .setName(path + "_" + i) .build()) .toArray(Component[]::new); when(system2.now()).thenReturn(timeStamp); Arrays.stream(files).forEach(file -> IntStream.range(0, 1 + random.nextInt(10)) .forEach(i -> underTest.addWarning(file, new LineReader.ReadError(SYMBOLS, line + i)))); verifyNoInteractions(taskMessages); underTest.commitWarnings(); String expectedMessage = "Inconsistent symbol data detected on some files (" + fileCount + " in total). " + "File source may have been modified while analysis was running." + Arrays.stream(files).map(Component::getName).collect(Collectors.joining("\n ° ", "\n ° ", "")); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message(expectedMessage, timeStamp)); } @Test public void create_symbol_warning_when_any_number_of_read_error_for_more_than_5_files_only_the_5_first_by_ref() { int fileCount = 6 + random.nextInt(4); Component[] files = IntStream.range(0, fileCount) .mapToObj(i -> ReportComponent.builder(Component.Type.FILE, i) .setUuid("uuid_" + i) .setName(path + "_" + i) .build()) .toArray(Component[]::new); when(system2.now()).thenReturn(timeStamp); Arrays.stream(files).forEach(file -> IntStream.range(0, 1 + random.nextInt(10)) .forEach(i -> underTest.addWarning(file, new LineReader.ReadError(SYMBOLS, line + i)))); verifyNoInteractions(taskMessages); underTest.commitWarnings(); String expectedMessage = "Inconsistent symbol data detected on some files (" + fileCount + " in total). " + "File source may have been modified while analysis was running." + Arrays.stream(files).limit(5).map(Component::getName).collect(Collectors.joining("\n ° ", "\n ° ", "")); verify(taskMessages, times(1)) .add(new CeTaskMessages.Message(expectedMessage, timeStamp)); } @Test @UseDataProvider("anyDataButHighlightAndSymbols") public void creates_no_warning_when_read_error_for_anything_but_highlighting_and_symbols(LineReader.Data data) { ReportComponent file = ReportComponent.builder(Component.Type.FILE, 1) .setUuid("uuid") .setName(path) .build(); LineReader.ReadError readError = new LineReader.ReadError(data, line); when(system2.now()).thenReturn(timeStamp); underTest.addWarning(file, readError); verifyNoInteractions(taskMessages); underTest.commitWarnings(); verifyNoInteractions(taskMessages); } @DataProvider public static Object[][] anyDataButHighlightAndSymbols() { return Arrays.stream(LineReader.Data.values()) .filter(t -> t != HIGHLIGHTING && t != SYMBOLS) .map(t -> new Object[] {t}) .toArray(Object[][]::new); } }
12,188
38.833333
121
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/LastCommitVisitorTest.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.source; import com.google.common.collect.Lists; 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.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.ViewsComponent; import org.sonar.ce.task.projectanalysis.component.VisitorsCrawler; 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.scm.Changeset; import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepositoryRule; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.LAST_COMMIT_DATE_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.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 LastCommitVisitorTest { private static final int PROJECT_REF = 1; private static final int DIR_REF = 2; private static final int FILE_1_REF = 1_111; private static final int FILE_2_REF = 1_112; private static final int FILE_3_REF = 1_121; private static final int DIR_1_REF = 3; private static final int DIR_2_REF = 4; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.LAST_COMMIT_DATE); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public ScmInfoRepositoryRule scmInfoRepository = new ScmInfoRepositoryRule(); @Test public void aggregate_date_of_last_commit_to_directories_and_project() { final long FILE_1_DATE = 1_100_000_000_000L; // FILE_2 is the most recent file in DIR_1 final long FILE_2_DATE = 1_200_000_000_000L; // FILE_3 is the most recent file in the project final long FILE_3_DATE = 1_300_000_000_000L; // simulate the output of visitFile() LastCommitVisitor visitor = new LastCommitVisitor(metricRepository, measureRepository, scmInfoRepository) { @Override public void visitFile(Component file, Path<LastCommit> path) { long fileDate; switch (file.getReportAttributes().getRef()) { case FILE_1_REF: fileDate = FILE_1_DATE; break; case FILE_2_REF: fileDate = FILE_2_DATE; break; case FILE_3_REF: fileDate = FILE_3_DATE; break; default: throw new IllegalArgumentException(); } path.parent().addDate(fileDate); } }; // project with 1 module, 2 directories and 3 files ReportComponent project = ReportComponent.builder(PROJECT, PROJECT_REF) .addChildren( ReportComponent.builder(DIRECTORY, DIR_REF) .addChildren( ReportComponent.builder(DIRECTORY, DIR_1_REF) .addChildren( createFileComponent(FILE_1_REF), createFileComponent(FILE_2_REF)) .build(), ReportComponent.builder(DIRECTORY, DIR_2_REF) .addChildren( createFileComponent(FILE_3_REF)) .build()) .build()) .build(); treeRootHolder.setRoot(project); VisitorsCrawler underTest = new VisitorsCrawler(Lists.newArrayList(visitor)); underTest.visit(project); assertDate(DIR_1_REF, FILE_2_DATE); assertDate(DIR_2_REF, FILE_3_DATE); assertDate(DIR_REF, FILE_3_DATE); // project assertDate(PROJECT_REF, FILE_3_DATE); } @Test public void aggregate_date_of_last_commit_to_views() { final int VIEW_REF = 1; final int SUBVIEW_1_REF = 2; final int SUBVIEW_2_REF = 3; final int SUBVIEW_3_REF = 4; final int PROJECT_1_REF = 5; final int PROJECT_2_REF = 6; final int PROJECT_3_REF = 7; final long PROJECT_1_DATE = 1_500_000_000_000L; // the second project has the most recent commit date final long PROJECT_2_DATE = 1_700_000_000_000L; final long PROJECT_3_DATE = 1_600_000_000_000L; // view with 3 nested sub-views and 3 projects ViewsComponent view = ViewsComponent.builder(VIEW, VIEW_REF) .addChildren( builder(SUBVIEW, SUBVIEW_1_REF) .addChildren( builder(SUBVIEW, SUBVIEW_2_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_1_REF).build(), builder(PROJECT_VIEW, PROJECT_2_REF).build()) .build(), builder(SUBVIEW, SUBVIEW_3_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_3_REF).build()) .build()) .build()) .build(); treeRootHolder.setRoot(view); measureRepository.addRawMeasure(PROJECT_1_REF, LAST_COMMIT_DATE_KEY, newMeasureBuilder().create(PROJECT_1_DATE)); measureRepository.addRawMeasure(PROJECT_2_REF, LAST_COMMIT_DATE_KEY, newMeasureBuilder().create(PROJECT_2_DATE)); measureRepository.addRawMeasure(PROJECT_3_REF, LAST_COMMIT_DATE_KEY, newMeasureBuilder().create(PROJECT_3_DATE)); VisitorsCrawler underTest = new VisitorsCrawler(Lists.newArrayList(new LastCommitVisitor(metricRepository, measureRepository, scmInfoRepository))); underTest.visit(view); // second level of sub-views assertDate(SUBVIEW_2_REF, PROJECT_2_DATE); assertDate(SUBVIEW_3_REF, PROJECT_3_DATE); // first level of sub-views assertDate(SUBVIEW_1_REF, PROJECT_2_DATE); // view assertDate(VIEW_REF, PROJECT_2_DATE); } @Test public void compute_date_of_file_from_scm_repo() { VisitorsCrawler underTest = new VisitorsCrawler(Lists.newArrayList(new LastCommitVisitor(metricRepository, measureRepository, scmInfoRepository))); scmInfoRepository.setScmInfo(FILE_1_REF, Changeset.newChangesetBuilder() .setAuthor("john") .setDate(1_500_000_000_000L) .setRevision("rev-1") .build(), Changeset.newChangesetBuilder() .setAuthor("tom") // this is the most recent change .setDate(1_600_000_000_000L) .setRevision("rev-2") .build(), Changeset.newChangesetBuilder() .setAuthor("john") .setDate(1_500_000_000_000L) .setRevision("rev-1") .build()); ReportComponent file = createFileComponent(FILE_1_REF); treeRootHolder.setRoot(file); underTest.visit(file); assertDate(FILE_1_REF, 1_600_000_000_000L); } @Test public void date_is_not_computed_on_file_if_blame_is_not_in_scm_repo() { VisitorsCrawler underTest = new VisitorsCrawler(Lists.newArrayList(new LastCommitVisitor(metricRepository, measureRepository, scmInfoRepository))); ReportComponent file = createFileComponent(FILE_1_REF); treeRootHolder.setRoot(file); underTest.visit(file); Optional<Measure> measure = measureRepository.getAddedRawMeasure(FILE_1_REF, LAST_COMMIT_DATE_KEY); assertThat(measure).isEmpty(); } private void assertDate(int componentRef, long expectedDate) { Optional<Measure> measure = measureRepository.getAddedRawMeasure(componentRef, LAST_COMMIT_DATE_KEY); assertThat(measure).isPresent(); assertThat(measure.get().getLongValue()).isEqualTo(expectedDate); } private ReportComponent createFileComponent(int fileRef) { return ReportComponent.builder(FILE, fileRef).setFileAttributes(new FileAttributes(false, "js", 1)).build(); } }
9,175
38.213675
151
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/LineReadersImplTest.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.source; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Random; import java.util.function.Consumer; import java.util.stream.IntStream; import org.junit.Test; import org.sonar.ce.task.projectanalysis.scm.Changeset; import org.sonar.ce.task.projectanalysis.source.linereader.LineReader; import org.sonar.ce.task.projectanalysis.source.linereader.LineReader.ReadError; import org.sonar.ce.task.projectanalysis.source.linereader.ScmLineReader; import org.sonar.core.util.CloseableIterator; import org.sonar.db.protobuf.DbFileSources; import static java.util.Arrays.asList; import static java.util.Arrays.stream; import static java.util.stream.Collectors.toList; 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.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class LineReadersImplTest { private static final Consumer<ReadError> NOOP_READ_ERROR_CONSUMER = readError -> { }; @Test public void close_closes_all_closeables() { LineReader r1 = mock(LineReader.class); LineReader r2 = mock(LineReader.class); CloseableIterator<Object> c1 = newCloseableIteratorMock(); CloseableIterator<Object> c2 = newCloseableIteratorMock(); SourceLineReadersFactory.LineReaders lineReaders = new SourceLineReadersFactory.LineReadersImpl(asList(r1, r2), null, asList(c1, c2)); lineReaders.close(); verify(c1).close(); verify(c2).close(); verifyNoMoreInteractions(c1, c2); verifyNoInteractions(r1, r2); } @Test public void read_calls_all_readers() { LineReader r1 = mock(LineReader.class); LineReader r2 = mock(LineReader.class); CloseableIterator<Object> c1 = newCloseableIteratorMock(); CloseableIterator<Object> c2 = newCloseableIteratorMock(); SourceLineReadersFactory.LineReadersImpl lineReaders = new SourceLineReadersFactory.LineReadersImpl(asList(r1, r2), null, asList(c1, c2)); DbFileSources.Line.Builder builder = DbFileSources.Line.newBuilder(); lineReaders.read(builder, NOOP_READ_ERROR_CONSUMER); verify(r1).read(builder); verify(r2).read(builder); verifyNoMoreInteractions(r1, r2); verifyNoInteractions(c1, c2); } @Test public void read_calls_ReaderError_consumer_with_each_read_error_returned_by_all_readers() { int readErrorCount = 2 + 2 * new Random().nextInt(10); int halfCount = readErrorCount / 2; ReadError[] expectedReadErrors = IntStream.range(0, readErrorCount) .mapToObj(i -> new ReadError(LineReader.Data.SYMBOLS, i)) .toArray(ReadError[]::new); LineReader[] lineReaders = IntStream.range(0, halfCount) .mapToObj(i -> { LineReader lineReader = mock(LineReader.class); when(lineReader.read(any())) .thenReturn(Optional.of(expectedReadErrors[i])) .thenReturn(Optional.of(expectedReadErrors[i + halfCount])) .thenReturn(Optional.empty()); return lineReader; }) .toArray(LineReader[]::new); DbFileSources.Line.Builder builder = DbFileSources.Line.newBuilder(); SourceLineReadersFactory.LineReadersImpl underTest = new SourceLineReadersFactory.LineReadersImpl( stream(lineReaders).collect(toList()), null, Collections.emptyList()); List<ReadError> readErrors = new ArrayList<>(); // calls first mocked result of each Reader mock => we get first half read errors underTest.read(builder, readErrors::add); assertThat(readErrors).contains(stream(expectedReadErrors).limit(halfCount).toArray(ReadError[]::new)); // calls first mocked result of each Reader mock => we get second half read errors readErrors.clear(); underTest.read(builder, readErrors::add); assertThat(readErrors).contains(stream(expectedReadErrors).skip(halfCount).toArray(ReadError[]::new)); // calls third mocked result of each Reader mock (empty) => consumer is never called => empty list readErrors.clear(); underTest.read(builder, readErrors::add); assertThat(readErrors).isEmpty(); } @Test public void getLatestChangeWithRevision_delegates_to_ScmLineReader_if_non_null() { ScmLineReader scmLineReader = mock(ScmLineReader.class); Changeset changeset = Changeset.newChangesetBuilder().setDate(0L).build(); when(scmLineReader.getLatestChangeWithRevision()).thenReturn(changeset); SourceLineReadersFactory.LineReaders lineReaders = new SourceLineReadersFactory.LineReadersImpl(Collections.emptyList(), scmLineReader, Collections.emptyList()); assertThat(lineReaders.getLatestChangeWithRevision()).isEqualTo(changeset); verify(scmLineReader).getLatestChangeWithRevision(); verifyNoMoreInteractions(scmLineReader); } @Test public void getLatestChangeWithRevision_returns_null_if_ScmLineReader_is_null() { SourceLineReadersFactory.LineReaders lineReaders = new SourceLineReadersFactory.LineReadersImpl(Collections.emptyList(), null, Collections.emptyList()); assertThat(lineReaders.getLatestChangeWithRevision()).isNull(); } @SuppressWarnings("unchecked") private static CloseableIterator<Object> newCloseableIteratorMock() { return (CloseableIterator<Object>)mock(CloseableIterator.class); } }
6,314
41.959184
165
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/NewLinesRepositoryTest.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.source; import java.util.Arrays; 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.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.period.Period; import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule; import org.sonar.ce.task.projectanalysis.scm.Changeset; import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepositoryRule; import org.sonar.db.component.BranchType; import org.sonar.db.newcodeperiod.NewCodePeriodType; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class NewLinesRepositoryTest { private final static ReportComponent FILE = ReportComponent.builder(Component.Type.FILE, 1).build(); @Rule public BatchReportReaderRule reader = new BatchReportReaderRule(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); @Rule public PeriodHolderRule periodHolder = new PeriodHolderRule(); @Rule public ScmInfoRepositoryRule scmInfoRepository = new ScmInfoRepositoryRule(); private final NewLinesRepository repository = new NewLinesRepository(reader, analysisMetadataHolder, periodHolder, scmInfoRepository); @Test public void load_new_lines_from_report_when_available_and_pullrequest() { setPullRequest(); createChangedLinesInReport(1, 2, 5); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isPresent(); assertThat(newLines.get()).containsOnly(1, 2, 5); assertThat(repository.newLinesAvailable()).isTrue(); } @Test public void load_new_lines_from_report_when_available_and_using_reference_branch() { periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), null, null)); createChangedLinesInReport(1, 2, 5); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isPresent(); assertThat(newLines.get()).containsOnly(1, 2, 5); assertThat(repository.newLinesAvailable()).isTrue(); } @Test public void compute_new_lines_using_scm_info_for_period() { periodHolder.setPeriod(new Period("", null, 1000L)); scmInfoRepository.setScmInfo(FILE.getReportAttributes().getRef(), createChangesets(1100L, 900L, 1000L, 800L)); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isPresent(); assertThat(newLines.get()).containsOnly(1); assertThat(repository.newLinesAvailable()).isTrue(); } @Test public void compute_new_lines_using_scm_info_for_period_with_missing_line() { periodHolder.setPeriod(new Period("", null, 1000L)); scmInfoRepository.setScmInfo(FILE.getReportAttributes().getRef(), createChangesets(1100L, 900L, null, 800L)); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isPresent(); assertThat(newLines.get()).containsOnly(1); assertThat(repository.newLinesAvailable()).isTrue(); } @Test public void compute_new_lines_using_scm_info_for_pullrequest() { periodHolder.setPeriod(null); setPullRequest(); analysisMetadataHolder.setAnalysisDate(1000L); scmInfoRepository.setScmInfo(FILE.getReportAttributes().getRef(), createChangesets(1100L, 900L, 1000L, 800L)); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isPresent(); assertThat(newLines.get()).containsOnly(1, 3); assertThat(repository.newLinesAvailable()).isTrue(); } @Test public void return_empty_if_no_period_no_pullrequest_and_no_reference_branch() { periodHolder.setPeriod(null); // even though we have lines in the report and scm data, nothing should be returned since we have no period createChangedLinesInReport(1, 2, 5); scmInfoRepository.setScmInfo(FILE.getReportAttributes().getRef(), createChangesets(1100L, 900L, 1000L, 800L)); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isNotPresent(); assertThat(repository.newLinesAvailable()).isFalse(); } @Test public void return_empty_if_no_report_and_no_scm_info() { periodHolder.setPeriod(new Period("", null, 1000L)); Optional<Set<Integer>> newLines = repository.getNewLines(FILE); assertThat(newLines).isNotPresent(); assertThat(repository.newLinesAvailable()).isTrue(); } private void setPullRequest() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); analysisMetadataHolder.setBranch(branch); } private Changeset[] createChangesets(Long... dates) { return Arrays.stream(dates) .map(l -> l == null ? null : Changeset.newChangesetBuilder().setDate(l).build()) .toArray(Changeset[]::new); } private void createChangedLinesInReport(Integer... lines) { ScannerReport.ChangedLines changedLines = ScannerReport.ChangedLines.newBuilder() .addAllLine(Arrays.asList(lines)) .build(); reader.putChangedLines(FILE.getReportAttributes().getRef(), changedLines); } }
6,348
37.95092
136
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/RangeOffsetConverterTest.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.source; import org.junit.Test; import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter; import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.RangeOffsetConverterException; 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 RangeOffsetConverterTest { static final int LINE_1 = 1; static final int LINE_2 = 2; static final int LINE_3 = 3; static final int OFFSET_0 = 0; static final int OFFSET_2 = 2; static final int OFFSET_3 = 3; static final int OFFSET_4 = 4; static final int BIG_OFFSET = 10; static final int DEFAULT_LINE_LENGTH = 5; RangeOffsetConverter underTest = new RangeOffsetConverter(); @Test public void return_range() { assertThat(underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_2, OFFSET_3), LINE_1, DEFAULT_LINE_LENGTH)) .isEqualTo(OFFSET_2 + "," + OFFSET_3); } @Test public void return_range_not_finishing_in_current_line() { assertThat(underTest.offsetToString(createTextRange(LINE_1, LINE_3, OFFSET_2, OFFSET_3), LINE_1, DEFAULT_LINE_LENGTH)) .isEqualTo(OFFSET_2 + "," + DEFAULT_LINE_LENGTH); } @Test public void return_range_that_began_in_previous_line_and_finish_in_current_line() { assertThat(underTest.offsetToString(createTextRange(LINE_1, LINE_3, OFFSET_2, OFFSET_3), LINE_3, DEFAULT_LINE_LENGTH)) .isEqualTo(OFFSET_0 + "," + OFFSET_3); } @Test public void return_range_that_began_in_previous_line_and_not_finishing_in_current_line() { assertThat(underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_2, OFFSET_3), LINE_2, DEFAULT_LINE_LENGTH)) .isEqualTo(OFFSET_0 + "," + DEFAULT_LINE_LENGTH); } @Test public void return_empty_string_when_offset_is_empty() { assertThat(underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_0, OFFSET_0), LINE_1, DEFAULT_LINE_LENGTH)) .isEmpty(); } @Test public void return_whole_line_offset_when_range_begin_at_first_character_and_ends_at_first_character_of_next_line() { assertThat(underTest.offsetToString(createTextRange(LINE_1, LINE_2, OFFSET_0, OFFSET_0), LINE_1, DEFAULT_LINE_LENGTH)) .isEqualTo(OFFSET_0 + "," + DEFAULT_LINE_LENGTH); } @Test public void fail_when_end_offset_is_before_start_offset() { assertThatThrownBy(() -> underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_4, OFFSET_2), LINE_1, DEFAULT_LINE_LENGTH)) .isInstanceOf(RangeOffsetConverterException.class) .hasMessage("End offset 2 cannot be defined before start offset 4 on line 1"); } @Test public void fail_when_end_offset_is_higher_than_line_length() { assertThatThrownBy(() -> underTest.offsetToString(createTextRange(LINE_1, LINE_1, OFFSET_4, BIG_OFFSET), LINE_1, DEFAULT_LINE_LENGTH)) .isInstanceOf(RangeOffsetConverterException.class) .hasMessage("End offset 10 is defined outside the length (5) of the line 1"); } @Test public void fail_when_start_offset_is_higher_than_line_length() { assertThatThrownBy(() -> underTest.offsetToString(createTextRange(LINE_1, LINE_1, BIG_OFFSET, BIG_OFFSET + 1), LINE_1, DEFAULT_LINE_LENGTH)) .isInstanceOf(RangeOffsetConverterException.class) .hasMessage("Start offset 10 is defined outside the length (5) of the line 1"); } private static ScannerReport.TextRange createTextRange(int startLine, int enLine, int startOffset, int endOffset) { return ScannerReport.TextRange.newBuilder() .setStartLine(startLine).setEndLine(enLine) .setStartOffset(startOffset).setEndOffset(endOffset) .build(); } }
4,675
38.627119
144
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/ReportIteratorTest.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.source; import java.io.File; import java.util.NoSuchElementException; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.scanner.protocol.output.FileStructure; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReportWriter; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ReportIteratorTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private File file; private ReportIterator<ScannerReport.LineCoverage> underTest; @Before public void setUp() throws Exception { File dir = temp.newFolder(); FileStructure fileStructure = new FileStructure(dir); ScannerReportWriter writer = new ScannerReportWriter(fileStructure); writer.writeComponentCoverage(1, newArrayList( ScannerReport.LineCoverage.newBuilder() .setLine(1) .build())); file = new FileStructure(dir).fileFor(FileStructure.Domain.COVERAGES, 1); } @After public void tearDown() { if (underTest != null) { underTest.close(); } } @Test public void read_report() { underTest = new ReportIterator<>(file, ScannerReport.LineCoverage.parser()); assertThat(underTest.next().getLine()).isOne(); } @Test public void do_not_fail_when_calling_has_next_with_iterator_already_closed() { underTest = new ReportIterator<>(file, ScannerReport.LineCoverage.parser()); assertThat(underTest.next().getLine()).isOne(); assertThat(underTest.hasNext()).isFalse(); underTest.close(); assertThat(underTest.hasNext()).isFalse(); } @Test public void test_error() { underTest = new ReportIterator<>(file, ScannerReport.LineCoverage.parser()); underTest.next(); assertThatThrownBy(() -> { // fail ! underTest.next(); }) .isInstanceOf(NoSuchElementException.class); } }
2,972
30.294737
80
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SignificantCodeRepositoryTest.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.source; import java.util.ArrayList; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.core.hash.LineRange; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.LineSgnificantCode; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class SignificantCodeRepositoryTest { private static final String FILE_UUID = "FILE_UUID"; private static final String FILE_KEY = "FILE_KEY"; private static final int FILE_REF = 2; @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); private SignificantCodeRepository underTest = new SignificantCodeRepository(reportReader); @Test public void return_empty_if_information_not_available() { assertThat(underTest.getRangesPerLine(createComponent(3))).isEmpty(); } @Test public void return_null_for_lines_without_information() { Component component = createComponent(5); List<ScannerReport.LineSgnificantCode> significantCode = new ArrayList<>(); // line 3 and 5 missing significantCode.add(createLineSignificantCode(1, 1, 2)); significantCode.add(createLineSignificantCode(2, 1, 2)); significantCode.add(createLineSignificantCode(4, 1, 2)); reportReader.putSignificantCode(component.getReportAttributes().getRef(), significantCode); assertThat(underTest.getRangesPerLine(component)).isNotEmpty(); LineRange[] lines = underTest.getRangesPerLine(component).get(); assertThat(lines).hasSize(5); assertThat(lines[0]).isNotNull(); assertThat(lines[1]).isNotNull(); assertThat(lines[2]).isNull(); assertThat(lines[3]).isNotNull(); assertThat(lines[4]).isNull(); } @Test public void translate_offset_for_each_line() { Component component = createComponent(1); List<ScannerReport.LineSgnificantCode> significantCode = new ArrayList<>(); significantCode.add(createLineSignificantCode(1, 1, 2)); reportReader.putSignificantCode(component.getReportAttributes().getRef(), significantCode); assertThat(underTest.getRangesPerLine(component)).isNotEmpty(); LineRange[] lines = underTest.getRangesPerLine(component).get(); assertThat(lines).hasSize(1); assertThat(lines[0].startOffset()).isOne(); assertThat(lines[0].endOffset()).isEqualTo(2); } private static LineSgnificantCode createLineSignificantCode(int line, int start, int end) { return LineSgnificantCode.newBuilder() .setLine(line) .setStartOffset(start) .setEndOffset(end) .build(); } private static Component createComponent(int lineCount) { return builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .setFileAttributes(new FileAttributes(false, null, lineCount)) .build(); } }
3,987
37.346154
95
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceHashRepositoryImplTest.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.source; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; 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 javax.annotation.Nullable; import org.junit.Rule; 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.component.ViewsComponent; import org.sonar.core.hash.SourceHashComputer; import org.sonar.core.util.CloseableIterator; 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.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(DataProviderRunner.class) public class SourceHashRepositoryImplTest { private static final int FILE_REF = 112; private static final String FILE_KEY = "file key"; private static final Component FILE_COMPONENT = ReportComponent.builder(Component.Type.FILE, FILE_REF).setKey(FILE_KEY).build(); private static final String[] SOME_LINES = {"line 1", "line after line 1", "line 4 minus 1", "line 100 by 10"}; @Rule public SourceLinesRepositoryRule sourceLinesRepository = new SourceLinesRepositoryRule(); private SourceLinesRepository mockedSourceLinesRepository = mock(SourceLinesRepository.class); private SourceHashRepositoryImpl underTest = new SourceHashRepositoryImpl(sourceLinesRepository); private SourceHashRepositoryImpl mockedUnderTest = new SourceHashRepositoryImpl(mockedSourceLinesRepository); @Test public void getRawSourceHash_throws_NPE_if_Component_argument_is_null() { assertThatThrownBy(() -> underTest.getRawSourceHash(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Specified component can not be null"); } @Test @UseDataProvider("componentsOfAllTypesButFile") public void getRawSourceHash_throws_IAE_if_Component_argument_is_not_FILE(Component component) { assertThatThrownBy(() -> underTest.getRawSourceHash(component)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("File source information can only be retrieved from FILE components (got " + component.getType() + ")"); } @DataProvider public static Object[][] componentsOfAllTypesButFile() { return FluentIterable.from(Arrays.asList(Component.Type.values())) .filter(new Predicate<Component.Type>() { @Override public boolean apply(@Nullable Component.Type input) { return input != Component.Type.FILE; } }) .transform(new Function<Component.Type, Component>() { @Nullable @Override public Component apply(Component.Type input) { if (input.isReportType()) { return ReportComponent.builder(input, input.hashCode()) .setKey(input.name() + "_key") .build(); } else if (input.isViewsType()) { return ViewsComponent.builder(input, input.name() + "_key") .build(); } else { throw new IllegalArgumentException("Unsupported type " + input); } } }).transform(new Function<Component, Component[]>() { @Nullable @Override public Component[] apply(@Nullable Component input) { return new Component[] {input}; } }).toArray(Component[].class); } @Test public void getRawSourceHash_returns_hash_of_lines_from_SourceLinesRepository() { sourceLinesRepository.addLines(FILE_REF, SOME_LINES); String rawSourceHash = underTest.getRawSourceHash(FILE_COMPONENT); SourceHashComputer sourceHashComputer = new SourceHashComputer(); for (int i = 0; i < SOME_LINES.length; i++) { sourceHashComputer.addLine(SOME_LINES[i], i < (SOME_LINES.length - 1)); } assertThat(rawSourceHash).isEqualTo(sourceHashComputer.getHash()); } @Test public void getRawSourceHash_reads_lines_from_SourceLinesRepository_only_the_first_time() { when(mockedSourceLinesRepository.readLines(FILE_COMPONENT)).thenReturn(CloseableIterator.from(Arrays.asList(SOME_LINES).iterator())); String rawSourceHash = mockedUnderTest.getRawSourceHash(FILE_COMPONENT); String rawSourceHash1 = mockedUnderTest.getRawSourceHash(FILE_COMPONENT); assertThat(rawSourceHash).isSameAs(rawSourceHash1); verify(mockedSourceLinesRepository, times(1)).readLines(FILE_COMPONENT); } @Test public void getRawSourceHash_let_exception_go_through() { IllegalArgumentException thrown = new IllegalArgumentException("this IAE will cause the hash computation to fail"); when(mockedSourceLinesRepository.readLines(FILE_COMPONENT)).thenThrow(thrown); assertThatThrownBy(() -> mockedUnderTest.getRawSourceHash(FILE_COMPONENT)) .isInstanceOf(IllegalArgumentException.class) .hasMessage(thrown.getMessage()); } }
6,084
40.965517
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLineReadersFactoryTest.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.source; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepositoryRule; import org.sonar.ce.task.projectanalysis.scm.ScmInfoRepositoryRule; import org.sonar.ce.task.projectanalysis.source.SourceLineReadersFactory.LineReadersImpl; import org.sonar.scanner.protocol.output.ScannerReport; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; public class SourceLineReadersFactoryTest { private static final int FILE1_REF = 3; private static final String PROJECT_UUID = "PROJECT"; private static final String PROJECT_KEY = "PROJECT_KEY"; private static final String FILE1_UUID = "FILE1"; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public ScmInfoRepositoryRule scmInfoRepository = new ScmInfoRepositoryRule(); @Rule public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(treeRootHolder); private NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private SourceLineReadersFactory underTest = new SourceLineReadersFactory(reportReader, scmInfoRepository, duplicationRepository, newLinesRepository); @Test public void should_create_readers() { initBasicReport(10); LineReadersImpl lineReaders = (LineReadersImpl) underTest.getLineReaders(fileComponent()); assertThat(lineReaders).isNotNull(); assertThat(lineReaders.closeables).hasSize(3); assertThat(lineReaders.readers).hasSize(5); } private Component fileComponent() { return ReportComponent.builder(Component.Type.FILE, FILE1_REF).build(); } private void initBasicReport(int numberOfLines) { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(PROJECT_UUID).setKey(PROJECT_KEY).addChildren( ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid("MODULE").setKey("MODULE_KEY").addChildren( ReportComponent.builder(Component.Type.FILE, FILE1_REF).setUuid(FILE1_UUID).setKey("MODULE_KEY:src/Foo.java") .setFileAttributes(new FileAttributes(false, null, numberOfLines)).build()) .build()) .build()); reportReader.putComponent(ScannerReport.Component.newBuilder() .setRef(1) .setType(ScannerReport.Component.ComponentType.PROJECT) .addChildRef(2) .build()); reportReader.putComponent(ScannerReport.Component.newBuilder() .setRef(2) .setType(ScannerReport.Component.ComponentType.MODULE) .addChildRef(FILE1_REF) .build()); reportReader.putComponent(ScannerReport.Component.newBuilder() .setRef(FILE1_REF) .setType(ScannerReport.Component.ComponentType.FILE) .setLines(numberOfLines) .build()); } }
4,083
41.541667
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesDiffFinderTest.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.source; import java.util.ArrayList; import java.util.List; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; public class SourceLinesDiffFinderTest { @Test public void shouldFindNothingWhenContentAreIdentical() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); database.add("line - 4"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - 2"); report.add("line - 3"); report.add("line - 4"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 3, 4, 5); } @Test public void shouldFindNothingWhenContentAreIdentical2() { List<String> database = new ArrayList<>(); database.add("package sample;\n"); database.add("\n"); database.add("public class Sample {\n"); database.add("\n"); database.add(" private String myMethod() {\n"); database.add(" }\n"); database.add("}\n"); List<String> report = new ArrayList<>(); report.add("package sample;\n"); report.add("\n"); report.add("public class Sample {\n"); report.add("\n"); report.add(" private String attr;\n"); report.add("\n"); report.add(" public Sample(String attr) {\n"); report.add(" this.attr = attr;\n"); report.add(" }\n"); report.add("\n"); report.add(" private String myMethod() {\n"); report.add(" }\n"); report.add("}\n"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 5, 6, 7); } @Test public void shouldDetectWhenStartingWithModifiedLines() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); List<String> report = new ArrayList<>(); report.add("line - 0 - modified"); report.add("line - 1 - modified"); report.add("line - 2"); report.add("line - 3"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(0, 0, 3, 4); } @Test public void shouldDetectWhenEndingWithModifiedLines() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - 2 - modified"); report.add("line - 3 - modified"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 0, 0); } @Test public void shouldDetectModifiedLinesInMiddleOfTheFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); database.add("line - 4"); database.add("line - 5"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - 2 - modified"); report.add("line - 3 - modified"); report.add("line - 4"); report.add("line - 5"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 0, 0, 5, 6); } @Test public void shouldDetectNewLinesAtBeginningOfFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); List<String> report = new ArrayList<>(); report.add("line - new"); report.add("line - new"); report.add("line - 0"); report.add("line - 1"); report.add("line - 2"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(0, 0, 1, 2, 3); } @Test public void shouldDetectNewLinesInMiddleOfFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - new"); report.add("line - new"); report.add("line - 2"); report.add("line - 3"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 0, 0, 3, 4); } @Test public void shouldDetectNewLinesAtEndOfFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - 2"); report.add("line - new"); report.add("line - new"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 3, 0, 0); } @Test public void shouldIgnoreDeletedLinesAtEndOfFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); database.add("line - 4"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - 2"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 3); } @Test public void shouldIgnoreDeletedLinesInTheMiddleOfFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); database.add("line - 4"); database.add("line - 5"); List<String> report = new ArrayList<>(); report.add("line - 0"); report.add("line - 1"); report.add("line - 4"); report.add("line - 5"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(1, 2, 5, 6); } @Test public void shouldIgnoreDeletedLinesAtTheStartOfTheFile() { List<String> database = new ArrayList<>(); database.add("line - 0"); database.add("line - 1"); database.add("line - 2"); database.add("line - 3"); List<String> report = new ArrayList<>(); report.add("line - 2"); report.add("line - 3"); int[] diff = new SourceLinesDiffFinder().findMatchingLines(database, report); assertThat(diff).containsExactly(3, 4); } }
7,698
28.841085
81
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesDiffImplTest.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.source; import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.period.NewCodeReferenceBranchComponentUuids; import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids; import org.sonar.ce.task.projectanalysis.filemove.MutableMovedFilesRepositoryRule; import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDao; import org.sonar.db.source.FileSourceDao; 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.Component.Type.FILE; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class SourceLinesDiffImplTest { private final DbClient dbClient = mock(DbClient.class); private final DbSession dbSession = mock(DbSession.class); private final ComponentDao componentDao = mock(ComponentDao.class); private final FileSourceDao fileSourceDao = mock(FileSourceDao.class); private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class); private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class); private final NewCodeReferenceBranchComponentUuids newCodeReferenceBranchComponentUuids = mock(NewCodeReferenceBranchComponentUuids.class); @Rule public PeriodHolderRule periodHolder = new PeriodHolderRule(); @Rule public MutableMovedFilesRepositoryRule movedFiles = new MutableMovedFilesRepositoryRule(); private final SourceLinesDiffImpl underTest = new SourceLinesDiffImpl(dbClient, fileSourceDao, sourceLinesHash, referenceBranchComponentUuids, movedFiles, analysisMetadataHolder, periodHolder, newCodeReferenceBranchComponentUuids); private static final int FILE_REF = 1; private static final String[] CONTENT = { "package org.sonar.ce.task.projectanalysis.source_diff;", "", "public class Foo {", " public String bar() {", " return \"Doh!\";", " }", "}" }; @Before public void setUp() { when(dbClient.openSession(false)).thenReturn(dbSession); when(dbClient.componentDao()).thenReturn(componentDao); when(dbClient.fileSourceDao()).thenReturn(fileSourceDao); } @Test public void should_find_diff_with_reference_branch_for_prs() { periodHolder.setPeriod(null); Component component = fileComponent(FILE_REF); mockLineHashesInDb(2, CONTENT); setLineHashesInReport(component, CONTENT); when(analysisMetadataHolder.isPullRequest()).thenReturn(true); when(referenceBranchComponentUuids.getComponentUuid(component.getKey())).thenReturn("uuid_2"); assertThat(underTest.computeMatchingLines(component)).containsExactly(1, 2, 3, 4, 5, 6, 7); } @Test public void all_file_is_modified_if_no_source_in_db() { periodHolder.setPeriod(null); Component component = fileComponent(FILE_REF); setLineHashesInReport(component, CONTENT); assertThat(underTest.computeMatchingLines(component)).containsExactly(0, 0, 0, 0, 0, 0, 0); } @Test public void should_find_no_diff_when_report_and_db_content_are_identical() { periodHolder.setPeriod(null); Component component = fileComponent(FILE_REF); mockLineHashesInDb(FILE_REF, CONTENT); setLineHashesInReport(component, CONTENT); assertThat(underTest.computeMatchingLines(component)).containsExactly(1, 2, 3, 4, 5, 6, 7); } private void mockLineHashesInDb(int ref, String[] lineHashes) { when(fileSourceDao.selectLineHashes(dbSession, componentUuidOf(String.valueOf(ref)))) .thenReturn(Arrays.asList(lineHashes)); } private static String componentUuidOf(String key) { return "uuid_" + key; } private static Component fileComponent(int ref) { return builder(FILE, ref) .setName("report_path" + ref) .setUuid(componentUuidOf("" + ref)) .build(); } private void setLineHashesInReport(Component component, String[] content) { when(sourceLinesHash.getLineHashesMatchingDBVersion(component)).thenReturn(Arrays.asList(content)); } }
5,397
38.691176
141
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashCacheTest.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.source; import java.util.Collections; import java.util.List; import java.util.function.Function; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.JUnitTempFolder; 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; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class SourceLinesHashCacheTest { private static final String FILE_UUID = "FILE_UUID"; private static final String FILE_KEY = "FILE_KEY"; @Rule public JUnitTempFolder tempFolder = new JUnitTempFolder(); private SourceLinesHashCache underTest; @Before public void setUp() { underTest = new SourceLinesHashCache(tempFolder); } @Test public void should_computeIfAbsent() { Component component = createComponent(1); Function<Component, List<String>> f = mock(Function.class); List<String> list = Collections.singletonList("hash1"); when(f.apply(component)).thenReturn(list); assertThat(underTest.contains(component)).isFalse(); List<String> returned = underTest.computeIfAbsent(component, f); assertThat(returned).isEqualTo(list); assertThat(underTest.contains(component)).isTrue(); returned = underTest.computeIfAbsent(component, f); assertThat(returned).isEqualTo(list); verify(f).apply(component); } @Test public void get_throws_ISE_if_not_cached() { Component component = createComponent(1); assertThatThrownBy(() -> underTest.get(component)) .isInstanceOf(IllegalStateException.class) .hasMessage("Source line hashes for component ReportComponent{ref=1, key='FILE_KEY', type=FILE} not cached"); } @Test public void get_returns_value_if_cached() { List<String> list = Collections.singletonList("hash1"); Component component = createComponent(1); underTest.computeIfAbsent(component, c -> list); assertThat(underTest.get(component)).isEqualTo(list); } private static Component createComponent(int ref) { return ReportComponent.builder(Component.Type.FILE, ref) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build(); } }
3,254
33.62766
115
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashImplTest.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.source; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import static org.mockito.Mockito.mock; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class SourceLinesHashImplTest { private static final String FILE_UUID = "FILE_UUID"; private static final String FILE_KEY = "FILE_KEY"; @Rule public SourceLinesRepositoryRule sourceLinesRepository = new SourceLinesRepositoryRule(); public SignificantCodeRepository significantCodeRepository = mock(SignificantCodeRepository.class); public SourceLinesHashCache cache = mock(SourceLinesHashCache.class); public DbLineHashVersion dbLineHashVersion = mock(DbLineHashVersion.class); private SourceLinesHashRepositoryImpl underTest = new SourceLinesHashRepositoryImpl(sourceLinesRepository, significantCodeRepository, cache, dbLineHashVersion); @Test public void should_generate_correct_version_of_line_hashes() { Component component = createComponent(1); underTest.getLineHashesMatchingDBVersion(component); } private static Component createComponent(int ref) { return builder(Component.Type.FILE, ref) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build(); } }
2,146
37.339286
162
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesHashRepositoryImplTest.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.source; import com.google.common.collect.Lists; import java.util.List; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.JUnitTempFolder; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.Component.Type; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepositoryImpl.CachedLineHashesComputer; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepositoryImpl.LineHashesComputer; import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepositoryImpl.SignificantCodeLineHashesComputer; import org.sonar.core.hash.LineRange; import org.sonar.core.hash.SourceLineHashesComputer; import org.sonar.db.source.LineHashVersion; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; 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 SourceLinesHashRepositoryImplTest { private static final int FILE_REF = 1; @Rule public JUnitTempFolder temp = new JUnitTempFolder(); @Rule public SourceLinesRepositoryRule sourceLinesRepository = new SourceLinesRepositoryRule(); private SourceLinesHashCache sourceLinesHashCache; private SignificantCodeRepository significantCodeRepository = mock(SignificantCodeRepository.class); private DbLineHashVersion dbLineHashVersion = mock(DbLineHashVersion.class); private Component file = ReportComponent.builder(Type.FILE, FILE_REF).build(); private SourceLinesHashRepositoryImpl underTest; @Before public void setUp() { sourceLinesHashCache = new SourceLinesHashCache(temp); underTest = new SourceLinesHashRepositoryImpl(sourceLinesRepository, significantCodeRepository, sourceLinesHashCache, dbLineHashVersion); sourceLinesRepository.addLines(FILE_REF, "line1", "line2", "line3"); } @Test public void should_return_with_significant_code_if_report_contains_it() { when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(new LineRange[0])); assertThat(underTest.getLineHashesVersion(file)).isEqualTo(LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue()); verify(significantCodeRepository).getRangesPerLine(file); verifyNoMoreInteractions(significantCodeRepository); verifyNoInteractions(dbLineHashVersion); } @Test public void should_return_without_significant_code_if_report_does_not_contain_it() { when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty()); assertThat(underTest.getLineHashesVersion(file)).isEqualTo(LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue()); verify(significantCodeRepository).getRangesPerLine(file); verifyNoMoreInteractions(significantCodeRepository); verifyNoInteractions(dbLineHashVersion); } @Test public void should_create_hash_without_significant_code_if_db_has_no_significant_code() { when(dbLineHashVersion.hasLineHashesWithoutSignificantCode(file)).thenReturn(true); List<String> lineHashes = underTest.getLineHashesMatchingDBVersion(file); assertLineHashes(lineHashes, "line1", "line2", "line3"); verify(dbLineHashVersion).hasLineHashesWithoutSignificantCode(file); verifyNoMoreInteractions(dbLineHashVersion); verifyNoInteractions(significantCodeRepository); } @Test public void should_create_hash_without_significant_code_if_report_has_no_significant_code() { when(dbLineHashVersion.hasLineHashesWithoutSignificantCode(file)).thenReturn(false); when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty()); List<String> lineHashes = underTest.getLineHashesMatchingDBVersion(file); assertLineHashes(lineHashes, "line1", "line2", "line3"); verify(dbLineHashVersion).hasLineHashesWithoutSignificantCode(file); verifyNoMoreInteractions(dbLineHashVersion); verify(significantCodeRepository).getRangesPerLine(file); verifyNoMoreInteractions(significantCodeRepository); } @Test public void should_create_hash_with_significant_code() { LineRange[] lineRanges = {new LineRange(0, 1), null, new LineRange(1, 5)}; when(dbLineHashVersion.hasLineHashesWithSignificantCode(file)).thenReturn(true); when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(lineRanges)); List<String> lineHashes = underTest.getLineHashesMatchingDBVersion(file); assertLineHashes(lineHashes, "l", "", "ine3"); verify(dbLineHashVersion).hasLineHashesWithoutSignificantCode(file); verifyNoMoreInteractions(dbLineHashVersion); verify(significantCodeRepository).getRangesPerLine(file); verifyNoMoreInteractions(significantCodeRepository); } @Test public void should_return_version_of_line_hashes_with_significant_code_in_the_report() { LineRange[] lineRanges = {new LineRange(0, 1), null, new LineRange(1, 5)}; when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(lineRanges)); assertThat(underTest.getLineHashesVersion(file)).isEqualTo(LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue()); verify(significantCodeRepository).getRangesPerLine(file); verifyNoMoreInteractions(significantCodeRepository); verifyNoInteractions(dbLineHashVersion); } @Test public void should_return_version_of_line_hashes_without_significant_code_in_the_report() { when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty()); assertThat(underTest.getLineHashesVersion(file)).isEqualTo(LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue()); verify(significantCodeRepository).getRangesPerLine(file); verifyNoMoreInteractions(significantCodeRepository); verifyNoInteractions(dbLineHashVersion); } @Test public void should_persist_with_significant_code_from_cache_if_possible() { List<String> lineHashes = Lists.newArrayList("line1", "line2", "line3"); LineRange[] lineRanges = {new LineRange(0, 1), null, new LineRange(1, 5)}; sourceLinesHashCache.computeIfAbsent(file, c -> lineHashes); when(dbLineHashVersion.hasLineHashesWithoutSignificantCode(file)).thenReturn(false); when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(lineRanges)); LineHashesComputer hashesComputer = underTest.getLineHashesComputerToPersist(file); assertThat(hashesComputer).isInstanceOf(CachedLineHashesComputer.class); assertThat(hashesComputer.getResult()).isEqualTo(lineHashes); } @Test public void should_persist_without_significant_code_from_cache_if_possible() { List<String> lineHashes = Lists.newArrayList("line1", "line2", "line3"); sourceLinesHashCache.computeIfAbsent(file, c -> lineHashes); when(dbLineHashVersion.hasLineHashesWithoutSignificantCode(file)).thenReturn(true); when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.empty()); LineHashesComputer hashesComputer = underTest.getLineHashesComputerToPersist(file); assertThat(hashesComputer).isInstanceOf(CachedLineHashesComputer.class); assertThat(hashesComputer.getResult()).isEqualTo(lineHashes); } @Test public void should_generate_to_persist_if_needed() { List<String> lineHashes = Lists.newArrayList("line1", "line2", "line3"); LineRange[] lineRanges = {new LineRange(0, 1), null, new LineRange(1, 5)}; sourceLinesHashCache.computeIfAbsent(file, c -> lineHashes); // DB has line hashes without significant code and significant code is available in the report, so we need to generate new line hashes when(dbLineHashVersion.hasLineHashesWithoutSignificantCode(file)).thenReturn(true); when(significantCodeRepository.getRangesPerLine(file)).thenReturn(Optional.of(lineRanges)); LineHashesComputer hashesComputer = underTest.getLineHashesComputerToPersist(file); assertThat(hashesComputer).isInstanceOf(SignificantCodeLineHashesComputer.class); } @Test public void SignificantCodeLineHashesComputer_delegates_after_taking_ranges_into_account() { LineRange[] lineRanges = { new LineRange(0, 1), null, new LineRange(1, 5), new LineRange(2, 7), new LineRange(4, 5) }; SourceLineHashesComputer lineHashComputer = mock(SourceLineHashesComputer.class); SignificantCodeLineHashesComputer computer = new SignificantCodeLineHashesComputer(lineHashComputer, lineRanges); computer.addLine("testline"); computer.addLine("testline"); computer.addLine("testline"); computer.addLine("testline"); computer.addLine("testline"); computer.addLine("testline"); verify(lineHashComputer).addLine("t"); // there is an extra line at the end which will be ignored since there is no range for it verify(lineHashComputer, times(2)).addLine(""); verify(lineHashComputer).addLine("estl"); verify(lineHashComputer).addLine("stlin"); verify(lineHashComputer).addLine("l"); verifyNoMoreInteractions(lineHashComputer); } private void assertLineHashes(List<String> actualLines, String... lines) { assertThat(actualLines).hasSize(lines.length); SourceLineHashesComputer computer = new SourceLineHashesComputer(); for (String line : lines) { computer.addLine(line); } List<String> expectedLines = computer.getLineHashes(); for (int i = 0; i < expectedLines.size(); i++) { assertThat(actualLines.get(i)) .withFailMessage("Line hash is different for line %d", i) .isEqualTo(expectedLines.get(i)); } } }
10,655
43.215768
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryImplTest.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.source; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.core.util.CloseableIterator; 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 SourceLinesRepositoryImplTest { private static final String FILE_UUID = "FILE_UUID"; private static final String FILE_KEY = "FILE_KEY"; private static final int FILE_REF = 2; @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); private SourceLinesRepositoryImpl underTest = new SourceLinesRepositoryImpl(reportReader); @Test public void read_lines_from_report() { reportReader.putFileSourceLines(FILE_REF, "line1", "line2"); assertThat(underTest.readLines(createComponent(2))).toIterable().containsOnly("line1", "line2"); } @Test public void read_lines_adds_one_extra_empty_line_when_sourceLine_has_elements_count_equals_to_lineCount_minus_1() { reportReader.putFileSourceLines(FILE_REF, "line1", "line2"); assertThat(underTest.readLines(createComponent(3))).toIterable().containsOnly("line1", "line2", ""); } @Test public void read_lines_throws_ISE_when_sourceLine_has_less_elements_then_lineCount_minus_1() { reportReader.putFileSourceLines(FILE_REF, "line1", "line2"); assertThatThrownBy(() -> consume(underTest.readLines(createComponent(10)))) .isInstanceOf(IllegalStateException.class) .hasMessage("Source of file 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has less lines (2) than the expected number (10)"); } @Test public void read_lines_throws_ISE_when_sourceLines_has_more_elements_then_lineCount() { reportReader.putFileSourceLines(FILE_REF, "line1", "line2", "line3"); assertThatThrownBy(() -> consume(underTest.readLines(createComponent(2)))) .isInstanceOf(IllegalStateException.class) .hasMessage("Source of file 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has at least one more line than the expected number (2)"); } @Test public void fail_with_ISE_when_file_has_no_source() { assertThatThrownBy(() -> { underTest.readLines(builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .build()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("File 'ReportComponent{ref=2, key='FILE_KEY', type=FILE}' has no source code"); } @Test public void fail_with_NPE_to_read_lines_on_null_component() { assertThatThrownBy(() -> underTest.readLines(null)) .isInstanceOf(NullPointerException.class) .hasMessage("Component should not be null"); } @Test public void fail_with_IAE_to_read_lines_on_not_file_component() { assertThatThrownBy(() -> underTest.readLines(builder(Component.Type.PROJECT, 123).setKey("NotFile").build())) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Component 'ReportComponent{ref=123, key='NotFile', type=PROJECT}' is not a file"); } private static Component createComponent(int lineCount) { return builder(Component.Type.FILE, FILE_REF) .setKey(FILE_KEY) .setUuid(FILE_UUID) .setFileAttributes(new FileAttributes(false, null, lineCount)) .build(); } private static void consume(CloseableIterator<String> stringCloseableIterator) { try { while (stringCloseableIterator.hasNext()) { stringCloseableIterator.next(); } } finally { stringCloseableIterator.close(); } } }
4,668
37.270492
144
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/SourceLinesRepositoryRule.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.source; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.Multimap; import java.util.Arrays; import java.util.Collection; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.util.CloseableIterator; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; public class SourceLinesRepositoryRule extends ExternalResource implements SourceLinesRepository { private Multimap<Integer, String> lines = ArrayListMultimap.create(); @Override protected void after() { lines.clear(); } @Override public CloseableIterator<String> readLines(Component component) { checkNotNull(component, "Component should not be bull"); if (!component.getType().equals(Component.Type.FILE)) { throw new IllegalArgumentException(String.format("Component '%s' is not a file", component)); } Collection<String> componentLines = lines.get(component.getReportAttributes().getRef()); checkState(!componentLines.isEmpty(), String.format("File '%s' has no source code", component)); return CloseableIterator.from(componentLines.iterator()); } public SourceLinesRepositoryRule addLine(int componentRef, String line) { this.lines.put(componentRef, line); return this; } public SourceLinesRepositoryRule addLines(int componentRef, String... lines) { this.lines.putAll(componentRef, Arrays.asList(lines)); return this; } }
2,428
36.953125
100
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/linereader/CoverageLineReaderTest.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.source.linereader; import java.util.Collections; import org.junit.Test; import org.sonar.db.protobuf.DbFileSources; import org.sonar.scanner.protocol.output.ScannerReport; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThat; public class CoverageLineReaderTest { @Test public void set_coverage() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setHits(true) .setCoveredConditions(2) .build()).iterator()); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(computeCoverageLine.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.getLineHits()).isOne(); assertThat(lineBuilder.getConditions()).isEqualTo(10); assertThat(lineBuilder.getCoveredConditions()).isEqualTo(2); } // Some tools are only able to report condition coverage @Test public void set_coverage_only_conditions() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setCoveredConditions(2) .build()).iterator()); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(computeCoverageLine.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.hasLineHits()).isFalse(); assertThat(lineBuilder.getConditions()).isEqualTo(10); } @Test public void set_coverage_on_uncovered_lines() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(ScannerReport.LineCoverage.newBuilder() .setLine(1) .setHits(false) .build()).iterator()); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(computeCoverageLine.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.hasLineHits()).isTrue(); assertThat(lineBuilder.getLineHits()).isZero(); } @Test public void nothing_to_do_when_no_coverage_info() { CoverageLineReader computeCoverageLine = new CoverageLineReader(Collections.<ScannerReport.LineCoverage>emptyList().iterator()); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(computeCoverageLine.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.hasLineHits()).isFalse(); assertThat(lineBuilder.hasConditions()).isFalse(); assertThat(lineBuilder.hasCoveredConditions()).isFalse(); } @Test public void nothing_to_do_when_no_coverage_info_for_current_line() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList( ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setHits(true) .setCoveredConditions(2) .build() // No coverage info on line 2 ).iterator()); DbFileSources.Line.Builder line2Builder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(2); computeCoverageLine.read(line2Builder); assertThat(line2Builder.hasLineHits()).isFalse(); assertThat(line2Builder.hasConditions()).isFalse(); assertThat(line2Builder.hasCoveredConditions()).isFalse(); } @Test public void nothing_to_do_when_no_coverage_info_for_next_line() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList( ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setHits(true) .setCoveredConditions(2) .build() // No coverage info on line 2 ).iterator()); DbFileSources.Data.Builder fileSourceBuilder = DbFileSources.Data.newBuilder(); DbFileSources.Line.Builder line1Builder = fileSourceBuilder.addLinesBuilder().setLine(1); DbFileSources.Line.Builder line2Builder = fileSourceBuilder.addLinesBuilder().setLine(2); computeCoverageLine.read(line1Builder); computeCoverageLine.read(line2Builder); assertThat(line2Builder.hasLineHits()).isFalse(); assertThat(line2Builder.hasConditions()).isFalse(); assertThat(line2Builder.hasCoveredConditions()).isFalse(); } @Test public void does_not_set_deprecated_coverage_fields() { CoverageLineReader computeCoverageLine = new CoverageLineReader(newArrayList(ScannerReport.LineCoverage.newBuilder() .setLine(1) .setConditions(10) .setHits(true) .setCoveredConditions(2) .build()).iterator()); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(computeCoverageLine.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.hasDeprecatedUtLineHits()).isFalse(); assertThat(lineBuilder.hasDeprecatedUtConditions()).isFalse(); assertThat(lineBuilder.hasDeprecatedUtCoveredConditions()).isFalse(); assertThat(lineBuilder.hasDeprecatedOverallLineHits()).isFalse(); assertThat(lineBuilder.hasDeprecatedOverallConditions()).isFalse(); assertThat(lineBuilder.hasDeprecatedOverallCoveredConditions()).isFalse(); assertThat(lineBuilder.hasDeprecatedItLineHits()).isFalse(); assertThat(lineBuilder.hasDeprecatedItConditions()).isFalse(); assertThat(lineBuilder.hasDeprecatedItCoveredConditions()).isFalse(); } }
6,313
38.962025
132
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/linereader/DuplicationLineReaderTest.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.source.linereader; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collections; 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.duplication.CrossProjectDuplicate; import org.sonar.ce.task.projectanalysis.duplication.Duplicate; import org.sonar.ce.task.projectanalysis.duplication.Duplication; import org.sonar.ce.task.projectanalysis.duplication.InProjectDuplicate; import org.sonar.ce.task.projectanalysis.duplication.InnerDuplicate; import org.sonar.ce.task.projectanalysis.duplication.TextBlock; import org.sonar.db.protobuf.DbFileSources; import static org.assertj.core.api.Assertions.assertThat; public class DuplicationLineReaderTest { DbFileSources.Data.Builder sourceData = DbFileSources.Data.newBuilder(); DbFileSources.Line.Builder line1 = sourceData.addLinesBuilder().setSource("line1").setLine(1); DbFileSources.Line.Builder line2 = sourceData.addLinesBuilder().setSource("line2").setLine(2); DbFileSources.Line.Builder line3 = sourceData.addLinesBuilder().setSource("line3").setLine(3); DbFileSources.Line.Builder line4 = sourceData.addLinesBuilder().setSource("line4").setLine(4); @Test public void read_nothing() { DuplicationLineReader reader = new DuplicationLineReader(Collections.emptySet()); assertThat(reader.read(line1)).isEmpty(); assertThat(line1.getDuplicationList()).isEmpty(); } @Test public void read_duplication_with_duplicates_on_same_file() { DuplicationLineReader reader = duplicationLineReader(duplication(1, 2, innerDuplicate(3, 4))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1); assertThat(line2.getDuplicationList()).containsExactly(1); assertThat(line3.getDuplicationList()).containsExactly(2); assertThat(line4.getDuplicationList()).containsExactly(2); } @Test public void read_duplication_with_repeated_text_blocks() { DuplicationLineReader reader = duplicationLineReader( duplication(1, 2, innerDuplicate(3, 4)), duplication(3, 4, innerDuplicate(1, 2))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1); assertThat(line2.getDuplicationList()).containsExactly(1); assertThat(line3.getDuplicationList()).containsExactly(3); assertThat(line4.getDuplicationList()).containsExactly(3); } @Test public void read_duplication_with_duplicates_on_other_file() { DuplicationLineReader reader = duplicationLineReader( duplication( 1, 2, new InProjectDuplicate(fileComponent(1).build(), new TextBlock(3, 4)))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1); assertThat(line2.getDuplicationList()).containsExactly(1); assertThat(line3.getDuplicationList()).isEmpty(); assertThat(line4.getDuplicationList()).isEmpty(); } @Test public void read_duplication_with_duplicates_on_other_file_from_other_project() { DuplicationLineReader reader = duplicationLineReader( duplication( 1, 2, new CrossProjectDuplicate("other-component-key-from-another-project", new TextBlock(3, 4)))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1); assertThat(line2.getDuplicationList()).containsExactly(1); assertThat(line3.getDuplicationList()).isEmpty(); assertThat(line4.getDuplicationList()).isEmpty(); } @Test public void read_many_duplications() { DuplicationLineReader reader = duplicationLineReader( duplication( 1, 1, innerDuplicate(2, 2)), duplication( 1, 2, innerDuplicate(3, 4))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1, 2); assertThat(line2.getDuplicationList()).containsExactly(2, 3); assertThat(line3.getDuplicationList()).containsExactly(4); assertThat(line4.getDuplicationList()).containsExactly(4); } @Test public void should_be_sorted_by_line_block() { DuplicationLineReader reader = duplicationLineReader( duplication( 2, 2, innerDuplicate(4, 4)), duplication( 1, 1, innerDuplicate(3, 3))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1); assertThat(line2.getDuplicationList()).containsExactly(2); assertThat(line3.getDuplicationList()).containsExactly(3); assertThat(line4.getDuplicationList()).containsExactly(4); } @Test public void should_be_sorted_by_line_length() { DuplicationLineReader reader = duplicationLineReader( duplication( 1, 2, innerDuplicate(3, 4)), duplication( 1, 1, innerDuplicate(4, 4))); assertThat(reader.read(line1)).isEmpty(); assertThat(reader.read(line2)).isEmpty(); assertThat(reader.read(line3)).isEmpty(); assertThat(reader.read(line4)).isEmpty(); assertThat(line1.getDuplicationList()).containsExactly(1, 2); assertThat(line2.getDuplicationList()).containsExactly(2); assertThat(line3.getDuplicationList()).containsExactly(3); assertThat(line4.getDuplicationList()).containsExactly(3, 4); } private static ReportComponent.Builder fileComponent(int ref) { return ReportComponent.builder(Component.Type.FILE, ref); } private static DuplicationLineReader duplicationLineReader(Duplication... duplications) { return new DuplicationLineReader(ImmutableSet.copyOf(Arrays.asList(duplications))); } private static Duplication duplication(int originalStart, int originalEnd, Duplicate... duplicates) { return new Duplication(new TextBlock(originalStart, originalEnd), Arrays.asList(duplicates)); } private static InnerDuplicate innerDuplicate(int start, int end) { return new InnerDuplicate(new TextBlock(start, end)); } }
7,798
37.418719
103
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/linereader/HighlightingLineReaderTest.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.source.linereader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Random; 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.component.Component; import org.sonar.ce.task.projectanalysis.source.linereader.RangeOffsetConverter.RangeOffsetConverterException; import org.sonar.db.protobuf.DbFileSources; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType; import org.sonar.scanner.protocol.output.ScannerReport.TextRange; import static com.google.common.collect.ImmutableMap.of; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.slf4j.event.Level.DEBUG; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.HIGHLIGHTING; import static org.sonar.db.protobuf.DbFileSources.Data.newBuilder; import static org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType.ANNOTATION; import static org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType.COMMENT; import static org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType.CONSTANT; import static org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType.HIGHLIGHTING_STRING; import static org.sonar.scanner.protocol.output.ScannerReport.SyntaxHighlightingRule.HighlightingType.KEYWORD; public class HighlightingLineReaderTest { @Rule public LogTester logTester = new LogTester(); private static final Component FILE = builder(Component.Type.FILE, 1).setUuid("FILE_UUID").setKey("FILE_KEY").build(); private static final int DEFAULT_LINE_LENGTH = 5; private static final int LINE_1 = 1; private static final int LINE_2 = 2; private static final int LINE_3 = 3; private static final int LINE_4 = 4; private static final String RANGE_LABEL_1 = "1,2"; private static final String RANGE_LABEL_2 = "2,3"; private static final String RANGE_LABEL_3 = "3,4"; private static final String RANGE_LABEL_4 = "0,2"; private static final String RANGE_LABEL_5 = "0,3"; private RangeOffsetConverter rangeOffsetConverter = mock(RangeOffsetConverter.class); private DbFileSources.Data.Builder sourceData = newBuilder(); private DbFileSources.Line.Builder line1 = sourceData.addLinesBuilder().setSource("line1").setLine(1); private DbFileSources.Line.Builder line2 = sourceData.addLinesBuilder().setSource("line2").setLine(2); private DbFileSources.Line.Builder line3 = sourceData.addLinesBuilder().setSource("line3").setLine(3); private DbFileSources.Line.Builder line4 = sourceData.addLinesBuilder().setSource("line4").setLine(4); @Before public void before() { logTester.setLevel(Level.TRACE); } @Test public void nothing_to_read() { HighlightingLineReader highlightingLineReader = newReader(Collections.emptyMap()); DbFileSources.Line.Builder lineBuilder = newBuilder().addLinesBuilder().setLine(1); assertThat(highlightingLineReader.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.hasHighlighting()).isFalse(); } @Test public void read_one_line() { HighlightingLineReader highlightingLineReader = newReader(of( newSingleLineTextRangeWithExpectingLabel(LINE_1, RANGE_LABEL_1), ANNOTATION)); assertThat(highlightingLineReader.read(line1)).isEmpty(); assertThat(line1.getHighlighting()).isEqualTo(RANGE_LABEL_1 + ",a"); } @Test public void read_many_lines() { HighlightingLineReader highlightingLineReader = newReader(of( newSingleLineTextRangeWithExpectingLabel(LINE_1, RANGE_LABEL_1), ANNOTATION, newSingleLineTextRangeWithExpectingLabel(LINE_2, RANGE_LABEL_2), COMMENT, newSingleLineTextRangeWithExpectingLabel(LINE_4, RANGE_LABEL_3), CONSTANT)); assertThat(highlightingLineReader.read(line1)).isEmpty(); assertThat(highlightingLineReader.read(line2)).isEmpty(); assertThat(highlightingLineReader.read(line3)).isEmpty(); assertThat(highlightingLineReader.read(line4)).isEmpty(); assertThat(line1.getHighlighting()).isEqualTo(RANGE_LABEL_1 + ",a"); assertThat(line2.getHighlighting()).isEqualTo(RANGE_LABEL_2 + ",cd"); assertThat(line4.getHighlighting()).isEqualTo(RANGE_LABEL_3 + ",c"); } @Test public void supports_highlighting_over_multiple_lines_including_an_empty_one() { List<ScannerReport.SyntaxHighlightingRule> syntaxHighlightingList = new ArrayList<>(); addHighlighting(syntaxHighlightingList, 1, 0, 1, 7, KEYWORD); // package addHighlighting(syntaxHighlightingList, 2, 0, 4, 6, COMMENT); // comment over 3 lines addHighlighting(syntaxHighlightingList, 5, 0, 5, 6, KEYWORD); // public addHighlighting(syntaxHighlightingList, 5, 7, 5, 12, KEYWORD); // class HighlightingLineReader highlightingLineReader = new HighlightingLineReader(FILE, syntaxHighlightingList.iterator(), new RangeOffsetConverter()); DbFileSources.Line.Builder[] builders = new DbFileSources.Line.Builder[] { addSourceLine(highlightingLineReader, 1, "package example;"), addSourceLine(highlightingLineReader, 2, "/*"), addSourceLine(highlightingLineReader, 3, ""), addSourceLine(highlightingLineReader, 4, " foo*/"), addSourceLine(highlightingLineReader, 5, "public class One {"), addSourceLine(highlightingLineReader, 6, "}") }; assertThat(builders) .extracting("highlighting") .containsExactly( "0,7,k", "0,2,cd", "", "0,6,cd", "0,6,k;7,12,k", ""); } private DbFileSources.Line.Builder addSourceLine(HighlightingLineReader highlightingLineReader, int line, String source) { DbFileSources.Line.Builder lineBuilder = sourceData.addLinesBuilder().setSource(source).setLine(line); assertThat(highlightingLineReader.read(lineBuilder)).isEmpty(); return lineBuilder; } private void addHighlighting(List<ScannerReport.SyntaxHighlightingRule> syntaxHighlightingList, int startLine, int startOffset, int endLine, int endOffset, HighlightingType type) { TextRange.Builder textRangeBuilder = TextRange.newBuilder(); ScannerReport.SyntaxHighlightingRule.Builder ruleBuilder = ScannerReport.SyntaxHighlightingRule.newBuilder(); syntaxHighlightingList.add(ruleBuilder .setRange(textRangeBuilder .setStartLine(startLine).setEndLine(endLine) .setStartOffset(startOffset).setEndOffset(endOffset) .build()) .setType(type) .build()); } @Test public void read_many_syntax_highlighting_on_same_line() { HighlightingLineReader highlightingLineReader = newReader(of( newSingleLineTextRangeWithExpectingLabel(LINE_1, RANGE_LABEL_1), ANNOTATION, newSingleLineTextRangeWithExpectingLabel(LINE_1, RANGE_LABEL_2), COMMENT)); assertThat(highlightingLineReader.read(line1)).isEmpty(); assertThat(line1.getHighlighting()).isEqualTo(RANGE_LABEL_1 + ",a;" + RANGE_LABEL_2 + ",cd"); } @Test public void read_one_syntax_highlighting_on_many_lines() { // This highlighting begin on line 1 and finish on line 3 TextRange textRange = newTextRange(LINE_1, LINE_3); when(rangeOffsetConverter.offsetToString(textRange, LINE_1, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1); when(rangeOffsetConverter.offsetToString(textRange, LINE_2, 6)).thenReturn(RANGE_LABEL_2); when(rangeOffsetConverter.offsetToString(textRange, LINE_3, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_3); HighlightingLineReader highlightingLineReader = newReader(of(textRange, ANNOTATION)); assertThat(highlightingLineReader.read(line1)).isEmpty(); DbFileSources.Line.Builder line2 = sourceData.addLinesBuilder().setSource("line 2").setLine(2); assertThat(highlightingLineReader.read(line2)).isEmpty(); assertThat(highlightingLineReader.read(line3)).isEmpty(); assertThat(line1.getHighlighting()).isEqualTo(RANGE_LABEL_1 + ",a"); assertThat(line2.getHighlighting()).isEqualTo(RANGE_LABEL_2 + ",a"); assertThat(line3.getHighlighting()).isEqualTo(RANGE_LABEL_3 + ",a"); } @Test public void read_many_syntax_highlighting_on_many_lines() { TextRange textRange1 = newTextRange(LINE_1, LINE_3); when(rangeOffsetConverter.offsetToString(textRange1, LINE_1, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1); when(rangeOffsetConverter.offsetToString(textRange1, LINE_2, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_2); when(rangeOffsetConverter.offsetToString(textRange1, LINE_3, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_3); TextRange textRange2 = newTextRange(LINE_2, LINE_4); when(rangeOffsetConverter.offsetToString(textRange2, LINE_2, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_2); when(rangeOffsetConverter.offsetToString(textRange2, LINE_3, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_2); when(rangeOffsetConverter.offsetToString(textRange2, LINE_4, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_4); TextRange textRange3 = newTextRange(LINE_2, LINE_2); when(rangeOffsetConverter.offsetToString(textRange3, LINE_2, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_5); HighlightingLineReader highlightingLineReader = newReader(of( textRange1, ANNOTATION, textRange2, HIGHLIGHTING_STRING, textRange3, COMMENT)); assertThat(highlightingLineReader.read(line1)).isEmpty(); assertThat(highlightingLineReader.read(line2)).isEmpty(); assertThat(highlightingLineReader.read(line3)).isEmpty(); assertThat(highlightingLineReader.read(line4)).isEmpty(); assertThat(line1.getHighlighting()).isEqualTo(RANGE_LABEL_1 + ",a"); assertThat(line2.getHighlighting()).isEqualTo(RANGE_LABEL_2 + ",a;" + RANGE_LABEL_2 + ",s;" + RANGE_LABEL_5 + ",cd"); assertThat(line3.getHighlighting()).isEqualTo(RANGE_LABEL_3 + ",a;" + RANGE_LABEL_2 + ",s"); assertThat(line4.getHighlighting()).isEqualTo(RANGE_LABEL_4 + ",s"); } @Test public void read_highlighting_declared_on_a_whole_line() { TextRange textRange = newTextRange(LINE_1, LINE_2); when(rangeOffsetConverter.offsetToString(textRange, LINE_1, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1); when(rangeOffsetConverter.offsetToString(textRange, LINE_2, DEFAULT_LINE_LENGTH)).thenReturn(""); HighlightingLineReader highlightingLineReader = newReader(of(textRange, ANNOTATION)); assertThat(highlightingLineReader.read(line1)).isEmpty(); assertThat(highlightingLineReader.read(line2)).isEmpty(); assertThat(highlightingLineReader.read(line3)).isEmpty(); assertThat(line1.getHighlighting()).isEqualTo(RANGE_LABEL_1 + ",a"); // Nothing should be set on line 2 assertThat(line2.getHighlighting()).isEmpty(); assertThat(line3.getHighlighting()).isEmpty(); } @Test public void not_fail_and_stop_processing_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange textRange1 = newTextRange(LINE_1, LINE_1); doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange1, LINE_1, DEFAULT_LINE_LENGTH); HighlightingLineReader highlightingLineReader = newReader(of( textRange1, HighlightingType.ANNOTATION, newSingleLineTextRangeWithExpectingLabel(LINE_2, RANGE_LABEL_1), HIGHLIGHTING_STRING)); LineReader.ReadError readErrorLine1 = new LineReader.ReadError(HIGHLIGHTING, LINE_1); assertThat(highlightingLineReader.read(line1)).contains(readErrorLine1); assertThat(highlightingLineReader.read(line2)).contains(readErrorLine1); assertNoHighlighting(); assertThat(logTester.logs(DEBUG)).isNotEmpty(); } @Test public void keep_existing_processed_highlighting_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange textRange2 = newTextRange(LINE_2, LINE_2); doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange2, LINE_2, DEFAULT_LINE_LENGTH); TextRange textRange3 = newTextRange(LINE_3, LINE_3); HighlightingLineReader highlightingLineReader = newReader(of( newSingleLineTextRangeWithExpectingLabel(LINE_1, RANGE_LABEL_1), ANNOTATION, textRange2, HIGHLIGHTING_STRING, textRange3, COMMENT)); assertThat(highlightingLineReader.read(line1)).isEmpty(); LineReader.ReadError readErrorLine2 = new LineReader.ReadError(HIGHLIGHTING, LINE_2); assertThat(highlightingLineReader.read(line2)).contains(readErrorLine2); assertThat(highlightingLineReader.read(line3)).contains(readErrorLine2); assertThat(line1.hasHighlighting()).isTrue(); assertThat(line2.hasHighlighting()).isFalse(); assertThat(line3.hasHighlighting()).isFalse(); assertThat(logTester.logs(DEBUG)).isNotEmpty(); } @Test public void display_file_key_in_debug_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange textRange1 = newTextRange(LINE_1, LINE_1); doThrow(RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(textRange1, LINE_1, DEFAULT_LINE_LENGTH); HighlightingLineReader highlightingLineReader = newReader(of(textRange1, ANNOTATION)); assertThat(highlightingLineReader.read(line1)) .contains(new LineReader.ReadError(HIGHLIGHTING, 1)); assertThat(logTester.logs(DEBUG)).containsOnly("Inconsistency detected in Highlighting data. Highlighting will be ignored for file 'FILE_KEY'"); } private HighlightingLineReader newReader(Map<TextRange, HighlightingType> textRangeByType) { List<ScannerReport.SyntaxHighlightingRule> syntaxHighlightingList = new ArrayList<>(); for (Map.Entry<TextRange, HighlightingType> entry : textRangeByType.entrySet()) { syntaxHighlightingList.add(ScannerReport.SyntaxHighlightingRule.newBuilder() .setRange(entry.getKey()) .setType(entry.getValue()) .build()); } return new HighlightingLineReader(FILE, syntaxHighlightingList.iterator(), rangeOffsetConverter); } private static TextRange newTextRange(int startLine, int enLine) { Random random = new Random(); return TextRange.newBuilder() .setStartLine(startLine).setEndLine(enLine) // Offsets are not used by the reader .setStartOffset(random.nextInt()).setEndOffset(random.nextInt()) .build(); } private TextRange newSingleLineTextRangeWithExpectingLabel(int line, String rangeLabel) { TextRange textRange = newTextRange(line, line); when(rangeOffsetConverter.offsetToString(textRange, line, DEFAULT_LINE_LENGTH)).thenReturn(rangeLabel); return textRange; } private void assertNoHighlighting() { assertThat(line1.hasHighlighting()).isFalse(); assertThat(line2.hasHighlighting()).isFalse(); assertThat(line3.hasHighlighting()).isFalse(); assertThat(line4.hasHighlighting()).isFalse(); } }
16,086
46.454277
148
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/linereader/IsNewLineReaderTest.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.source.linereader; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.junit.Test; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.source.NewLinesRepository; import org.sonar.db.protobuf.DbFileSources; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class IsNewLineReaderTest { private NewLinesRepository repository = mock(NewLinesRepository.class); private Component component = mock(Component.class); @Test public void should_set_isNewLines_in_builder() { Set<Integer> newLines = new HashSet<>(Arrays.asList(1, 3)); when(repository.getNewLines(component)).thenReturn(Optional.of(newLines)); IsNewLineReader reader = new IsNewLineReader(repository, component); DbFileSources.Line.Builder[] builders = runReader(reader); assertThat(builders[0].getIsNewLine()).isTrue(); assertThat(builders[1].getIsNewLine()).isFalse(); assertThat(builders[2].getIsNewLine()).isTrue(); } @Test public void should_set_isNewLines_false_if_no_new_lines_available() { when(repository.getNewLines(component)).thenReturn(Optional.empty()); IsNewLineReader reader = new IsNewLineReader(repository, component); DbFileSources.Line.Builder[] builders = runReader(reader); assertThat(builders[0].getIsNewLine()).isFalse(); assertThat(builders[1].getIsNewLine()).isFalse(); assertThat(builders[2].getIsNewLine()).isFalse(); } private DbFileSources.Line.Builder[] runReader(LineReader reader) { DbFileSources.Line.Builder[] builders = new DbFileSources.Line.Builder[3]; for (int i = 1; i <= 3; i++) { builders[i - 1] = DbFileSources.Line.newBuilder() .setLine(i); reader.read(builders[i - 1]); } return builders; } }
2,802
36.373333
78
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/linereader/ScmLineReaderTest.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.source.linereader; import org.junit.Test; import org.sonar.ce.task.projectanalysis.scm.Changeset; import org.sonar.ce.task.projectanalysis.scm.ScmInfo; import org.sonar.ce.task.projectanalysis.scm.ScmInfoImpl; import org.sonar.db.protobuf.DbFileSources; import static org.assertj.core.api.Assertions.assertThat; public class ScmLineReaderTest { @Test public void set_scm() { ScmInfo scmInfo = new ScmInfoImpl(new Changeset[] { Changeset.newChangesetBuilder() .setAuthor("john") .setDate(123_456_789L) .setRevision("rev-1") .build()}); ScmLineReader lineScm = new ScmLineReader(scmInfo); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(lineScm.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.getScmAuthor()).isEqualTo("john"); assertThat(lineBuilder.getScmDate()).isEqualTo(123_456_789L); assertThat(lineBuilder.getScmRevision()).isEqualTo("rev-1"); } @Test public void set_scm_with_minim_fields() { ScmInfo scmInfo = new ScmInfoImpl(new Changeset[] { Changeset.newChangesetBuilder() .setDate(123456789L) .build()}); ScmLineReader lineScm = new ScmLineReader(scmInfo); DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(1); assertThat(lineScm.read(lineBuilder)).isEmpty(); assertThat(lineBuilder.hasScmAuthor()).isFalse(); assertThat(lineBuilder.getScmDate()).isEqualTo(123456789L); assertThat(lineBuilder.hasScmRevision()).isFalse(); } @Test public void getLatestChange_returns_changeset_with_highest_date_of_read_lines() { long refDate = 123_456_789L; Changeset changeset0 = Changeset.newChangesetBuilder().setDate(refDate - 636).setRevision("rev-1").build(); Changeset changeset1 = Changeset.newChangesetBuilder().setDate(refDate + 1).setRevision("rev-2").build(); Changeset changeset2 = Changeset.newChangesetBuilder().setDate(refDate + 2).build(); ScmInfo scmInfo = new ScmInfoImpl(setup8LinesChangeset(changeset0, changeset1, changeset2)); ScmLineReader lineScm = new ScmLineReader(scmInfo); // before any line is read, the latest changes are null assertThat(lineScm.getLatestChange()).isNull(); assertThat(lineScm.getLatestChangeWithRevision()).isNull(); // read line 1, only one changeset => 0 readLineAndAssertLatestChanges(lineScm, 1, changeset0, changeset0); // read line 2, latest changeset is 1 readLineAndAssertLatestChanges(lineScm, 2, changeset1, changeset1); // read line 3, latest changeset is still 1 readLineAndAssertLatestChanges(lineScm, 3, changeset1, changeset1); // read line 4, latest changeset is now 2 readLineAndAssertLatestChanges(lineScm, 4, changeset2, changeset1); // read line 5 to 8, there will never be any changeset more recent than 2 readLineAndAssertLatestChanges(lineScm, 5, changeset2, changeset1); readLineAndAssertLatestChanges(lineScm, 6, changeset2, changeset1); readLineAndAssertLatestChanges(lineScm, 7, changeset2, changeset1); readLineAndAssertLatestChanges(lineScm, 8, changeset2, changeset1); } private static Changeset[] setup8LinesChangeset(Changeset changeset0, Changeset changeset1, Changeset changeset2) { return new Changeset[] { changeset0, changeset1, changeset1, changeset2, changeset0, changeset1, changeset0, changeset0}; } private void readLineAndAssertLatestChanges(ScmLineReader lineScm, int line, Changeset expectedChangeset, Changeset expectedChangesetWithRevision) { DbFileSources.Line.Builder lineBuilder = DbFileSources.Data.newBuilder().addLinesBuilder().setLine(line); assertThat(lineScm.read(lineBuilder)).isEmpty(); assertThat(lineScm.getLatestChange()).isSameAs(expectedChangeset); assertThat(lineScm.getLatestChangeWithRevision()).isSameAs(expectedChangesetWithRevision); } }
4,877
38.658537
150
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/source/linereader/SymbolsLineReaderTest.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.source.linereader; import java.util.Arrays; import org.junit.Rule; import org.junit.Test; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.db.protobuf.DbFileSources; import org.sonar.scanner.protocol.output.ScannerReport; import org.sonar.scanner.protocol.output.ScannerReport.TextRange; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.slf4j.event.Level.WARN; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; import static org.sonar.ce.task.projectanalysis.source.linereader.LineReader.Data.SYMBOLS; public class SymbolsLineReaderTest { @Rule public LogTester logTester = new LogTester(); private static final Component FILE = builder(Component.Type.FILE, 1).setUuid("FILE_UUID").setKey("FILE_KEY").build(); private static final int DEFAULT_LINE_LENGTH = 5; private static final int LINE_1 = 1; private static final int LINE_2 = 2; private static final int LINE_3 = 3; private static final int LINE_4 = 4; private static final int OFFSET_0 = 0; private static final int OFFSET_1 = 1; private static final int OFFSET_2 = 2; private static final int OFFSET_3 = 3; private static final int OFFSET_4 = 4; private static final String RANGE_LABEL_1 = "1,2"; private static final String RANGE_LABEL_2 = "2,3"; private static final String RANGE_LABEL_3 = "3,4"; private static final String RANGE_LABEL_4 = "0,2"; private RangeOffsetConverter rangeOffsetConverter = mock(RangeOffsetConverter.class); private DbFileSources.Data.Builder sourceData = DbFileSources.Data.newBuilder(); private DbFileSources.Line.Builder line1 = sourceData.addLinesBuilder().setSource("line1").setLine(1); private DbFileSources.Line.Builder line2 = sourceData.addLinesBuilder().setSource("line2").setLine(2); private DbFileSources.Line.Builder line3 = sourceData.addLinesBuilder().setSource("line3").setLine(3); private DbFileSources.Line.Builder line4 = sourceData.addLinesBuilder().setSource("line4").setLine(4); @Test public void read_nothing() { SymbolsLineReader symbolsLineReader = newReader(); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(line1.getSymbols()).isEmpty(); } @Test public void read_symbols() { SymbolsLineReader symbolsLineReader = newReader(newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_2, OFFSET_4, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_1, OFFSET_3, RANGE_LABEL_2))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(symbolsLineReader.read(line3)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line2.getSymbols()).isEmpty(); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1"); } @Test public void read_symbols_with_reference_on_same_line() { SymbolsLineReader symbolsLineReader = newReader(newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_0, OFFSET_1, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_2, OFFSET_3, RANGE_LABEL_2))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1;" + RANGE_LABEL_2 + ",1"); } @Test public void read_symbols_with_two_references() { SymbolsLineReader symbolsLineReader = newReader(newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_2, OFFSET_4, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_1, OFFSET_3, RANGE_LABEL_2), newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_0, OFFSET_2, RANGE_LABEL_3))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(symbolsLineReader.read(line3)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line2.getSymbols()).isEqualTo(RANGE_LABEL_3 + ",1"); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1"); } @Test public void read_symbols_with_two_references_on_the_same_line() { SymbolsLineReader symbolsLineReader = newReader(newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_2, OFFSET_3, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_0, OFFSET_1, RANGE_LABEL_2), newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_2, OFFSET_3, RANGE_LABEL_3))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line2.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1;" + RANGE_LABEL_3 + ",1"); } @Test public void read_symbols_when_reference_line_is_before_declaration_line() { SymbolsLineReader symbolsLineReader = newReader(newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_3, OFFSET_4, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_1, OFFSET_2, RANGE_LABEL_2))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1"); assertThat(line2.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); } @Test public void read_many_symbols_on_lines() { SymbolsLineReader symbolsLineReader = newReader( newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_1, OFFSET_2, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_2, OFFSET_3, RANGE_LABEL_2)), newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_3, OFFSET_4, RANGE_LABEL_3), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_0, OFFSET_1, RANGE_LABEL_4))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(symbolsLineReader.read(line3)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1;" + RANGE_LABEL_3 + ",2"); assertThat(line2.getSymbols()).isEmpty(); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1;" + RANGE_LABEL_4 + ",2"); } @Test public void symbol_declaration_should_be_sorted_by_offset() { SymbolsLineReader symbolsLineReader = newReader( newSymbol( // This symbol begins after the second symbol, it should appear in second place newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_2, OFFSET_3, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_2, OFFSET_3, RANGE_LABEL_1)), newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_0, OFFSET_1, RANGE_LABEL_2), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_0, OFFSET_1, RANGE_LABEL_2))); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(symbolsLineReader.read(line3)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1;" + RANGE_LABEL_1 + ",2"); assertThat(line2.getSymbols()).isEmpty(); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1;" + RANGE_LABEL_1 + ",2"); } @Test public void symbol_declaration_should_be_sorted_by_line() { SymbolsLineReader symbolsLineReader = newReader( newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_0, OFFSET_1, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_2, OFFSET_3, RANGE_LABEL_2)), newSymbol( newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_0, OFFSET_1, RANGE_LABEL_1), newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_0, OFFSET_1, RANGE_LABEL_1))); assertThat(symbolsLineReader.read(line1)).isEmpty(); symbolsLineReader.read(line2); symbolsLineReader.read(line3); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line2.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",2"); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1;" + RANGE_LABEL_2 + ",2"); } @Test public void read_symbols_defined_on_many_lines() { TextRange declaration = newTextRange(LINE_1, LINE_2, OFFSET_1, OFFSET_3); when(rangeOffsetConverter.offsetToString(declaration, LINE_1, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1); when(rangeOffsetConverter.offsetToString(declaration, LINE_2, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_2); TextRange reference = newTextRange(LINE_3, LINE_4, OFFSET_1, OFFSET_3); when(rangeOffsetConverter.offsetToString(reference, LINE_3, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1); when(rangeOffsetConverter.offsetToString(reference, LINE_4, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_2); SymbolsLineReader symbolsLineReader = newReader(newSymbol(declaration, reference)); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(symbolsLineReader.read(line3)).isEmpty(); assertThat(symbolsLineReader.read(line4)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line2.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1"); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line4.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1"); } @Test public void read_symbols_declared_on_a_whole_line() { TextRange declaration = newTextRange(LINE_1, LINE_2, OFFSET_0, OFFSET_0); when(rangeOffsetConverter.offsetToString(declaration, LINE_1, DEFAULT_LINE_LENGTH)).thenReturn(RANGE_LABEL_1); when(rangeOffsetConverter.offsetToString(declaration, LINE_2, DEFAULT_LINE_LENGTH)).thenReturn(""); TextRange reference = newSingleLineTextRangeWithExpectedLabel(LINE_3, OFFSET_1, OFFSET_3, RANGE_LABEL_2); SymbolsLineReader symbolsLineReader = newReader(newSymbol(declaration, reference)); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).isEmpty(); assertThat(symbolsLineReader.read(line3)).isEmpty(); assertThat(symbolsLineReader.read(line4)).isEmpty(); assertThat(line1.getSymbols()).isEqualTo(RANGE_LABEL_1 + ",1"); assertThat(line2.getSymbols()).isEmpty(); assertThat(line3.getSymbols()).isEqualTo(RANGE_LABEL_2 + ",1"); assertThat(line4.getSymbols()).isEmpty(); } @Test public void not_fail_and_stop_processing_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange declaration = newTextRange(LINE_1, LINE_1, OFFSET_1, OFFSET_3); doThrow(RangeOffsetConverter.RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(declaration, LINE_1, DEFAULT_LINE_LENGTH); TextRange reference = newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_1, OFFSET_3, RANGE_LABEL_2); SymbolsLineReader symbolsLineReader = newReader(newSymbol(declaration, reference)); LineReader.ReadError readErrorLine1 = new LineReader.ReadError(SYMBOLS, LINE_1); assertThat(symbolsLineReader.read(line1)).contains(readErrorLine1); assertThat(symbolsLineReader.read(line2)).contains(readErrorLine1); assertNoSymbol(); assertThat(logTester.logs(WARN)).isNotEmpty(); } @Test public void keep_existing_processed_symbols_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange declaration = newSingleLineTextRangeWithExpectedLabel(LINE_1, OFFSET_1, OFFSET_3, RANGE_LABEL_2); TextRange reference = newTextRange(LINE_2, LINE_2, OFFSET_1, OFFSET_3); doThrow(RangeOffsetConverter.RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(reference, LINE_2, DEFAULT_LINE_LENGTH); SymbolsLineReader symbolsLineReader = newReader(newSymbol(declaration, reference)); assertThat(symbolsLineReader.read(line1)).isEmpty(); assertThat(symbolsLineReader.read(line2)).contains(new LineReader.ReadError(SYMBOLS, LINE_2)); assertThat(line1.hasSymbols()).isTrue(); assertThat(line2.hasSymbols()).isFalse(); assertThat(logTester.logs(WARN)).isNotEmpty(); } @Test public void display_file_key_in_warning_when_range_offset_converter_throw_RangeOffsetConverterException() { TextRange declaration = newTextRange(LINE_1, LINE_1, OFFSET_1, OFFSET_3); doThrow(RangeOffsetConverter.RangeOffsetConverterException.class).when(rangeOffsetConverter).offsetToString(declaration, LINE_1, DEFAULT_LINE_LENGTH); SymbolsLineReader symbolsLineReader = newReader(newSymbol(declaration, newSingleLineTextRangeWithExpectedLabel(LINE_2, OFFSET_1, OFFSET_3, RANGE_LABEL_2))); assertThat(symbolsLineReader.read(line1)) .contains(new LineReader.ReadError(SYMBOLS, LINE_1)); assertThat(logTester.logs(WARN)).containsOnly("Inconsistency detected in Symbols data. Symbols will be ignored for file 'FILE_KEY'"); } private ScannerReport.Symbol newSymbol(TextRange declaration, TextRange... references) { ScannerReport.Symbol.Builder builder = ScannerReport.Symbol.newBuilder() .setDeclaration(declaration); for (TextRange reference : references) { builder.addReference(reference); } return builder.build(); } private SymbolsLineReader newReader(ScannerReport.Symbol... symbols) { return new SymbolsLineReader(FILE, Arrays.asList(symbols).iterator(), rangeOffsetConverter); } private TextRange newSingleLineTextRangeWithExpectedLabel(int line, int startOffset, int endOffset, String rangeLabel) { TextRange textRange = newTextRange(line, line, startOffset, endOffset); when(rangeOffsetConverter.offsetToString(textRange, line, DEFAULT_LINE_LENGTH)).thenReturn(rangeLabel); return textRange; } private static TextRange newTextRange(int startLine, int endLine, int startOffset, int endOffset) { return TextRange.newBuilder() .setStartLine(startLine).setEndLine(endLine) .setStartOffset(startOffset).setEndOffset(endOffset) .build(); } private void assertNoSymbol() { assertThat(line1.hasSymbols()).isFalse(); assertThat(line2.hasSymbols()).isFalse(); assertThat(line3.hasSymbols()).isFalse(); assertThat(line4.hasSymbols()).isFalse(); } }
15,399
45.52568
160
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ComputeQProfileMeasureStepTest.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.step; import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.Date; import java.util.List; import org.junit.Rule; 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.FileAttributes; 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.server.qualityprofile.QPMeasureData; import org.sonar.server.qualityprofile.QualityProfile; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES; import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_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; public class ComputeQProfileMeasureStepTest { private static final String QP_NAME_1 = "qp1"; private static final String QP_NAME_2 = "qp1"; private static final String LANGUAGE_KEY_1 = "java"; private static final String LANGUAGE_KEY_2 = "php"; private static final String PROJECT_KEY = "PROJECT KEY"; private static final int PROJECT_REF = 1; private static final int FOLDER_1_REF = 1111; private static final int FOLDER_2_REF = 1112; private static final int FILE_1_1_REF = 11111; private static final int FILE_1_2_REF = 11112; private static final int FILE_2_1_REF = 11121; private static final int FILE_2_2_REF = 11122; private static final Component MULTI_MODULE_PROJECT = ReportComponent.builder(PROJECT, PROJECT_REF).setKey(PROJECT_KEY) .addChildren(ReportComponent.builder(DIRECTORY, FOLDER_1_REF) .addChildren( ReportComponent.builder(FILE, FILE_1_1_REF).setFileAttributes(new FileAttributes(false, "java", 1)).build(), ReportComponent.builder(FILE, FILE_1_2_REF).setFileAttributes(new FileAttributes(false, "java", 1)).build()) .build(), ReportComponent.builder(DIRECTORY, FOLDER_2_REF) .addChildren( ReportComponent.builder(FILE, FILE_2_1_REF).setFileAttributes(new FileAttributes(false, null, 1)).build(), ReportComponent.builder(FILE, FILE_2_2_REF).setFileAttributes(new FileAttributes(false, "php", 1)).build()) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule().add(QUALITY_PROFILES); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private ComputeQProfileMeasureStep underTest = new ComputeQProfileMeasureStep(treeRootHolder, measureRepository, metricRepository, analysisMetadataHolder); @Test public void add_quality_profile_measure_on_project() { treeRootHolder.setRoot(MULTI_MODULE_PROJECT); QualityProfile qpJava = createQProfile(QP_NAME_1, LANGUAGE_KEY_1); QualityProfile qpPhp = createQProfile(QP_NAME_2, LANGUAGE_KEY_2); analysisMetadataHolder.setQProfilesByLanguage(ImmutableMap.of(LANGUAGE_KEY_1, qpJava, LANGUAGE_KEY_2, qpPhp)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasures(PROJECT_REF).get(QUALITY_PROFILES_KEY)) .extracting("data").isEqualTo(toJson(qpJava, qpPhp)); } @Test public void nothing_to_add_when_no_files() { ReportComponent project = ReportComponent.builder(PROJECT, PROJECT_REF).build(); treeRootHolder.setRoot(project); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasures(PROJECT_REF)).isEmpty(); } @Test public void fail_if_report_inconsistent() { treeRootHolder.setRoot(MULTI_MODULE_PROJECT); QualityProfile qpJava = createQProfile(QP_NAME_1, LANGUAGE_KEY_1); analysisMetadataHolder.setQProfilesByLanguage(ImmutableMap.of(LANGUAGE_KEY_1, qpJava)); try { underTest.execute(new TestComputationStepContext()); fail("Expected exception"); } catch (Exception e) { assertThat(e).hasCause(new IllegalStateException("Report contains a file with language 'php' but no matching quality profile")); } } private static QualityProfile createQProfile(String qpName, String languageKey) { return new QualityProfile(qpName + "-" + languageKey, qpName, languageKey, new Date()); } private static String toJson(QualityProfile... qps) { List<QualityProfile> qualityProfiles = Arrays.asList(qps); return QPMeasureData.toJson(new QPMeasureData(qualityProfiles)); } }
6,065
42.640288
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/DuplicationMeasuresStepTest.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.step; import org.junit.Test; import org.sonar.ce.task.projectanalysis.duplication.DuplicationMeasures; import org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class DuplicationMeasuresStepTest extends BaseStepTest { private DuplicationMeasures defaultDuplicationMeasures = mock(DuplicationMeasures.class); private DuplicationMeasuresStep underTest = new DuplicationMeasuresStep(defaultDuplicationMeasures); @Test public void full_analysis_mode() { underTest.execute(new TestComputationStepContext()); verify(defaultDuplicationMeasures).execute(); } @Override protected ComputationStep step() { return underTest; } }
1,674
34.638298
102
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ExecuteVisitorsStepTest.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.step; import java.util.List; 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.api.utils.log.LoggerLevel; import org.sonar.ce.task.ChangeLogLevel; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ComponentVisitor; import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit; import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitorAdapter; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.step.TestComputationStepContext; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.assertj.core.api.Assertions.assertThat; 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.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; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; public class ExecuteVisitorsStepTest { private static final String TEST_METRIC_KEY = "test"; private static final int ROOT_REF = 1; private static final int DIRECTORY_REF = 123; private static final int FILE_1_REF = 1231; private static final int FILE_2_REF = 1232; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add("1", NCLOC) .add(new MetricImpl("2", TEST_METRIC_KEY, "name", Metric.MetricType.INT)); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public LogTester logTester = new LogTester(); @Before public void setUp() throws Exception { logTester.setLevel(Level.DEBUG); treeRootHolder.setRoot( builder(PROJECT, ROOT_REF).setKey("project") .addChildren( builder(DIRECTORY, DIRECTORY_REF).setKey("directory") .addChildren( builder(FILE, FILE_1_REF).setKey("file1").build(), builder(FILE, FILE_2_REF).setKey("file2").build()) .build()) .build()); } @Test public void execute_with_type_aware_visitor() { ExecuteVisitorsStep underStep = new ExecuteVisitorsStep(treeRootHolder, singletonList(new TestTypeAwareVisitor())); measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(DIRECTORY_REF, NCLOC_KEY, newMeasureBuilder().create(3)); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(3)); underStep.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(2); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(3); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(4); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(4); } @Test public void execute_with_path_aware_visitor() { ExecuteVisitorsStep underTest = new ExecuteVisitorsStep(treeRootHolder, singletonList(new TestPathAwareVisitor())); measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(1)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_METRIC_KEY).get().getIntValue()).isOne(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_METRIC_KEY).get().getIntValue()).isOne(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(2); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_METRIC_KEY).get().getIntValue()).isEqualTo(2); } @Test public void execute_logs_at_info_level_all_execution_duration_of_all_visitors() { try (ChangeLogLevel executor = new ChangeLogLevel(ExecuteVisitorsStep.class, LoggerLevel.DEBUG); ChangeLogLevel step1 = new ChangeLogLevel(VisitorA.class, LoggerLevel.DEBUG); ChangeLogLevel step2 = new ChangeLogLevel(VisitorB.class, LoggerLevel.DEBUG); ChangeLogLevel step3 = new ChangeLogLevel(VisitorB.class, LoggerLevel.DEBUG)) { ExecuteVisitorsStep underTest = new ExecuteVisitorsStep( treeRootHolder, asList(new VisitorA(), new VisitorB(), new VisitorC())); underTest.execute(new TestComputationStepContext()); List<String> logs = logTester.logs(Level.DEBUG); assertThat(logs).hasSize(4); assertThat(logs.get(0)).isEqualTo(" Execution time for each component visitor:"); assertThat(logs.get(1)).startsWith(" - VisitorA | time="); assertThat(logs.get(2)).startsWith(" - VisitorB | time="); assertThat(logs.get(3)).startsWith(" - VisitorC | time="); } } private static class VisitorA extends TypeAwareVisitorAdapter { VisitorA() { super(CrawlerDepthLimit.PROJECT, Order.PRE_ORDER); } } private static class VisitorB extends TypeAwareVisitorAdapter { VisitorB() { super(CrawlerDepthLimit.PROJECT, Order.PRE_ORDER); } } private static class VisitorC extends TypeAwareVisitorAdapter { VisitorC() { super(CrawlerDepthLimit.PROJECT, Order.PRE_ORDER); } } private class TestTypeAwareVisitor extends TypeAwareVisitorAdapter { TestTypeAwareVisitor() { super(CrawlerDepthLimit.FILE, ComponentVisitor.Order.POST_ORDER); } @Override public void visitAny(Component any) { int ncloc = measureRepository.getRawMeasure(any, metricRepository.getByKey(NCLOC_KEY)).get().getIntValue(); measureRepository.add(any, metricRepository.getByKey(TEST_METRIC_KEY), newMeasureBuilder().create(ncloc + 1)); } } private class TestPathAwareVisitor extends PathAwareVisitorAdapter<Counter> { TestPathAwareVisitor() { super(CrawlerDepthLimit.FILE, ComponentVisitor.Order.POST_ORDER, new SimpleStackElementFactory<Counter>() { @Override public Counter createForAny(Component component) { return new Counter(); } }); } @Override public void visitProject(Component project, Path<Counter> path) { computeAndSaveMeasures(project, path); } @Override public void visitDirectory(Component directory, Path<Counter> path) { computeAndSaveMeasures(directory, path); } @Override public void visitFile(Component file, Path<Counter> path) { int ncloc = measureRepository.getRawMeasure(file, metricRepository.getByKey(NCLOC_KEY)).get().getIntValue(); path.current().add(ncloc); computeAndSaveMeasures(file, path); } private void computeAndSaveMeasures(Component component, Path<Counter> path) { measureRepository.add(component, metricRepository.getByKey(TEST_METRIC_KEY), newMeasureBuilder().create(path.current().getValue())); increaseParentValue(path); } private void increaseParentValue(Path<Counter> path) { if (!path.isRoot()) { path.parent().add(path.current().getValue()); } } } public static class Counter { private int value = 0; public void add(int value) { this.value += value; } public int getValue() { return value; } } }
9,199
40.071429
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadDuplicationsFromReportStepTest.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.step; import java.util.Arrays; 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.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.component.VisitException; import org.sonar.ce.task.projectanalysis.duplication.DetailedTextBlock; import org.sonar.ce.task.projectanalysis.duplication.Duplicate; import org.sonar.ce.task.projectanalysis.duplication.Duplication; import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepositoryRule; import org.sonar.ce.task.projectanalysis.duplication.InExtendedProjectDuplicate; import org.sonar.ce.task.projectanalysis.duplication.InProjectDuplicate; import org.sonar.ce.task.projectanalysis.duplication.InnerDuplicate; import org.sonar.ce.task.projectanalysis.duplication.TextBlock; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.db.component.BranchType; import org.sonar.scanner.protocol.output.ScannerReport; 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.Component.Type.PROJECT; import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder; public class LoadDuplicationsFromReportStepTest { private static final int LINE = 2; private static final int OTHER_LINE = 300; private static final int ROOT_REF = 1; private static final int FILE_1_REF = 11; private static final int FILE_2_REF = 12; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(FILE, FILE_1_REF).build(), // status has no effect except if it's a PR builder(FILE, FILE_2_REF).setStatus(Component.Status.SAME).build()) .build()); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(treeRootHolder); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private LoadDuplicationsFromReportStep underTest = new LoadDuplicationsFromReportStep(treeRootHolder, analysisMetadataHolder, reportReader, duplicationRepository); @Test public void verify_description() { assertThat(underTest.getDescription()).isEqualTo("Load duplications"); } @Test public void loads_duplication_without_otherFileRef_as_inner_duplication() { reportReader.putDuplications(FILE_2_REF, createDuplication(singleLineTextRange(LINE), createInnerDuplicate(LINE + 1))); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertNoDuplication(FILE_1_REF); assertDuplications(FILE_2_REF, singleLineDetailedTextBlock(1, LINE), new InnerDuplicate(singleLineTextBlock(LINE + 1))); assertNbOfDuplications(context, 1); } @Test public void loads_duplication_with_otherFileRef_as_inProject_duplication() { reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(LINE), createInProjectDuplicate(FILE_2_REF, LINE + 1))); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertDuplications(FILE_1_REF, singleLineDetailedTextBlock(1, LINE), new InProjectDuplicate(treeRootHolder.getComponentByRef(FILE_2_REF), singleLineTextBlock(LINE + 1))); assertNoDuplication(FILE_2_REF); assertNbOfDuplications(context, 1); } @Test public void loads_duplication_with_otherFileRef_as_InExtendedProject_duplication() { Branch branch = mock(Branch.class); when(branch.getType()).thenReturn(BranchType.PULL_REQUEST); analysisMetadataHolder.setBranch(branch); reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(LINE), createInProjectDuplicate(FILE_2_REF, LINE + 1))); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); assertDuplications(FILE_1_REF, singleLineDetailedTextBlock(1, LINE), new InExtendedProjectDuplicate(treeRootHolder.getComponentByRef(FILE_2_REF), singleLineTextBlock(LINE + 1))); assertNoDuplication(FILE_2_REF); assertNbOfDuplications(context, 1); } @Test public void loads_multiple_duplications_with_multiple_duplicates() { reportReader.putDuplications( FILE_2_REF, createDuplication( singleLineTextRange(LINE), createInnerDuplicate(LINE + 1), createInnerDuplicate(LINE + 2), createInProjectDuplicate(FILE_1_REF, LINE), createInProjectDuplicate(FILE_1_REF, LINE + 10)), createDuplication( singleLineTextRange(OTHER_LINE), createInProjectDuplicate(FILE_1_REF, OTHER_LINE)), createDuplication( singleLineTextRange(OTHER_LINE + 80), createInnerDuplicate(LINE), createInnerDuplicate(LINE + 10))); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); Component file1Component = treeRootHolder.getComponentByRef(FILE_1_REF); assertThat(duplicationRepository.getDuplications(FILE_2_REF)).containsOnly( duplication( singleLineDetailedTextBlock(1, LINE), new InnerDuplicate(singleLineTextBlock(LINE + 1)), new InnerDuplicate(singleLineTextBlock(LINE + 2)), new InProjectDuplicate(file1Component, singleLineTextBlock(LINE)), new InProjectDuplicate(file1Component, singleLineTextBlock(LINE + 10))), duplication( singleLineDetailedTextBlock(2, OTHER_LINE), new InProjectDuplicate(file1Component, singleLineTextBlock(OTHER_LINE))), duplication( singleLineDetailedTextBlock(3, OTHER_LINE + 80), new InnerDuplicate(singleLineTextBlock(LINE)), new InnerDuplicate(singleLineTextBlock(LINE + 10)))); assertNbOfDuplications(context, 3); } @Test public void loads_never_consider_originals_from_batch_on_same_lines_as_the_equals() { reportReader.putDuplications( FILE_2_REF, createDuplication( singleLineTextRange(LINE), createInnerDuplicate(LINE + 1), createInnerDuplicate(LINE + 2), createInProjectDuplicate(FILE_1_REF, LINE + 2)), createDuplication( singleLineTextRange(LINE), createInnerDuplicate(LINE + 2), createInnerDuplicate(LINE + 3), createInProjectDuplicate(FILE_1_REF, LINE + 2))); TestComputationStepContext context = new TestComputationStepContext(); underTest.execute(context); Component file1Component = treeRootHolder.getComponentByRef(FILE_1_REF); assertThat(duplicationRepository.getDuplications(FILE_2_REF)).containsOnly( duplication( singleLineDetailedTextBlock(1, LINE), new InnerDuplicate(singleLineTextBlock(LINE + 1)), new InnerDuplicate(singleLineTextBlock(LINE + 2)), new InProjectDuplicate(file1Component, singleLineTextBlock(LINE + 2))), duplication( singleLineDetailedTextBlock(2, LINE), new InnerDuplicate(singleLineTextBlock(LINE + 2)), new InnerDuplicate(singleLineTextBlock(LINE + 3)), new InProjectDuplicate(file1Component, singleLineTextBlock(LINE + 2)))); assertNbOfDuplications(context, 2); } @Test public void loads_duplication_with_otherFileRef_throws_IAE_if_component_does_not_exist() { int line = 2; reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(line), createInProjectDuplicate(666, line + 1))); assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) .isInstanceOf(VisitException.class) .hasCauseInstanceOf(IllegalArgumentException.class) .hasRootCauseMessage("Component with ref '666' can't be found"); } @Test public void loads_duplication_with_otherFileRef_throws_IAE_if_references_itself() { int line = 2; reportReader.putDuplications(FILE_1_REF, createDuplication(singleLineTextRange(line), createInProjectDuplicate(FILE_1_REF, line + 1))); assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) .isInstanceOf(VisitException.class) .hasCauseInstanceOf(IllegalArgumentException.class) .hasRootCauseMessage("file and otherFile references can not be the same"); } private void assertDuplications(int fileRef, TextBlock original, Duplicate... duplicates) { assertThat(duplicationRepository.getDuplications(fileRef)).containsExactly(duplication(original, duplicates)); } private static Duplication duplication(TextBlock original, Duplicate... duplicates) { return new Duplication(original, Arrays.asList(duplicates)); } private TextBlock singleLineTextBlock(int line) { return new TextBlock(line, line); } private DetailedTextBlock singleLineDetailedTextBlock(int id, int line) { return new DetailedTextBlock(id, line, line); } private static ScannerReport.Duplication createDuplication(ScannerReport.TextRange original, ScannerReport.Duplicate... duplicates) { ScannerReport.Duplication.Builder builder = ScannerReport.Duplication.newBuilder() .setOriginPosition(original); for (ScannerReport.Duplicate duplicate : duplicates) { builder.addDuplicate(duplicate); } return builder.build(); } private static ScannerReport.Duplicate createInnerDuplicate(int line) { return ScannerReport.Duplicate.newBuilder() .setRange(singleLineTextRange(line)) .build(); } private static ScannerReport.Duplicate createInProjectDuplicate(int componentRef, int line) { return ScannerReport.Duplicate.newBuilder() .setOtherFileRef(componentRef) .setRange(singleLineTextRange(line)) .build(); } private static ScannerReport.TextRange singleLineTextRange(int line) { return ScannerReport.TextRange.newBuilder() .setStartLine(line) .setEndLine(line) .build(); } private void assertNoDuplication(int fileRef) { assertThat(duplicationRepository.getDuplications(fileRef)).isEmpty(); } private static void assertNbOfDuplications(TestComputationStepContext context, int expected) { context.getStatistics().assertValue("duplications", expected); } }
11,496
43.562016
176
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadMeasureComputersStepTest.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.step; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import java.util.Collections; import java.util.List; import java.util.Set; import org.junit.Test; import org.sonar.api.ce.measure.MeasureComputer; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; import org.sonar.ce.task.projectanalysis.api.measurecomputer.MeasureComputerWrapper; import org.sonar.ce.task.projectanalysis.measure.MeasureComputersHolderImpl; import org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; 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.util.Arrays.array; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.Metric.ValueType.DATA; import static org.sonar.api.measures.Metric.ValueType.FLOAT; import static org.sonar.api.measures.Metric.ValueType.INT; import static org.sonar.api.measures.Metric.ValueType.MILLISEC; public class LoadMeasureComputersStepTest { private static final String NEW_METRIC_1 = "metric1"; private static final String NEW_METRIC_2 = "metric2"; private static final String NEW_METRIC_3 = "metric3"; private static final String NEW_METRIC_4 = "metric4"; private MeasureComputersHolderImpl holder = new MeasureComputersHolderImpl(); @Test public void support_core_metrics_as_input_metrics() { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); assertThat(holder.getMeasureComputers()).hasSize(1); } @Test public void support_plugin_metrics_as_input_metrics() { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_1), array(NEW_METRIC_2))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); assertThat(holder.getMeasureComputers()).hasSize(1); } @Test public void sort_computers() { // Should be the last to be executed MeasureComputer measureComputer1 = newMeasureComputer(array(NEW_METRIC_3), array(NEW_METRIC_4)); // Should be the first to be executed MeasureComputer measureComputer2 = newMeasureComputer(array(NEW_METRIC_1), array(NEW_METRIC_2)); // Should be the second to be executed MeasureComputer measureComputer3 = newMeasureComputer(array(NEW_METRIC_2), array(NEW_METRIC_3)); MeasureComputer[] computers = new MeasureComputer[] {measureComputer1, measureComputer2, measureComputer3}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); List<MeasureComputerWrapper> result = newArrayList(holder.getMeasureComputers()); assertThat(result).hasSize(3); assertThat(result.get(0).getComputer()).isEqualTo(measureComputer2); assertThat(result.get(1).getComputer()).isEqualTo(measureComputer3); assertThat(result.get(2).getComputer()).isEqualTo(measureComputer1); } @Test public void sort_computers_when_one_computer_has_no_input_metric() { // Should be the last to be executed MeasureComputer measureComputer1 = newMeasureComputer(array(NEW_METRIC_3), array(NEW_METRIC_4)); // Should be the first to be executed MeasureComputer measureComputer2 = newMeasureComputer(new String[] {}, array(NEW_METRIC_2)); // Should be the second to be executed MeasureComputer measureComputer3 = newMeasureComputer(array(NEW_METRIC_2), array(NEW_METRIC_3)); MeasureComputer[] computers = new MeasureComputer[] {measureComputer1, measureComputer2, measureComputer3}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); List<MeasureComputerWrapper> result = newArrayList(holder.getMeasureComputers()); assertThat(result).hasSize(3); assertThat(result.get(0).getComputer()).isEqualTo(measureComputer2); assertThat(result.get(1).getComputer()).isEqualTo(measureComputer3); assertThat(result.get(2).getComputer()).isEqualTo(measureComputer1); } @Test public void fail_with_ISE_when_input_metric_is_unknown() { assertThatThrownBy(() -> { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array("unknown"), array(NEW_METRIC_4))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric 'unknown' cannot be used as an input metric as it's not a core metric and no plugin declare this metric"); } @Test public void fail_with_ISE_when_output_metric_is_not_define_by_plugin() { assertThatThrownBy(() -> { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array("unknown"))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric 'unknown' cannot be used as an output metric because no plugins declare this metric"); } @Test public void fail_with_ISE_when_output_metric_is_a_core_metric() { assertThatThrownBy(() -> { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_4), array(NCLOC_KEY))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric 'ncloc' cannot be used as an output metric because it's a core metric"); } @Test public void not_fail_if_input_metrics_are_same_as_output_metrics() { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NEW_METRIC_1), array(NEW_METRIC_1))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); assertThat(holder.getMeasureComputers()).hasSize(1); } @Test public void return_empty_list_when_no_measure_computers() { ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics())); underTest.execute(new TestComputationStepContext()); assertThat(holder.getMeasureComputers()).isEmpty(); } @Test public void return_empty_list_when_no_metrics_neither_measure_computers() { ComputationStep underTest = new LoadMeasureComputersStep(holder); underTest.execute(new TestComputationStepContext()); assertThat(holder.getMeasureComputers()).isEmpty(); } @Test public void fail_with_ISE_when_no_metrics_are_defined_by_plugin_but_measure_computer_use_a_new_metric() { assertThatThrownBy(() -> { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, computers); underTest.execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Metric 'metric1' cannot be used as an output metric because no plugins declare this metric"); } @Test public void fail_with_ISE_when_two_measure_computers_generate_the_same_output_metric() { assertThatThrownBy(() -> { MeasureComputer[] computers = new MeasureComputer[] {newMeasureComputer(array(NCLOC_KEY), array(NEW_METRIC_1)), newMeasureComputer(array(CLASSES_KEY), array(NEW_METRIC_1))}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalStateException.class) .hasMessage("Output metric 'metric1' is already defined by another measure computer 'TestMeasureComputer'"); } @Test public void fail_with_IAE_when_creating_measure_computer_definition_without_using_the_builder_and_with_invalid_output_metrics() { assertThatThrownBy(() -> { MeasureComputer measureComputer = new MeasureComputer() { @Override public MeasureComputerDefinition define(MeasureComputerDefinitionContext defContext) { // Create a instance of MeasureComputerDefinition without using the builder return new MeasureComputer.MeasureComputerDefinition() { @Override public Set<String> getInputMetrics() { return ImmutableSet.of(NCLOC_KEY); } @Override public Set<String> getOutputMetrics() { // Empty output metric is not allowed ! return Collections.emptySet(); } }; } @Override public void compute(MeasureComputerContext context) { // Nothing needs to be done as we're only testing metada } }; MeasureComputer[] computers = new MeasureComputer[] {measureComputer}; ComputationStep underTest = new LoadMeasureComputersStep(holder, array(new TestMetrics()), computers); underTest.execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalArgumentException.class) .hasMessage("At least one output metric must be defined"); } private static MeasureComputer newMeasureComputer(final String[] inputMetrics, final String[] outputMetrics) { return new MeasureComputer() { @Override public MeasureComputerDefinition define(MeasureComputerDefinitionContext defContext) { return defContext.newDefinitionBuilder() .setInputMetrics(inputMetrics) .setOutputMetrics(outputMetrics) .build(); } @Override public void compute(MeasureComputerContext context) { // Nothing needs to be done as we're only testing metada } @Override public String toString() { return "TestMeasureComputer"; } }; } private static class TestMetrics implements Metrics { @Override public List<Metric> getMetrics() { return Lists.newArrayList( new Metric.Builder(NEW_METRIC_1, "metric1", DATA).create(), new Metric.Builder(NEW_METRIC_2, "metric2", MILLISEC).create(), new Metric.Builder(NEW_METRIC_3, "metric3", INT).create(), new Metric.Builder(NEW_METRIC_4, "metric4", FLOAT).create()); } } }
11,895
44.060606
179
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadQualityGateStepTest.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.step; import java.util.Arrays; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateHolderRule; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGate; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateServiceImpl; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.server.project.Project; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LoadQualityGateStepTest { @Rule public MutableQualityGateHolderRule mutableQualityGateHolder = new MutableQualityGateHolderRule(); private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private final QualityGateServiceImpl qualityGateService = mock(QualityGateServiceImpl.class); private final LoadQualityGateStep underTest = new LoadQualityGateStep(qualityGateService, mutableQualityGateHolder, analysisMetadataHolder); private final Project project = mock(Project.class); @Before public void before() { when(analysisMetadataHolder.getProject()).thenReturn(project); } @Test public void filter_conditions_on_pull_request() { Metric newMetric = new MetricImpl("1", "new_key", "name", Metric.MetricType.INT); Metric metric = new MetricImpl("2", "key", "name", Metric.MetricType.INT); Condition variation = new Condition(newMetric, Condition.Operator.GREATER_THAN.getDbValue(), "1.0"); Condition condition = new Condition(metric, Condition.Operator.GREATER_THAN.getDbValue(), "1.0"); when(analysisMetadataHolder.isPullRequest()).thenReturn(true); QualityGate defaultGate = new QualityGate("1", "qg", Arrays.asList(variation, condition)); when(qualityGateService.findEffectiveQualityGate(project)).thenReturn(defaultGate); underTest.execute(new TestComputationStepContext()); assertThat(mutableQualityGateHolder.getQualityGate().get().getConditions()).containsExactly(variation); } @Test public void execute_sets_effective_quality_gate() { QualityGate qg = mock(QualityGate.class); when(qualityGateService.findEffectiveQualityGate(project)).thenReturn(qg); underTest.execute(new TestComputationStepContext()); assertThat(mutableQualityGateHolder.getQualityGate()).containsSame(qg); } }
3,542
42.740741
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/LoadQualityProfilesStepTest.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.step; import org.assertj.core.data.MapEntry; import org.junit.Rule; import org.junit.Test; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.issue.DumbRule; import org.sonar.ce.task.projectanalysis.issue.RuleRepositoryRule; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRule; import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderImpl; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.scanner.protocol.Constants; import org.sonar.scanner.protocol.output.ScannerReport; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.rule.RuleTesting.XOO_X1; import static org.sonar.db.rule.RuleTesting.XOO_X2; public class LoadQualityProfilesStepTest { @Rule public BatchReportReaderRule batchReportReader = new BatchReportReaderRule(); @Rule public RuleRepositoryRule ruleRepository = new RuleRepositoryRule(); private ActiveRulesHolderImpl activeRulesHolder = new ActiveRulesHolderImpl(); private LoadQualityProfilesStep underTest = new LoadQualityProfilesStep(batchReportReader, activeRulesHolder, ruleRepository); @Test public void feed_active_rules() { ruleRepository.add(XOO_X1) .setPluginKey("xoo"); ruleRepository.add(XOO_X2) .setPluginKey("xoo"); ScannerReport.ActiveRule.Builder batch1 = ScannerReport.ActiveRule.newBuilder() .setRuleRepository(XOO_X1.repository()) .setRuleKey(XOO_X1.rule()) .setSeverity(Constants.Severity.BLOCKER) .setCreatedAt(1000L) .setUpdatedAt(1200L); batch1.getMutableParamsByKey().put("p1", "v1"); ScannerReport.ActiveRule.Builder batch2 = ScannerReport.ActiveRule.newBuilder() .setRuleRepository(XOO_X2.repository()).setRuleKey(XOO_X2.rule()).setSeverity(Constants.Severity.MAJOR); batchReportReader.putActiveRules(asList(batch1.build(), batch2.build())); underTest.execute(new TestComputationStepContext()); assertThat(activeRulesHolder.getAll()).hasSize(2); ActiveRule ar1 = activeRulesHolder.get(XOO_X1).get(); assertThat(ar1.getSeverity()).isEqualTo(Severity.BLOCKER); assertThat(ar1.getParams()).containsExactly(MapEntry.entry("p1", "v1")); assertThat(ar1.getPluginKey()).isEqualTo("xoo"); assertThat(ar1.getUpdatedAt()).isEqualTo(1200L); ActiveRule ar2 = activeRulesHolder.get(XOO_X2).get(); assertThat(ar2.getSeverity()).isEqualTo(Severity.MAJOR); assertThat(ar2.getParams()).isEmpty(); assertThat(ar2.getPluginKey()).isEqualTo("xoo"); assertThat(ar1.getUpdatedAt()).isEqualTo(1200L); } @Test public void ignore_rules_with_status_REMOVED() { ruleRepository.add(new DumbRule(XOO_X1).setStatus(RuleStatus.REMOVED)); ScannerReport.ActiveRule.Builder batch1 = ScannerReport.ActiveRule.newBuilder() .setRuleRepository(XOO_X1.repository()).setRuleKey(XOO_X1.rule()) .setSeverity(Constants.Severity.BLOCKER); batchReportReader.putActiveRules(asList(batch1.build())); underTest.execute(new TestComputationStepContext()); assertThat(activeRulesHolder.getAll()).isEmpty(); } @Test public void ignore_not_found_rules() { ScannerReport.ActiveRule.Builder batch1 = ScannerReport.ActiveRule.newBuilder() .setRuleRepository(XOO_X1.repository()).setRuleKey(XOO_X1.rule()) .setSeverity(Constants.Severity.BLOCKER); batchReportReader.putActiveRules(asList(batch1.build())); underTest.execute(new TestComputationStepContext()); assertThat(activeRulesHolder.getAll()).isEmpty(); } }
4,579
39.175439
128
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/NewCoverageMeasuresStepTest.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.step; import java.util.Collections; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredMetricKeys; import org.sonar.ce.task.projectanalysis.measure.Measure; 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.ce.task.projectanalysis.source.NewLinesRepository; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.scanner.protocol.output.ScannerReport; import static java.util.Arrays.asList; 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.NEW_CONDITIONS_TO_COVER_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_LINES_TO_COVER_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_UNCOVERED_CONDITIONS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_UNCOVERED_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; 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 NewCoverageMeasuresStepTest { private static final int ROOT_REF = 1; private static final int DIRECTORY_1_REF = 1111; private static final int FILE_1_REF = 11111; private static final int DIRECTORY_2_REF = 1112; private static final int FILE_2_REF = 11121; private static final int FILE_3_REF = 11122; private static final Component FILE_1 = builder(FILE, FILE_1_REF).build(); private static final Component FILE_2 = builder(FILE, FILE_2_REF).build(); private static final Component FILE_3 = builder(FILE, FILE_3_REF).build(); private static final ReportComponent MULTIPLE_FILES_TREE = builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_1_REF) .addChildren(FILE_1) .build(), builder(DIRECTORY, DIRECTORY_2_REF) .addChildren(FILE_2, FILE_3) .build()) .build(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.NEW_LINES_TO_COVER) .add(CoreMetrics.NEW_UNCOVERED_LINES) .add(CoreMetrics.NEW_CONDITIONS_TO_COVER) .add(CoreMetrics.NEW_UNCOVERED_CONDITIONS) .add(CoreMetrics.NEW_COVERAGE) .add(CoreMetrics.NEW_BRANCH_COVERAGE) .add(CoreMetrics.NEW_LINE_COVERAGE); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); private NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private NewCoverageMeasuresStep underTest = new NewCoverageMeasuresStep(treeRootHolder, measureRepository, metricRepository, newLinesRepository, reportReader); public static final ReportComponent FILE_COMPONENT = ReportComponent.builder(Component.Type.FILE, FILE_1_REF) .setFileAttributes(new FileAttributes(false, null, 1)).build(); @Test public void no_measure_for_PROJECT_component() { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, ROOT_REF).build()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.isEmpty()).isTrue(); } @Test public void no_measure_for_DIRECTORY_component() { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.DIRECTORY, DIRECTORY_1_REF).build()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.isEmpty()).isTrue(); } @Test public void no_measure_for_unit_test_FILE_component() { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.FILE, FILE_1_REF).setFileAttributes(new FileAttributes(true, null, 1)).build()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.isEmpty()).isTrue(); } @Test public void no_measures_for_FILE_component_without_code() { treeRootHolder.setRoot(ReportComponent.builder(Component.Type.FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, null, 1)).build()); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.isEmpty()).isTrue(); } @Test public void zero_measures_when_nothing_has_changed() { treeRootHolder.setRoot(FILE_COMPONENT); when(newLinesRepository.newLinesAvailable()).thenReturn(true); when(newLinesRepository.getNewLines(FILE_COMPONENT)).thenReturn(Optional.of(Collections.emptySet())); reportReader.putCoverage(FILE_COMPONENT.getReportAttributes().getRef(), asList( ScannerReport.LineCoverage.newBuilder().setLine(2).setHits(true).setConditions(1).setCoveredConditions(1).build(), ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(true).build())); underTest.execute(new TestComputationStepContext()); verify_only_zero_measures_on_new_lines_and_conditions_measures(FILE_COMPONENT); } @Test public void zero_measures_for_FILE_component_without_CoverageData() { treeRootHolder.setRoot(FILE_1); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); verify_only_zero_measures_on_new_lines_and_conditions_measures(FILE_1); } @Test public void verify_computation_of_measures_for_new_lines_for_FILE() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); treeRootHolder.setRoot(FILE_COMPONENT); setNewLines(FILE_1, 1, 2, 4); reportReader.putCoverage(FILE_COMPONENT.getReportAttributes().getRef(), asList( ScannerReport.LineCoverage.newBuilder().setLine(2).setHits(false).build(), ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(true).build(), ScannerReport.LineCoverage.newBuilder().setLine(4).setHits(true).build())); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_COMPONENT.getReportAttributes().getRef()))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(2)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(1)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(0)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(0))); } @Test public void verify_computation_of_measures_for_new_conditions_for_FILE() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); verify_computation_of_measures_for_new_conditions(); } @Test public void verify_aggregation_of_measures_for_new_conditions() { when(newLinesRepository.newLinesAvailable()).thenReturn(true); treeRootHolder.setRoot(MULTIPLE_FILES_TREE); defineNewLinesAndLineCoverage(FILE_1, new LineCoverageValues(3, 4, 1), new LineCoverageValues(0, 3, 2)); defineNewLinesAndLineCoverage(FILE_2, new LineCoverageValues(0, 14, 6), new LineCoverageValues(0, 13, 7)); defineNewLinesAndLineCoverage(FILE_3, new LineCoverageValues(3, 4, 1), new LineCoverageValues(1, 13, 7)); underTest.execute(new TestComputationStepContext()); // files assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_1_REF))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(5)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(3)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(7)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(4))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_2_REF))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(5)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(4)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(27)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(14))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_3_REF))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(5)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(2)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(17)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(9))); // directories assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_1_REF))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(5)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(3)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(7)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(4))); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_2_REF))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(10)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(6)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(44)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(23))); // submodule MeasureRepoEntry[] repoEntriesFromProject = {entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(15)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(9)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(51)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(27))}; // project assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(repoEntriesFromProject); } private void defineNewLinesAndLineCoverage(Component c, LineCoverageValues line4, LineCoverageValues line6) { setNewLines(c, 1, 2, 4, 5, 6, 7); reportReader.putCoverage(c.getReportAttributes().getRef(), asList( ScannerReport.LineCoverage.newBuilder().setLine(2).setHits(false).build(), ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(true).build(), ScannerReport.LineCoverage.newBuilder().setLine(4).setHits(line4.lineHits > 0).setConditions(line4.conditions).setCoveredConditions(line4.coveredConditions).build(), ScannerReport.LineCoverage.newBuilder().setLine(5).setHits(true).build(), ScannerReport.LineCoverage.newBuilder().setLine(6).setHits(line6.lineHits > 0).setConditions(line6.conditions).setCoveredConditions(line6.coveredConditions).build(), ScannerReport.LineCoverage.newBuilder().setLine(7).setHits(false).build())); } @Test public void verify_aggregates_variations_for_new_code_line_and_branch_Coverage() { LinesAndConditionsWithUncoveredMetricKeys metricKeys = new LinesAndConditionsWithUncoveredMetricKeys( CoreMetrics.NEW_LINES_TO_COVER_KEY, CoreMetrics.NEW_CONDITIONS_TO_COVER_KEY, CoreMetrics.NEW_UNCOVERED_LINES_KEY, CoreMetrics.NEW_UNCOVERED_CONDITIONS_KEY); String codeCoverageKey = CoreMetrics.NEW_COVERAGE_KEY; String lineCoverageKey = CoreMetrics.NEW_LINE_COVERAGE_KEY; String branchCoverageKey = CoreMetrics.NEW_BRANCH_COVERAGE_KEY; verify_aggregates_variations(metricKeys, codeCoverageKey, lineCoverageKey, branchCoverageKey); } private void verify_aggregates_variations(LinesAndConditionsWithUncoveredMetricKeys metricKeys, String codeCoverageKey, String lineCoverageKey, String branchCoverageKey) { treeRootHolder.setRoot(MULTIPLE_FILES_TREE); measureRepository .addRawMeasure(FILE_1_REF, metricKeys.lines(), createMeasure(3000)) .addRawMeasure(FILE_1_REF, metricKeys.conditions(), createMeasure(300)) .addRawMeasure(FILE_1_REF, metricKeys.uncoveredLines(), createMeasure(30)) .addRawMeasure(FILE_1_REF, metricKeys.uncoveredConditions(), createMeasure(9)) .addRawMeasure(FILE_2_REF, metricKeys.lines(), createMeasure(2000)) .addRawMeasure(FILE_2_REF, metricKeys.conditions(), createMeasure(400)) .addRawMeasure(FILE_2_REF, metricKeys.uncoveredLines(), createMeasure(200)) .addRawMeasure(FILE_2_REF, metricKeys.uncoveredConditions(), createMeasure(16)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_1_REF))).containsOnly( entryOf(codeCoverageKey, createMeasure(98.8d)), entryOf(lineCoverageKey, createMeasure(99d)), entryOf(branchCoverageKey, createMeasure(97d))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_2_REF))).containsOnly( entryOf(codeCoverageKey, createMeasure(91d)), entryOf(lineCoverageKey, createMeasure(90d)), entryOf(branchCoverageKey, createMeasure(96d))); assertThat(measureRepository.getAddedRawMeasures(FILE_3_REF)).isEmpty(); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_1_REF))).containsOnly( entryOf(codeCoverageKey, createMeasure(98.8d)), entryOf(lineCoverageKey, createMeasure(99d)), entryOf(branchCoverageKey, createMeasure(97d))); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_2_REF))).containsOnly( entryOf(codeCoverageKey, createMeasure(91d)), entryOf(lineCoverageKey, createMeasure(90d)), entryOf(branchCoverageKey, createMeasure(96d))); MeasureRepoEntry[] modulesAndProjectEntries = { entryOf(codeCoverageKey, createMeasure(95.5d)), entryOf(lineCoverageKey, createMeasure(95.4d)), entryOf(branchCoverageKey, createMeasure(96.4d)) }; assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly(modulesAndProjectEntries); } private void verify_only_zero_measures_on_new_lines_and_conditions_measures(Component component) { assertThat(toEntries(measureRepository.getAddedRawMeasures(component.getReportAttributes().getRef()))).containsOnly( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(0)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(0)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(0)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(0))); } private static final class LineCoverageValues { private final int lineHits; private final int conditions; private final int coveredConditions; public LineCoverageValues(int lineHits, int conditions, int coveredConditions) { this.lineHits = lineHits; this.conditions = conditions; this.coveredConditions = coveredConditions; } } private void verify_computation_of_measures_for_new_conditions() { treeRootHolder.setRoot(FILE_COMPONENT); defineNewLinesAndLineCoverage(FILE_COMPONENT, new LineCoverageValues(3, 4, 1), new LineCoverageValues(0, 3, 2)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_COMPONENT.getReportAttributes().getRef()))).contains( entryOf(NEW_LINES_TO_COVER_KEY, createMeasure(5)), entryOf(NEW_UNCOVERED_LINES_KEY, createMeasure(3)), entryOf(NEW_CONDITIONS_TO_COVER_KEY, createMeasure(7)), entryOf(NEW_UNCOVERED_CONDITIONS_KEY, createMeasure(4))); } private static Measure createMeasure(int expectedValue) { return newMeasureBuilder().create(expectedValue); } private static Measure createMeasure(double expectedValue) { return newMeasureBuilder().create(expectedValue); } private void setNewLines(Component c, Integer... lines) { when(newLinesRepository.newLinesAvailable()).thenReturn(true); Set<Integer> newLines = new HashSet<>(asList(lines)); when(newLinesRepository.getNewLines(c)).thenReturn(Optional.of(newLines)); } }
17,099
46.89916
173
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/NewSizeMeasuresStepTest.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.step; import java.util.Arrays; import java.util.HashSet; import java.util.Optional; import java.util.Set; import org.assertj.core.data.Offset; 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.ce.task.projectanalysis.duplication.DuplicationRepositoryRule; import org.sonar.ce.task.projectanalysis.duplication.TextBlock; import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.projectanalysis.source.NewLinesRepository; import org.sonar.ce.task.step.TestComputationStepContext; 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.NEW_BLOCKS_DUPLICATED; import static org.sonar.api.measures.CoreMetrics.NEW_BLOCKS_DUPLICATED_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_DUPLICATED_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_LINES; import static org.sonar.api.measures.CoreMetrics.NEW_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 NewSizeMeasuresStepTest { private static final Offset<Double> DEFAULT_OFFSET = Offset.offset(0.1d); private static final int ROOT_REF = 1; private static final int DIRECTORY_REF = 1234; private static final int DIRECTORY_2_REF = 1235; 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 Component FILE_1 = builder(FILE, FILE_1_REF).build(); private static final Component FILE_2 = builder(FILE, FILE_2_REF).build(); private static final Component FILE_3 = builder(FILE, FILE_3_REF).build(); private static final Component FILE_4 = builder(FILE, FILE_4_REF).build(); 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(FILE_1, FILE_2) .build(), builder(DIRECTORY, DIRECTORY_2_REF).build(), FILE_3, FILE_4) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NEW_LINES) .add(NEW_DUPLICATED_LINES) .add(NEW_DUPLICATED_LINES_DENSITY) .add(NEW_BLOCKS_DUPLICATED); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(treeRootHolder); private NewLinesRepository newLinesRepository = mock(NewLinesRepository.class); private NewSizeMeasuresStep underTest = new NewSizeMeasuresStep(treeRootHolder, metricRepository, measureRepository, newLinesRepository, duplicationRepository); @Test public void compute_new_lines() { setNewLines(FILE_1, FILE_2, FILE_4); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_LINES_KEY, 11); assertRawMeasureValue(FILE_2_REF, NEW_LINES_KEY, 11); assertNoRawMeasure(FILE_3_REF, NEW_LINES_KEY); assertRawMeasureValue(FILE_4_REF, NEW_LINES_KEY, 11); assertRawMeasureValue(DIRECTORY_REF, NEW_LINES_KEY, 22); assertNoRawMeasure(DIRECTORY_2_REF, NEW_LINES_KEY); assertRawMeasureValue(ROOT_REF, NEW_LINES_KEY, 33); } @Test public void compute_new_lines_with_only_some_lines_having_changesets() { setFirstTwoLinesAsNew(FILE_1, FILE_2, FILE_4); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_LINES_KEY, 2); assertRawMeasureValue(FILE_2_REF, NEW_LINES_KEY, 2); assertNoRawMeasure(FILE_3_REF, NEW_LINES_KEY); assertRawMeasureValue(FILE_4_REF, NEW_LINES_KEY, 2); assertRawMeasureValue(DIRECTORY_REF, NEW_LINES_KEY, 4); assertNoRawMeasure(DIRECTORY_2_REF, NEW_LINES_KEY); assertRawMeasureValue(ROOT_REF, NEW_LINES_KEY, 6); } @Test public void does_not_compute_new_lines_when_no_changeset() { underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(NEW_LINES_KEY); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_of_a_single_line() { duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(1, 1), new TextBlock(2, 2)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_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)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_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)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_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)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_KEY, 6); } @Test public void compute_duplicated_lines_counts_lines_from_original_and_InnerDuplicate_only_once() { TextBlock original = new TextBlock(1, 10); duplicationRepository.addDuplication(FILE_1_REF, original, new TextBlock(10, 11), new TextBlock(11, 12)); duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(2, 2), new TextBlock(4, 4)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_KEY, 11); } @Test public void compute_and_aggregate_duplicated_lines() { addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_3_REF, 10); addDuplicatedBlock(FILE_4_REF, 12); setNewLines(FILE_1, FILE_2, FILE_3, FILE_4); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(FILE_2_REF, NEW_DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(FILE_3_REF, NEW_DUPLICATED_LINES_KEY, 9); assertRawMeasureValue(FILE_4_REF, NEW_DUPLICATED_LINES_KEY, 11); assertRawMeasureValue(DIRECTORY_REF, NEW_DUPLICATED_LINES_KEY, 2); assertNoRawMeasure(DIRECTORY_2_REF, NEW_DUPLICATED_LINES_KEY); assertRawMeasureValue(ROOT_REF, NEW_DUPLICATED_LINES_KEY, 22); } @Test public void compute_and_aggregate_duplicated_lines_when_only_some_lines_have_changesets() { // 2 new duplicated lines in each, since only the first 2 lines are new addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_3_REF, 10); addDuplicatedBlock(FILE_4_REF, 12); setFirstTwoLinesAsNew(FILE_1, FILE_2, FILE_3, FILE_4); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(FILE_2_REF, NEW_DUPLICATED_LINES_KEY, 0); assertRawMeasureValue(FILE_3_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(FILE_4_REF, NEW_DUPLICATED_LINES_KEY, 2); assertRawMeasureValue(DIRECTORY_REF, NEW_DUPLICATED_LINES_KEY, 2); assertNoRawMeasure(DIRECTORY_2_REF, NEW_DUPLICATED_LINES_KEY); assertRawMeasureValue(ROOT_REF, NEW_DUPLICATED_LINES_KEY, 6); } @Test public void compute_and_aggregate_zero_duplicated_line_when_no_duplication() { setNewLines(FILE_1, FILE_2, FILE_3, FILE_4); underTest.execute(new TestComputationStepContext()); assertComputedAndAggregatedToZeroInt(NEW_DUPLICATED_LINES_KEY); } @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(4, 4), new TextBlock(3, 4)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_BLOCKS_DUPLICATED_KEY, 4); } @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(4, 4)); duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(2, 2), new TextBlock(4, 4)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_BLOCKS_DUPLICATED_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)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_BLOCKS_DUPLICATED_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)); setNewLines(FILE_1); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_BLOCKS_DUPLICATED_KEY, 1); } @Test public void compute_and_aggregate_duplicated_blocks_from_single_duplication() { addDuplicatedBlock(FILE_1_REF, 11); addDuplicatedBlock(FILE_2_REF, 2); addDuplicatedBlock(FILE_4_REF, 7); setNewLines(FILE_1, FILE_2, FILE_3, FILE_4); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_BLOCKS_DUPLICATED_KEY, 10); assertRawMeasureValue(FILE_2_REF, NEW_BLOCKS_DUPLICATED_KEY, 2); assertRawMeasureValue(FILE_3_REF, NEW_BLOCKS_DUPLICATED_KEY, 0); assertRawMeasureValue(FILE_4_REF, NEW_BLOCKS_DUPLICATED_KEY, 6); assertRawMeasureValue(DIRECTORY_REF, NEW_BLOCKS_DUPLICATED_KEY, 12); assertRawMeasureValue(ROOT_REF, NEW_BLOCKS_DUPLICATED_KEY, 18); } @Test public void compute_and_aggregate_duplicated_blocks_to_zero_when_no_duplication() { setNewLines(FILE_1, FILE_2, FILE_3, FILE_4); underTest.execute(new TestComputationStepContext()); assertComputedAndAggregatedToZeroInt(NEW_BLOCKS_DUPLICATED_KEY); } @Test public void compute_new_duplicated_lines_density() { setNewLines(FILE_1, FILE_2, FILE_4); addDuplicatedBlock(FILE_1_REF, 2); addDuplicatedBlock(FILE_3_REF, 10); addDuplicatedBlock(FILE_4_REF, 12); underTest.execute(new TestComputationStepContext()); assertRawMeasureValue(FILE_1_REF, NEW_DUPLICATED_LINES_DENSITY_KEY, 18.2d); assertRawMeasureValue(FILE_2_REF, NEW_DUPLICATED_LINES_DENSITY_KEY, 0d); assertNoRawMeasure(FILE_3_REF, NEW_DUPLICATED_LINES_DENSITY_KEY); assertRawMeasureValue(FILE_4_REF, NEW_DUPLICATED_LINES_DENSITY_KEY, 100d); assertRawMeasureValue(DIRECTORY_REF, NEW_DUPLICATED_LINES_DENSITY_KEY, 9.1d); assertNoRawMeasure(DIRECTORY_2_REF, NEW_DUPLICATED_LINES_DENSITY_KEY); assertRawMeasureValue(ROOT_REF, NEW_DUPLICATED_LINES_DENSITY_KEY, 39.4d); } @Test public void compute_no_new_duplicated_lines_density_when_no_lines() { underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(NEW_DUPLICATED_LINES_DENSITY_KEY); } /** * 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 = 2; i < blockCount + 1; i++) { duplicates[i - 2] = new TextBlock(i, i); } duplicationRepository.addDuplication(fileRef, original, duplicates); } private void setFirstTwoLinesAsNew(Component... components) { when(newLinesRepository.newLinesAvailable()).thenReturn(true); Set<Integer> newLines = new HashSet<>(Arrays.asList(1, 2)); for (Component c : components) { when(newLinesRepository.getNewLines(c)).thenReturn(Optional.of(newLines)); } } private void setNewLines(Component... components) { when(newLinesRepository.newLinesAvailable()).thenReturn(true); Set<Integer> newLines = new HashSet<>(Arrays.asList(1, 2, 4, 5, 6, 7, 8, 9, 10, 11, 12)); for (Component c : components) { when(newLinesRepository.getNewLines(c)).thenReturn(Optional.of(newLines)); } } private void assertRawMeasureValue(int componentRef, String metricKey, int expectedValue) { int value = measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getIntValue(); assertThat(value).isEqualTo(expectedValue); } private void assertRawMeasureValue(int componentRef, String metricKey, double expectedValue) { double value = measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getDoubleValue(); assertThat(value).isEqualTo(expectedValue, DEFAULT_OFFSET); } 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); } private void assertNoRawMeasure(int componentRef, String metricKey) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey)).isNotPresent(); } 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(FILE_3_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(FILE_4_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(DIRECTORY_REF).get(metricKey)).isNull(); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF).get(metricKey)).isNull(); } }
16,672
41.424936
162
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisWarningsStepTest.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.step; import com.google.common.collect.ImmutableList; import java.util.List; 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.ce.task.log.CeTaskMessages; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.db.ce.CeTaskMessageType; import org.sonar.scanner.protocol.output.ScannerReport; import static com.google.common.collect.ImmutableList.of; import static java.util.Collections.emptyList; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @RunWith(MockitoJUnitRunner.class) public class PersistAnalysisWarningsStepTest { @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Captor private ArgumentCaptor<List<CeTaskMessages.Message>> argumentCaptor; private final CeTaskMessages ceTaskMessages = mock(CeTaskMessages.class); private final PersistAnalysisWarningsStep underTest = new PersistAnalysisWarningsStep(reportReader, ceTaskMessages); @Test public void getDescription() { assertThat(underTest.getDescription()).isEqualTo(PersistAnalysisWarningsStep.DESCRIPTION); } @Test public void execute_persists_warnings_from_reportReader() { 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); underTest.execute(new TestComputationStepContext()); verify(ceTaskMessages, times(1)).addAll(argumentCaptor.capture()); assertThat(argumentCaptor.getValue()) .extracting(CeTaskMessages.Message::getText, CeTaskMessages.Message::getType) .containsExactly(tuple("warning 1", CeTaskMessageType.GENERIC), tuple("warning 2", CeTaskMessageType.GENERIC)); } @Test public void execute_does_not_persist_warnings_from_reportReader_when_empty() { reportReader.setScannerLogs(emptyList()); underTest.execute(new TestComputationStepContext()); verifyNoInteractions(ceTaskMessages); } }
3,462
39.267442
118
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PersistComponentsStepTest.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.step; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.component.BranchPersister; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.MutableDisabledComponentsHolder; import org.sonar.ce.task.projectanalysis.component.ProjectPersister; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.component.ComponentDao; import static java.util.Collections.emptyList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; 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.doReturn; import static org.mockito.Mockito.mock; public class PersistComponentsStepTest { @Test public void should_fail_if_project_is_not_stored_in_database_yet() { TreeRootHolder treeRootHolder = mock(TreeRootHolder.class); Component component = mock(Component.class); DbClient dbClient = mock(DbClient.class); ComponentDao componentDao = mock(ComponentDao.class); String projectKey = randomAlphabetic(20); doReturn(component).when(treeRootHolder).getRoot(); doReturn(projectKey).when(component).getKey(); doReturn(componentDao).when(dbClient).componentDao(); doReturn(emptyList()).when(componentDao).selectByBranchUuid(eq(projectKey), any(DbSession.class)); assertThatThrownBy(() -> { new PersistComponentsStep( dbClient, treeRootHolder, System2.INSTANCE, mock(MutableDisabledComponentsHolder.class), mock(AnalysisMetadataHolder.class), mock(BranchPersister.class), mock(ProjectPersister.class)).execute(new TestComputationStepContext()); }) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("The project '" + projectKey + "' is not stored in the database, during a project analysis"); } }
3,091
41.944444
121
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/PublishTaskResultStepTest.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.step; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.ce.task.taskprocessor.MutableTaskResultHolder; import org.sonar.ce.task.taskprocessor.MutableTaskResultHolderImpl; import static org.assertj.core.api.Assertions.assertThat; public class PublishTaskResultStepTest { private static final String AN_ANALYSIS_UUID = "U1"; private MutableTaskResultHolder taskResultHolder = new MutableTaskResultHolderImpl(); @Rule public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule(); private PublishTaskResultStep underTest = new PublishTaskResultStep(taskResultHolder, analysisMetadataHolder); @Test public void verify_getDescription() { assertThat(underTest.getDescription()).isEqualTo("Publish task results"); } @Test public void execute_populate_TaskResultHolder_with_a_TaskResult_with_snapshot_id_of_the_root_taken_from_DbIdsRepository() { analysisMetadataHolder.setUuid(AN_ANALYSIS_UUID); underTest.execute(new TestComputationStepContext()); assertThat(taskResultHolder.getResult().getAnalysisUuid()).contains(AN_ANALYSIS_UUID); } }
2,167
37.714286
125
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateEventsStepTest.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.step; import java.util.Collection; import java.util.Optional; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.notifications.Notification; 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.component.DefaultBranchImpl; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.event.Event; import org.sonar.ce.task.projectanalysis.event.EventRepository; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepository; import org.sonar.ce.task.projectanalysis.measure.QualityGateStatus; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepository; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.db.component.BranchType; import org.sonar.server.notification.NotificationService; import org.sonar.server.project.Project; import org.sonar.server.qualitygate.notification.QGChangeNotification; import static java.util.Collections.emptyList; 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.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.ERROR; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME; public class QualityGateEventsStepTest { private static final String PROJECT_VERSION = randomAlphabetic(19); private static final ReportComponent PROJECT_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, 1) .setUuid("uuid 1") .setKey("key 1") .setProjectVersion(PROJECT_VERSION) .setBuildString("V1.9") .setScmRevisionId("456def") .addChildren(ReportComponent.builder(Component.Type.DIRECTORY, 2).build()) .build(); private static final String INVALID_ALERT_STATUS = "trololo"; private static final String ALERT_TEXT = "alert text"; private static final QualityGateStatus OK_QUALITY_GATE_STATUS = new QualityGateStatus(OK, ALERT_TEXT); private static final QualityGateStatus ERROR_QUALITY_GATE_STATUS = new QualityGateStatus(ERROR, ALERT_TEXT); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule(); private ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class); private ArgumentCaptor<Notification> notificationArgumentCaptor = ArgumentCaptor.forClass(Notification.class); private Metric alertStatusMetric = mock(Metric.class); private MetricRepository metricRepository = mock(MetricRepository.class); private MeasureRepository measureRepository = mock(MeasureRepository.class); private EventRepository eventRepository = mock(EventRepository.class); private NotificationService notificationService = mock(NotificationService.class); private QualityGateEventsStep underTest = new QualityGateEventsStep(treeRootHolder, metricRepository, measureRepository, eventRepository, notificationService, analysisMetadataHolder); @Before public void setUp() { when(metricRepository.getByKey(ALERT_STATUS_KEY)).thenReturn(alertStatusMetric); analysisMetadataHolder .setProject(new Project(PROJECT_COMPONENT.getUuid(), PROJECT_COMPONENT.getKey(), PROJECT_COMPONENT.getName(), PROJECT_COMPONENT.getDescription(), emptyList())); analysisMetadataHolder.setBranch(mock(Branch.class)); treeRootHolder.setRoot(PROJECT_COMPONENT); } @Test public void no_event_if_no_raw_ALERT_STATUS_measure() { when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(Optional.empty()); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verifyNoMoreInteractions(measureRepository, eventRepository); } @Test public void no_event_created_if_raw_ALERT_STATUS_measure_is_null() { when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().createNoValue())); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verifyNoMoreInteractions(measureRepository, eventRepository); } private static Optional<Measure> of(Measure measure) { return Optional.of(measure); } @Test public void no_event_created_if_raw_ALERT_STATUS_measure_is_unsupported_value() { when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().create(INVALID_ALERT_STATUS))); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verifyNoMoreInteractions(measureRepository, eventRepository); } @Test public void no_event_created_if_no_base_ALERT_STATUS_and_raw_is_OK() { QualityGateStatus someQGStatus = new QualityGateStatus(Measure.Level.OK); when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(someQGStatus).createNoValue())); when(measureRepository.getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().createNoValue())); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verify(measureRepository).getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric); verifyNoMoreInteractions(measureRepository, eventRepository); } @Test public void event_created_if_base_ALERT_STATUS_has_no_alertStatus_and_raw_is_ERROR() { verify_event_created_if_no_base_ALERT_STATUS_measure(ERROR, "Failed"); } @Test public void event_created_if_base_ALERT_STATUS_has_invalid_alertStatus_and_raw_is_ERROR() { verify_event_created_if_no_base_ALERT_STATUS_measure(ERROR, "Failed"); } private void verify_event_created_if_no_base_ALERT_STATUS_measure(Measure.Level rawAlterStatus, String expectedLabel) { QualityGateStatus someQGStatus = new QualityGateStatus(rawAlterStatus, ALERT_TEXT); when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(someQGStatus).createNoValue())); when(measureRepository.getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn(of(Measure.newMeasureBuilder().createNoValue())); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verify(measureRepository).getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(measureRepository, eventRepository); Event event = eventArgumentCaptor.getValue(); assertThat(event.getCategory()).isEqualTo(Event.Category.ALERT); assertThat(event.getName()).isEqualTo(expectedLabel); assertThat(event.getDescription()).isEqualTo(ALERT_TEXT); assertThat(event.getData()).isNull(); ArgumentCaptor<Collection> collectionCaptor = ArgumentCaptor.forClass(Collection.class); verify(notificationService).deliverEmails(collectionCaptor.capture()); verify(notificationService).deliver(notificationArgumentCaptor.capture()); Notification notification = notificationArgumentCaptor.getValue(); assertThat(collectionCaptor.getValue()).hasSize(1); assertThat(collectionCaptor.getValue().iterator().next()).isSameAs(notification); assertThat(notification).isInstanceOf(QGChangeNotification.class); assertThat(notification.getType()).isEqualTo("alerts"); assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey()); assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName()); assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getProjectVersion()); assertThat(notification.getFieldValue("branch")).isNull(); assertThat(notification.getFieldValue("alertLevel")).isEqualTo(rawAlterStatus.name()); assertThat(notification.getFieldValue("alertName")).isEqualTo(expectedLabel); } @Test public void no_event_created_if_base_ALERT_STATUS_measure_but_status_is_the_same() { when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)) .thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(OK_QUALITY_GATE_STATUS).createNoValue())); when(measureRepository.getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric)) .thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(OK_QUALITY_GATE_STATUS).createNoValue())); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verify(measureRepository).getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric); verifyNoMoreInteractions(measureRepository, eventRepository); } @Test public void event_created_if_base_ALERT_STATUS_measure_exists_and_status_has_changed() { verify_event_created_if_base_ALERT_STATUS_measure_exists_and_status_has_changed(OK, ERROR_QUALITY_GATE_STATUS, "Failed"); verify_event_created_if_base_ALERT_STATUS_measure_exists_and_status_has_changed(ERROR, OK_QUALITY_GATE_STATUS, "Passed"); } private void verify_event_created_if_base_ALERT_STATUS_measure_exists_and_status_has_changed(Measure.Level previousAlertStatus, QualityGateStatus newQualityGateStatus, String expectedLabel) { when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)) .thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(newQualityGateStatus).createNoValue())); when(measureRepository.getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn( of(Measure.newMeasureBuilder().setQualityGateStatus(new QualityGateStatus(previousAlertStatus)).createNoValue())); underTest.execute(new TestComputationStepContext()); verify(measureRepository).getRawMeasure(PROJECT_COMPONENT, alertStatusMetric); verify(measureRepository).getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(measureRepository, eventRepository); Event event = eventArgumentCaptor.getValue(); assertThat(event.getCategory()).isEqualTo(Event.Category.ALERT); assertThat(event.getName()).isEqualTo(expectedLabel); assertThat(event.getDescription()).isEqualTo(ALERT_TEXT); assertThat(event.getData()).isNull(); verify(notificationService).deliver(notificationArgumentCaptor.capture()); Notification notification = notificationArgumentCaptor.getValue(); assertThat(notification.getType()).isEqualTo("alerts"); assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey()); assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName()); assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getProjectVersion()); assertThat(notification.getFieldValue("branch")).isNull(); assertThat(notification.getFieldValue("alertLevel")).isEqualTo(newQualityGateStatus.getStatus().name()); assertThat(notification.getFieldValue("alertName")).isEqualTo(expectedLabel); reset(measureRepository, eventRepository, notificationService); } @Test public void verify_branch_name_is_not_set_in_notification_when_main() { analysisMetadataHolder.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME)); when(measureRepository.getRawMeasure(PROJECT_COMPONENT, alertStatusMetric)) .thenReturn(of(Measure.newMeasureBuilder().setQualityGateStatus(OK_QUALITY_GATE_STATUS).createNoValue())); when(measureRepository.getBaseMeasure(PROJECT_COMPONENT, alertStatusMetric)).thenReturn( of(Measure.newMeasureBuilder().setQualityGateStatus(new QualityGateStatus(ERROR)).createNoValue())); underTest.execute(new TestComputationStepContext()); verify(notificationService).deliver(notificationArgumentCaptor.capture()); Notification notification = notificationArgumentCaptor.getValue(); assertThat(notification.getType()).isEqualTo("alerts"); assertThat(notification.getFieldValue("projectKey")).isEqualTo(PROJECT_COMPONENT.getKey()); assertThat(notification.getFieldValue("projectName")).isEqualTo(PROJECT_COMPONENT.getName()); assertThat(notification.getFieldValue("projectVersion")).isEqualTo(PROJECT_COMPONENT.getProjectAttributes().getProjectVersion()); assertThat(notification.getFieldValue("branch")).isNull(); reset(measureRepository, eventRepository, notificationService); } @Test public void no_alert_on_pull_request_branches() { Branch pr = mock(Branch.class); when(pr.getType()).thenReturn(BranchType.PULL_REQUEST); analysisMetadataHolder.setBranch(pr); TreeRootHolder treeRootHolder = mock(TreeRootHolder.class); MetricRepository metricRepository = mock(MetricRepository.class); MeasureRepository measureRepository = mock(MeasureRepository.class); EventRepository eventRepository = mock(EventRepository.class); NotificationService notificationService = mock(NotificationService.class); QualityGateEventsStep underTest = new QualityGateEventsStep(treeRootHolder, metricRepository, measureRepository, eventRepository, notificationService, analysisMetadataHolder); underTest.execute(new TestComputationStepContext()); verifyNoInteractions(treeRootHolder, metricRepository, measureRepository, eventRepository, notificationService); } }
15,501
52.089041
175
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityGateMeasuresStepTest.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.step; import java.util.Collections; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.config.internal.ConfigurationBridge; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ReportComponent; import org.sonar.ce.task.projectanalysis.component.TestSettingsRepository; 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.measure.qualitygatedetails.EvaluatedCondition; import org.sonar.ce.task.projectanalysis.measure.qualitygatedetails.QualityGateDetailsData; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricImpl; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus; import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResult; import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResultTextConverter; import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateStatusHolderRule; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGate; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateHolderRule; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus; import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatusHolder; import org.sonar.ce.task.step.TestComputationStepContext; import static com.google.common.collect.ImmutableList.of; 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.when; import static org.sonar.api.measures.CoreMetrics.ALERT_STATUS_KEY; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.ERROR; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; import static org.sonar.ce.task.projectanalysis.measure.MeasureAssert.assertThat; public class QualityGateMeasuresStepTest { private static final MetricImpl INT_METRIC_1 = createIntMetric(1); private static final String INT_METRIC_1_KEY = INT_METRIC_1.getKey(); private static final MetricImpl INT_METRIC_2 = createIntMetric(2); private static final String INT_METRIC_2_KEY = INT_METRIC_2.getKey(); private static final int PROJECT_REF = 1; private static final ReportComponent PROJECT_COMPONENT = ReportComponent.builder(Component.Type.PROJECT, PROJECT_REF).build(); private static final String SOME_QG_UUID = "7521551"; private static final String SOME_QG_NAME = "name"; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public QualityGateHolderRule qualityGateHolder = new QualityGateHolderRule(); @Rule public MutableQualityGateStatusHolderRule qualityGateStatusHolder = new MutableQualityGateStatusHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule(); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private EvaluationResultTextConverter resultTextConverter = mock(EvaluationResultTextConverter.class); private MapSettings mapSettings = new MapSettings(); private TestSettingsRepository settings = new TestSettingsRepository(new ConfigurationBridge(mapSettings)); private QualityGateMeasuresStep underTest = new QualityGateMeasuresStep(treeRootHolder, qualityGateHolder, qualityGateStatusHolder, measureRepository, metricRepository, resultTextConverter, new SmallChangesetQualityGateSpecialCase(measureRepository, metricRepository, settings)); @Before public void setUp() { metricRepository .add(CoreMetrics.ALERT_STATUS) .add(CoreMetrics.QUALITY_GATE_DETAILS) .add(INT_METRIC_1) .add(INT_METRIC_2); treeRootHolder.setRoot(PROJECT_COMPONENT); // mock response of asText to any argument to return the result of dumbResultTextAnswer method when(resultTextConverter.asText(any(Condition.class), any(EvaluationResult.class))).thenAnswer(new Answer<String>() { @Override public String answer(InvocationOnMock invocation) { Condition condition = (Condition) invocation.getArguments()[0]; EvaluationResult evaluationResult = (EvaluationResult) invocation.getArguments()[1]; return dumbResultTextAnswer(condition, evaluationResult.level(), evaluationResult.value()); } }); } private static String dumbResultTextAnswer(Condition condition, Measure.Level level, Object value) { return condition.toString() + level + value; } @Test public void no_measure_if_tree_has_no_project() { ReportComponent notAProjectComponent = ReportComponent.builder(Component.Type.DIRECTORY, 1).build(); treeRootHolder.setRoot(notAProjectComponent); underTest.execute(new TestComputationStepContext()); measureRepository.getAddedRawMeasures(1).isEmpty(); } @Test public void no_measure_if_there_is_no_qualitygate() { qualityGateHolder.setQualityGate(null); underTest.execute(new TestComputationStepContext()); measureRepository.getAddedRawMeasures(PROJECT_COMPONENT).isEmpty(); } @Test public void mutableQualityGateStatusHolder_is_not_populated_if_there_is_no_qualitygate() { qualityGateHolder.setQualityGate(null); underTest.execute(new TestComputationStepContext()); assertThatThrownBy(() -> qualityGateStatusHolder.getStatus()) .isInstanceOf(IllegalStateException.class) .hasMessage("Quality gate status has not been set yet"); } @Test public void new_measures_are_created_even_if_there_is_no_rawMeasure_for_metric_of_condition() { Condition equals2Condition = createLessThanCondition(INT_METRIC_1, "2"); qualityGateHolder.setQualityGate(new QualityGate(SOME_QG_UUID, SOME_QG_NAME, of(equals2Condition))); underTest.execute(new TestComputationStepContext()); Optional<Measure> addedRawMeasure = measureRepository.getAddedRawMeasure(PROJECT_COMPONENT, INT_METRIC_1_KEY); assertThat(addedRawMeasure).isAbsent(); assertThat(getAlertStatusMeasure()) .hasQualityGateLevel(OK) .hasQualityGateText(""); assertThat(getQGDetailsMeasure()) .hasValue(new QualityGateDetailsData(OK, Collections.emptyList(), false).toJson()); QualityGateStatusHolderAssertions.assertThat(qualityGateStatusHolder) .hasStatus(QualityGateStatus.OK) .hasConditionCount(1) .hasCondition(equals2Condition, ConditionStatus.EvaluationStatus.NO_VALUE, null); } @Test public void rawMeasure_is_updated_if_present_and_new_measures_are_created_if_project_has_measure_for_metric_of_condition() { int rawValue = 3; Condition equals2Condition = createLessThanCondition(INT_METRIC_1, "2"); Measure rawMeasure = newMeasureBuilder().create(rawValue, null); qualityGateHolder.setQualityGate(new QualityGate(SOME_QG_UUID, SOME_QG_NAME, of(equals2Condition))); measureRepository.addRawMeasure(PROJECT_REF, INT_METRIC_1_KEY, rawMeasure); underTest.execute(new TestComputationStepContext()); Optional<Measure> addedRawMeasure = measureRepository.getAddedRawMeasure(PROJECT_COMPONENT, INT_METRIC_1_KEY); assertThat(addedRawMeasure) .hasQualityGateLevel(OK) .hasQualityGateText(dumbResultTextAnswer(equals2Condition, OK, rawValue)); assertThat(getAlertStatusMeasure()) .hasQualityGateLevel(OK) .hasQualityGateText(dumbResultTextAnswer(equals2Condition, OK, rawValue)); assertThat(getQGDetailsMeasure().get()) .hasValue(new QualityGateDetailsData(OK, of(new EvaluatedCondition(equals2Condition, OK, rawValue)), false).toJson()); QualityGateStatusHolderAssertions.assertThat(qualityGateStatusHolder) .hasStatus(QualityGateStatus.OK) .hasConditionCount(1) .hasCondition(equals2Condition, ConditionStatus.EvaluationStatus.OK, String.valueOf(rawValue)); } @Test public void new_measures_have_ERROR_level_if_at_least_one_updated_measure_has_ERROR_level() { int rawValue = 3; Condition equalsOneErrorCondition = createLessThanCondition(INT_METRIC_1, "4"); Condition equalsOneOkCondition = createLessThanCondition(INT_METRIC_2, "2"); Measure rawMeasure = newMeasureBuilder().create(rawValue, null); qualityGateHolder.setQualityGate(new QualityGate(SOME_QG_UUID, SOME_QG_NAME, of(equalsOneErrorCondition, equalsOneOkCondition))); measureRepository.addRawMeasure(PROJECT_REF, INT_METRIC_1_KEY, rawMeasure); measureRepository.addRawMeasure(PROJECT_REF, INT_METRIC_2_KEY, rawMeasure); underTest.execute(new TestComputationStepContext()); Optional<Measure> rawMeasure1 = measureRepository.getAddedRawMeasure(PROJECT_REF, INT_METRIC_1_KEY); Optional<Measure> rawMeasure2 = measureRepository.getAddedRawMeasure(PROJECT_REF, INT_METRIC_2_KEY); assertThat(rawMeasure1.get()) .hasQualityGateLevel(ERROR) .hasQualityGateText(dumbResultTextAnswer(equalsOneErrorCondition, ERROR, rawValue)); assertThat(rawMeasure2.get()) .hasQualityGateLevel(OK) .hasQualityGateText(dumbResultTextAnswer(equalsOneOkCondition, OK, rawValue)); assertThat(getAlertStatusMeasure()) .hasQualityGateLevel(ERROR) .hasQualityGateText(dumbResultTextAnswer(equalsOneErrorCondition, ERROR, rawValue) + ", " + dumbResultTextAnswer(equalsOneOkCondition, OK, rawValue)); assertThat(getQGDetailsMeasure()) .hasValue(new QualityGateDetailsData(ERROR, of( new EvaluatedCondition(equalsOneErrorCondition, ERROR, rawValue), new EvaluatedCondition(equalsOneOkCondition, OK, rawValue)), false).toJson()); QualityGateStatusHolderAssertions.assertThat(qualityGateStatusHolder) .hasStatus(QualityGateStatus.ERROR) .hasConditionCount(2) .hasCondition(equalsOneErrorCondition, ConditionStatus.EvaluationStatus.ERROR, String.valueOf(rawValue)) .hasCondition(equalsOneOkCondition, ConditionStatus.EvaluationStatus.OK, String.valueOf(rawValue)); } @Test public void new_measure_has_ERROR_level_of_all_conditions_for_a_specific_metric_if_its_the_worst() { int rawValue = 3; Condition fixedCondition = createLessThanCondition(INT_METRIC_1, "4"); Condition periodCondition = createLessThanCondition(INT_METRIC_1, "2"); qualityGateHolder.setQualityGate(new QualityGate(SOME_QG_UUID, SOME_QG_NAME, of(fixedCondition, periodCondition))); Measure measure = newMeasureBuilder().create(rawValue, null); measureRepository.addRawMeasure(PROJECT_REF, INT_METRIC_1_KEY, measure); underTest.execute(new TestComputationStepContext()); Optional<Measure> rawMeasure1 = measureRepository.getAddedRawMeasure(PROJECT_REF, INT_METRIC_1_KEY); assertThat(rawMeasure1.get()) .hasQualityGateLevel(ERROR) .hasQualityGateText(dumbResultTextAnswer(fixedCondition, ERROR, rawValue)); } @Test public void new_measure_has_condition_on_leak_period_when_all_conditions_on_specific_metric_has_same_QG_level() { int rawValue = 0; Condition fixedCondition = createLessThanCondition(INT_METRIC_1, "1"); Condition periodCondition = createLessThanCondition(INT_METRIC_1, "1"); qualityGateHolder.setQualityGate(new QualityGate(SOME_QG_UUID, SOME_QG_NAME, of(fixedCondition, periodCondition))); Measure measure = newMeasureBuilder().create(rawValue); measureRepository.addRawMeasure(PROJECT_REF, INT_METRIC_1_KEY, measure); underTest.execute(new TestComputationStepContext()); Optional<Measure> rawMeasure1 = measureRepository.getAddedRawMeasure(PROJECT_REF, INT_METRIC_1_KEY); assertThat(rawMeasure1.get()) .hasQualityGateLevel(ERROR) .hasQualityGateText(dumbResultTextAnswer(periodCondition, ERROR, rawValue)); } private Measure getAlertStatusMeasure() { return measureRepository.getAddedRawMeasure(PROJECT_REF, ALERT_STATUS_KEY).get(); } private Optional<Measure> getQGDetailsMeasure() { return measureRepository.getAddedRawMeasure(PROJECT_REF, CoreMetrics.QUALITY_GATE_DETAILS_KEY); } private static Condition createLessThanCondition(Metric metric, String errorThreshold) { return new Condition(metric, Condition.Operator.LESS_THAN.getDbValue(), errorThreshold); } private static MetricImpl createIntMetric(int index) { return new MetricImpl("uuid" + index, "metricKey" + index, "metricName" + index, Metric.MetricType.INT); } private static class QualityGateStatusHolderAssertions extends AbstractAssert<QualityGateStatusHolderAssertions, QualityGateStatusHolder> { private QualityGateStatusHolderAssertions(QualityGateStatusHolder actual) { super(actual, QualityGateStatusHolderAssertions.class); } public static QualityGateStatusHolderAssertions assertThat(QualityGateStatusHolder holder) { return new QualityGateStatusHolderAssertions(holder); } public QualityGateStatusHolderAssertions hasStatus(QualityGateStatus status) { if (actual.getStatus() != status) { failWithMessage( "Expected QualityGateStatusHolder to have global status <%s> but was <%s>", status, actual.getStatus()); } return this; } public QualityGateStatusHolderAssertions hasConditionCount(int count) { int conditionCount = actual.getStatusPerConditions().size(); if (conditionCount != count) { failWithMessage( "Expected QualityGateStatusHolder to have <%s> conditions but it has <%s>", count, conditionCount); } return this; } public QualityGateStatusHolderAssertions hasCondition(Condition condition, ConditionStatus.EvaluationStatus evaluationStatus, @Nullable String expectedValue) { for (Map.Entry<Condition, ConditionStatus> entry : actual.getStatusPerConditions().entrySet()) { if (entry.getKey() == condition) { ConditionStatus.EvaluationStatus actualStatus = entry.getValue().getStatus(); if (actualStatus != evaluationStatus) { failWithMessage( "Expected Status of condition <%s> in QualityGateStatusHolder to be <%s> but it was <%s>", condition, evaluationStatus, actualStatus); } String actualValue = entry.getValue().getValue(); if (!Objects.equals(expectedValue, actualValue)) { failWithMessage( "Expected Value of condition <%s> in QualityGateStatusHolder to be <%s> but it was <%s>", condition, expectedValue, actualValue); } return this; } } failWithMessage( "Expected QualityGateStatusHolder to have an entry for <%s> but none was found", condition); return this; } } }
16,262
45.465714
170
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/QualityProfileEventsStepTest.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.step; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.resources.AbstractLanguage; import org.sonar.api.resources.Language; 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.event.Event; import org.sonar.ce.task.projectanalysis.event.EventRepository; import org.sonar.ce.task.projectanalysis.language.LanguageRepository; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepository; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepository; import org.sonar.ce.task.projectanalysis.qualityprofile.MutableQProfileStatusRepository; import org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepositoryImpl; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.util.UtcDateUtils; import org.sonar.server.qualityprofile.QPMeasureData; import org.sonar.server.qualityprofile.QualityProfile; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.api.utils.DateUtils.parseDateTime; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.ADDED; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.REMOVED; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UNCHANGED; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UPDATED; public class QualityProfileEventsStepTest { @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); private static final String QP_NAME_1 = "qp_1"; private static final String QP_NAME_2 = "qp_2"; private static final String LANGUAGE_KEY_1 = "language_key1"; private static final String LANGUAGE_KEY_2 = "language_key_2"; private static final String LANGUAGE_KEY_3 = "languageKey3"; private MetricRepository metricRepository = mock(MetricRepository.class); private MeasureRepository measureRepository = mock(MeasureRepository.class); private LanguageRepository languageRepository = mock(LanguageRepository.class); private EventRepository eventRepository = mock(EventRepository.class); private ArgumentCaptor<Event> eventArgumentCaptor = ArgumentCaptor.forClass(Event.class); private MutableQProfileStatusRepository qProfileStatusRepository = new QProfileStatusRepositoryImpl(); private Metric qualityProfileMetric = mock(Metric.class); private QualityProfileEventsStep underTest = new QualityProfileEventsStep(treeRootHolder, metricRepository, measureRepository, languageRepository, eventRepository, qProfileStatusRepository); @Before public void setUp() { when(metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY)).thenReturn(qualityProfileMetric); treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("uuid").setKey("key").build()); } @Test public void no_event_if_no_base_measure() { when(measureRepository.getBaseMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.empty()); underTest.execute(new TestComputationStepContext()); verifyNoMoreInteractions(eventRepository); } @Test public void no_event_if_no_raw_measure() { when(measureRepository.getBaseMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.of(newMeasure())); when(measureRepository.getRawMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.empty()); underTest.execute(new TestComputationStepContext()); verifyNoMoreInteractions(eventRepository); } @Test public void no_event_if_no_base_and_quality_profile_measure_is_empty() { mockMeasures(treeRootHolder.getRoot(), null, null); underTest.execute(new TestComputationStepContext()); verifyNoMoreInteractions(eventRepository); } @Test public void added_event_if_qp_is_added() { QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date()); qProfileStatusRepository.register(qp.getQpKey(), ADDED); Language language = mockLanguageInRepository(LANGUAGE_KEY_1); mockMeasures(treeRootHolder.getRoot(), null, arrayOf(qp)); underTest.execute(new TestComputationStepContext()); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(eventRepository); verifyEvent(eventArgumentCaptor.getValue(), "Use '" + qp.getQpName() + "' (" + language.getName() + ")", null); } @Test public void added_event_uses_language_key_in_message_if_language_not_found() { QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date()); qProfileStatusRepository.register(qp.getQpKey(), ADDED); mockLanguageNotInRepository(LANGUAGE_KEY_1); mockMeasures(treeRootHolder.getRoot(), null, arrayOf(qp)); underTest.execute(new TestComputationStepContext()); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(eventRepository); verifyEvent(eventArgumentCaptor.getValue(), "Use '" + qp.getQpName() + "' (" + qp.getLanguageKey() + ")", null); } @Test public void no_more_used_event_if_qp_is_removed() { QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date()); qProfileStatusRepository.register(qp.getQpKey(), REMOVED); mockMeasures(treeRootHolder.getRoot(), arrayOf(qp), null); Language language = mockLanguageInRepository(LANGUAGE_KEY_1); underTest.execute(new TestComputationStepContext()); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(eventRepository); verifyEvent(eventArgumentCaptor.getValue(), "Stop using '" + qp.getQpName() + "' (" + language.getName() + ")", null); } @Test public void no_more_used_event_uses_language_key_in_message_if_language_not_found() { QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date()); qProfileStatusRepository.register(qp.getQpKey(), REMOVED); mockMeasures(treeRootHolder.getRoot(), arrayOf(qp), null); mockLanguageNotInRepository(LANGUAGE_KEY_1); underTest.execute(new TestComputationStepContext()); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(eventRepository); verifyEvent(eventArgumentCaptor.getValue(), "Stop using '" + qp.getQpName() + "' (" + qp.getLanguageKey() + ")", null); } @Test public void no_event_if_qp_is_unchanged() { QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date()); qProfileStatusRepository.register(qp.getQpKey(), UNCHANGED); mockMeasures(treeRootHolder.getRoot(), arrayOf(qp), arrayOf(qp)); underTest.execute(new TestComputationStepContext()); verify(eventRepository, never()).add(any(Event.class)); } @Test public void changed_event_if_qp_has_been_updated() { QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:13+0100")); QualityProfile qp2 = qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:17+0100")); qProfileStatusRepository.register(qp2.getQpKey(), UPDATED); mockMeasures(treeRootHolder.getRoot(), arrayOf(qp1), arrayOf(qp2)); Language language = mockLanguageInRepository(LANGUAGE_KEY_1); underTest.execute(new TestComputationStepContext()); verify(eventRepository).add(eventArgumentCaptor.capture()); verifyNoMoreInteractions(eventRepository); verifyEvent(eventArgumentCaptor.getValue(), "Changes in '" + qp2.getQpName() + "' (" + language.getName() + ")", "from=" + UtcDateUtils.formatDateTime(parseDateTime("2011-04-25T01:05:14+0100")) + ";key=" + qp1.getQpKey() + ";to=" + UtcDateUtils.formatDateTime(parseDateTime("2011-04-25T01:05:18+0100"))); } @Test public void verify_detection_with_complex_mix_of_qps() { final Set<Event> events = new HashSet<>(); doAnswer(invocationOnMock -> { events.add((Event) invocationOnMock.getArguments()[0]); return null; }).when(eventRepository).add(any(Event.class)); Date date = new Date(); QualityProfile qp1 = qp(QP_NAME_2, LANGUAGE_KEY_1, date); QualityProfile qp2 = qp(QP_NAME_2, LANGUAGE_KEY_2, date); QualityProfile qp3 = qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:13+0100")); QualityProfile qp3_updated = qp(QP_NAME_1, LANGUAGE_KEY_1, parseDateTime("2011-04-25T01:05:17+0100")); QualityProfile qp4 = qp(QP_NAME_2, LANGUAGE_KEY_3, date); mockMeasures( treeRootHolder.getRoot(), arrayOf(qp1, qp2, qp3), arrayOf(qp3_updated, qp2, qp4)); mockNoLanguageInRepository(); qProfileStatusRepository.register(qp1.getQpKey(), REMOVED); qProfileStatusRepository.register(qp2.getQpKey(), UNCHANGED); qProfileStatusRepository.register(qp3.getQpKey(), UPDATED); qProfileStatusRepository.register(qp4.getQpKey(), ADDED); underTest.execute(new TestComputationStepContext()); assertThat(events).extracting("name").containsOnly( "Stop using '" + QP_NAME_2 + "' (" + LANGUAGE_KEY_1 + ")", "Use '" + QP_NAME_2 + "' (" + LANGUAGE_KEY_3 + ")", "Changes in '" + QP_NAME_1 + "' (" + LANGUAGE_KEY_1 + ")"); } private Language mockLanguageInRepository(String languageKey) { Language language = new AbstractLanguage(languageKey, languageKey + "_name") { @Override public String[] getFileSuffixes() { return new String[0]; } }; when(languageRepository.find(languageKey)).thenReturn(Optional.of(language)); return language; } private void mockLanguageNotInRepository(String languageKey) { when(languageRepository.find(languageKey)).thenReturn(Optional.empty()); } private void mockNoLanguageInRepository() { when(languageRepository.find(anyString())).thenReturn(Optional.empty()); } private void mockMeasures(Component component, @Nullable QualityProfile[] previous, @Nullable QualityProfile[] current) { when(measureRepository.getBaseMeasure(component, qualityProfileMetric)).thenReturn(Optional.of(newMeasure(previous))); when(measureRepository.getRawMeasure(component, qualityProfileMetric)).thenReturn(Optional.of(newMeasure(current))); } private static void verifyEvent(Event event, String expectedName, @Nullable String expectedData) { assertThat(event.getName()).isEqualTo(expectedName); assertThat(event.getData()).isEqualTo(expectedData); assertThat(event.getCategory()).isEqualTo(Event.Category.PROFILE); assertThat(event.getDescription()).isNull(); } private static QualityProfile qp(String qpName, String languageKey, Date date) { return new QualityProfile(qpName + "-" + languageKey, qpName, languageKey, date); } /** * Just a trick to use variable args which is shorter than writing new QualityProfile[] { } */ private static QualityProfile[] arrayOf(QualityProfile... qps) { return qps; } private static Measure newMeasure(@Nullable QualityProfile... qps) { return Measure.newMeasureBuilder().create(toJson(qps)); } private static String toJson(@Nullable QualityProfile... qps) { List<QualityProfile> qualityProfiles = qps == null ? Collections.emptyList() : Arrays.asList(qps); return QPMeasureData.toJson(new QPMeasureData(qualityProfiles)); } }
13,003
42.784512
192
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/RegisterQualityProfileStatusStepTest.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.step; import com.google.common.collect.ImmutableList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; 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.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.measure.Measure; import org.sonar.ce.task.projectanalysis.measure.MeasureRepository; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepository; import org.sonar.ce.task.projectanalysis.qualityprofile.MutableQProfileStatusRepository; import org.sonar.ce.task.projectanalysis.qualityprofile.RegisterQualityProfileStatusStep; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.server.qualityprofile.QPMeasureData; import org.sonar.server.qualityprofile.QualityProfile; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.ADDED; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.REMOVED; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UNCHANGED; import static org.sonar.ce.task.projectanalysis.qualityprofile.QProfileStatusRepository.Status.UPDATED; public class RegisterQualityProfileStatusStepTest { private static final String QP_NAME_1 = "qp_1"; private static final String QP_NAME_2 = "qp_2"; private static final String LANGUAGE_KEY_1 = "language_key1"; private static final String LANGUAGE_KEY_2 = "language_key_2"; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); private MetricRepository metricRepository = mock(MetricRepository.class); private MeasureRepository measureRepository = mock(MeasureRepository.class); private MutableQProfileStatusRepository qProfileStatusRepository = mock(MutableQProfileStatusRepository.class); private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); private Metric qualityProfileMetric = mock(Metric.class); private RegisterQualityProfileStatusStep underTest = new RegisterQualityProfileStatusStep(treeRootHolder, measureRepository, metricRepository, qProfileStatusRepository, analysisMetadataHolder); @Before public void setUp() { when(metricRepository.getByKey(CoreMetrics.QUALITY_PROFILES_KEY)).thenReturn(qualityProfileMetric); treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("uuid").setKey("key").build()); } @Test public void register_nothing_if_no_base_measure() { when(measureRepository.getBaseMeasure(treeRootHolder.getRoot(), qualityProfileMetric)).thenReturn(Optional.empty()); underTest.execute(new TestComputationStepContext()); verifyNoMoreInteractions(qProfileStatusRepository); } @Test public void register_nothing_if_no_base_and_quality_profile_measure_is_empty() { mockBaseQPMeasures(treeRootHolder.getRoot(), null); underTest.execute(new TestComputationStepContext()); verifyNoMoreInteractions(qProfileStatusRepository); } @Test public void register_removed_profile() { QualityProfile qp = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date()); mockBaseQPMeasures(treeRootHolder.getRoot(), new QualityProfile[] {qp}); underTest.execute(new TestComputationStepContext()); verify(qProfileStatusRepository).register(qp.getQpKey(), REMOVED); verifyNoMoreInteractions(qProfileStatusRepository); } @Test public void register_added_profile() { QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date(1000L)); QualityProfile qp2 = qp(QP_NAME_2, LANGUAGE_KEY_2, new Date(1000L)); mockBaseQPMeasures(treeRootHolder.getRoot(), arrayOf(qp1)); mockRawQProfiles(ImmutableList.of(qp1, qp2)); underTest.execute(new TestComputationStepContext()); verify(qProfileStatusRepository).register(qp1.getQpKey(), UNCHANGED); verify(qProfileStatusRepository).register(qp2.getQpKey(), ADDED); verifyNoMoreInteractions(qProfileStatusRepository); } @Test public void register_updated_profile() { QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date(1000L)); QualityProfile qp2 = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date(1200L)); mockBaseQPMeasures(treeRootHolder.getRoot(), arrayOf(qp1)); mockRawQProfiles(ImmutableList.of(qp2)); underTest.execute(new TestComputationStepContext()); verify(qProfileStatusRepository).register(qp2.getQpKey(), UPDATED); verifyNoMoreInteractions(qProfileStatusRepository); } @Test public void register_unchanged_profile() { QualityProfile qp1 = qp(QP_NAME_1, LANGUAGE_KEY_1, new Date(1000L)); mockBaseQPMeasures(treeRootHolder.getRoot(), arrayOf(qp1)); mockRawQProfiles(ImmutableList.of(qp1)); underTest.execute(new TestComputationStepContext()); verify(qProfileStatusRepository).register(qp1.getQpKey(), UNCHANGED); verifyNoMoreInteractions(qProfileStatusRepository); } private void mockBaseQPMeasures(Component component, @Nullable QualityProfile[] previous) { when(measureRepository.getBaseMeasure(component, qualityProfileMetric)).thenReturn(Optional.of(newMeasure(previous))); } private void mockRawQProfiles(@Nullable List<QualityProfile> previous) { Map<String, QualityProfile> qpByLanguages = previous.stream().collect(Collectors.toMap(QualityProfile::getLanguageKey, q -> q)); when(analysisMetadataHolder.getQProfilesByLanguage()).thenReturn(qpByLanguages); } private static QualityProfile qp(String qpName, String languageKey, Date date) { return new QualityProfile(qpName + "-" + languageKey, qpName, languageKey, date); } private static QualityProfile[] arrayOf(QualityProfile... qps) { return qps; } private static Measure newMeasure(@Nullable QualityProfile... qps) { return Measure.newMeasureBuilder().create(toJson(qps)); } private static String toJson(@Nullable QualityProfile... qps) { List<QualityProfile> qualityProfiles = qps == null ? Collections.emptyList() : Arrays.asList(qps); return QPMeasureData.toJson(new QPMeasureData(qualityProfiles)); } }
7,609
41.513966
195
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportCommentMeasuresStepTest.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.step; import org.junit.Before; 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 org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; 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_DENSITY; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_API; import static org.sonar.api.measures.CoreMetrics.PUBLIC_API_KEY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_UNDOCUMENTED_API; import static org.sonar.api.measures.CoreMetrics.PUBLIC_UNDOCUMENTED_API_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; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; public class ReportCommentMeasuresStepTest { 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; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC) .add(COMMENT_LINES) .add(COMMENT_LINES_DENSITY) .add(PUBLIC_API) .add(PUBLIC_UNDOCUMENTED_API) .add(PUBLIC_DOCUMENTED_API_DENSITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); ComputationStep underTest = new CommentMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Before public void setUp() { treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF) .addChildren( builder(FILE, FILE_1_REF).build(), builder(FILE, FILE_2_REF).build()) .build()) .build()); } @Test public void aggregate_comment_lines() { measureRepository.addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(400)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, COMMENT_LINES_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, COMMENT_LINES_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, COMMENT_LINES_KEY).get().getIntValue()).isEqualTo(500); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, COMMENT_LINES_KEY).get().getIntValue()).isEqualTo(500); } @Test public void compute_comment_density() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(150)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(200)); measureRepository.addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(50)); measureRepository.addRawMeasure(DIRECTORY_REF, NCLOC_KEY, newMeasureBuilder().create(300)); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(300)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(60d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(20d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(40d); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(40d); } @Test public void compute_zero_comment_density_when_zero_comment() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(200)); measureRepository.addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(DIRECTORY_REF, NCLOC_KEY, newMeasureBuilder().create(300)); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(300)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, COMMENT_LINES_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); } @Test public void not_compute_comment_density_when_zero_ncloc_and_zero_comment() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(DIRECTORY_REF, NCLOC_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(0)); underTest.execute(new TestComputationStepContext()); assertNoNewMeasures(COMMENT_LINES_DENSITY_KEY); } @Test public void not_compute_comment_density_when_no_ncloc() { measureRepository.addRawMeasure(FILE_1_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(150)); measureRepository.addRawMeasure(FILE_2_REF, COMMENT_LINES_KEY, newMeasureBuilder().create(50)); underTest.execute(new TestComputationStepContext()); assertNoNewMeasures(COMMENT_LINES_DENSITY_KEY); } @Test public void not_compute_comment_density_when_no_comment() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(DIRECTORY_REF, NCLOC_KEY, newMeasureBuilder().create(200)); measureRepository.addRawMeasure(ROOT_REF, NCLOC_KEY, newMeasureBuilder().create(200)); underTest.execute(new TestComputationStepContext()); assertNoNewMeasures(COMMENT_LINES_DENSITY_KEY); } @Test public void aggregate_public_api() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_API_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_API_KEY, newMeasureBuilder().create(400)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, PUBLIC_API_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, PUBLIC_API_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, PUBLIC_API_KEY).get().getIntValue()).isEqualTo(500); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, PUBLIC_API_KEY).get().getIntValue()).isEqualTo(500); } @Test public void aggregate_public_undocumented_api() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(400)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, PUBLIC_UNDOCUMENTED_API_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, PUBLIC_UNDOCUMENTED_API_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, PUBLIC_UNDOCUMENTED_API_KEY).get().getIntValue()).isEqualTo(500); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, PUBLIC_UNDOCUMENTED_API_KEY).get().getIntValue()).isEqualTo(500); } @Test public void compute_public_documented_api_density() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_API_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(50)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_API_KEY, newMeasureBuilder().create(400)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(100)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(50d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(75d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(70d); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(70d); } @Test public void not_compute_public_documented_api_density_when_no_public_api() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(50)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(100)); underTest.execute(new TestComputationStepContext()); assertNoNewMeasures(PUBLIC_DOCUMENTED_API_DENSITY_KEY); } @Test public void not_compute_public_documented_api_density_when_no_public_undocumented_api() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_API_KEY, newMeasureBuilder().create(50)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_API_KEY, newMeasureBuilder().create(100)); underTest.execute(new TestComputationStepContext()); assertNoNewMeasures(PUBLIC_DOCUMENTED_API_DENSITY_KEY); } @Test public void not_compute_public_documented_api_density_when_public_api_is_zero() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_API_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(50)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_API_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(100)); underTest.execute(new TestComputationStepContext()); assertNoNewMeasures(PUBLIC_DOCUMENTED_API_DENSITY_KEY); } @Test public void compute_100_percent_public_documented_api_density_when_public_undocumented_api_is_zero() { measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_API_KEY, newMeasureBuilder().create(100)); measureRepository.addRawMeasure(FILE_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_API_KEY, newMeasureBuilder().create(400)); measureRepository.addRawMeasure(FILE_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, newMeasureBuilder().create(0)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); } @Test public void compute_nothing_when_no_data() { underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasures(FILE_1_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(FILE_2_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(DIRECTORY_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF)).isEmpty(); } private void assertNoNewMeasures(String metric) { assertThat(measureRepository.getAddedRawMeasures(FILE_1_REF).get(metric)).isNull(); assertThat(measureRepository.getAddedRawMeasures(FILE_2_REF).get(metric)).isNull(); assertThat(measureRepository.getAddedRawMeasures(DIRECTORY_REF).get(metric)).isNull(); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF).get(metric)).isNull(); } }
14,769
51.375887
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportComplexityMeasuresStepTest.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.step; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; 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.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.CLASSES; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.CLASS_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.CLASS_COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.FILES; import static org.sonar.api.measures.CoreMetrics.FILES_KEY; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION_KEY; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_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.FILE; 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 ReportComplexityMeasuresStepTest { private static final int ROOT_REF = 1; private static final int DIRECTORY_REF = 1111; private static final int FILE_1_REF = 11111; private static final int FILE_2_REF = 11121; @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot(builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF) .addChildren( builder(FILE, FILE_1_REF).build(), builder(FILE, FILE_2_REF).build()) .build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(COMPLEXITY) .add(COMPLEXITY_IN_CLASSES) .add(COMPLEXITY_IN_FUNCTIONS) .add(FUNCTION_COMPLEXITY_DISTRIBUTION) .add(FILE_COMPLEXITY_DISTRIBUTION) .add(FILE_COMPLEXITY) .add(FILES) .add(CLASS_COMPLEXITY) .add(CLASSES) .add(FUNCTION_COMPLEXITY) .add(FUNCTIONS) .add(COGNITIVE_COMPLEXITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private ComputationStep underTest = new ComplexityMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Test public void aggregate_complexity() { verify_sum_aggregation(COMPLEXITY_KEY); } @Test public void aggregate_complexity_in_classes() { verify_sum_aggregation(COMPLEXITY_IN_CLASSES_KEY); } @Test public void aggregate_complexity_in_functions() { verify_sum_aggregation(COMPLEXITY_IN_FUNCTIONS_KEY); } @Test public void aggregate_cognitive_complexity() { verify_sum_aggregation(COGNITIVE_COMPLEXITY_KEY); } private void verify_sum_aggregation(String metricKey) { measureRepository.addRawMeasure(FILE_1_REF, metricKey, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, metricKey, newMeasureBuilder().create(40)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, metricKey)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, metricKey)).isNotPresent(); int expectedNonFileValue = 50; assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(expectedNonFileValue))); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(expectedNonFileValue))); } @Test public void aggregate_function_complexity_distribution() { verify_distribution_aggregation(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY); } @Test public void aggregate_file_complexity_distribution() { verify_distribution_aggregation(FILE_COMPLEXITY_DISTRIBUTION_KEY); } private void verify_distribution_aggregation(String metricKey) { measureRepository.addRawMeasure(FILE_1_REF, metricKey, newMeasureBuilder().create("0.5=3;3.5=5;6.5=9")); measureRepository.addRawMeasure(FILE_2_REF, metricKey, newMeasureBuilder().create("0.5=0;3.5=2;6.5=1")); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, metricKey)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, metricKey)).isNotPresent(); String expectedNonFileValue = "0.5=3;3.5=7;6.5=10"; assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(expectedNonFileValue))); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(expectedNonFileValue))); } @Test public void compute_and_aggregate_file_complexity() { verify_average_compute_and_aggregation(FILE_COMPLEXITY_KEY, COMPLEXITY_KEY, FILES_KEY); } @Test public void compute_and_aggregate_class_complexity() { verify_average_compute_and_aggregation(CLASS_COMPLEXITY_KEY, COMPLEXITY_IN_CLASSES_KEY, CLASSES_KEY); } @Test public void compute_and_aggregate_function_complexity() { verify_average_compute_and_aggregation(FUNCTION_COMPLEXITY_KEY, COMPLEXITY_IN_FUNCTIONS_KEY, FUNCTIONS_KEY); } private void verify_average_compute_and_aggregation(String metricKey, String mainMetric, String byMetric) { measureRepository.addRawMeasure(FILE_1_REF, mainMetric, newMeasureBuilder().create(5)); measureRepository.addRawMeasure(FILE_1_REF, byMetric, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(FILE_2_REF, mainMetric, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(FILE_2_REF, byMetric, newMeasureBuilder().create(1)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_1_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(2.5, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_2_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(1d, 1))); double expectedNonFileValue = 2d; assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(expectedNonFileValue, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(entryOf(metricKey, newMeasureBuilder().create(expectedNonFileValue, 1))); } }
9,161
46.226804
162
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportComputationStepsTest.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.step; import org.junit.Test; import org.sonar.ce.task.container.TaskContainerImpl; import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.SpringComponentContainer; import static com.google.common.collect.Lists.newArrayList; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class ReportComputationStepsTest { @Test public void instances_throws_ISE_if_container_does_not_have_any_step() { TaskContainerImpl computeEngineContainer = new TaskContainerImpl(new SpringComponentContainer(), container -> { // do nothing }); Iterable<ComputationStep> instances = new ReportComputationSteps(computeEngineContainer).instances(); assertThatThrownBy(() -> newArrayList(instances)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining(ExtractReportStep.class.getName()); } @Test public void instances_throws_ISE_if_container_does_not_have_second_step() { ExtractReportStep reportExtractionStep = mock(ExtractReportStep.class); SpringComponentContainer componentContainer = new SpringComponentContainer() { { add(reportExtractionStep); } }.startComponents(); TaskContainerImpl computeEngineContainer = new TaskContainerImpl(componentContainer, container -> { // do nothing }); computeEngineContainer.startComponents(); Iterable<ComputationStep> instances = new ReportComputationSteps(computeEngineContainer).instances(); assertThatThrownBy(() -> newArrayList(instances)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("org.sonar.ce.task.projectanalysis.step.PersistScannerContextStep"); } }
2,600
40.951613
115
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportCoverageMeasuresStepTest.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.step; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; import org.sonar.ce.task.projectanalysis.component.FileAttributes; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredMetricKeys; 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.ce.task.step.TestComputationStepContext; import org.sonar.scanner.protocol.output.ScannerReport; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.CONDITIONS_TO_COVER_KEY; import static org.sonar.api.measures.CoreMetrics.LINES_TO_COVER_KEY; import static org.sonar.api.measures.CoreMetrics.UNCOVERED_CONDITIONS_KEY; import static org.sonar.api.measures.CoreMetrics.UNCOVERED_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; 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 ReportCoverageMeasuresStepTest { 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 UNIT_TEST_FILE_REF = 12342; private static final int FILE_2_REF = 12343; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.LINES_TO_COVER) .add(CoreMetrics.CONDITIONS_TO_COVER) .add(CoreMetrics.UNCOVERED_LINES) .add(CoreMetrics.UNCOVERED_CONDITIONS) .add(CoreMetrics.COVERAGE) .add(CoreMetrics.BRANCH_COVERAGE) .add(CoreMetrics.LINE_COVERAGE); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); CoverageMeasuresStep underTest = new CoverageMeasuresStep(treeRootHolder, metricRepository, measureRepository, reportReader); @Before public void setUp() { treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF) .addChildren( builder(FILE, FILE_1_REF).build(), builder(FILE, UNIT_TEST_FILE_REF).setFileAttributes(new FileAttributes(true, "some language", 1)).build(), builder(FILE, FILE_2_REF).build()) .build()) .build()); } @Test public void verify_aggregates_values_for_lines_and_conditions() { reportReader.putCoverage(FILE_1_REF, asList( ScannerReport.LineCoverage.newBuilder().setLine(2).setHits(false).build(), ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(true).build(), ScannerReport.LineCoverage.newBuilder().setLine(4).setHits(true).setConditions(4).setCoveredConditions(1).build(), ScannerReport.LineCoverage.newBuilder().setLine(5).setConditions(8).setCoveredConditions(2).build(), ScannerReport.LineCoverage.newBuilder().setLine(6).setHits(false).setConditions(3).setCoveredConditions(0).build(), ScannerReport.LineCoverage.newBuilder().setLine(7).setHits(false).build())); reportReader.putCoverage(FILE_2_REF, asList( ScannerReport.LineCoverage.newBuilder().setLine(2).setHits(true).build(), ScannerReport.LineCoverage.newBuilder().setLine(3).setHits(false).build(), ScannerReport.LineCoverage.newBuilder().setLine(5).setHits(true).setConditions(5).setCoveredConditions(1).build(), ScannerReport.LineCoverage.newBuilder().setLine(6).setConditions(10).setCoveredConditions(3).build(), ScannerReport.LineCoverage.newBuilder().setLine(7).setHits(false).setConditions(1).setCoveredConditions(0).build(), ScannerReport.LineCoverage.newBuilder().setLine(8).setHits(false).build())); underTest.execute(new TestComputationStepContext()); MeasureRepoEntry[] nonFileRepoEntries = { entryOf(LINES_TO_COVER_KEY, newMeasureBuilder().create(5 + 5)), entryOf(CONDITIONS_TO_COVER_KEY, newMeasureBuilder().create(4 + 8 + 3 + 5 + 10 + 1)), entryOf(UNCOVERED_LINES_KEY, newMeasureBuilder().create(3 + 3)), entryOf(UNCOVERED_CONDITIONS_KEY, newMeasureBuilder().create(3 + 6 + 3 + 4 + 7 + 1)) }; assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).contains(nonFileRepoEntries); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(nonFileRepoEntries); } @Test public void verify_aggregates_values_for_code_line_and_branch_coverage() { LinesAndConditionsWithUncoveredMetricKeys metricKeys = new LinesAndConditionsWithUncoveredMetricKeys( LINES_TO_COVER_KEY, CONDITIONS_TO_COVER_KEY, UNCOVERED_LINES_KEY, UNCOVERED_CONDITIONS_KEY); String codeCoverageKey = CoreMetrics.COVERAGE_KEY; String lineCoverageKey = CoreMetrics.LINE_COVERAGE_KEY; String branchCoverageKey = CoreMetrics.BRANCH_COVERAGE_KEY; verify_coverage_aggregates_values(metricKeys, codeCoverageKey, lineCoverageKey, branchCoverageKey); } private void verify_coverage_aggregates_values(LinesAndConditionsWithUncoveredMetricKeys metricKeys, String codeCoverageKey, String lineCoverageKey, String branchCoverageKey) { measureRepository .addRawMeasure(FILE_1_REF, metricKeys.lines(), newMeasureBuilder().create(3000)) .addRawMeasure(FILE_1_REF, metricKeys.conditions(), newMeasureBuilder().create(300)) .addRawMeasure(FILE_1_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(30)) .addRawMeasure(FILE_1_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(9)) .addRawMeasure(FILE_2_REF, metricKeys.lines(), newMeasureBuilder().create(2000)) .addRawMeasure(FILE_2_REF, metricKeys.conditions(), newMeasureBuilder().create(400)) .addRawMeasure(FILE_2_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(200)) .addRawMeasure(FILE_2_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(16)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_1_REF))).contains( entryOf(codeCoverageKey, newMeasureBuilder().create(98.8d, 1)), entryOf(lineCoverageKey, newMeasureBuilder().create(99d, 1)), entryOf(branchCoverageKey, newMeasureBuilder().create(97d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_2_REF))).contains( entryOf(codeCoverageKey, newMeasureBuilder().create(91d, 1)), entryOf(lineCoverageKey, newMeasureBuilder().create(90d, 1)), entryOf(branchCoverageKey, newMeasureBuilder().create(96d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(UNIT_TEST_FILE_REF))).isEmpty(); MeasureRepoEntry[] nonFileRepoEntries = { entryOf(codeCoverageKey, newMeasureBuilder().create(95.5d, 1)), entryOf(lineCoverageKey, newMeasureBuilder().create(95.4d, 1)), entryOf(branchCoverageKey, newMeasureBuilder().create(96.4d, 1)) }; assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).contains(nonFileRepoEntries); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(nonFileRepoEntries); } }
8,928
50.912791
178
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportLanguageDistributionMeasuresStepTest.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.step; 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 org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_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; import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder; public class ReportLanguageDistributionMeasuresStepTest { private static final String XOO_LANGUAGE = "xoo"; private static final String JAVA_LANGUAGE = "java"; 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 = 12343; private static final int FILE_4_REF = 12344; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC) .add(NCLOC_LANGUAGE_DISTRIBUTION); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); ComputationStep underTest = new LanguageDistributionMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Before public void setUp() { treeRootHolder.setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF) .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, XOO_LANGUAGE, 1)).build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(false, XOO_LANGUAGE, 1)).build(), builder(FILE, FILE_3_REF).setFileAttributes(new FileAttributes(false, JAVA_LANGUAGE, 1)).build(), builder(FILE, FILE_4_REF).setFileAttributes(new FileAttributes(false, null, 1)).build()) .build()) .build()); } @Test public void compute_ncloc_language_distribution() { measureRepository.addRawMeasure(FILE_1_REF, NCLOC_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, NCLOC_KEY, newMeasureBuilder().create(8)); measureRepository.addRawMeasure(FILE_3_REF, NCLOC_KEY, newMeasureBuilder().create(6)); measureRepository.addRawMeasure(FILE_4_REF, NCLOC_KEY, newMeasureBuilder().create(2)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY).get().getStringValue()).isEqualTo("xoo=10"); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY).get().getStringValue()).isEqualTo("xoo=8"); assertThat(measureRepository.getAddedRawMeasure(FILE_3_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY).get().getStringValue()).isEqualTo("java=6"); assertThat(measureRepository.getAddedRawMeasure(FILE_4_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY).get().getStringValue()).isEqualTo("<null>=2"); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY).get().getStringValue()).isEqualTo("<null>=2;java=6;xoo=18"); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY).get().getStringValue()).isEqualTo("<null>=2;java=6;xoo=18"); } @Test public void do_not_compute_ncloc_language_distribution_when_no_ncloc() { underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_3_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_4_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY)).isNotPresent(); } }
5,888
50.208696
160
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportSizeMeasuresStepTest.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.step; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.FileAttributes; 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.ce.task.step.TestComputationStepContext; import static com.google.common.base.Predicates.notNull; import static com.google.common.collect.FluentIterable.from; import static com.google.common.collect.Iterables.concat; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.FILES_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.GENERATED_LINES_KEY; 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.STATEMENTS_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; 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 ReportSizeMeasuresStepTest { private static final String LANGUAGE_DOES_NOT_MATTER_HERE = null; private static final int ROOT_REF = 1; private static final int DIRECTORY_1_REF = 1234; private static final int DIRECTORY_2_REF = 1235; private static final int DIRECTORY_3_REF = 1236; private static final int DIRECTORY_4_REF = 1237; private static final int DIRECTORY_4_1_REF = 1238; private static final int DIRECTORY_4_2_REF = 1239; private static final int DIRECTORY_4_3_REF = 1240; private static final int FILE_1_REF = 12341; private static final int FILE_2_REF = 12343; private static final int FILE_3_REF = 12351; private static final int FILE_4_REF = 12371; private static final int FILE_5_REF = 12372; private static final int UNIT_TEST_1_REF = 12352; private static final int UNIT_TEST_2_REF = 12361; private static final int UNIT_TEST_3_REF = 12362; private static final Integer NO_METRIC = null; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_1_REF) .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_DOES_NOT_MATTER_HERE, 1)).build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_DOES_NOT_MATTER_HERE, 2)).build()) .build(), builder(DIRECTORY, DIRECTORY_2_REF) .addChildren( builder(FILE, FILE_3_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_DOES_NOT_MATTER_HERE, 7)).build(), builder(FILE, UNIT_TEST_1_REF).setFileAttributes(new FileAttributes(true, LANGUAGE_DOES_NOT_MATTER_HERE, 4)).build()) .build(), builder(DIRECTORY, DIRECTORY_3_REF) .addChildren( builder(FILE, UNIT_TEST_2_REF).setFileAttributes(new FileAttributes(true, LANGUAGE_DOES_NOT_MATTER_HERE, 10)).build()) .build(), builder(DIRECTORY, DIRECTORY_4_REF) .addChildren( builder(DIRECTORY, DIRECTORY_4_1_REF) .addChildren( builder(FILE, FILE_4_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_DOES_NOT_MATTER_HERE, 9)).build()).build(), builder(DIRECTORY, DIRECTORY_4_2_REF) .addChildren( builder(FILE, FILE_5_REF).setFileAttributes(new FileAttributes(false, LANGUAGE_DOES_NOT_MATTER_HERE, 5)).build()).build(), builder(DIRECTORY, DIRECTORY_4_3_REF) .addChildren( builder(FILE, UNIT_TEST_3_REF).setFileAttributes(new FileAttributes(true, LANGUAGE_DOES_NOT_MATTER_HERE, 6)).build()).build() ).build() ).build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.FILES) .add(CoreMetrics.DIRECTORIES) .add(CoreMetrics.LINES) .add(CoreMetrics.GENERATED_LINES) .add(CoreMetrics.NCLOC) .add(CoreMetrics.GENERATED_NCLOC) .add(CoreMetrics.FUNCTIONS) .add(CoreMetrics.STATEMENTS) .add(CoreMetrics.CLASSES); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private SizeMeasuresStep underTest = new SizeMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Test public void verify_LINES_and_FILE_and_DIRECTORY_computation_and_aggregation() { underTest.execute(new TestComputationStepContext()); verifyMeasuresOnFile(FILE_1_REF, 1, 1); verifyMeasuresOnFile(FILE_2_REF, 2, 1); verifyMeasuresOnFile(FILE_3_REF, 7, 1); verifyMeasuresOnFile(FILE_4_REF, 9, 1); verifyMeasuresOnFile(FILE_5_REF, 5, 1); verifyNoMeasure(UNIT_TEST_1_REF); verifyNoMeasure(UNIT_TEST_2_REF); verifyMeasuresOnOtherComponent(DIRECTORY_1_REF, 3, 2, NO_METRIC); verifyMeasuresOnOtherComponent(DIRECTORY_2_REF, 7, 1, NO_METRIC); verifyMeasuresOnOtherComponent(DIRECTORY_3_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasuresOnOtherComponent(DIRECTORY_4_REF, 14, 2, 2); verifyMeasuresOnOtherComponent(ROOT_REF, 24, 5, 5); } @Test public void verify_GENERATED_LINES_related_measures_aggregation() { verifyMetricAggregation(GENERATED_LINES_KEY); } @Test public void verify_NCLOC_measure_aggregation() { verifyMetricAggregation(NCLOC_KEY); } private void verifyMetricAggregation(String metricKey) { measureRepository.addRawMeasure(FILE_1_REF, metricKey, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, metricKey, newMeasureBuilder().create(6)); measureRepository.addRawMeasure(UNIT_TEST_1_REF, metricKey, newMeasureBuilder().create(3)); underTest.execute(new TestComputationStepContext()); verifyMeasuresOnFile(FILE_1_REF, 1, 1); verifyMeasuresOnFile(FILE_2_REF, 2, 1); verifyMeasuresOnFile(FILE_3_REF, 7, 1); verifyMeasuresOnFile(FILE_4_REF, 9, 1); verifyMeasuresOnFile(FILE_5_REF, 5, 1); verifyNoMeasure(UNIT_TEST_1_REF); verifyNoMeasure(UNIT_TEST_2_REF); verifyMeasuresOnOtherComponent(DIRECTORY_1_REF, 3, 2, NO_METRIC, entryOf(metricKey, newMeasureBuilder().create(16))); verifyMeasuresOnOtherComponent(DIRECTORY_2_REF, 7, 1, NO_METRIC, entryOf(metricKey, newMeasureBuilder().create(3))); verifyMeasuresOnOtherComponent(DIRECTORY_3_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasuresOnOtherComponent(DIRECTORY_4_REF, 14, 2, 2); verifyMeasuresOnOtherComponent(ROOT_REF, 24, 5, 5, entryOf(metricKey, newMeasureBuilder().create(19))); } private void verifyTwoMeasureAggregation(String metric1Key, String metric2Key) { measureRepository.addRawMeasure(FILE_1_REF, metric1Key, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(FILE_1_REF, metric2Key, newMeasureBuilder().create(10)); // FILE_2_REF has no metric2 measure measureRepository.addRawMeasure(FILE_2_REF, metric1Key, newMeasureBuilder().create(6)); // FILE_3_REF has no measure at all // UNIT_TEST_1_REF has no metric1 measureRepository.addRawMeasure(UNIT_TEST_1_REF, metric2Key, newMeasureBuilder().create(90)); measureRepository.addRawMeasure(FILE_4_REF, metric1Key, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(FILE_4_REF, metric2Key, newMeasureBuilder().create(3)); underTest.execute(new TestComputationStepContext()); verifyMeasuresOnFile(FILE_1_REF, 1, 1); verifyMeasuresOnFile(FILE_2_REF, 2, 1); verifyMeasuresOnFile(FILE_3_REF, 7, 1); verifyNoMeasure(UNIT_TEST_1_REF); verifyNoMeasure(UNIT_TEST_2_REF); verifyMeasuresOnOtherComponent(DIRECTORY_1_REF, 3, 2, NO_METRIC, entryOf(metric1Key, newMeasureBuilder().create(7)), entryOf(metric2Key, newMeasureBuilder().create(10))); verifyMeasuresOnOtherComponent(DIRECTORY_2_REF, 7, 1, NO_METRIC, entryOf(metric2Key, newMeasureBuilder().create(90))); MeasureRepoEntry[] subModuleAndAboveEntries = { entryOf(metric1Key, newMeasureBuilder().create(9)), entryOf(metric2Key, newMeasureBuilder().create(103)) }; verifyMeasuresOnOtherComponent(DIRECTORY_3_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasuresOnOtherComponent(ROOT_REF, 24, 5, 5, subModuleAndAboveEntries); } @Test public void verify_FUNCTIONS_and_STATEMENT_measure_aggregation() { verifyTwoMeasureAggregation(FUNCTIONS_KEY, STATEMENTS_KEY); } @Test public void verify_CLASSES_measure_aggregation() { verifyMetricAggregation(CLASSES_KEY); } private void verifyMeasuresOnFile(int componentRef, int linesCount, int fileCount) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))) .containsOnly( entryOf(LINES_KEY, newMeasureBuilder().create(linesCount)), entryOf(FILES_KEY, newMeasureBuilder().create(fileCount))); } private void verifyMeasuresOnOtherComponent(int componentRef, @Nullable Integer linesCount, @Nullable Integer fileCount, @Nullable Integer directoryCount, MeasureRepoEntry... otherMeasures) { MeasureRepoEntry[] measureRepoEntries = concatIntoArray( otherMeasures, linesCount == null ? null : entryOf(LINES_KEY, newMeasureBuilder().create(linesCount)), fileCount == null ? null : entryOf(FILES_KEY, newMeasureBuilder().create(fileCount))); assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))) .containsOnly(measureRepoEntries); } private static MeasureRepoEntry[] concatIntoArray(MeasureRepoEntry[] otherMeasures, MeasureRepoEntry... measureRepoEntries) { return from(concat( asList(otherMeasures), from(asList(measureRepoEntries)).filter(notNull()))) .toArray(MeasureRepoEntry.class); } private void verifyNoMeasure(int componentRef) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).isEmpty(); } }
11,606
47.564854
156
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ReportUnitTestMeasuresStepTest.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.step; import org.assertj.core.data.Offset; 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 org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.SKIPPED_TESTS; import static org.sonar.api.measures.CoreMetrics.SKIPPED_TESTS_KEY; import static org.sonar.api.measures.CoreMetrics.TESTS; import static org.sonar.api.measures.CoreMetrics.TESTS_KEY; import static org.sonar.api.measures.CoreMetrics.TEST_ERRORS; import static org.sonar.api.measures.CoreMetrics.TEST_ERRORS_KEY; import static org.sonar.api.measures.CoreMetrics.TEST_EXECUTION_TIME; import static org.sonar.api.measures.CoreMetrics.TEST_EXECUTION_TIME_KEY; import static org.sonar.api.measures.CoreMetrics.TEST_FAILURES; import static org.sonar.api.measures.CoreMetrics.TEST_FAILURES_KEY; import static org.sonar.api.measures.CoreMetrics.TEST_SUCCESS_DENSITY; import static org.sonar.api.measures.CoreMetrics.TEST_SUCCESS_DENSITY_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; 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 ReportUnitTestMeasuresStepTest { private static final Offset<Double> DEFAULT_OFFSET = Offset.offset(0.01d); 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; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot( builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF) .addChildren( builder(FILE, FILE_1_REF).setFileAttributes(new FileAttributes(true, null, 1)).build(), builder(FILE, FILE_2_REF).setFileAttributes(new FileAttributes(true, null, 1)).build()) .build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(TESTS) .add(TEST_ERRORS) .add(TEST_FAILURES) .add(TEST_EXECUTION_TIME) .add(SKIPPED_TESTS) .add(TEST_SUCCESS_DENSITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); ComputationStep underTest = new UnitTestMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Test public void aggregate_tests() { checkMeasuresAggregation(TESTS_KEY, 100, 400, 500); } @Test public void aggregate_tests_in_errors() { checkMeasuresAggregation(TEST_ERRORS_KEY, 100, 400, 500); } @Test public void aggregate_tests_in_failures() { checkMeasuresAggregation(TEST_FAILURES_KEY, 100, 400, 500); } @Test public void aggregate_tests_execution_time() { checkMeasuresAggregation(TEST_EXECUTION_TIME_KEY, 100L, 400L, 500L); } @Test public void aggregate_skipped_tests() { checkMeasuresAggregation(SKIPPED_TESTS_KEY, 100, 400, 500); } @Test public void compute_test_success_density() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(FILE_2_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(5)); measureRepository.addRawMeasure(FILE_1_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(4)); measureRepository.addRawMeasure(FILE_2_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(1)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_1_REF))).contains(entryOf(TEST_SUCCESS_DENSITY_KEY, newMeasureBuilder().create(40d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(FILE_2_REF))).contains(entryOf(TEST_SUCCESS_DENSITY_KEY, newMeasureBuilder().create(70d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).contains(entryOf(TEST_SUCCESS_DENSITY_KEY, newMeasureBuilder().create(60d, 1))); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains(entryOf(TEST_SUCCESS_DENSITY_KEY, newMeasureBuilder().create(60d, 1))); } @Test public void compute_test_success_density_when_zero_tests_in_errors() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_1_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(4)); measureRepository.addRawMeasure(FILE_2_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(1)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(60d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(95d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(83.3d, DEFAULT_OFFSET); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(83.3d, DEFAULT_OFFSET); } @Test public void compute_test_success_density_when_zero_tests_in_failures() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(FILE_2_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(5)); measureRepository.addRawMeasure(FILE_1_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(0)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(80d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(75d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(76.7d, DEFAULT_OFFSET); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(76.7d, DEFAULT_OFFSET); } @Test public void compute_100_percent_test_success_density_when_no_tests_in_errors_or_failures() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_1_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(0)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(100d); } @Test public void compute_0_percent_test_success_density() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(8)); measureRepository.addRawMeasure(FILE_2_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(15)); measureRepository.addRawMeasure(FILE_1_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(FILE_2_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(5)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY).get().getDoubleValue()).isEqualTo(0d); } @Test public void do_not_compute_test_success_density_when_no_tests_in_errors() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(4)); measureRepository.addRawMeasure(FILE_2_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(1)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); } @Test public void do_not_compute_test_success_density_when_no_tests_in_failure() { measureRepository.addRawMeasure(FILE_1_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(FILE_2_REF, TESTS_KEY, newMeasureBuilder().create(20)); measureRepository.addRawMeasure(FILE_1_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(0)); measureRepository.addRawMeasure(FILE_2_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(0)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(DIRECTORY_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY)).isNotPresent(); } @Test public void aggregate_measures_when_tests_measures_are_defined_on_directory() { treeRootHolder.setRoot(builder(PROJECT, ROOT_REF) .addChildren( builder(DIRECTORY, DIRECTORY_REF).build()) .build()); measureRepository.addRawMeasure(DIRECTORY_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(DIRECTORY_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(DIRECTORY_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(DIRECTORY_REF, SKIPPED_TESTS_KEY, newMeasureBuilder().create(5)); measureRepository.addRawMeasure(DIRECTORY_REF, TEST_EXECUTION_TIME_KEY, newMeasureBuilder().create(100L)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly( entryOf(TESTS_KEY, newMeasureBuilder().create(10)), entryOf(TEST_ERRORS_KEY, newMeasureBuilder().create(2)), entryOf(TEST_FAILURES_KEY, newMeasureBuilder().create(1)), entryOf(SKIPPED_TESTS_KEY, newMeasureBuilder().create(5)), entryOf(TEST_EXECUTION_TIME_KEY, newMeasureBuilder().create(100L)), entryOf(TEST_SUCCESS_DENSITY_KEY, newMeasureBuilder().create(70d, 1))); } @Test public void compute_test_success_density_measure_when_tests_measures_are_defined_at_project_level_and_no_children() { treeRootHolder.setRoot(builder(PROJECT, ROOT_REF).build()); measureRepository.addRawMeasure(ROOT_REF, TESTS_KEY, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(ROOT_REF, TEST_ERRORS_KEY, newMeasureBuilder().create(2)); measureRepository.addRawMeasure(ROOT_REF, TEST_FAILURES_KEY, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(ROOT_REF, SKIPPED_TESTS_KEY, newMeasureBuilder().create(5)); measureRepository.addRawMeasure(ROOT_REF, TEST_EXECUTION_TIME_KEY, newMeasureBuilder().create(100L)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly( entryOf(TEST_SUCCESS_DENSITY_KEY, newMeasureBuilder().create(70d, 1))); } private void checkMeasuresAggregation(String metricKey, int file1Value, int file2Value, int expectedValue) { measureRepository.addRawMeasure(FILE_1_REF, metricKey, newMeasureBuilder().create(file1Value)); measureRepository.addRawMeasure(FILE_2_REF, metricKey, newMeasureBuilder().create(file2Value)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, metricKey)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, metricKey)).isNotPresent(); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(expectedValue))); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(expectedValue))); } private void checkMeasuresAggregation(String metricKey, long file1Value, long file2Value, long expectedValue) { measureRepository.addRawMeasure(FILE_1_REF, metricKey, newMeasureBuilder().create(file1Value)); measureRepository.addRawMeasure(FILE_2_REF, metricKey, newMeasureBuilder().create(file2Value)); underTest.execute(new TestComputationStepContext()); assertThat(measureRepository.getAddedRawMeasure(FILE_1_REF, metricKey)).isNotPresent(); assertThat(measureRepository.getAddedRawMeasure(FILE_2_REF, metricKey)).isNotPresent(); assertThat(toEntries(measureRepository.getAddedRawMeasures(DIRECTORY_REF))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(expectedValue))); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(expectedValue))); } }
16,886
55.29
160
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/SmallChangesetQualityGateSpecialCaseTest.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.step; import org.junit.Rule; import org.junit.Test; import org.sonar.api.CoreProperties; import org.sonar.api.config.internal.ConfigurationBridge; import org.sonar.api.config.internal.MapSettings; import org.sonar.api.measures.CoreMetrics; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.TestSettingsRepository; 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 org.sonar.ce.task.projectanalysis.qualitygate.Condition; import org.sonar.ce.task.projectanalysis.qualitygate.EvaluationResult; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.sonar.api.measures.CoreMetrics.NEW_BUGS_KEY; import static org.sonar.api.measures.CoreMetrics.NEW_COVERAGE_KEY; 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.Measure.Level.ERROR; import static org.sonar.ce.task.projectanalysis.measure.Measure.Level.OK; public class SmallChangesetQualityGateSpecialCaseTest { public static final int PROJECT_REF = 1234; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.NEW_LINES) .add(CoreMetrics.NEW_COVERAGE) .add(CoreMetrics.NEW_BUGS); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private final MapSettings mapSettings = new MapSettings(); private final TestSettingsRepository settings = new TestSettingsRepository(new ConfigurationBridge(mapSettings)); private final SmallChangesetQualityGateSpecialCase underTest = new SmallChangesetQualityGateSpecialCase(measureRepository, metricRepository, settings); @Test public void ignore_errors_about_new_coverage_for_small_changesets() { mapSettings.setProperty(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES, true); QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR); Component project = generateNewRootProject(); measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, newMeasureBuilder().create(19)); boolean result = underTest.appliesTo(project, metricEvaluationResult); assertThat(result).isTrue(); } @Test public void dont_ignore_errors_about_new_coverage_for_small_changesets_if_disabled() { mapSettings.setProperty(CoreProperties.QUALITY_GATE_IGNORE_SMALL_CHANGES, false); QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR); Component project = generateNewRootProject(); measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, newMeasureBuilder().create(19)); boolean result = underTest.appliesTo(project, metricEvaluationResult); assertThat(result).isFalse(); } @Test public void should_not_change_for_bigger_changesets() { QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR); Component project = generateNewRootProject(); measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, newMeasureBuilder().create(20)); boolean result = underTest.appliesTo(project, metricEvaluationResult); assertThat(result).isFalse(); } @Test public void should_not_change_issue_related_metrics() { QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_BUGS_KEY, ERROR); Component project = generateNewRootProject(); measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, newMeasureBuilder().create(19)); boolean result = underTest.appliesTo(project, metricEvaluationResult); assertThat(result).isFalse(); } @Test public void should_not_change_green_conditions() { QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_BUGS_KEY, OK); Component project = generateNewRootProject(); measureRepository.addRawMeasure(PROJECT_REF, CoreMetrics.NEW_LINES_KEY, newMeasureBuilder().create(19)); boolean result = underTest.appliesTo(project, metricEvaluationResult); assertThat(result).isFalse(); } @Test public void should_not_change_quality_gate_if_new_lines_is_not_defined() { QualityGateMeasuresStep.MetricEvaluationResult metricEvaluationResult = generateEvaluationResult(NEW_COVERAGE_KEY, ERROR); Component project = generateNewRootProject(); boolean result = underTest.appliesTo(project, metricEvaluationResult); assertThat(result).isFalse(); } @Test public void should_silently_ignore_null_values() { boolean result = underTest.appliesTo(mock(Component.class), null); assertThat(result).isFalse(); } @Test public void apply() { Comparable<?> value = mock(Comparable.class); Condition condition = mock(Condition.class); QualityGateMeasuresStep.MetricEvaluationResult original = new QualityGateMeasuresStep.MetricEvaluationResult( new EvaluationResult(Measure.Level.ERROR, value), condition); QualityGateMeasuresStep.MetricEvaluationResult modified = underTest.apply(original); assertThat(modified.evaluationResult.level()).isSameAs(OK); assertThat(modified.evaluationResult.value()).isSameAs(value); assertThat(modified.condition).isSameAs(condition); } private Component generateNewRootProject() { treeRootHolder.setRoot(builder(Component.Type.PROJECT, PROJECT_REF).build()); return treeRootHolder.getRoot(); } private QualityGateMeasuresStep.MetricEvaluationResult generateEvaluationResult(String metric, Measure.Level level) { Metric newCoverageMetric = metricRepository.getByKey(metric); Condition condition = new Condition(newCoverageMetric, "LT", "80"); EvaluationResult evaluationResult = new EvaluationResult(level, mock(Comparable.class)); return new QualityGateMeasuresStep.MetricEvaluationResult(evaluationResult, condition); } }
7,399
43.848485
153
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/TriggerViewRefreshStepTest.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.step; import org.junit.Test; import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder; import org.sonar.ce.task.projectanalysis.view.TriggerViewRefreshDelegate; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.server.project.Project; 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 TriggerViewRefreshStepTest { private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class); @Test public void execute_has_no_effect_if_constructor_without_delegate() { TriggerViewRefreshStep underTest = new TriggerViewRefreshStep(analysisMetadataHolder); underTest.execute(new TestComputationStepContext()); verifyNoInteractions(analysisMetadataHolder); } @Test public void execute_has_no_effect_if_constructor_with_null_delegate() { TriggerViewRefreshStep underTest = new TriggerViewRefreshStep(analysisMetadataHolder); underTest.execute(new TestComputationStepContext()); verifyNoInteractions(analysisMetadataHolder); } @Test public void execute_calls_delegate_with_project_from_holder_if_passed_to_constructor() { TriggerViewRefreshDelegate delegate = mock(TriggerViewRefreshDelegate.class); Project project = mock(Project.class); when(analysisMetadataHolder.getProject()).thenReturn(project); TriggerViewRefreshStep underTest = new TriggerViewRefreshStep(analysisMetadataHolder, new TriggerViewRefreshDelegate[]{delegate}); underTest.execute(new TestComputationStepContext()); verify(analysisMetadataHolder).getProject(); verify(delegate).triggerFrom(project); } }
2,634
38.328358
134
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsCommentMeasuresStepTest.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.step; import org.junit.Before; 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 org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; 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_DENSITY; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.COMMENT_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.NCLOC; import static org.sonar.api.measures.CoreMetrics.NCLOC_KEY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_API; import static org.sonar.api.measures.CoreMetrics.PUBLIC_API_KEY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_DOCUMENTED_API_DENSITY_KEY; import static org.sonar.api.measures.CoreMetrics.PUBLIC_UNDOCUMENTED_API; import static org.sonar.api.measures.CoreMetrics.PUBLIC_UNDOCUMENTED_API_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 ViewsCommentMeasuresStepTest { private static final int ROOT_REF = 1; private static final int MODULE_REF = 12; private static final int SUB_MODULE_REF = 123; private static final int PROJECTVIEW_1_REF = 1231; private static final int PROJECTVIEW_2_REF = 1232; private static final int PROJECTVIEW_3_REF = 1233; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC) .add(COMMENT_LINES) .add(COMMENT_LINES_DENSITY) .add(PUBLIC_API) .add(PUBLIC_UNDOCUMENTED_API) .add(PUBLIC_DOCUMENTED_API_DENSITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); ComputationStep underTest = new CommentMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Before public void setUp() { treeRootHolder.setRoot( builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, MODULE_REF) .addChildren( builder(SUBVIEW, SUB_MODULE_REF) .addChildren( builder(PROJECT_VIEW, PROJECTVIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECTVIEW_2_REF).build()) .build()) .build(), builder(PROJECT_VIEW, PROJECTVIEW_3_REF).build()) .build()); } @Test public void aggregate_comment_lines() { addRawMeasure(PROJECTVIEW_1_REF, COMMENT_LINES_KEY, 100); addRawMeasure(PROJECTVIEW_2_REF, COMMENT_LINES_KEY, 400); addRawMeasure(PROJECTVIEW_3_REF, COMMENT_LINES_KEY, 500); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, COMMENT_LINES_KEY, 500); assertRawMeasureValue(MODULE_REF, COMMENT_LINES_KEY, 500); assertRawMeasureValue(ROOT_REF, COMMENT_LINES_KEY, 1000); } @Test public void compute_comment_density() { addRawMeasure(PROJECTVIEW_1_REF, NCLOC_KEY, 100); addRawMeasure(PROJECTVIEW_1_REF, COMMENT_LINES_KEY, 150); addRawMeasure(PROJECTVIEW_2_REF, NCLOC_KEY, 200); addRawMeasure(PROJECTVIEW_2_REF, COMMENT_LINES_KEY, 50); addRawMeasure(PROJECTVIEW_3_REF, NCLOC_KEY, 300); addRawMeasure(PROJECTVIEW_3_REF, COMMENT_LINES_KEY, 5); addRawMeasure(SUB_MODULE_REF, NCLOC_KEY, 300); addRawMeasure(MODULE_REF, NCLOC_KEY, 300); addRawMeasure(ROOT_REF, NCLOC_KEY, 300); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, COMMENT_LINES_DENSITY_KEY, 40d); assertRawMeasureValue(MODULE_REF, COMMENT_LINES_DENSITY_KEY, 40d); assertRawMeasureValue(ROOT_REF, COMMENT_LINES_DENSITY_KEY, 40.6d); } @Test public void compute_zero_comment_density_when_zero_comment() { addRawMeasure(PROJECTVIEW_1_REF, NCLOC_KEY, 100); addRawMeasure(PROJECTVIEW_1_REF, COMMENT_LINES_KEY, 0); addRawMeasure(PROJECTVIEW_2_REF, NCLOC_KEY, 200); addRawMeasure(PROJECTVIEW_2_REF, COMMENT_LINES_KEY, 0); addRawMeasure(SUB_MODULE_REF, NCLOC_KEY, 300); addRawMeasure(MODULE_REF, NCLOC_KEY, 300); addRawMeasure(ROOT_REF, NCLOC_KEY, 300); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, COMMENT_LINES_DENSITY_KEY, 0d); assertRawMeasureValue(MODULE_REF, COMMENT_LINES_DENSITY_KEY, 0d); assertRawMeasureValue(ROOT_REF, COMMENT_LINES_DENSITY_KEY, 0d); } @Test public void not_compute_comment_density_when_zero_ncloc_and_zero_comment() { addRawMeasure(PROJECTVIEW_1_REF, NCLOC_KEY, 0); addRawMeasure(PROJECTVIEW_1_REF, COMMENT_LINES_KEY, 0); addRawMeasure(PROJECTVIEW_2_REF, NCLOC_KEY, 0); addRawMeasure(PROJECTVIEW_2_REF, COMMENT_LINES_KEY, 0); addRawMeasure(SUB_MODULE_REF, NCLOC_KEY, 0); addRawMeasure(MODULE_REF, NCLOC_KEY, 0); addRawMeasure(ROOT_REF, NCLOC_KEY, 0); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertNoRawMeasures(COMMENT_LINES_DENSITY_KEY); } @Test public void not_compute_comment_density_when_no_ncloc() { addRawMeasure(PROJECTVIEW_1_REF, COMMENT_LINES_KEY, 150); addRawMeasure(PROJECTVIEW_2_REF, COMMENT_LINES_KEY, 50); underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(COMMENT_LINES_DENSITY_KEY); } @Test public void not_compute_comment_density_when_no_comment() { addRawMeasure(PROJECTVIEW_1_REF, NCLOC_KEY, 100); addRawMeasure(PROJECTVIEW_2_REF, NCLOC_KEY, 100); addRawMeasure(SUB_MODULE_REF, NCLOC_KEY, 200); addRawMeasure(MODULE_REF, NCLOC_KEY, 200); addRawMeasure(ROOT_REF, NCLOC_KEY, 200); underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(COMMENT_LINES_DENSITY_KEY); } @Test public void aggregate_public_api() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_API_KEY, 100); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_API_KEY, 400); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, PUBLIC_API_KEY, 500); assertRawMeasureValue(MODULE_REF, PUBLIC_API_KEY, 500); assertRawMeasureValue(ROOT_REF, PUBLIC_API_KEY, 500); } @Test public void aggregate_public_undocumented_api() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, 100); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, 400); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, PUBLIC_UNDOCUMENTED_API_KEY, 500); assertRawMeasureValue(MODULE_REF, PUBLIC_UNDOCUMENTED_API_KEY, 500); assertRawMeasureValue(ROOT_REF, PUBLIC_UNDOCUMENTED_API_KEY, 500); } @Test public void compute_public_documented_api_density() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_API_KEY, 100); addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, 50); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_API_KEY, 400); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, 100); addRawMeasure(PROJECTVIEW_3_REF, PUBLIC_API_KEY, 300); addRawMeasure(PROJECTVIEW_3_REF, PUBLIC_UNDOCUMENTED_API_KEY, 200); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY, 70d); assertRawMeasureValue(MODULE_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY, 70d); assertRawMeasureValue(ROOT_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY, 56.3d); } @Test public void not_compute_public_documented_api_density_when_no_public_api() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, 50); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, 100); underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(PUBLIC_DOCUMENTED_API_DENSITY_KEY); } @Test public void not_compute_public_documented_api_density_when_no_public_undocumented_api() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_API_KEY, 50); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_API_KEY, 100); underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(PUBLIC_DOCUMENTED_API_DENSITY_KEY); } @Test public void not_compute_public_documented_api_density_when_public_api_is_zero() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_API_KEY, 0); addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, 50); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_API_KEY, 0); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, 100); underTest.execute(new TestComputationStepContext()); assertNoRawMeasures(PUBLIC_DOCUMENTED_API_DENSITY_KEY); } @Test public void compute_100_percent_public_documented_api_density_when_public_undocumented_api_is_zero() { addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_API_KEY, 100); addRawMeasure(PROJECTVIEW_1_REF, PUBLIC_UNDOCUMENTED_API_KEY, 0); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_API_KEY, 400); addRawMeasure(PROJECTVIEW_2_REF, PUBLIC_UNDOCUMENTED_API_KEY, 0); underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertRawMeasureValue(SUB_MODULE_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY, 100d); assertRawMeasureValue(MODULE_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY, 100d); assertRawMeasureValue(ROOT_REF, PUBLIC_DOCUMENTED_API_DENSITY_KEY, 100d); } @Test public void compute_nothing_when_no_data() { underTest.execute(new TestComputationStepContext()); assertProjectViewsHasNoNewRawMeasure(); assertThat(measureRepository.getAddedRawMeasures(SUB_MODULE_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(MODULE_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(ROOT_REF)).isEmpty(); } private void assertNoRawMeasures(String metricKey) { assertNoRawMeasure(metricKey, SUB_MODULE_REF); assertNoRawMeasure(metricKey, MODULE_REF); assertNoRawMeasure(metricKey, ROOT_REF); } private void assertNoRawMeasure(String metricKey, int componentRef) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey)).isNotPresent(); } private void addRawMeasure(int componentRef, String metricKey, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertProjectViewsHasNoNewRawMeasure() { assertThat(measureRepository.getAddedRawMeasures(PROJECTVIEW_1_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(PROJECTVIEW_2_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,826
39.084375
118
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsComplexityMeasuresStepTest.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.step; import org.junit.Rule; import org.junit.Test; import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule; 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.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.CLASSES; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.CLASS_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.CLASS_COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.COGNITIVE_COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_IN_FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.FILES; import static org.sonar.api.measures.CoreMetrics.FILES_KEY; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_DISTRIBUTION_KEY; import static org.sonar.api.measures.CoreMetrics.FILE_COMPLEXITY_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTION_COMPLEXITY_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 ViewsComplexityMeasuresStepTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_REF = 11; private static final int SUB_SUBVIEW_1_REF = 111; private static final int PROJECT_VIEW_1_REF = 11111; private static final int PROJECT_VIEW_2_REF = 11121; private static final int SUB_SUBVIEW_2_REF = 112; private static final int PROJECT_VIEW_3_REF = 12; @Rule public BatchReportReaderRule reportReader = new BatchReportReaderRule(); @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot(builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, SUBVIEW_REF) .addChildren( builder(SUBVIEW, SUB_SUBVIEW_1_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECT_VIEW_2_REF).build()) .build(), builder(SUBVIEW, SUB_SUBVIEW_2_REF).build()) .build(), builder(PROJECT_VIEW, PROJECT_VIEW_3_REF).build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(COMPLEXITY) .add(COMPLEXITY_IN_CLASSES) .add(COMPLEXITY_IN_FUNCTIONS) .add(FUNCTION_COMPLEXITY_DISTRIBUTION) .add(FILE_COMPLEXITY_DISTRIBUTION) .add(FILE_COMPLEXITY) .add(FILES) .add(CLASS_COMPLEXITY) .add(CLASSES) .add(FUNCTION_COMPLEXITY) .add(FUNCTIONS) .add(COGNITIVE_COMPLEXITY); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); private ComputationStep underTest = new ComplexityMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Test public void aggregate_complexity() { verify_sum_aggregation(COMPLEXITY_KEY); } @Test public void aggregate_complexity_in_classes() { verify_sum_aggregation(COMPLEXITY_IN_CLASSES_KEY); } @Test public void aggregate_complexity_in_functions() { verify_sum_aggregation(COMPLEXITY_IN_FUNCTIONS_KEY); } @Test public void aggregate_cognitive_complexity_in_functions() { verify_sum_aggregation(COGNITIVE_COMPLEXITY_KEY); } private void verify_sum_aggregation(String metricKey) { addRawMeasureValue(PROJECT_VIEW_1_REF, metricKey, 10); addRawMeasureValue(PROJECT_VIEW_2_REF, metricKey, 40); addRawMeasureValue(PROJECT_VIEW_3_REF, metricKey, 20); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasures(SUB_SUBVIEW_1_REF, metricKey, 50); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF); assertAddedRawMeasures(SUBVIEW_REF, metricKey, 50); assertAddedRawMeasures(ROOT_REF, metricKey, 70); } @Test public void aggregate_function_complexity_distribution() { verify_distribution_aggregation(FUNCTION_COMPLEXITY_DISTRIBUTION_KEY); } @Test public void aggregate_file_complexity_distribution() { verify_distribution_aggregation(FILE_COMPLEXITY_DISTRIBUTION_KEY); } private void verify_distribution_aggregation(String metricKey) { addRawMeasure(PROJECT_VIEW_1_REF, metricKey, "0.5=3;3.5=5;6.5=9"); addRawMeasure(PROJECT_VIEW_2_REF, metricKey, "0.5=0;3.5=2;6.5=1"); addRawMeasure(PROJECT_VIEW_3_REF, metricKey, "0.5=1;3.5=1;6.5=0"); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasures(SUB_SUBVIEW_1_REF, metricKey, "0.5=3;3.5=7;6.5=10"); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF); assertAddedRawMeasures(SUBVIEW_REF, metricKey, "0.5=3;3.5=7;6.5=10"); assertAddedRawMeasures(ROOT_REF, metricKey, "0.5=4;3.5=8;6.5=10"); } @Test public void compute_and_aggregate_file_complexity() { verify_average_compute_and_aggregation(FILE_COMPLEXITY_KEY, COMPLEXITY_KEY, FILES_KEY); } @Test public void compute_and_aggregate_class_complexity() { verify_average_compute_and_aggregation(CLASS_COMPLEXITY_KEY, COMPLEXITY_IN_CLASSES_KEY, CLASSES_KEY); } @Test public void compute_and_aggregate_function_complexity() { verify_average_compute_and_aggregation(FUNCTION_COMPLEXITY_KEY, COMPLEXITY_IN_FUNCTIONS_KEY, FUNCTIONS_KEY); } private void verify_average_compute_and_aggregation(String metricKey, String mainMetric, String byMetric) { addRawMeasureValue(PROJECT_VIEW_1_REF, mainMetric, 5); addRawMeasureValue(PROJECT_VIEW_1_REF, byMetric, 2); addRawMeasureValue(PROJECT_VIEW_2_REF, mainMetric, 1); addRawMeasureValue(PROJECT_VIEW_2_REF, byMetric, 1); addRawMeasureValue(PROJECT_VIEW_3_REF, mainMetric, 6); addRawMeasureValue(PROJECT_VIEW_3_REF, byMetric, 8); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasures(SUB_SUBVIEW_1_REF, metricKey, 2d); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF); assertAddedRawMeasures(SUBVIEW_REF, metricKey, 2d); assertAddedRawMeasures(ROOT_REF, metricKey, 1.1d); } private void addRawMeasure(int componentRef, String metricKey, String value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertNoAddedRawMeasureOnProjectViews() { assertNoAddedRawMeasure(PROJECT_VIEW_1_REF); assertNoAddedRawMeasure(PROJECT_VIEW_2_REF); assertNoAddedRawMeasure(PROJECT_VIEW_3_REF); } private void assertNoAddedRawMeasure(int componentRef) { assertThat(measureRepository.getAddedRawMeasures(componentRef)).isEmpty(); } private void assertAddedRawMeasures(int componentRef, String metricKey, String expected) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(expected))); } private void assertAddedRawMeasures(int componentRef, String metricKey, int expected) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(expected))); } private void assertAddedRawMeasures(int componentRef, String metricKey, double expected) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).contains(entryOf(metricKey, newMeasureBuilder().create(expected, 1))); } private void addRawMeasureValue(int componentRef, String metricKey, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } }
10,132
42.303419
149
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsCoverageMeasuresStepTest.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.step; 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.TreeRootHolderRule; import org.sonar.ce.task.projectanalysis.formula.coverage.LinesAndConditionsWithUncoveredMetricKeys; 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.ce.task.step.TestComputationStepContext; 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.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 ViewsCoverageMeasuresStepTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_REF = 12; private static final int SUB_SUBVIEW_REF = 121; private static final int PROJECTVIEW_1_REF = 1211; private static final int PROJECTVIEW_2_REF = 1212; private static final int PROJECTVIEW_3_REF = 123; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule(); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(CoreMetrics.LINES_TO_COVER) .add(CoreMetrics.CONDITIONS_TO_COVER) .add(CoreMetrics.UNCOVERED_LINES) .add(CoreMetrics.UNCOVERED_CONDITIONS) .add(CoreMetrics.COVERAGE) .add(CoreMetrics.BRANCH_COVERAGE) .add(CoreMetrics.LINE_COVERAGE); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); CoverageMeasuresStep underTest = new CoverageMeasuresStep(treeRootHolder, metricRepository, measureRepository, null); @Before public void setUp() { treeRootHolder.setRoot( builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, SUBVIEW_REF) .addChildren( builder(SUBVIEW, SUB_SUBVIEW_REF) .addChildren( builder(PROJECT_VIEW, PROJECTVIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECTVIEW_2_REF).build()) .build()) .build(), builder(PROJECT_VIEW, PROJECTVIEW_3_REF).build()) .build()); } @Test public void verify_aggregates_values_for_ut_lines_and_conditions() { LinesAndConditionsWithUncoveredMetricKeys metricKeys = new LinesAndConditionsWithUncoveredMetricKeys( CoreMetrics.LINES_TO_COVER_KEY, CoreMetrics.CONDITIONS_TO_COVER_KEY, CoreMetrics.UNCOVERED_LINES_KEY, CoreMetrics.UNCOVERED_CONDITIONS_KEY); verify_lines_and_conditions_aggregates_values(metricKeys); } private void verify_lines_and_conditions_aggregates_values(LinesAndConditionsWithUncoveredMetricKeys metricKeys) { measureRepository .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.lines(), newMeasureBuilder().create(3000)) .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.conditions(), newMeasureBuilder().create(300)) .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(30)) .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(9)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.lines(), newMeasureBuilder().create(2000)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.conditions(), newMeasureBuilder().create(400)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(200)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(16)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.lines(), newMeasureBuilder().create(1000)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.conditions(), newMeasureBuilder().create(500)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(300)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(19)); underTest.execute(new TestComputationStepContext()); MeasureRepoEntry[] subViewRepoEntries = { entryOf(metricKeys.lines(), newMeasureBuilder().create(5000)), entryOf(metricKeys.conditions(), newMeasureBuilder().create(700)), entryOf(metricKeys.uncoveredLines(), newMeasureBuilder().create(230)), entryOf(metricKeys.uncoveredConditions(), newMeasureBuilder().create(25)) }; assertThat(toEntries(measureRepository.getAddedRawMeasures(SUB_SUBVIEW_REF))).contains(subViewRepoEntries); assertThat(toEntries(measureRepository.getAddedRawMeasures(SUBVIEW_REF))).contains(subViewRepoEntries); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains( entryOf(metricKeys.lines(), newMeasureBuilder().create(6000)), entryOf(metricKeys.conditions(), newMeasureBuilder().create(1200)), entryOf(metricKeys.uncoveredLines(), newMeasureBuilder().create(530)), entryOf(metricKeys.uncoveredConditions(), newMeasureBuilder().create(44))); } @Test public void verify_aggregates_values_for_code_line_and_branch_coverage() { LinesAndConditionsWithUncoveredMetricKeys metricKeys = new LinesAndConditionsWithUncoveredMetricKeys( CoreMetrics.LINES_TO_COVER_KEY, CoreMetrics.CONDITIONS_TO_COVER_KEY, CoreMetrics.UNCOVERED_LINES_KEY, CoreMetrics.UNCOVERED_CONDITIONS_KEY); String codeCoverageKey = CoreMetrics.COVERAGE_KEY; String lineCoverageKey = CoreMetrics.LINE_COVERAGE_KEY; String branchCoverageKey = CoreMetrics.BRANCH_COVERAGE_KEY; verify_coverage_aggregates_values(metricKeys, codeCoverageKey, lineCoverageKey, branchCoverageKey); } private void verify_coverage_aggregates_values(LinesAndConditionsWithUncoveredMetricKeys metricKeys, String codeCoverageKey, String lineCoverageKey, String branchCoverageKey) { measureRepository .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.lines(), newMeasureBuilder().create(3000)) .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.conditions(), newMeasureBuilder().create(300)) .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(30)) .addRawMeasure(PROJECTVIEW_1_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(9)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.lines(), newMeasureBuilder().create(2000)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.conditions(), newMeasureBuilder().create(400)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(200)) .addRawMeasure(PROJECTVIEW_2_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(16)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.lines(), newMeasureBuilder().create(1000)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.conditions(), newMeasureBuilder().create(500)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredLines(), newMeasureBuilder().create(300)) .addRawMeasure(PROJECTVIEW_3_REF, metricKeys.uncoveredConditions(), newMeasureBuilder().create(19)); underTest.execute(new TestComputationStepContext()); assertThat(toEntries(measureRepository.getAddedRawMeasures(PROJECTVIEW_1_REF))).isEmpty(); assertThat(toEntries(measureRepository.getAddedRawMeasures(PROJECTVIEW_2_REF))).isEmpty(); assertThat(toEntries(measureRepository.getAddedRawMeasures(PROJECTVIEW_3_REF))).isEmpty(); MeasureRepoEntry[] subViewRepoEntries = { entryOf(codeCoverageKey, newMeasureBuilder().create(95.5d, 1)), entryOf(lineCoverageKey, newMeasureBuilder().create(95.4d, 1)), entryOf(branchCoverageKey, newMeasureBuilder().create(96.4d, 1)) }; assertThat(toEntries(measureRepository.getAddedRawMeasures(SUB_SUBVIEW_REF))).contains(subViewRepoEntries); assertThat(toEntries(measureRepository.getAddedRawMeasures(SUBVIEW_REF))).contains(subViewRepoEntries); assertThat(toEntries(measureRepository.getAddedRawMeasures(ROOT_REF))).contains( entryOf(codeCoverageKey, newMeasureBuilder().create(92d, 1)), entryOf(lineCoverageKey, newMeasureBuilder().create(91.2d, 1)), entryOf(branchCoverageKey, newMeasureBuilder().create(96.3d, 1))); } }
9,563
53.033898
178
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsLanguageDistributionMeasuresStepTest.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.step; 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 org.sonar.ce.task.step.ComputationStep; import org.sonar.ce.task.step.TestComputationStepContext; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION; import static org.sonar.api.measures.CoreMetrics.NCLOC_LANGUAGE_DISTRIBUTION_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 ViewsLanguageDistributionMeasuresStepTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_1_REF = 12; private static final int SUB_SUBVIEW_1_REF = 121; private static final int PROJECT_VIEW_1_REF = 1211; private static final int PROJECT_VIEW_2_REF = 1212; private static final int PROJECT_VIEW_3_REF = 1213; private static final int SUB_SUBVIEW_2_REF = 122; private static final int SUBVIEW_2_REF = 13; private static final int PROJECT_VIEW_4_REF = 131; private static final int PROJECT_VIEW_5_REF = 14; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule() .setRoot(builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, SUBVIEW_1_REF) .addChildren( builder(SUBVIEW, SUB_SUBVIEW_1_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECT_VIEW_2_REF).build(), builder(PROJECT_VIEW, PROJECT_VIEW_3_REF).build()) .build(), builder(SUBVIEW, SUB_SUBVIEW_2_REF).build()) .build(), builder(SUBVIEW, SUBVIEW_2_REF) .addChildren( builder(PROJECT_VIEW, PROJECT_VIEW_4_REF).build()) .build(), builder(PROJECT_VIEW, PROJECT_VIEW_5_REF).build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(NCLOC_LANGUAGE_DISTRIBUTION); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository); ComputationStep underTest = new LanguageDistributionMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Test public void compute_ncloc_language_distribution() { addRawMeasure(PROJECT_VIEW_1_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "xoo=10"); addRawMeasure(PROJECT_VIEW_2_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "java=6"); addRawMeasure(PROJECT_VIEW_3_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "java=10;xoo=5"); // no raw measure on PROJECT_VIEW_4_REF addRawMeasure(PROJECT_VIEW_5_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "<null>=3;foo=10"); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasure(SUB_SUBVIEW_1_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "java=16;xoo=15"); assertNoAddedRawMeasures(SUB_SUBVIEW_2_REF); assertNoAddedRawMeasures(SUBVIEW_2_REF); assertAddedRawMeasure(SUBVIEW_1_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "java=16;xoo=15"); assertAddedRawMeasure(ROOT_REF, NCLOC_LANGUAGE_DISTRIBUTION_KEY, "<null>=3;foo=10;java=16;xoo=15"); } private void assertAddedRawMeasure(int componentRef, String metricKey, String value) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey).get().getStringValue()).isEqualTo(value); } private void addRawMeasure(int componentRef, String metricKey, String value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertNoAddedRawMeasureOnProjectViews() { assertNoAddedRawMeasures(PROJECT_VIEW_1_REF); assertNoAddedRawMeasures(PROJECT_VIEW_2_REF); assertNoAddedRawMeasures(PROJECT_VIEW_3_REF); assertNoAddedRawMeasures(PROJECT_VIEW_4_REF); assertNoAddedRawMeasures(PROJECT_VIEW_5_REF); } private void assertNoAddedRawMeasures(int componentRef) { assertThat(measureRepository.getAddedRawMeasures(componentRef)).isEmpty(); } }
5,430
44.638655
120
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/step/ViewsSizeMeasuresStepTest.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.step; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; 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.ce.task.step.TestComputationStepContext; import static com.google.common.base.Predicates.notNull; import static com.google.common.collect.FluentIterable.from; import static com.google.common.collect.Iterables.concat; import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.api.measures.CoreMetrics.CLASSES; import static org.sonar.api.measures.CoreMetrics.CLASSES_KEY; import static org.sonar.api.measures.CoreMetrics.DIRECTORIES; import static org.sonar.api.measures.CoreMetrics.FILES; import static org.sonar.api.measures.CoreMetrics.FILES_KEY; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS; import static org.sonar.api.measures.CoreMetrics.FUNCTIONS_KEY; import static org.sonar.api.measures.CoreMetrics.GENERATED_LINES; import static org.sonar.api.measures.CoreMetrics.GENERATED_LINES_KEY; import static org.sonar.api.measures.CoreMetrics.GENERATED_NCLOC; 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.api.measures.CoreMetrics.STATEMENTS; import static org.sonar.api.measures.CoreMetrics.STATEMENTS_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 ViewsSizeMeasuresStepTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_1_REF = 12; private static final int SUBVIEW_2_REF = 13; private static final int SUB_SUBVIEW_1_REF = 121; private static final int SUB_SUBVIEW_2_REF = 122; private static final int SUB_SUBVIEW_3_REF = 123; private static final int PROJECTVIEW_1_REF = 1231; private static final int PROJECTVIEW_2_REF = 1232; private static final int PROJECTVIEW_3_REF = 1241; private static final int PROJECTVIEW_4_REF = 1251; private static final int PROJECTVIEW_5_REF = 14; private static final Integer NO_METRIC = null; @Rule public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot( builder(VIEW, ROOT_REF) .addChildren( builder(SUBVIEW, SUBVIEW_1_REF) .addChildren( builder(SUBVIEW, SUB_SUBVIEW_1_REF) .addChildren( builder(PROJECT_VIEW, PROJECTVIEW_1_REF).build(), builder(PROJECT_VIEW, PROJECTVIEW_2_REF).build()) .build(), builder(SUBVIEW, SUB_SUBVIEW_2_REF) .addChildren( builder(PROJECT_VIEW, PROJECTVIEW_3_REF).build()) .build(), builder(SUBVIEW, SUB_SUBVIEW_3_REF).addChildren( builder(PROJECT_VIEW, PROJECTVIEW_4_REF).build()) .build()) .build(), builder(SUBVIEW, SUBVIEW_2_REF).build(), builder(PROJECT_VIEW, PROJECTVIEW_5_REF).build()) .build()); @Rule public MetricRepositoryRule metricRepository = new MetricRepositoryRule() .add(FILES) .add(DIRECTORIES) .add(LINES) .add(GENERATED_LINES) .add(NCLOC) .add(GENERATED_NCLOC) .add(FUNCTIONS) .add(STATEMENTS) .add(CLASSES); @Rule public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository) .addRawMeasure(PROJECTVIEW_1_REF, LINES_KEY, newMeasureBuilder().create(1)) .addRawMeasure(PROJECTVIEW_2_REF, LINES_KEY, newMeasureBuilder().create(2)) .addRawMeasure(PROJECTVIEW_3_REF, LINES_KEY, newMeasureBuilder().create(5)) // PROJECTVIEW_4_REF has no lines metric .addRawMeasure(PROJECTVIEW_5_REF, LINES_KEY, newMeasureBuilder().create(5)) .addRawMeasure(PROJECTVIEW_1_REF, FILES_KEY, newMeasureBuilder().create(1)) .addRawMeasure(PROJECTVIEW_2_REF, FILES_KEY, newMeasureBuilder().create(2)) .addRawMeasure(PROJECTVIEW_3_REF, FILES_KEY, newMeasureBuilder().create(3)) // PROJECTVIEW_4_REF has no file metric .addRawMeasure(PROJECTVIEW_5_REF, FILES_KEY, newMeasureBuilder().create(5)); // PROJECTVIEW_3_REF has no directory metric private SizeMeasuresStep underTest = new SizeMeasuresStep(treeRootHolder, metricRepository, measureRepository); @Test public void verify_FILE_and_DIRECTORY_computation_and_aggregation() { underTest.execute(new TestComputationStepContext()); verifyNoMeasure(PROJECTVIEW_1_REF); verifyNoMeasure(PROJECTVIEW_2_REF); verifyNoMeasure(PROJECTVIEW_3_REF); verifyNoMeasure(PROJECTVIEW_4_REF); verifyNoMeasure(PROJECTVIEW_5_REF); verifyMeasures(SUB_SUBVIEW_1_REF, 3, 3, 3); verifyMeasures(SUB_SUBVIEW_2_REF, 5, 3, 0); verifyMeasures(SUB_SUBVIEW_3_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasures(SUBVIEW_1_REF, 8, 6, 7); verifyMeasures(SUBVIEW_2_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasures(ROOT_REF, 13, 11, 12); } @Test public void verify_GENERATED_LINES_related_measures_aggregation() { verifyMetricAggregation(GENERATED_LINES_KEY); } @Test public void verify_NCLOC_measure_aggregation() { verifyMetricAggregation(NCLOC_KEY); } private void verifyMetricAggregation(String metricKey) { measureRepository.addRawMeasure(PROJECTVIEW_1_REF, metricKey, newMeasureBuilder().create(10)); measureRepository.addRawMeasure(PROJECTVIEW_2_REF, metricKey, newMeasureBuilder().create(6)); measureRepository.addRawMeasure(PROJECTVIEW_4_REF, metricKey, newMeasureBuilder().create(3)); measureRepository.addRawMeasure(PROJECTVIEW_5_REF, metricKey, newMeasureBuilder().create(7)); underTest.execute(new TestComputationStepContext()); verifyNoMeasure(PROJECTVIEW_1_REF); verifyNoMeasure(PROJECTVIEW_2_REF); verifyNoMeasure(PROJECTVIEW_3_REF); verifyNoMeasure(PROJECTVIEW_4_REF); verifyNoMeasure(PROJECTVIEW_5_REF); verifyMeasures(SUB_SUBVIEW_1_REF, 3, 3, 3, entryOf(metricKey, newMeasureBuilder().create(16))); verifyMeasures(SUB_SUBVIEW_2_REF, 5, 3, 0); verifyMeasures(SUB_SUBVIEW_3_REF, NO_METRIC, NO_METRIC, NO_METRIC, entryOf(metricKey, newMeasureBuilder().create(3))); verifyMeasures(SUBVIEW_1_REF, 8, 6, 7, entryOf(metricKey, newMeasureBuilder().create(19))); verifyMeasures(SUBVIEW_2_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasures(ROOT_REF, 13, 11, 12, entryOf(metricKey, newMeasureBuilder().create(26))); } private void verifyTwoMeasureAggregation(String metric1Key, String metric2Key) { measureRepository.addRawMeasure(PROJECTVIEW_1_REF, metric1Key, newMeasureBuilder().create(1)); measureRepository.addRawMeasure(PROJECTVIEW_1_REF, metric2Key, newMeasureBuilder().create(10)); // PROJECTVIEW_2_REF has no metric2 measure measureRepository.addRawMeasure(PROJECTVIEW_2_REF, metric1Key, newMeasureBuilder().create(6)); // PROJECTVIEW_3_REF has no measure at all // PROJECTVIEW_4_REF has no metric1 measureRepository.addRawMeasure(PROJECTVIEW_4_REF, metric2Key, newMeasureBuilder().create(90)); measureRepository.addRawMeasure(PROJECTVIEW_5_REF, metric1Key, newMeasureBuilder().create(3)); measureRepository.addRawMeasure(PROJECTVIEW_5_REF, metric2Key, newMeasureBuilder().create(7)); underTest.execute(new TestComputationStepContext()); verifyNoMeasure(PROJECTVIEW_1_REF); verifyNoMeasure(PROJECTVIEW_2_REF); verifyNoMeasure(PROJECTVIEW_3_REF); verifyNoMeasure(PROJECTVIEW_4_REF); verifyNoMeasure(PROJECTVIEW_5_REF); verifyNoMeasure(PROJECTVIEW_4_REF); verifyMeasures(SUB_SUBVIEW_1_REF, 3, 3, 3, entryOf(metric1Key, newMeasureBuilder().create(7)), entryOf(metric2Key, newMeasureBuilder().create(10))); verifyMeasures(SUB_SUBVIEW_2_REF, 5, 3, 0); verifyMeasures(SUB_SUBVIEW_3_REF, NO_METRIC, NO_METRIC, NO_METRIC, entryOf(metric2Key, newMeasureBuilder().create(90))); verifyMeasures(SUBVIEW_1_REF, 8, 6, 7, entryOf(metric1Key, newMeasureBuilder().create(7)), entryOf(metric2Key, newMeasureBuilder().create(100))); verifyMeasures(SUBVIEW_2_REF, NO_METRIC, NO_METRIC, NO_METRIC); verifyMeasures(ROOT_REF, 13, 11, 12, entryOf(metric1Key, newMeasureBuilder().create(10)), entryOf(metric2Key, newMeasureBuilder().create(107))); } @Test public void verify_FUNCTIONS_and_STATEMENT_measure_aggregation() { verifyTwoMeasureAggregation(FUNCTIONS_KEY, STATEMENTS_KEY); } @Test public void verify_CLASSES_measure_aggregation() { verifyMetricAggregation(CLASSES_KEY); } private void verifyMeasures(int componentRef, @Nullable Integer linesCount, @Nullable Integer fileCount, @Nullable Integer directoryCount, MeasureRepoEntry... otherMeasures) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))) .containsOnly( concatIntoArray(otherMeasures, createFileAndDirectoryEntries(linesCount, fileCount, directoryCount))); } private static MeasureRepoEntry[] createFileAndDirectoryEntries(@Nullable Integer linesCount, @Nullable Integer fileCount, @Nullable Integer directoryCount) { return new MeasureRepoEntry[] { linesCount == null ? null : entryOf(LINES_KEY, newMeasureBuilder().create(linesCount)), fileCount == null ? null : entryOf(FILES_KEY, newMeasureBuilder().create(fileCount)) }; } private static MeasureRepoEntry[] concatIntoArray(MeasureRepoEntry[] otherMeasures, MeasureRepoEntry... measureRepoEntries) { return from(concat( asList(otherMeasures), from(asList(measureRepoEntries)).filter(notNull()))) .toArray(MeasureRepoEntry.class); } private void verifyNoMeasure(int componentRef) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).isEmpty(); } }
11,420
46.987395
177
java