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/step/ViewsUnitTestMeasuresStepTest.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.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.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 ViewsUnitTestMeasuresStepTest { private static final int ROOT_REF = 1; private static final int SUBVIEW_REF = 12; private static final int SUB_SUBVIEW_1_REF = 123; private static final int PROJECT_VIEW_1_REF = 12341; private static final int PROJECT_VIEW_2_REF = 12342; private static final int SUB_SUBVIEW_2_REF = 124; @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()) .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_time() { checkMeasuresAggregation(SKIPPED_TESTS_KEY, 100, 400, 500); } @Test public void compute_test_success_density() { addedRawMeasure(PROJECT_VIEW_1_REF, TESTS_KEY, 10); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_ERRORS_KEY, 2); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_ERRORS_KEY, 5); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_FAILURES_KEY, 4); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_FAILURES_KEY, 1); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY, 60d); assertAddedRawMeasureValue(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY, 60d); assertAddedRawMeasureValue(ROOT_REF, TEST_SUCCESS_DENSITY_KEY, 60d); } @Test public void compute_test_success_density_when_zero_tests_in_errors() { addedRawMeasure(PROJECT_VIEW_1_REF, TESTS_KEY, 10); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_ERRORS_KEY, 0); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_ERRORS_KEY, 0); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_FAILURES_KEY, 4); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_FAILURES_KEY, 1); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY, 83.3d); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF, TEST_SUCCESS_DENSITY_KEY); assertAddedRawMeasureValue(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY, 83.3d); assertAddedRawMeasureValue(ROOT_REF, TEST_SUCCESS_DENSITY_KEY, 83.3d); } @Test public void compute_test_success_density_when_zero_tests_in_failures() { addedRawMeasure(PROJECT_VIEW_1_REF, TESTS_KEY, 10); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_ERRORS_KEY, 2); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_ERRORS_KEY, 5); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_FAILURES_KEY, 0); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_FAILURES_KEY, 0); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY, 76.7d); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF, TEST_SUCCESS_DENSITY_KEY); assertAddedRawMeasureValue(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY, 76.7d); assertAddedRawMeasureValue(ROOT_REF, TEST_SUCCESS_DENSITY_KEY, 76.7d); } @Test public void compute_100_percent_test_success_density_when_no_tests_in_errors_or_failures() { addedRawMeasure(PROJECT_VIEW_1_REF, TESTS_KEY, 10); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_ERRORS_KEY, 0); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_ERRORS_KEY, 0); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_FAILURES_KEY, 0); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_FAILURES_KEY, 0); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY, 100d); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF, TEST_SUCCESS_DENSITY_KEY); assertAddedRawMeasureValue(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY, 100d); assertAddedRawMeasureValue(ROOT_REF, TEST_SUCCESS_DENSITY_KEY, 100d); } @Test public void compute_0_percent_test_success_density() { int value = 10; String metricKey = TESTS_KEY; int componentRef = PROJECT_VIEW_1_REF; addedRawMeasure(componentRef, metricKey, value); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_ERRORS_KEY, 8); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_ERRORS_KEY, 15); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_FAILURES_KEY, 2); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_FAILURES_KEY, 5); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY, 0d); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF, TEST_SUCCESS_DENSITY_KEY); assertAddedRawMeasureValue(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY, 0d); assertAddedRawMeasureValue(ROOT_REF, TEST_SUCCESS_DENSITY_KEY, 0d); } @Test public void do_not_compute_test_success_density_when_no_tests_in_errors() { addedRawMeasure(PROJECT_VIEW_1_REF, TESTS_KEY, 10); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_FAILURES_KEY, 4); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_FAILURES_KEY, 1); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertNoAddedRawMeasure(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY); assertNoAddedRawMeasure(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY); assertNoAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY); } @Test public void do_not_compute_test_success_density_when_no_tests_in_failure() { addedRawMeasure(PROJECT_VIEW_1_REF, TESTS_KEY, 10); addedRawMeasure(PROJECT_VIEW_2_REF, TESTS_KEY, 20); addedRawMeasure(PROJECT_VIEW_1_REF, TEST_ERRORS_KEY, 0); addedRawMeasure(PROJECT_VIEW_2_REF, TEST_ERRORS_KEY, 0); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertNoAddedRawMeasure(SUB_SUBVIEW_1_REF, TEST_SUCCESS_DENSITY_KEY); assertNoAddedRawMeasure(SUBVIEW_REF, TEST_SUCCESS_DENSITY_KEY); assertNoAddedRawMeasure(ROOT_REF, TEST_SUCCESS_DENSITY_KEY); } private void checkMeasuresAggregation(String metricKey, int file1Value, int file2Value, int expectedValue) { addedRawMeasure(PROJECT_VIEW_1_REF, metricKey, file1Value); addedRawMeasure(PROJECT_VIEW_2_REF, metricKey, file2Value); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, metricKey, expectedValue); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF, TEST_SUCCESS_DENSITY_KEY); assertAddedRawMeasureValue(SUBVIEW_REF, metricKey, expectedValue); assertAddedRawMeasureValue(ROOT_REF, metricKey, expectedValue); } private void checkMeasuresAggregation(String metricKey, long file1Value, long file2Value, long expectedValue) { measureRepository.addRawMeasure(PROJECT_VIEW_1_REF, metricKey, newMeasureBuilder().create(file1Value)); measureRepository.addRawMeasure(PROJECT_VIEW_2_REF, metricKey, newMeasureBuilder().create(file2Value)); underTest.execute(new TestComputationStepContext()); assertNoAddedRawMeasureOnProjectViews(); assertAddedRawMeasureValue(SUB_SUBVIEW_1_REF, metricKey, expectedValue); assertNoAddedRawMeasure(SUB_SUBVIEW_2_REF, TEST_SUCCESS_DENSITY_KEY); assertAddedRawMeasureValue(SUBVIEW_REF, metricKey, expectedValue); assertAddedRawMeasureValue(ROOT_REF, metricKey, expectedValue); } private void addedRawMeasure(int componentRef, String metricKey, int value) { measureRepository.addRawMeasure(componentRef, metricKey, newMeasureBuilder().create(value)); } private void assertAddedRawMeasureValue(int componentRef, String metricKey, double value) { assertThat(entryOf(metricKey, measureRepository.getAddedRawMeasure(componentRef, metricKey).get())) .isEqualTo(entryOf(metricKey, newMeasureBuilder().create(value, 1))); } private void assertAddedRawMeasureValue(int componentRef, String metricKey, long value) { assertThat(entryOf(metricKey, measureRepository.getAddedRawMeasure(componentRef, metricKey).get())) .isEqualTo(entryOf(metricKey, newMeasureBuilder().create(value))); } private void assertNoAddedRawMeasure(int componentRef, String metricKey) { assertThat(measureRepository.getAddedRawMeasure(componentRef, metricKey)).isNotPresent(); } private void assertAddedRawMeasureValue(int componentRef, String metricKey, int expectedValue) { assertThat(toEntries(measureRepository.getAddedRawMeasures(componentRef))).containsOnly(entryOf(metricKey, newMeasureBuilder().create(expectedValue))); } private void assertNoAddedRawMeasureOnProjectViews() { assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_1_REF)).isEmpty(); assertThat(measureRepository.getAddedRawMeasures(PROJECT_VIEW_2_REF)).isEmpty(); } }
13,015
42.242525
155
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskModuleTest.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.taskprocessor; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class AuditPurgeTaskModuleTest { @Test public void verifyCountOfAddedComponents() { ListContainer container = new ListContainer(); new AuditPurgeTaskModule().configure(container); assertThat(container.getAddedObjects()).hasSize(1); } }
1,291
35.914286
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeTaskProcessorTest.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.taskprocessor; import java.util.List; import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.Mockito; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.container.TaskContainer; import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.SpringComponentContainer; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.sonar.ce.task.projectanalysis.taskprocessor.AuditPurgeTaskProcessor.AuditPurgeComputationSteps; import static org.sonar.db.ce.CeTaskTypes.AUDIT_PURGE; public class AuditPurgeTaskProcessorTest { private final SpringComponentContainer ceEngineContainer = mock(SpringComponentContainer.class); private final AuditPurgeTaskProcessor underTest = new AuditPurgeTaskProcessor(ceEngineContainer); private final TaskContainer container = Mockito.spy(TaskContainer.class); @Test public void getHandledCeTaskTypes() { Assertions.assertThat(underTest.getHandledCeTaskTypes()).containsExactly(AUDIT_PURGE); } @Test public void processThrowsNPEIfCeTaskIsNull() { assertThatThrownBy(() -> underTest.process(null)) .isInstanceOf(NullPointerException.class); } @Test public void newContainerPopulator() { CeTask task = new CeTask.Builder() .setUuid("TASK_UUID") .setType("Type") .build(); AuditPurgeTaskProcessor.newContainerPopulator(task).populateContainer(container); Mockito.verify(container, Mockito.times(5)).add(any()); } @Test public void orderedStepClasses(){ AuditPurgeComputationSteps auditPurgeComputationSteps = new AuditPurgeComputationSteps(null); List<Class<? extends ComputationStep>> steps = auditPurgeComputationSteps.orderedStepClasses(); Assertions.assertThat(steps).containsExactly(AuditPurgeStep.class); } }
2,784
36.635135
113
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/taskprocessor/IssueSyncTaskProcessorTest.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.taskprocessor; import java.util.List; import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.Mockito; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.container.TaskContainer; import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.SpringComponentContainer; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.sonar.ce.task.projectanalysis.taskprocessor.IssueSyncTaskProcessor.SyncComputationSteps; import static org.sonar.db.ce.CeTaskTypes.BRANCH_ISSUE_SYNC; public class IssueSyncTaskProcessorTest { private final SpringComponentContainer ceEngineContainer = mock(SpringComponentContainer.class); private final IssueSyncTaskProcessor underTest = new IssueSyncTaskProcessor(ceEngineContainer); private final TaskContainer container = Mockito.spy(TaskContainer.class); @Test public void getHandledCeTaskTypes() { Assertions.assertThat(underTest.getHandledCeTaskTypes()).containsExactly(BRANCH_ISSUE_SYNC); } @Test public void newContainerPopulator() { CeTask task = new CeTask.Builder() .setUuid("TASK_UUID") .setType("Type") .build(); IssueSyncTaskProcessor.newContainerPopulator(task).populateContainer(container); Mockito.verify(container, Mockito.times(5)).add(any()); } @Test public void orderedStepClasses(){ SyncComputationSteps syncComputationSteps = new SyncComputationSteps(null); List<Class<? extends ComputationStep>> steps = syncComputationSteps.orderedStepClasses(); Assertions.assertThat(steps).containsExactly(IgnoreOrphanBranchStep.class, IndexIssuesStep.class); } }
2,562
36.691176
106
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/WrapInSingleElementArray.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.util; import java.util.function.Function; import javax.annotation.Nonnull; public enum WrapInSingleElementArray implements Function<Object, Object[]> { INSTANCE; @Override @Nonnull public Object[] apply(Object input) { return new Object[] {input}; } }
1,154
32.970588
76
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/JavaSerializationDiskCacheTest.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.util.cache; import java.io.ObjectOutputStream; import java.io.Serializable; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.utils.System2; import org.sonar.core.util.CloseableIterator; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class JavaSerializationDiskCacheTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); @Test public void write_and_read() throws Exception { DiskCache<String> cache = new JavaSerializationDiskCache<>(temp.newFile(), System2.INSTANCE); try (CloseableIterator<String> traverse = cache.traverse()) { assertThat(traverse).isExhausted(); } cache.newAppender() .append("foo") .append("bar") .close(); try (CloseableIterator<String> traverse = cache.traverse()) { assertThat(traverse).toIterable().containsExactly("foo", "bar"); } } @Test public void fail_if_file_is_not_writable() throws Exception { try { new JavaSerializationDiskCache<>(temp.newFolder(), System2.INSTANCE); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessageContaining("Fail to write into file"); } } @Test public void fail_to_serialize() throws Exception { class Unserializable implements Serializable { private void writeObject(ObjectOutputStream out) { throw new UnsupportedOperationException("expected error"); } } DiskCache<Serializable> cache = new JavaSerializationDiskCache<>(temp.newFile(), System2.INSTANCE); try { cache.newAppender().append(new Unserializable()); fail(); } catch (UnsupportedOperationException e) { assertThat(e).hasMessage("expected error"); } } }
2,675
32.45
103
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/MemoryCacheTest.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.util.cache; import com.google.common.collect.ImmutableMap; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.anyCollection; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; public class MemoryCacheTest { private CacheLoader<String, String> loader = mock(CacheLoader.class); private MemoryCache<String, String> cache = new MemoryCache<>(loader); @Test public void getNullable() { when(loader.load("foo")).thenReturn("bar"); assertThat(cache.getNullable("foo")).isEqualTo("bar"); assertThat(cache.getNullable("foo")).isEqualTo("bar"); verify(loader, times(1)).load("foo"); // return null if key not found assertThat(cache.getNullable("not_exists")).isNull(); // clear cache -> new calls to CacheLoader cache.clear(); assertThat(cache.getNullable("foo")).isEqualTo("bar"); verify(loader, times(2)).load("foo"); } @Test public void get_throws_exception_if_not_exists() { when(loader.load("foo")).thenReturn("bar"); assertThat(cache.get("foo")).isEqualTo("bar"); assertThat(cache.get("foo")).isEqualTo("bar"); verify(loader, times(1)).load("foo"); assertThatThrownBy(() -> cache.get("not_exists")) .isInstanceOf(IllegalStateException.class) .hasMessage("No cache entry found for key: not_exists"); } @Test public void getAllNullable() { // ask for 3 keys but only 2 are available in backed (third key is missing) List<String> keys = Arrays.asList("one", "two", "three"); Map<String, String> values = new HashMap<>(); values.put("one", "un"); values.put("two", "deux"); when(loader.loadAll(keys)).thenReturn(values); assertThat(cache.getAll(keys)) .hasSize(3) .containsEntry("one", "un") .containsEntry("two", "deux") .containsEntry("three", null); // ask for 4 keys. Only a single one was never loaded. The 3 others are kept from cache when(loader.loadAll(Arrays.asList("four"))).thenReturn(ImmutableMap.of("four", "quatre")); assertThat(cache.getAll(Arrays.asList("one", "two", "three", "four"))) .hasSize(4) .containsEntry("one", "un") .containsEntry("two", "deux") .containsEntry("three", null) .containsEntry("four", "quatre"); verify(loader, times(2)).loadAll(anyCollection()); } }
3,511
35.968421
94
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/ObjectInputStreamIteratorTest.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.util.cache; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.NoSuchElementException; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class ObjectInputStreamIteratorTest { @Test public void read_objects() throws Exception { ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytesOutput); objectOutputStream.writeObject(new SimpleSerializable("first")); objectOutputStream.writeObject(new SimpleSerializable("second")); objectOutputStream.writeObject(new SimpleSerializable("third")); objectOutputStream.flush(); objectOutputStream.close(); ObjectInputStreamIterator<SimpleSerializable> it = new ObjectInputStreamIterator<>(new ByteArrayInputStream(bytesOutput.toByteArray())); assertThat(it.next().value).isEqualTo("first"); assertThat(it.next().value).isEqualTo("second"); assertThat(it.next().value).isEqualTo("third"); try { it.next(); fail(); } catch (NoSuchElementException expected) { } } @Test public void test_error() throws Exception { ByteArrayOutputStream bytesOutput = new ByteArrayOutputStream(); ObjectOutputStream objectOutputStream = new ObjectOutputStream(bytesOutput); objectOutputStream.writeObject(new SimpleSerializable("first")); objectOutputStream.writeBoolean(false); objectOutputStream.flush(); objectOutputStream.close(); ObjectInputStreamIterator<SimpleSerializable> it = new ObjectInputStreamIterator<>(new ByteArrayInputStream(bytesOutput.toByteArray())); assertThat(it.next().value).isEqualTo("first"); try { it.next(); fail(); } catch (RuntimeException expected) { } } static class SimpleSerializable implements Serializable { String value; public SimpleSerializable() { } public SimpleSerializable(String value) { this.value = value; } } }
2,997
33.45977
140
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/util/cache/ProtobufIssueDiskCacheTest.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.util.cache; import java.util.Date; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.rules.RuleType; import org.sonar.core.issue.DefaultIssue; import static org.assertj.core.api.Assertions.assertThat; public class ProtobufIssueDiskCacheTest { private static final String TEST_CONTEXT_KEY = "test_context_key"; @Test public void toDefaultIssue_whenRuleDescriptionContextKeyPresent_shouldSetItInDefaultIssue() { IssueCache.Issue issue = prepareIssueWithCompulsoryFields() .setRuleDescriptionContextKey(TEST_CONTEXT_KEY) .build(); DefaultIssue defaultIssue = ProtobufIssueDiskCache.toDefaultIssue(issue); assertThat(defaultIssue.getRuleDescriptionContextKey()).contains(TEST_CONTEXT_KEY); } @Test public void toDefaultIssue_whenRuleDescriptionContextKeyAbsent_shouldNotSetItInDefaultIssue() { IssueCache.Issue issue = prepareIssueWithCompulsoryFields() .build(); DefaultIssue defaultIssue = ProtobufIssueDiskCache.toDefaultIssue(issue); assertThat(defaultIssue.getRuleDescriptionContextKey()).isEmpty(); } @Test public void toProto_whenRuleDescriptionContextKeySet_shouldCopyToIssueProto() { DefaultIssue defaultIssue = createDefaultIssueWithMandatoryFields(); defaultIssue.setRuleDescriptionContextKey(TEST_CONTEXT_KEY); IssueCache.Issue issue = ProtobufIssueDiskCache.toProto(IssueCache.Issue.newBuilder(), defaultIssue); assertThat(issue.hasRuleDescriptionContextKey()).isTrue(); assertThat(issue.getRuleDescriptionContextKey()).isEqualTo(TEST_CONTEXT_KEY); } @Test public void toProto_whenRuleDescriptionContextKeyNotSet_shouldCopyToIssueProto() { DefaultIssue defaultIssue = createDefaultIssueWithMandatoryFields(); defaultIssue.setRuleDescriptionContextKey(null); IssueCache.Issue issue = ProtobufIssueDiskCache.toProto(IssueCache.Issue.newBuilder(), defaultIssue); assertThat(issue.hasRuleDescriptionContextKey()).isFalse(); } private static DefaultIssue createDefaultIssueWithMandatoryFields() { DefaultIssue defaultIssue = new DefaultIssue(); defaultIssue.setKey("test_issue:key"); defaultIssue.setType(RuleType.CODE_SMELL); defaultIssue.setComponentKey("component_key"); defaultIssue.setProjectUuid("project_uuid"); defaultIssue.setProjectKey("project_key"); defaultIssue.setRuleKey(RuleKey.of("ruleRepo", "rule1")); defaultIssue.setStatus("open"); defaultIssue.setCreationDate(new Date()); return defaultIssue; } private static IssueCache.Issue.Builder prepareIssueWithCompulsoryFields() { return IssueCache.Issue.newBuilder() .setRuleType(RuleType.CODE_SMELL.getDbConstant()) .setRuleKey("test_issue:key") .setStatus("open"); } }
3,646
36.597938
105
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectanalysis/webhook/WebhookPostTaskTest.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.webhook; import com.google.common.collect.ImmutableMap; import java.util.Collections; import java.util.Date; import java.util.Map; import java.util.Random; import java.util.function.Supplier; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.ce.posttask.Branch; import org.sonar.api.ce.posttask.CeTask; import org.sonar.api.ce.posttask.PostProjectAnalysisTask.LogStatistics; import org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester; import org.sonar.api.ce.posttask.Project; import org.sonar.api.ce.posttask.QualityGate; import org.sonar.api.config.Configuration; import org.sonar.api.measures.Metric; import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository; import org.sonar.server.qualitygate.Condition; import org.sonar.server.qualitygate.EvaluatedCondition; import org.sonar.server.qualitygate.EvaluatedQualityGate; import org.sonar.server.webhook.Analysis; import org.sonar.server.webhook.ProjectAnalysis; import org.sonar.server.webhook.WebHooks; import org.sonar.server.webhook.WebhookPayload; import org.sonar.server.webhook.WebhookPayloadFactory; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; 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.verify; import static org.mockito.Mockito.when; import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newBranchBuilder; import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newCeTaskBuilder; import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newConditionBuilder; import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newProjectBuilder; import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newQualityGateBuilder; import static org.sonar.api.ce.posttask.PostProjectAnalysisTaskTester.newScannerContextBuilder; public class WebhookPostTaskTest { private final Random random = new Random(); private final Configuration configuration = mock(Configuration.class); private final WebhookPayload webhookPayload = mock(WebhookPayload.class); private final WebhookPayloadFactory payloadFactory = mock(WebhookPayloadFactory.class); private final WebHooks webHooks = mock(WebHooks.class); private final ConfigurationRepository configurationRepository = mock(ConfigurationRepository.class); private WebhookPostTask underTest = new WebhookPostTask(payloadFactory, webHooks); @Before public void wireMocks() { when(payloadFactory.create(any(ProjectAnalysis.class))).thenReturn(webhookPayload); when(configurationRepository.getConfiguration()).thenReturn(configuration); } @Test public void has_description() { assertThat(underTest.getDescription()).isNotEmpty(); } @Test public void call_webhooks_when_no_analysis_not_qualitygate() { callWebHooks(null, null); } @Test public void call_webhooks_with_analysis_and_qualitygate() { QualityGate.Condition condition = newConditionBuilder() .setMetricKey(randomAlphanumeric(96)) .setOperator(QualityGate.Operator.LESS_THAN) .setErrorThreshold(randomAlphanumeric(22)) .setOnLeakPeriod(random.nextBoolean()) .build(QualityGate.EvaluationStatus.OK, randomAlphanumeric(33)); QualityGate qualityGate = newQualityGateBuilder() .setId(randomAlphanumeric(23)) .setName(randomAlphanumeric(66)) .setStatus(QualityGate.Status.values()[random.nextInt(QualityGate.Status.values().length)]) .add(condition) .build(); callWebHooks(randomAlphanumeric(40), qualityGate); } private void callWebHooks(@Nullable String analysisUUid, @Nullable QualityGate qualityGate) { Project project = newProjectBuilder() .setUuid(randomAlphanumeric(3)) .setKey(randomAlphanumeric(4)) .setName(randomAlphanumeric(5)) .build(); CeTask ceTask = newCeTaskBuilder() .setStatus(CeTask.Status.values()[random.nextInt(CeTask.Status.values().length)]) .setId(randomAlphanumeric(6)) .build(); Date date = new Date(); Map<String, String> properties = ImmutableMap.of(randomAlphanumeric(17), randomAlphanumeric(18)); Branch branch = newBranchBuilder() .setIsMain(random.nextBoolean()) .setType(Branch.Type.values()[random.nextInt(Branch.Type.values().length)]) .setName(randomAlphanumeric(29)) .build(); PostProjectAnalysisTaskTester.of(underTest) .at(date) .withCeTask(ceTask) .withProject(project) .withBranch(branch) .withQualityGate(qualityGate) .withScannerContext(newScannerContextBuilder() .addProperties(properties) .build()) .withAnalysisUuid(analysisUUid) .withQualityGate(qualityGate) .execute(); ArgumentCaptor<Supplier> supplierCaptor = ArgumentCaptor.forClass(Supplier.class); verify(webHooks) .sendProjectAnalysisUpdate( eq(new WebHooks.Analysis(project.getUuid(), analysisUUid, ceTask.getId())), supplierCaptor.capture(), any(LogStatistics.class)); assertThat(supplierCaptor.getValue().get()).isSameAs(webhookPayload); EvaluatedQualityGate webQualityGate = null; if (qualityGate != null) { QualityGate.Condition condition = qualityGate.getConditions().iterator().next(); Condition qgCondition = new Condition( condition.getMetricKey(), Condition.Operator.valueOf(condition.getOperator().name()), condition.getErrorThreshold()); webQualityGate = EvaluatedQualityGate.newBuilder() .setQualityGate(new org.sonar.server.qualitygate.QualityGate(qualityGate.getId(), qualityGate.getName(), Collections.singleton(qgCondition))) .setStatus(Metric.Level.valueOf(qualityGate.getStatus().name())) .addEvaluatedCondition(qgCondition, EvaluatedCondition.EvaluationStatus.valueOf(condition.getStatus().name()), condition.getValue()) .build(); } verify(payloadFactory).create(new ProjectAnalysis( new org.sonar.server.webhook.Project(project.getUuid(), project.getKey(), project.getName()), new org.sonar.server.webhook.CeTask(ceTask.getId(), org.sonar.server.webhook.CeTask.Status.valueOf(ceTask.getStatus().name())), analysisUUid == null ? null : new Analysis(analysisUUid, date.getTime(), null), new org.sonar.server.webhook.Branch(branch.isMain(), branch.getName().get(), org.sonar.server.webhook.Branch.Type.valueOf(branch.getType().name())), webQualityGate, analysisUUid == null ? null : date.getTime(), properties)); } }
7,652
42.982759
154
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/ProjectExportComputationStepsTest.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.projectexport; import com.google.common.collect.Lists; import org.junit.Test; import org.sonar.ce.task.container.TaskContainer; import org.sonar.ce.task.container.TaskContainerImpl; import org.sonar.ce.task.projectanalysis.step.ComplexityMeasuresStep; import org.sonar.ce.task.step.ComputationStep; import org.sonar.core.platform.SpringComponentContainer; import static com.google.common.collect.ImmutableList.copyOf; 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.when; public class ProjectExportComputationStepsTest { private final TaskContainer container = mock(TaskContainer.class); private final ProjectExportComputationSteps underTest = new ProjectExportComputationSteps(container); @Test public void count_step_classes() { assertThat(copyOf(underTest.orderedStepClasses())).hasSize(19); } @Test public void instances_throws_ISE_if_steps_do_not_exist_in_container() { when(container.getComponentByType(any())).thenThrow(new IllegalStateException("Error")); Iterable<ComputationStep> instances = underTest.instances(); assertThatThrownBy(() -> copyOf(instances)) .isInstanceOf(IllegalStateException.class) .hasMessage("Error"); } @Test public void instances_throws_ISE_if_container_does_not_have_second_step() { ComplexityMeasuresStep reportExtractionStep = mock(ComplexityMeasuresStep.class); SpringComponentContainer componentContainer = new SpringComponentContainer() { { add(reportExtractionStep); } }.startComponents(); TaskContainerImpl computeEngineContainer = new TaskContainerImpl(componentContainer, container -> { // do nothing }); computeEngineContainer.startComponents(); Iterable<ComputationStep> instances = new ProjectExportComputationSteps(computeEngineContainer).instances(); assertThatThrownBy(() -> Lists.newArrayList(instances)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("class org.sonar.ce.task.projectexport.steps.LoadProjectStep"); } }
3,084
40.133333
112
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/ProjectExportContainerPopulatorTest.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.projectexport; import org.junit.Test; import org.sonar.ce.task.projectanalysis.task.ListTaskContainer; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.setting.SettingsLoader; import static org.assertj.core.api.Assertions.assertThat; public class ProjectExportContainerPopulatorTest { private final ProjectDescriptor descriptor = new ProjectDescriptor("project_uuid", "project_key", "Project Name"); private final ProjectExportContainerPopulator underTest = new ProjectExportContainerPopulator(descriptor); @Test public void test_populateContainer() { ListTaskContainer container = new ListTaskContainer(); underTest.populateContainer(container); assertThat(container.getAddedComponents()) .hasSize(29) .contains(descriptor, SettingsLoader.class); } }
1,707
39.666667
116
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/component/ComponentRepositoryImplTest.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.projectexport.component; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ComponentRepositoryImplTest { private static final int SOME_REF = 121; private static final String SOME_UUID = "uuid"; private ComponentRepositoryImpl underTest = new ComponentRepositoryImpl(); @Test public void register_throws_NPE_if_uuid_is_null() { assertThatThrownBy(() -> underTest.register(SOME_REF, null, true)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can not be null"); } @Test public void register_throws_IAE_same_uuid_added_with_different_refs() { underTest.register(SOME_REF, SOME_UUID, true); assertThatThrownBy(() -> underTest.register(946512, SOME_UUID, true)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Uuid '" + SOME_UUID + "' already registered under ref '" + SOME_REF + "' in repository"); } @Test public void register_throws_IAE_same_uuid_added_with_as_file() { underTest.register(SOME_REF, SOME_UUID, true); assertThatThrownBy(() -> underTest.register(SOME_REF, SOME_UUID, false)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Uuid '" + SOME_UUID + "' already registered but as a File"); } @Test public void register_throws_IAE_same_uuid_added_with_as_not_file() { underTest.register(SOME_REF, SOME_UUID, false); assertThatThrownBy(() -> underTest.register(SOME_REF, SOME_UUID, true)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Uuid '" + SOME_UUID + "' already registered but not as a File"); } @Test public void getRef_throws_NPE_if_uuid_is_null() { assertThatThrownBy(() -> underTest.getRef(null)) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can not be null"); } @Test public void getRef_throws_ISE_if_uuid_not_in_repository() { assertThatThrownBy(() -> underTest.getRef(SOME_UUID)) .isInstanceOf(IllegalStateException.class) .hasMessage("No reference registered in the repository for uuid '" + SOME_UUID + "'"); } @Test public void getRef_returns_ref_added_with_register_when_file() { underTest.register(SOME_REF, SOME_UUID, true); assertThat(underTest.getRef(SOME_UUID)).isEqualTo(SOME_REF); } @Test public void getRef_returns_ref_added_with_register_when_not_file() { underTest.register(SOME_REF, SOME_UUID, false); assertThat(underTest.getRef(SOME_UUID)).isEqualTo(SOME_REF); } @Test public void getFileUuids_returns_empty_when_repository_is_empty() { assertThat(underTest.getFileUuids()).isEmpty(); } @Test public void getFileUuids_returns_uuids_of_only_components_added_with_file_flag_is_true() { underTest.register(SOME_REF, "file id 1", true); underTest.register(546, SOME_UUID, false); underTest.register(987, "file id 2", true); underTest.register(123, "not file id", false); assertThat(underTest.getFileUuids()).containsOnly("file id 1", "file id 2"); } }
3,959
34.675676
108
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/ExportRuleStepTest.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.projectexport.rule; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.junit.Test; import org.slf4j.event.Level; import org.sonar.api.rule.RuleKey; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.ce.task.projectexport.steps.DumpElement; import org.sonar.ce.task.projectexport.steps.FakeDumpWriter; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.util.Uuids; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class ExportRuleStepTest { private static final String REPOSITORY = "repository"; @org.junit.Rule public LogTester logTester = new LogTester(); private FakeDumpWriter dumpWriter = new FakeDumpWriter(); private SimpleRuleRepository ruleRepository = new SimpleRuleRepository(); private ExportRuleStep underTest = new ExportRuleStep(ruleRepository, dumpWriter); @Test public void getDescription_is_set() { assertThat(underTest.getDescription()).isEqualTo("Export rules"); } @Test public void execute_writes_no_rules_when_repository_is_empty() { underTest.execute(new TestComputationStepContext()); assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.RULES)).isEmpty(); } @Test public void execute_writes_all_rules_in_order_returned_by_repository() { String[] keys = new String[10]; for (int i = 0; i < 10; i++) { String key = "key_" + i; ruleRepository.add(key); keys[i] = key; } underTest.execute(new TestComputationStepContext()); List<ProjectDump.Rule> rules = dumpWriter.getWrittenMessagesOf(DumpElement.RULES); assertThat(rules).extracting(ProjectDump.Rule::getKey).containsExactly(keys); assertThat(rules).extracting(ProjectDump.Rule::getRepository).containsOnly(REPOSITORY); } @Test public void execute_logs_number_total_exported_rules_count_when_successful() { logTester.setLevel(Level.DEBUG); ruleRepository.add("A").add("B").add("C").add("D"); underTest.execute(new TestComputationStepContext()); assertThat(logTester.logs(Level.DEBUG)).containsExactly("4 rules exported"); } @Test public void excuse_throws_ISE_exception_with_number_of_successfully_exported_rules() { ruleRepository.add("A").add("B").add("C") // will cause NPE .addNull(); assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext())) .isInstanceOf(IllegalStateException.class) .hasMessage("Rule Export failed after processing 3 rules successfully"); } private static class SimpleRuleRepository implements RuleRepository { private List<Rule> rules = new ArrayList<>(); @Override public Rule register(String uuid, RuleKey ruleKey) { throw new UnsupportedOperationException("getByRuleKey not implemented"); } public SimpleRuleRepository add(String key) { this.rules.add(new Rule(Uuids.createFast(), REPOSITORY, key)); return this; } public SimpleRuleRepository addNull() { this.rules.add(null); return this; } @Override public Collection<Rule> getAll() { return rules; } } }
4,137
32.918033
91
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleRepositoryImplTest.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectexport.rule; import java.util.Collection; import java.util.Random; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.core.util.Uuids; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleRepositoryImplTest { private static final String SOME_UUID = "uuid-846"; private static final String SOME_REPOSITORY = "rep"; private static final String SOME_RULE_KEY = "key"; private static final Rule SOME_RULE = new Rule("uuid-1", SOME_REPOSITORY, SOME_RULE_KEY); private Random random = new Random(); private RuleRepositoryImpl underTest = new RuleRepositoryImpl(); @Test public void register_throws_NPE_if_ruleKey_is_null() { assertThatThrownBy(() -> underTest.register(SOME_UUID, null)) .isInstanceOf(NullPointerException.class) .hasMessage("ruleKey can not be null"); } @Test public void register_does_not_enforce_some_RuleKey_is_registered_under_a_single_id() { underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); for (int i = 0; i < someRandomInt(); i++) { Rule otherRule = underTest.register(Integer.toString(i), RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); assertThat(otherRule.ref()).isEqualTo(Integer.toString(i)); assertThat(otherRule.repository()).isEqualTo(SOME_REPOSITORY); assertThat(otherRule.key()).isEqualTo(SOME_RULE_KEY); } } @Test public void register_fails_IAE_if_RuleKey_is_not_the_same_repository_for_a_specific_ref() { underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); assertThatThrownBy(() -> underTest.register(SOME_UUID, RuleKey.of("other repo", SOME_RULE_KEY))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Specified RuleKey 'other repo:key' is not equal to the one already registered in repository for ref " + SOME_UUID + ": 'rep:key'"); } @Test public void register_fails_IAE_if_RuleKey_is_not_the_same_key_for_a_specific_ref() { underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); assertThatThrownBy(() -> underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, "other key"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Specified RuleKey 'rep:other key' is not equal to the one already registered in repository for ref " + SOME_UUID + ": 'rep:key'"); } @Test public void register_returns_the_same_object_for_every_call_with_equals_RuleKey_objects() { Rule rule = underTest.register(SOME_UUID, RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)); for (int i = 0; i < someRandomInt(); i++) { assertThat(underTest.register(Uuids.createFast(), RuleKey.of(SOME_REPOSITORY, SOME_RULE_KEY)).ref()).isNotEqualTo(rule.ref()); } } @Test public void register_returns_Rule_object_created_from_arguments() { for (int i = 0; i < someRandomInt(); i++) { String repository = SOME_REPOSITORY + i; String ruleKey = String.valueOf(i); Rule rule = underTest.register(Integer.toString(i), RuleKey.of(repository, ruleKey)); assertThat(rule.ref()).isEqualTo(Integer.toString(i)); assertThat(rule.repository()).isEqualTo(repository); assertThat(rule.key()).isEqualTo(ruleKey); } } @Test public void getAll_returns_immutable_empty_collection_when_register_was_never_called() { Collection<Rule> all = underTest.getAll(); assertThat(all).isEmpty(); assertThatThrownBy(() -> all.add(SOME_RULE)) .isInstanceOf(UnsupportedOperationException.class); } @Test public void getAll_returns_immutable_collection_with_one_Rule_for_each_distinct_RuleKey() { int size = someRandomInt(); String[] repositories = new String[size]; String[] keys = new String[size]; for (int i = 0; i < size; i++) { String key = "key_" + i; String repository = "repo_" + i; underTest.register(Uuids.createFast(), RuleKey.of(repository, key)); repositories[i] = repository; keys[i] = key; } Collection<Rule> all = underTest.getAll(); assertThat(all).extracting(Rule::repository).containsOnly(repositories); assertThat(all).extracting(Rule::key).containsOnly(keys); assertThatThrownBy(() -> all.add(SOME_RULE)) .isInstanceOf(UnsupportedOperationException.class); } private int someRandomInt() { return 50 + Math.abs(random.nextInt(500)); } }
5,319
39
150
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/rule/RuleTest.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.projectexport.rule; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class RuleTest { private static final String SOME_DUMP_UUID = "uuid-12334"; private static final String SOME_REPOSITORY = "some repository"; private static final String SOME_KEY = "some key"; private Rule underTest = new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, SOME_KEY); @Test public void constructor_throws_NPE_if_repository_is_null() { assertThatThrownBy(() -> new Rule(SOME_DUMP_UUID, null, SOME_KEY)) .isInstanceOf(NullPointerException.class) .hasMessage("repository can not be null"); } @Test public void constructor_throws_NPE_if_key_is_null() { assertThatThrownBy(() -> new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, null)) .isInstanceOf(NullPointerException.class) .hasMessage("key can not be null"); } @Test public void equals_compares_repository_and_key() { assertThat(underTest).isNotEqualTo(new Rule(SOME_DUMP_UUID, SOME_KEY, SOME_REPOSITORY)); assertThat(underTest).isNotEqualTo(new Rule(SOME_DUMP_UUID, "other repository", SOME_KEY)); assertThat(underTest).isNotEqualTo(new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, "other key")); } @Test public void equals_ignores_dump_id() { assertThat(underTest).isEqualTo(new Rule("uuid-8888", SOME_REPOSITORY, SOME_KEY)); } @Test public void hashcode_is_based_on_repository_and_key() { assertThat(underTest).hasSameHashCodeAs(new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, SOME_KEY)); assertThat(underTest.hashCode()).isNotEqualTo(new Rule(SOME_DUMP_UUID, SOME_KEY, SOME_REPOSITORY).hashCode()); assertThat(underTest.hashCode()).isNotEqualTo(new Rule(SOME_DUMP_UUID, "other repository", SOME_KEY).hashCode()); assertThat(underTest.hashCode()).isNotEqualTo(new Rule(SOME_DUMP_UUID, SOME_REPOSITORY, "other key").hashCode()); } @Test public void hashcode_ignores_dump_id() { assertThat(underTest).hasSameHashCodeAs(new Rule("uuid-8888", SOME_REPOSITORY, SOME_KEY)); } @Test public void toString_displays_all_fields() { assertThat(underTest).hasToString("Rule{ref='uuid-12334', repository='some repository', key='some key'}"); } }
3,144
38.3125
117
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpElementTest.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.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.projectexport.steps.DumpElement.ANALYSES; import static org.sonar.ce.task.projectexport.steps.DumpElement.COMPONENTS; import static org.sonar.ce.task.projectexport.steps.DumpElement.EVENTS; import static org.sonar.ce.task.projectexport.steps.DumpElement.ISSUES; import static org.sonar.ce.task.projectexport.steps.DumpElement.ISSUES_CHANGELOG; import static org.sonar.ce.task.projectexport.steps.DumpElement.LINKS; import static org.sonar.ce.task.projectexport.steps.DumpElement.MEASURES; import static org.sonar.ce.task.projectexport.steps.DumpElement.METADATA; import static org.sonar.ce.task.projectexport.steps.DumpElement.METRICS; import static org.sonar.ce.task.projectexport.steps.DumpElement.PLUGINS; import static org.sonar.ce.task.projectexport.steps.DumpElement.RULES; import static org.sonar.ce.task.projectexport.steps.DumpElement.SETTINGS; public class DumpElementTest { @Test public void test_filename() { assertThat(METADATA.filename()).isEqualTo("metadata.pb"); assertThat(COMPONENTS.filename()).isEqualTo("components.pb"); assertThat(MEASURES.filename()).isEqualTo("measures.pb"); assertThat(METRICS.filename()).isEqualTo("metrics.pb"); assertThat(ISSUES.filename()).isEqualTo("issues.pb"); assertThat(ISSUES_CHANGELOG.filename()).isEqualTo("issues_changelog.pb"); assertThat(RULES.filename()).isEqualTo("rules.pb"); assertThat(ANALYSES.filename()).isEqualTo("analyses.pb"); assertThat(SETTINGS.filename()).isEqualTo("settings.pb"); assertThat(LINKS.filename()).isEqualTo("links.pb"); assertThat(EVENTS.filename()).isEqualTo("events.pb"); assertThat(PLUGINS.filename()).isEqualTo("plugins.pb"); } @Test public void test_parser() { assertThat(METADATA.parser()).isSameAs(ProjectDump.Metadata.parser()); } }
2,864
45.209677
81
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/DumpWriterImplTest.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.projectexport.steps; import com.google.common.collect.Iterables; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.io.File; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.TempFolder; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import org.sonar.ce.task.projectexport.util.ProjectExportDumpFS; 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.projectexport.steps.DumpElement.COMPONENTS; public class DumpWriterImplTest { @Rule public TemporaryFolder junitTemp = new TemporaryFolder(); @Rule public LogTester logTester = new LogTester(); MutableDumpReaderImpl dumpReader = new MutableDumpReaderImpl(); ProjectExportDumpFS projectexportDumpFS = mock(ProjectExportDumpFS.class); TempFolder temp = mock(TempFolder.class); ProjectDescriptor descriptor = mock(ProjectDescriptor.class); File rootDir; File zipFile; File targetZipFile; DumpWriter underTest; @Before public void setUp() throws Exception { rootDir = junitTemp.newFolder(); dumpReader.setTempRootDir(rootDir); zipFile = junitTemp.newFile(); targetZipFile = junitTemp.newFile(); when(temp.newDir()).thenReturn(rootDir); when(temp.newFile()).thenReturn(zipFile); when(projectexportDumpFS.exportDumpOf(descriptor)).thenReturn(targetZipFile); underTest = new DumpWriterImpl(descriptor, projectexportDumpFS, temp); } @Test public void writeMetadata_writes_to_file() { underTest.write(newMetadata()); assertThat(dumpReader.metadata().getProjectKey()).isEqualTo("foo"); } @Test public void writeMetadata_fails_if_called_twice() { underTest.write(newMetadata()); assertThatThrownBy(() -> underTest.write(newMetadata())) .isInstanceOf(IllegalStateException.class) .hasMessage("Metadata has already been written"); } @Test public void publish_zips_directory_then_deletes_the_temp_directory() { underTest.write(newMetadata()); underTest.publish(); assertThat(rootDir).doesNotExist(); assertThat(targetZipFile).isFile().exists(); assertThat(logTester.logs(Level.INFO).get(0)) .contains("Dump file published", "size=", "path=" + targetZipFile.getAbsolutePath()); } @Test public void publish_fails_if_called_twice() { underTest.write(newMetadata()); underTest.publish(); assertThatThrownBy(() -> underTest.publish()) .isInstanceOf(IllegalStateException.class) .hasMessage("Dump is already published"); } @Test public void publish_fails_if_metadata_is_missing() { assertThatThrownBy(() -> underTest.publish()) .isInstanceOf(IllegalStateException.class) .hasMessage("Metadata is missing"); } @Test public void ensure_written_fields_can_be_read() { try (StreamWriter<ProjectDump.Component> writer = underTest.newStreamWriter(COMPONENTS)) { writer.write(ProjectDump.Component.newBuilder() .setKey("abc") .setScope("FIL") .setQualifier("FIL") .setLanguage("java") .build()); } try (MessageStream<ProjectDump.Component> reader = dumpReader.stream(COMPONENTS)) { ProjectDump.Component component = Iterables.getOnlyElement(reader); assertThat(component.getKey()).isEqualTo("abc"); assertThat(component.getScope()).isEqualTo("FIL"); assertThat(component.getQualifier()).isEqualTo("FIL"); assertThat(component.getLanguage()).isEqualTo("java"); } } @Test public void create_empty_file_if_stream_is_empty() { try (StreamWriter<ProjectDump.Component> writer = underTest.newStreamWriter(COMPONENTS)) { // no components } assertThat(new File(rootDir, COMPONENTS.filename())).isFile().exists(); try (MessageStream<ProjectDump.Component> reader = dumpReader.stream(COMPONENTS)) { assertThat(reader).isEmpty(); } } private static ProjectDump.Metadata newMetadata() { return ProjectDump.Metadata.newBuilder() .setProjectKey("foo") .build(); } }
5,212
33.523179
94
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/ExportPluginsStepTest.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.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.Arrays; import java.util.Collections; 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.ce.task.step.TestComputationStepContext; import org.sonar.core.platform.PluginInfo; import org.sonar.core.platform.PluginRepository; import org.sonar.updatecenter.common.Version; 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; public class ExportPluginsStepTest { @Rule public LogTester logTester = new LogTester(); private PluginRepository pluginRepository = mock(PluginRepository.class); private FakeDumpWriter dumpWriter = new FakeDumpWriter(); ExportPluginsStep underTest = new ExportPluginsStep(pluginRepository, dumpWriter); @Before public void before() { logTester.setLevel(Level.DEBUG); } @Test public void export_plugins() { when(pluginRepository.getPluginInfos()).thenReturn(Arrays.asList( new PluginInfo("java"), new PluginInfo("cs"))); underTest.execute(new TestComputationStepContext()); List<ProjectDump.Plugin> exportedPlugins = dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS); assertThat(exportedPlugins).hasSize(2); assertThat(exportedPlugins).extracting(ProjectDump.Plugin::getKey).containsExactlyInAnyOrder("java", "cs"); assertThat(logTester.logs(Level.DEBUG)).contains("2 plugins exported"); } @Test public void export_zero_plugins() { when(pluginRepository.getPluginInfos()).thenReturn(Collections.emptyList()); underTest.execute(new TestComputationStepContext()); assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS)).isEmpty(); assertThat(logTester.logs(Level.DEBUG)).contains("0 plugins exported"); } @Test public void test_exported_fields() { when(pluginRepository.getPluginInfos()).thenReturn(singletonList( new PluginInfo("java").setName("Java").setVersion(Version.create("1.2.3")))); underTest.execute(new TestComputationStepContext()); ProjectDump.Plugin exportedPlugin = dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS).get(0); assertThat(exportedPlugin.getKey()).isEqualTo("java"); assertThat(exportedPlugin.getName()).isEqualTo("Java"); assertThat(exportedPlugin.getVersion()).isEqualTo("1.2.3"); } @Test public void test_nullable_exported_fields() { when(pluginRepository.getPluginInfos()).thenReturn(singletonList( new PluginInfo("java"))); underTest.execute(new TestComputationStepContext()); ProjectDump.Plugin exportedPlugin = dumpWriter.getWrittenMessagesOf(DumpElement.PLUGINS).get(0); assertThat(exportedPlugin.getKey()).isEqualTo("java"); // if name is not set, then value is the same as key assertThat(exportedPlugin.getName()).isEqualTo("java"); assertThat(exportedPlugin.getVersion()).isEmpty(); } @Test public void test_getDescription() { assertThat(underTest.getDescription()).isEqualTo("Export plugins"); } }
4,104
36.318182
111
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/FakeDumpWriter.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.projectexport.steps; import com.google.common.base.MoreObjects; import com.google.protobuf.Message; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static org.sonar.ce.task.projectexport.steps.DumpElement.METADATA; public class FakeDumpWriter implements DumpWriter { private boolean published = false; private final Map<DumpElement<?>, ListStreamWriter<?>> writersByDumpElement = new HashMap<>(); private final Map<DumpElement<?>, Integer> failureThresholds = new HashMap<>(); @Override public void write(ProjectDump.Metadata metadata) { checkNotPublished(); newStreamWriter(METADATA).write(metadata); } /** * @throws IllegalStateException if metadata have not been written yet. * @see #write(ProjectDump.Metadata) */ public ProjectDump.Metadata getMetadata() { return getWrittenMessagesOf(METADATA).get(0); } /** * @throws IllegalStateException if messages have not been written yet for the specified {@code DumpElement} * @see #newStreamWriter(DumpElement) */ @SuppressWarnings("unchecked") public <MSG extends Message> List<MSG> getWrittenMessagesOf(DumpElement<MSG> elt) { ListStreamWriter<MSG> writer = (ListStreamWriter<MSG>) writersByDumpElement.get(elt); checkState(writer != null); return writer.messages; } @Override public <MSG extends Message> StreamWriter<MSG> newStreamWriter(DumpElement<MSG> elt) { checkNotPublished(); checkState(!writersByDumpElement.containsKey(elt)); int failureThreshold = MoreObjects.firstNonNull(failureThresholds.get(elt), Integer.MAX_VALUE); ListStreamWriter<MSG> writer = new ListStreamWriter<>(failureThreshold); writersByDumpElement.put(elt, writer); return writer; } /** * The stream returned by {@link #newStreamWriter(DumpElement)} will throw an * {@link IllegalStateException} if more than {@code count} messages are written. * By default no exception is thrown. */ public void failIfMoreThan(int count, DumpElement element) { failureThresholds.put(element, count); } @Override public void publish() { checkNotPublished(); published = true; } private void checkNotPublished() { checkState(!published, "Dump is already published"); } private static class ListStreamWriter<MSG extends Message> implements StreamWriter<MSG> { private final List<MSG> messages = new ArrayList<>(); private final int failureThreshold; private ListStreamWriter(int failureThreshold) { checkArgument(failureThreshold >= 0, "Threshold (%d) must be positive", failureThreshold); this.failureThreshold = failureThreshold; } @Override public void write(MSG msg) { checkState(messages.size() < failureThreshold, "Maximum of %d written messages has been reached", failureThreshold); messages.add(msg); } @Override public void close() { // nothing to do } } }
4,033
33.775862
122
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/MutableMetricRepositoryImplTest.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.projectexport.steps; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.entry; public class MutableMetricRepositoryImplTest { MutableMetricRepository underTest = new MutableMetricRepositoryImpl(); @Test public void add_ref() { underTest.add("10"); underTest.add("12"); assertThat(underTest.getRefByUuid().entrySet()).containsOnly(entry("10", 0), entry("12", 1)); } @Test public void add_multiple_times_the_same_ref() { underTest.add("10"); underTest.add("10"); assertThat(underTest.getRefByUuid().entrySet()).containsExactly(entry("10", 0)); } @Test public void getAll_returns_empty_set() { assertThat(underTest.getRefByUuid()).isEmpty(); } }
1,645
30.653846
97
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/PublishDumpStepTest.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.projectexport.steps; import org.junit.Test; import org.sonar.ce.task.step.TestComputationStepContext; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; public class PublishDumpStepTest { DumpWriter dumpWriter = mock(DumpWriter.class); PublishDumpStep underTest = new PublishDumpStep(dumpWriter); @Test public void archives_dump() { underTest.execute(new TestComputationStepContext()); verify(dumpWriter).publish(); } @Test public void getDescription_is_defined() { assertThat(underTest.getDescription()).isEqualTo("Publish dump file"); } }
1,532
33.840909
75
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/steps/WriteMetadataStepTest.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.projectexport.steps; import com.sonarsource.governance.projectdump.protobuf.ProjectDump; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.api.utils.Version; import org.sonar.ce.task.step.TestComputationStepContext; import org.sonar.core.platform.SonarQubeVersion; import org.sonar.db.project.ProjectDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; public class WriteMetadataStepTest { private static final String PROJECT_KEY = "project_key"; private static final String PROJECT_UUID = "project_uuid"; private static final long NOW = 123L; System2 system2 = spy(System2.INSTANCE); FakeDumpWriter dumpWriter = new FakeDumpWriter(); MutableProjectHolderImpl projectHolder = new MutableProjectHolderImpl(); Version sqVersion = Version.create(6, 0); WriteMetadataStep underTest = new WriteMetadataStep(system2, dumpWriter, projectHolder, new SonarQubeVersion(sqVersion)); @Test public void write_metadata() { when(system2.now()).thenReturn(NOW); ProjectDto dto = new ProjectDto().setKey(PROJECT_KEY).setUuid(PROJECT_UUID); projectHolder.setProjectDto(dto); underTest.execute(new TestComputationStepContext()); ProjectDump.Metadata metadata = dumpWriter.getMetadata(); assertThat(metadata.getProjectKey()).isEqualTo(PROJECT_KEY); assertThat(metadata.getProjectUuid()).isEqualTo(PROJECT_UUID); assertThat(metadata.getSonarqubeVersion()).isEqualTo(sqVersion.toString()); assertThat(metadata.getDumpDate()).isEqualTo(NOW); } @Test public void getDescription_is_defined() { assertThat(underTest.getDescription()).isNotEmpty(); } }
2,593
37.716418
89
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/util/ProjectExportDumpFSImplTest.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.projectexport.util; import java.io.File; import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.MapSettings; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import static org.assertj.core.api.Assertions.assertThat; public class ProjectExportDumpFSImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private final MapSettings settings = new MapSettings(); private final ProjectDescriptor projectDescriptor = new ProjectDescriptor("uuid", "project_key", "name"); private final ProjectDescriptor descriptorWithUglyKey = new ProjectDescriptor("uuid", " so:me à9ç& Key ", "name"); private File dataDir; private ProjectExportDumpFSImpl underTest; @Before public void setUp() throws Exception { this.dataDir = temp.newFolder(); settings.setProperty("sonar.path.data", dataDir.getAbsolutePath()); this.underTest = new ProjectExportDumpFSImpl(settings.asConfig()); } @Test public void start_creates_import_and_export_directories_including_missing_parents() throws IOException { dataDir = new File(temp.newFolder(), "data"); File importDir = new File(dataDir, "governance/project_dumps/import"); File exportDir = new File(dataDir, "governance/project_dumps/export"); settings.setProperty("sonar.path.data", dataDir.getAbsolutePath()); this.underTest = new ProjectExportDumpFSImpl(settings.asConfig()); assertThat(dataDir).doesNotExist(); assertThat(importDir).doesNotExist(); assertThat(exportDir).doesNotExist(); underTest.start(); assertThat(dataDir).exists().isDirectory(); assertThat(exportDir).exists().isDirectory(); } @Test public void exportDumpOf_is_located_in_governance_project_dump_out() { assertThat(underTest.exportDumpOf(projectDescriptor)).isEqualTo(new File(dataDir, "governance/project_dumps/export/project_key.zip")); } @Test public void exportDumpOf_slugifies_project_key() { assertThat(underTest.exportDumpOf(descriptorWithUglyKey)) .isEqualTo(new File(dataDir, "governance/project_dumps/export/so-me-a9c-key.zip")); } }
3,088
36.216867
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/projectexport/util/ProjectImportDumpFSImplTest.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.projectexport.util; import java.io.File; import java.io.IOException; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.config.internal.MapSettings; import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor; import static org.assertj.core.api.Assertions.assertThat; public class ProjectImportDumpFSImplTest { @Rule public TemporaryFolder temp = new TemporaryFolder(); private final MapSettings settings = new MapSettings(); private final ProjectDescriptor projectDescriptor = new ProjectDescriptor("uuid", "project_key", "name"); private final ProjectDescriptor descriptorWithUglyKey = new ProjectDescriptor("uuid", " so:me à9ç& Key ", "name"); private File dataDir; private ProjectImportDumpFSImpl underTest; @Before public void setUp() throws Exception { this.dataDir = temp.newFolder(); settings.setProperty("sonar.path.data", dataDir.getAbsolutePath()); this.underTest = new ProjectImportDumpFSImpl(settings.asConfig()); } @Test public void start_creates_import_and_export_directories_including_missing_parents() throws IOException { dataDir = new File(temp.newFolder(), "data"); File importDir = new File(dataDir, "governance/project_dumps/import"); File exportDir = new File(dataDir, "governance/project_dumps/export"); settings.setProperty("sonar.path.data", dataDir.getAbsolutePath()); this.underTest = new ProjectImportDumpFSImpl(settings.asConfig()); assertThat(dataDir).doesNotExist(); assertThat(importDir).doesNotExist(); assertThat(exportDir).doesNotExist(); underTest.start(); assertThat(dataDir).exists().isDirectory(); assertThat(importDir).exists().isDirectory(); } @Test public void importDumpOf_is_located_in_governance_project_dump_in() { assertThat(underTest.importDumpOf(projectDescriptor)).isEqualTo(new File(dataDir, "governance/project_dumps/import/project_key.zip")); } @Test public void importDumpOf_slugifies_project_key() { assertThat(underTest.importDumpOf(descriptorWithUglyKey)) .isEqualTo(new File(dataDir, "governance/project_dumps/import/so-me-a9c-key.zip")); } }
3,087
36.204819
138
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Files2Test.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.util; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; public class Files2Test { @Rule public TemporaryFolder temp = new TemporaryFolder(); Files2 underTest = spy(Files2.FILES2); @Test public void deleteIfExists_does_nothing_if_file_does_not_exist() throws Exception { File file = temp.newFile(); assertThat(file.delete()).isTrue(); underTest.deleteIfExists(file); assertThat(file).doesNotExist(); } @Test public void deleteIfExists_deletes_directory() throws Exception { File dir = temp.newFolder(); underTest.deleteIfExists(dir); assertThat(dir).doesNotExist(); } @Test public void deleteIfExists_deletes_file() throws Exception { File file = temp.newFile(); underTest.deleteIfExists(file); assertThat(file).doesNotExist(); } @Test public void deleteIfExists_throws_ISE_on_error() throws Exception { File file = temp.newFile(); doThrow(new IOException("failure")).when(underTest).deleteIfExistsOrThrowIOE(file); assertThatThrownBy(() -> underTest.deleteIfExists(file)) .isInstanceOf(IllegalStateException.class); } @Test public void openInputStream_opens_existing_file() throws Exception { File file = temp.newFile(); FileUtils.write(file, "foo"); try (FileInputStream input = underTest.openInputStream(file)) { assertThat(IOUtils.toString(input)).isEqualTo("foo"); } } @Test public void openInputStream_throws_ISE_if_file_does_not_exist() throws Exception { final File file = temp.newFile(); assertThat(file.delete()).isTrue(); assertThatThrownBy(() -> underTest.openInputStream(file)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not open file " + file) .hasRootCauseMessage("File " + file + " does not exist"); } @Test public void openInputStream_throws_ISE_if_file_is_a_directory() throws Exception { File dir = temp.newFolder(); assertThatThrownBy(() -> underTest.openInputStream(dir)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not open file " + dir) .hasRootCauseMessage("File " + dir + " exists but is a directory"); } @Test public void openOutputStream_creates_file() throws Exception { File file = temp.newFile(); assertThat(file.delete()).isTrue(); try (FileOutputStream outputStream = underTest.openOutputStream(file, false)) { IOUtils.write("foo", outputStream); } assertThat(FileUtils.readFileToString(file)).isEqualTo("foo"); } @Test public void openOutputStream_appends_bytes_to_existing_file() throws Exception { File file = temp.newFile(); FileUtils.write(file, "foo"); try (FileOutputStream outputStream = underTest.openOutputStream(file, true)) { IOUtils.write("bar", outputStream); } assertThat(FileUtils.readFileToString(file)).isEqualTo("foobar"); } @Test public void openOutputStream_overwrites_existing_file() throws Exception { File file = temp.newFile(); FileUtils.write(file, "foo"); try (FileOutputStream outputStream = underTest.openOutputStream(file, false)) { IOUtils.write("bar", outputStream); } assertThat(FileUtils.readFileToString(file)).isEqualTo("bar"); } @Test public void openOutputStream_throws_ISE_if_file_is_a_directory() throws Exception { File dir = temp.newFolder(); assertThatThrownBy(() -> underTest.openOutputStream(dir, false)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not open file " + dir) .hasRootCauseMessage("File " + dir + " exists but is a directory"); } @Test public void zipDir_an_existing_directory_then_unzipToDir() throws Exception { File dir = temp.newFolder(); FileUtils.write(new File(dir, "foo.txt"), "foo"); File zipFile = temp.newFile(); underTest.zipDir(dir, zipFile); assertThat(zipFile).exists().isFile(); File unzippedDir = temp.newFolder(); underTest.unzipToDir(zipFile, unzippedDir); assertThat(FileUtils.readFileToString(new File(unzippedDir, "foo.txt"))).isEqualTo("foo"); } @Test public void zipDir_throws_ISE_if_directory_does_not_exist() throws Exception { File dir = temp.newFolder(); underTest.deleteIfExists(dir); assertThatThrownBy(() -> underTest.zipDir(dir, temp.newFile())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Can not zip directory " + dir) .hasRootCauseMessage("Directory " + dir + " does not exist"); } @Test public void zipDir_throws_ISE_if_directory_is_a_file() throws Exception { File file = temp.newFile(); assertThatThrownBy(() -> underTest.zipDir(file, temp.newFile())) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Can not zip directory " + file) .hasRootCauseMessage("File " + file + " exists but is not a directory"); } @Test public void createDir_creates_specified_directory() throws IOException { File dir = new File(temp.newFolder(), "someDir"); assertThat(dir).doesNotExist(); underTest.createDir(dir); assertThat(dir).exists(); } @Test public void createDir_creates_specified_directory_and_missing_parents() throws IOException { File dir1 = new File(temp.newFolder(), "dir1"); File dir2 = new File(dir1, "dir2"); File dir = new File(dir2, "someDir"); assertThat(dir1).doesNotExist(); assertThat(dir2).doesNotExist(); assertThat(dir).doesNotExist(); underTest.createDir(dir); assertThat(dir1).exists(); assertThat(dir2).exists(); assertThat(dir).exists(); } @Test public void createDir_throws_ISE_if_File_is_an_existing_file() throws IOException { File file = temp.newFile(); assertThatThrownBy(() -> underTest.createDir(file)) .isInstanceOf(IllegalStateException.class) .hasMessage(file.toPath() + " is not a directory"); } @Test public void createDir_throws_ISE_if_File_is_an_existing_link() throws IOException { File file = Files.createLink(new File(temp.newFolder(), "toto.lnk").toPath(), temp.newFile().toPath()).toFile(); assertThatThrownBy(() -> underTest.createDir(file)) .isInstanceOf(IllegalStateException.class) .hasMessage(file.toPath() + " is not a directory"); } }
7,600
31.482906
116
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/test/java/org/sonar/ce/task/util/Protobuf2Test.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.util; import com.sonarsource.governance.projectdump.protobuf.ProjectDump.Metadata; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.sonar.ce.task.util.Files2.FILES2; public class Protobuf2Test { private static final String PROJECT_KEY_1 = "foo"; private static final String PROJECT_KEY_2 = "bar"; @Rule public TemporaryFolder temp = new TemporaryFolder(); Protobuf2 underTest = Protobuf2.PROTOBUF2; @Test public void write_to_and_parse_from_file() throws Exception { File file = temp.newFile(); try (FileOutputStream output = FILES2.openOutputStream(file, false)) { underTest.writeTo(newMetadata(PROJECT_KEY_1), output); } try (FileInputStream input = FILES2.openInputStream(file)) { Metadata metadata = underTest.parseFrom(Metadata.parser(), input); assertThat(metadata.getProjectKey()).isEqualTo(PROJECT_KEY_1); } } @Test public void write_to_and_parse_delimited_from_file() throws Exception { File file = temp.newFile(); try (FileOutputStream output = FILES2.openOutputStream(file, false)) { underTest.writeDelimitedTo(newMetadata(PROJECT_KEY_1), output); underTest.writeDelimitedTo(newMetadata(PROJECT_KEY_2), output); } try (FileInputStream input = FILES2.openInputStream(file)) { assertThat(underTest.parseDelimitedFrom(Metadata.parser(), input).getProjectKey()).isEqualTo(PROJECT_KEY_1); assertThat(underTest.parseDelimitedFrom(Metadata.parser(), input).getProjectKey()).isEqualTo(PROJECT_KEY_2); assertThat(underTest.parseDelimitedFrom(Metadata.parser(), input)).isNull(); } } @Test public void writeTo_throws_ISE_on_error() throws Exception { try (FailureOutputStream output = new FailureOutputStream()) { assertThatThrownBy(() -> underTest.writeTo(newMetadata(PROJECT_KEY_1), output)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Can not write message"); } } @Test public void writeDelimitedTo_throws_ISE_on_error() throws Exception { try (FailureOutputStream output = new FailureOutputStream()) { assertThatThrownBy(() -> underTest.writeDelimitedTo(newMetadata(PROJECT_KEY_1), output)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Can not write message"); } } @Test public void parseFrom_throws_ISE_on_error() throws Exception { try (FailureInputStream input = new FailureInputStream()) { assertThatThrownBy(() -> underTest.parseFrom(Metadata.parser(), input)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not parse message"); } } @Test public void parseDelimitedFrom_throws_ISE_on_error() throws Exception { try (FailureInputStream input = new FailureInputStream()) { assertThatThrownBy(() -> underTest.parseDelimitedFrom(Metadata.parser(), input)) .isInstanceOf(IllegalStateException.class) .hasMessage("Can not parse message"); } } private static Metadata newMetadata(String projectKey) { return Metadata.newBuilder().setProjectKey(projectKey).build(); } private static class FailureOutputStream extends OutputStream { @Override public void write(int b) throws IOException { throw new IOException("Failure"); } } private static class FailureInputStream extends InputStream { @Override public int read() throws IOException { throw new IOException("failure"); } } }
4,675
35.818898
114
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderRule.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.analysis; import java.util.Date; import java.util.Map; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.junit.rules.ExternalResource; import org.sonar.ce.task.util.InitializedProperty; import org.sonar.db.component.BranchType; import org.sonar.server.project.Project; import org.sonar.server.qualityprofile.QualityProfile; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static org.apache.commons.lang.StringUtils.defaultIfBlank; public class AnalysisMetadataHolderRule extends ExternalResource implements MutableAnalysisMetadataHolder { private final InitializedProperty<String> uuid = new InitializedProperty<>(); private final InitializedProperty<Long> analysisDate = new InitializedProperty<>(); private final InitializedProperty<Analysis> baseAnalysis = new InitializedProperty<>(); private final InitializedProperty<Boolean> crossProjectDuplicationEnabled = new InitializedProperty<>(); private final InitializedProperty<Branch> branch = new InitializedProperty<>(); private final InitializedProperty<String> pullRequestId = new InitializedProperty<>(); private final InitializedProperty<Project> project = new InitializedProperty<>(); private final InitializedProperty<Integer> rootComponentRef = new InitializedProperty<>(); private final InitializedProperty<Map<String, QualityProfile>> qProfilesPerLanguage = new InitializedProperty<>(); private final InitializedProperty<Map<String, ScannerPlugin>> pluginsByKey = new InitializedProperty<>(); private final InitializedProperty<String> scmRevision = new InitializedProperty<>(); private final InitializedProperty<String> newCodeReferenceBranch = new InitializedProperty<>(); @Override public AnalysisMetadataHolderRule setUuid(String s) { checkNotNull(s, "UUID must not be null"); this.uuid.setProperty(s); return this; } @Override public String getUuid() { checkState(uuid.isInitialized(), "Analysis UUID has not been set"); return this.uuid.getProperty(); } public AnalysisMetadataHolderRule setAnalysisDate(Date date) { checkNotNull(date, "Date must not be null"); this.analysisDate.setProperty(date.getTime()); return this; } @Override public AnalysisMetadataHolderRule setAnalysisDate(long date) { this.analysisDate.setProperty(date); return this; } @Override public long getAnalysisDate() { checkState(analysisDate.isInitialized(), "Analysis date has not been set"); return this.analysisDate.getProperty(); } @Override public boolean hasAnalysisDateBeenSet() { return analysisDate.isInitialized(); } @Override public boolean isFirstAnalysis() { return getBaseAnalysis() == null; } @Override public AnalysisMetadataHolderRule setBaseAnalysis(@Nullable Analysis baseAnalysis) { this.baseAnalysis.setProperty(baseAnalysis); return this; } @Override @CheckForNull public Analysis getBaseAnalysis() { checkState(baseAnalysis.isInitialized(), "Base analysis has not been set"); return baseAnalysis.getProperty(); } @Override public AnalysisMetadataHolderRule setCrossProjectDuplicationEnabled(boolean isCrossProjectDuplicationEnabled) { this.crossProjectDuplicationEnabled.setProperty(isCrossProjectDuplicationEnabled); return this; } @Override public boolean isCrossProjectDuplicationEnabled() { checkState(crossProjectDuplicationEnabled.isInitialized(), "Cross project duplication flag has not been set"); return crossProjectDuplicationEnabled.getProperty(); } @Override public AnalysisMetadataHolderRule setBranch(Branch branch) { this.branch.setProperty(branch); return this; } @Override public Branch getBranch() { checkState(branch.isInitialized(), "Branch has not been set"); return branch.getProperty(); } @Override public MutableAnalysisMetadataHolder setPullRequestKey(String pullRequestKey) { this.pullRequestId.setProperty(pullRequestKey); return this; } @Override public String getPullRequestKey() { checkState(pullRequestId.isInitialized(), "Pull request id has not been set"); return pullRequestId.getProperty(); } @Override public AnalysisMetadataHolderRule setProject(Project p) { this.project.setProperty(p); return this; } @Override public Project getProject() { checkState(project.isInitialized(), "Project has not been set"); return project.getProperty(); } @Override public AnalysisMetadataHolderRule setRootComponentRef(int rootComponentRef) { this.rootComponentRef.setProperty(rootComponentRef); return this; } @Override public int getRootComponentRef() { checkState(rootComponentRef.isInitialized(), "Root component ref has not been set"); return rootComponentRef.getProperty(); } @Override public AnalysisMetadataHolderRule setQProfilesByLanguage(Map<String, QualityProfile> qProfilesPerLanguage) { this.qProfilesPerLanguage.setProperty(qProfilesPerLanguage); return this; } @Override public Map<String, QualityProfile> getQProfilesByLanguage() { checkState(qProfilesPerLanguage.isInitialized(), "QProfile per language has not been set"); return qProfilesPerLanguage.getProperty(); } @Override public AnalysisMetadataHolderRule setScannerPluginsByKey(Map<String, ScannerPlugin> plugins) { this.pluginsByKey.setProperty(plugins); return this; } @Override public Map<String, ScannerPlugin> getScannerPluginsByKey() { checkState(pluginsByKey.isInitialized(), "Plugins per key has not been set"); return pluginsByKey.getProperty(); } @Override public MutableAnalysisMetadataHolder setScmRevision(@Nullable String s) { checkState(!this.scmRevision.isInitialized(), "ScmRevisionId has already been set"); this.scmRevision.setProperty(defaultIfBlank(s, null)); return this; } @Override public MutableAnalysisMetadataHolder setNewCodeReferenceBranch(String newCodeReferenceBranch) { checkState(!this.newCodeReferenceBranch.isInitialized(), "ScmRevisionId has already been set"); this.newCodeReferenceBranch.setProperty(defaultIfBlank(newCodeReferenceBranch, null)); return this; } @Override public Optional<String> getScmRevision() { if (!scmRevision.isInitialized()) { return Optional.empty(); } return Optional.ofNullable(scmRevision.getProperty()); } @Override public Optional<String> getNewCodeReferenceBranch() { if (!newCodeReferenceBranch.isInitialized()) { return Optional.empty(); } return Optional.ofNullable(newCodeReferenceBranch.getProperty()); } @Override public boolean isBranch() { Branch property = this.branch.getProperty(); return property != null && property.getType() == BranchType.BRANCH; } @Override public boolean isPullRequest() { Branch property = this.branch.getProperty(); return property != null && property.getType() == BranchType.PULL_REQUEST; } }
7,981
33.405172
116
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/analysis/MutableAnalysisMetadataHolderRule.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.analysis; import java.util.Map; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.junit.rules.ExternalResource; import org.sonar.core.platform.PlatformEditionProvider; import org.sonar.server.project.Project; import org.sonar.server.qualityprofile.QualityProfile; import static org.mockito.Mockito.mock; public class MutableAnalysisMetadataHolderRule extends ExternalResource implements MutableAnalysisMetadataHolder { private final PlatformEditionProvider editionProvider = mock(PlatformEditionProvider.class); private AnalysisMetadataHolderImpl delegate = new AnalysisMetadataHolderImpl(editionProvider); @Override protected void after() { delegate = new AnalysisMetadataHolderImpl(editionProvider); } public MutableAnalysisMetadataHolderRule setUuid(String s) { delegate.setUuid(s); return this; } @Override public String getUuid() { return delegate.getUuid(); } public MutableAnalysisMetadataHolderRule setAnalysisDate(long date) { delegate.setAnalysisDate(date); return this; } @Override public long getAnalysisDate() { return delegate.getAnalysisDate(); } @Override public boolean hasAnalysisDateBeenSet() { return delegate.hasAnalysisDateBeenSet(); } @Override public boolean isFirstAnalysis() { return delegate.isFirstAnalysis(); } @Override public MutableAnalysisMetadataHolderRule setBaseAnalysis(@Nullable Analysis baseAnalysis) { delegate.setBaseAnalysis(baseAnalysis); return this; } @Override @CheckForNull public Analysis getBaseAnalysis() { return delegate.getBaseAnalysis(); } @Override public boolean isCrossProjectDuplicationEnabled() { return delegate.isCrossProjectDuplicationEnabled(); } @Override public MutableAnalysisMetadataHolderRule setCrossProjectDuplicationEnabled(boolean isCrossProjectDuplicationEnabled) { delegate.setCrossProjectDuplicationEnabled(isCrossProjectDuplicationEnabled); return this; } @Override public Branch getBranch() { return delegate.getBranch(); } @Override public MutableAnalysisMetadataHolderRule setBranch(Branch branch) { delegate.setBranch(branch); return this; } @Override public String getPullRequestKey() { return delegate.getPullRequestKey(); } @Override public MutableAnalysisMetadataHolder setPullRequestKey(String pullRequestKey) { delegate.setPullRequestKey(pullRequestKey); return this; } @Override public MutableAnalysisMetadataHolderRule setProject(@Nullable Project project) { delegate.setProject(project); return this; } @Override public Project getProject() { return delegate.getProject(); } @Override public MutableAnalysisMetadataHolderRule setRootComponentRef(int rootComponentRef) { delegate.setRootComponentRef(rootComponentRef); return this; } @Override public int getRootComponentRef() { return delegate.getRootComponentRef(); } @Override public MutableAnalysisMetadataHolder setQProfilesByLanguage(Map<String, QualityProfile> qprofilesByLanguage) { delegate.setQProfilesByLanguage(qprofilesByLanguage); return this; } @Override public Map<String, QualityProfile> getQProfilesByLanguage() { return delegate.getQProfilesByLanguage(); } @Override public MutableAnalysisMetadataHolder setScannerPluginsByKey(Map<String, ScannerPlugin> plugins) { delegate.setScannerPluginsByKey(plugins); return this; } @Override public Map<String, ScannerPlugin> getScannerPluginsByKey() { return delegate.getScannerPluginsByKey(); } @Override public MutableAnalysisMetadataHolder setScmRevision(String scmRevisionId) { delegate.setScmRevision(scmRevisionId); return this; } @Override public MutableAnalysisMetadataHolder setNewCodeReferenceBranch(String newCodeReferenceBranch) { delegate.setNewCodeReferenceBranch(newCodeReferenceBranch); return this; } @Override public Optional<String> getScmRevision() { return delegate.getScmRevision(); } @Override public Optional<String> getNewCodeReferenceBranch() { return delegate.getNewCodeReferenceBranch(); } @Override public boolean isBranch() { return delegate.isBranch(); } @Override public boolean isPullRequest() { return delegate.isPullRequest(); } }
5,278
26.494792
120
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/analysis/TestBranch.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.analysis; import javax.annotation.Nullable; import org.sonar.core.component.ComponentKeys; import org.sonar.db.component.BranchType; import static org.apache.commons.lang.StringUtils.isEmpty; import static org.apache.commons.lang.StringUtils.trimToNull; public class TestBranch implements Branch { private final String name; public TestBranch(String name) { this.name = name; } @Override public BranchType getType() { return BranchType.BRANCH; } @Override public boolean isMain() { return false; } @Override public String getReferenceBranchUuid() { throw new UnsupportedOperationException(); } @Override public String getName() { return name; } @Override public boolean supportsCrossProjectCpd() { return false; } @Override public String getPullRequestKey() { throw new UnsupportedOperationException(); } @Override public String getTargetBranchName() { throw new UnsupportedOperationException(); } @Override public String generateKey(String projectKey, @Nullable String fileOrDirPath) { if (isEmpty(fileOrDirPath)) { return projectKey; } return ComponentKeys.createEffectiveKey(projectKey, trimToNull(fileOrDirPath)); } }
2,123
25.886076
83
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/AbstractComponentProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import static com.google.common.base.Preconditions.checkState; abstract class AbstractComponentProvider implements ComponentProvider { private boolean initialized = false; @Override public void ensureInitialized() { if (!this.initialized) { ensureInitializedImpl(); this.initialized = true; } } protected abstract void ensureInitializedImpl(); @Override public void reset() { resetImpl(); this.initialized = false; } protected abstract void resetImpl(); @Override public Component getByRef(int componentRef) { checkState(this.initialized, "%s has not been initialized", getClass().getSimpleName()); return getByRefImpl(componentRef); } protected abstract Component getByRefImpl(int componentRef); }
1,665
30.433962
92
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/ComponentProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; public interface ComponentProvider { /** * does nothing if already initialized */ void ensureInitialized(); void reset(); /** * @throws IllegalStateException if no component is found for the specified ref * @throws IllegalStateException if provider has not been initialized */ Component getByRef(int componentRef); }
1,241
33.5
81
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/MutableTreeRootHolderRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; public class MutableTreeRootHolderRule extends TreeRootHolderRule implements MutableTreeRootHolder { @Override public MutableTreeRootHolderRule setRoots(Component root, Component reportRoot) { delegate.setRoots(root, reportRoot); return this; } }
1,158
38.965517
100
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/NoComponentProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; public enum NoComponentProvider implements ComponentProvider { INSTANCE; private static final String ERROR_MSG = "Can not add a measure by Component ref if MeasureRepositoryRule has not been created for some Component provider"; @Override public void ensureInitialized() { throw new IllegalStateException(ERROR_MSG); } @Override public void reset() { // do nothing } @Override public Component getByRef(int componentRef) { throw new IllegalStateException(ERROR_MSG); } }
1,406
32.5
157
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/ReportComponent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; /** * Implementation of {@link Component} to unit test report components. */ public class ReportComponent implements Component { private static final FileAttributes DEFAULT_FILE_ATTRIBUTES = new FileAttributes(false, null, 1, false, null); public static final Component DUMB_PROJECT = builder(Type.PROJECT, 1) .setKey("PROJECT_KEY") .setUuid("PROJECT_UUID") .setName("Project Name") .setProjectVersion("1.0-SNAPSHOT") .build(); private final Type type; private final Status status; private final String name; private final String shortName; @CheckForNull private final String description; private final String key; private final String uuid; private final ProjectAttributes projectAttributes; private final ReportAttributes reportAttributes; private final FileAttributes fileAttributes; private final List<Component> children; private ReportComponent(Builder builder) { this.type = builder.type; this.status = builder.status; this.key = builder.key; this.name = builder.name == null ? String.valueOf(builder.key) : builder.name; this.shortName = builder.shortName == null ? this.name : builder.shortName; this.description = builder.description; this.uuid = builder.uuid; this.projectAttributes = Optional.ofNullable(builder.projectVersion) .map(v -> new ProjectAttributes(v, builder.buildString, builder.scmRevisionId)) .orElse(null); this.reportAttributes = ReportAttributes.newBuilder(builder.ref) .build(); this.fileAttributes = builder.fileAttributes == null ? DEFAULT_FILE_ATTRIBUTES : builder.fileAttributes; this.children = ImmutableList.copyOf(builder.children); } @Override public Type getType() { return type; } @Override public Status getStatus() { return status; } @Override public String getUuid() { if (uuid == null) { throw new UnsupportedOperationException(String.format("Component uuid of ref '%d' has not be fed yet", this.reportAttributes.getRef())); } return uuid; } @Override public String getKey() { if (key == null) { throw new UnsupportedOperationException(String.format("Component key of ref '%d' has not be fed yet", this.reportAttributes.getRef())); } return key; } @Override public String getName() { return this.name; } @Override public String getShortName() { return this.shortName; } @Override @CheckForNull public String getDescription() { return this.description; } @Override public List<Component> getChildren() { return children; } @Override public ProjectAttributes getProjectAttributes() { checkState(this.type == Type.PROJECT); return this.projectAttributes; } @Override public ReportAttributes getReportAttributes() { return this.reportAttributes; } @Override public FileAttributes getFileAttributes() { checkState(this.type == Type.FILE, "Only component of type FILE can have a FileAttributes object"); return this.fileAttributes; } @Override public ProjectViewAttributes getProjectViewAttributes() { throw new IllegalStateException("Only component of type PROJECT_VIEW can have a ProjectViewAttributes object"); } @Override public SubViewAttributes getSubViewAttributes() { throw new IllegalStateException("Only component of type SUBVIEW have a SubViewAttributes object"); } @Override public ViewAttributes getViewAttributes() { throw new IllegalStateException("Only component of type VIEW have a ViewAttributes object"); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ReportComponent that = (ReportComponent) o; return uuid.equals(that.uuid); } @Override public int hashCode() { return uuid.hashCode(); } @Override public String toString() { return "ReportComponent{" + "ref=" + this.reportAttributes.getRef() + ", key='" + key + '\'' + ", type=" + type + '}'; } public static Builder builder(Type type, int ref, String key) { return new Builder(type, ref).setKey(key).setUuid("uuid_" + ref).setName("name_" + ref); } public static Builder builder(Type type, int ref) { return builder(type, ref, "key_" + ref); } public static final class Builder { private final Type type; private final int ref; private Status status; private String uuid; private String key; private String name; private String shortName; private String projectVersion; private String buildString; private String scmRevisionId; private String description; private FileAttributes fileAttributes; private final List<Component> children = new ArrayList<>(); private Builder(Type type, int ref) { checkArgument(type.isReportType(), "Component type must be a report type"); this.type = type; this.ref = ref; if (type == Type.PROJECT) { this.projectVersion = "toBeDefined"; } } public Builder setStatus(Status s) { this.status = requireNonNull(s); return this; } public Builder setUuid(String s) { this.uuid = requireNonNull(s); return this; } public Builder setName(@Nullable String s) { this.name = s; return this; } public Builder setShortName(@Nullable String s) { this.shortName = s; return this; } public Builder setKey(String s) { this.key = requireNonNull(s); return this; } public Builder setProjectVersion(@Nullable String s) { checkProjectVersion(s); this.projectVersion = s; return this; } public Builder setBuildString(@Nullable String buildString) { checkBuildString(buildString); this.buildString = buildString; return this; } public Builder setScmRevisionId(@Nullable String scmRevisionId) { this.scmRevisionId = scmRevisionId; return this; } public Builder setFileAttributes(FileAttributes fileAttributes) { checkState(type == Type.FILE, "Only Component of type File can have File attributes"); this.fileAttributes = fileAttributes; return this; } public Builder setDescription(@Nullable String description) { this.description = description; return this; } public Builder addChildren(Component... c) { for (Component component : c) { checkArgument(component.getType().isReportType()); } this.children.addAll(asList(c)); return this; } public ReportComponent build() { checkProjectVersion(this.projectVersion); checkBuildString(this.buildString); return new ReportComponent(this); } private void checkProjectVersion(@Nullable String s) { checkArgument(type != Type.PROJECT ^ s != null, "Project version must and can only be set on Project"); } private void checkBuildString(@Nullable String s) { checkArgument(type == Type.PROJECT || s == null, "BuildString can only be set on Project"); } } }
8,481
28.147766
142
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/TreeComponentProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import java.util.HashMap; import java.util.Map; import static com.google.common.base.Preconditions.checkState; public final class TreeComponentProvider extends AbstractComponentProvider { private final Component root; private final Map<String, Component> componentsByRef = new HashMap<>(); public TreeComponentProvider(Component root) { this.root = root; ensureInitialized(); } private static String getRef(Component component) { return component.getType().isReportType() ? String.valueOf(component.getReportAttributes().getRef()) : component.getKey(); } @Override protected void ensureInitializedImpl() { new DepthTraversalTypeAwareCrawler( new TypeAwareVisitorAdapter(CrawlerDepthLimit.LEAVES, ComponentVisitor.Order.PRE_ORDER) { @Override public void visitAny(Component component) { String ref = getRef(component); checkState(!componentsByRef.containsKey(ref), "Tree contains more than one component with ref " + ref); componentsByRef.put(ref, component); } }).visit(root); } @Override protected void resetImpl() { // we can not reset } @Override protected Component getByRefImpl(int componentRef) { Component component = componentsByRef.get(String.valueOf(componentRef)); checkState(component != null, "Can not find Component for ref " + componentRef); return component; } }
2,311
34.569231
126
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderComponentProvider.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; public final class TreeRootHolderComponentProvider extends AbstractComponentProvider { private final TreeRootHolder treeRootHolder; private TreeComponentProvider delegate; public TreeRootHolderComponentProvider(TreeRootHolder treeRootHolder) { this.treeRootHolder = treeRootHolder; } @Override protected void ensureInitializedImpl() { if (this.delegate == null) { this.delegate = new TreeComponentProvider(treeRootHolder.getRoot()); this.delegate.ensureInitialized(); } } @Override protected void resetImpl() { this.delegate = null; } @Override protected Component getByRefImpl(int componentRef) { return delegate.getByRef(componentRef); } }
1,601
32.375
86
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/TreeRootHolderRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import com.google.common.collect.ImmutableMap; import java.util.Map; import java.util.Optional; import javax.annotation.CheckForNull; import org.junit.rules.ExternalResource; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.sonar.ce.task.projectanalysis.component.ComponentVisitor.Order.POST_ORDER; public class TreeRootHolderRule extends ExternalResource implements TreeRootHolder { protected TreeRootHolderImpl delegate = new TreeRootHolderImpl(); @CheckForNull private Map<String, Component> componentsByKey; @Override protected void after() { this.delegate = null; } public TreeRootHolderRule setRoot(Component root) { return setRoots(root, root); } public TreeRootHolderRule setRoots(Component root, Component reportRoot) { delegate = new TreeRootHolderImpl(); delegate.setRoots(root, reportRoot); return this; } public Component getComponentByKey(String key) { checkKeyArgument(key); ensureComponentByKeyIsPopulated(); Component component = componentsByKey.get(key); checkArgument(component != null, "Component with key '%s' can't be found", key); return component; } private static void checkKeyArgument(String key) { requireNonNull(key, "key can not be null"); } private void ensureComponentByKeyIsPopulated() { if (componentsByKey != null) { return; } final ImmutableMap.Builder<String, Component> builder = ImmutableMap.builder(); new DepthTraversalTypeAwareCrawler( new TypeAwareVisitorAdapter(CrawlerDepthLimit.LEAVES, POST_ORDER) { @Override public void visitAny(Component component) { builder.put(component.getKey(), component); } }).visit(getRoot()); this.componentsByKey = builder.build(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public Component getRoot() { return delegate.getRoot(); } @Override public Component getReportTreeRoot() { return delegate.getReportTreeRoot(); } @Override public Component getComponentByRef(int ref) { return delegate.getComponentByRef(ref); } @Override public Component getComponentByUuid(String uuid) { return delegate.getComponentByUuid(uuid); } @Override public Optional<Component> getOptionalComponentByRef(int ref) { return delegate.getOptionalComponentByRef(ref); } @Override public Component getReportTreeComponentByRef(int ref) { return delegate.getReportTreeComponentByRef(ref); } @Override public int getSize() { return delegate.getSize(); } }
3,564
28.46281
92
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/component/ViewsComponent.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.component; import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.List; import java.util.Objects; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Arrays.asList; import static java.util.Objects.requireNonNull; /** * Implementation of {@link Component} to unit test views components. */ public class ViewsComponent implements Component { private final Type type; private final String key; private final String uuid; private final String name; private final String description; private final List<Component> children; private final ProjectViewAttributes projectViewAttributes; private final SubViewAttributes subViewAttributes; private final ViewAttributes viewAttributes; private ViewsComponent(Type type, String key, @Nullable String uuid, @Nullable String name, @Nullable String description, List<Component> children, @Nullable ProjectViewAttributes projectViewAttributes, @Nullable SubViewAttributes subViewAttributes, @Nullable ViewAttributes viewAttributes) { checkArgument(type.isViewsType(), "Component type must be a Views type"); this.type = type; this.key = requireNonNull(key); this.uuid = uuid; this.name = name; this.description = description; this.children = ImmutableList.copyOf(children); this.projectViewAttributes = projectViewAttributes; this.subViewAttributes = subViewAttributes; this.viewAttributes = viewAttributes; } public static Builder builder(Type type, String key) { return new Builder(type, key); } public static Builder builder(Type type, int key) { return new Builder(type, String.valueOf(key)); } public static final class Builder { private final Type type; private String key; private String uuid; private String name; private String description; private List<Component> children = new ArrayList<>(); private ProjectViewAttributes projectViewAttributes; private SubViewAttributes subViewAttributes; private ViewAttributes viewAttributes; private Builder(Type type, String key) { this.type = type; this.key = key; } public Builder setUuid(@Nullable String uuid) { this.uuid = uuid; return this; } public Builder setKey(String key) { this.key = key; return this; } public Builder setName(@Nullable String name) { this.name = name; return this; } public Builder setDescription(String description) { this.description = description; return this; } public Builder setChildren(List<Component> children) { this.children = children; return this; } public Builder setProjectViewAttributes(@Nullable ProjectViewAttributes projectViewAttributes) { this.projectViewAttributes = projectViewAttributes; return this; } public Builder setSubViewAttributes(@Nullable SubViewAttributes subViewAttributes) { this.subViewAttributes = subViewAttributes; return this; } public Builder setViewAttributes(@Nullable ViewAttributes viewAttributes) { this.viewAttributes = viewAttributes; return this; } public Builder addChildren(Component... c) { for (Component viewsComponent : c) { checkArgument(viewsComponent.getType().isViewsType()); } this.children.addAll(asList(c)); return this; } public ViewsComponent build() { return new ViewsComponent(type, key, uuid, name, description, children, projectViewAttributes, subViewAttributes, viewAttributes); } } @Override public Type getType() { return type; } @Override public Status getStatus() { return Status.UNAVAILABLE; } @Override public String getUuid() { return uuid; } /** * Views has no branch feature, the public key is the same as the key */ @Override public String getKey() { return this.key; } @Override public String getName() { checkState(this.name != null, "No name has been set"); return this.name; } @Override public String getShortName() { return getName(); } @Override @CheckForNull public String getDescription() { return this.description; } @Override public List<Component> getChildren() { return children; } @Override public ProjectAttributes getProjectAttributes() { throw new IllegalStateException("A component of type " + type + " does not have project attributes"); } @Override public ReportAttributes getReportAttributes() { throw new IllegalStateException("A component of type " + type + " does not have report attributes"); } @Override public FileAttributes getFileAttributes() { throw new IllegalStateException("A component of type " + type + " does not have file attributes"); } @Override public ProjectViewAttributes getProjectViewAttributes() { checkState(this.type != Type.PROJECT_VIEW || this.projectViewAttributes != null, "A ProjectViewAttribute object should have been set"); return this.projectViewAttributes; } @Override public SubViewAttributes getSubViewAttributes() { checkState(this.type != Type.SUBVIEW || this.subViewAttributes != null, "A SubViewAttributes object should have been set"); return this.subViewAttributes; } @Override public ViewAttributes getViewAttributes() { checkState(this.type != Type.VIEW || this.viewAttributes != null, "A ViewAttributes object should have been set"); return viewAttributes; } @Override public String toString() { return "ViewsComponent{" + "type=" + type + ", key='" + key + '\'' + ", uuid='" + uuid + '\'' + ", name='" + name + '\'' + ", children=" + children + ", projectViewAttributes=" + projectViewAttributes + ", subViewAttributes=" + subViewAttributes + ", viewAttributes=" + viewAttributes + '}'; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ViewsComponent that = (ViewsComponent) o; return key.equals(that.key); } @Override public int hashCode() { return Objects.hash(key); } }
7,311
28.365462
139
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/measure/MeasureAssert.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.Objects; import java.util.Optional; import javax.annotation.Nullable; import org.assertj.core.api.AbstractAssert; import org.assertj.core.data.Offset; import static java.lang.Math.abs; public class MeasureAssert extends AbstractAssert<MeasureAssert, Measure> { protected MeasureAssert(@Nullable Measure actual) { super(actual, MeasureAssert.class); } public static MeasureAssert assertThat(Measure actual) { return new MeasureAssert(actual); } public static MeasureAssert assertThat(@Nullable Optional<Measure> actual) { return new MeasureAssert(actual == null ? null : actual.orElse(null)); } public MeasureAssert hasValue(int expected) { isNotNull(); if (actual.getValueType() != Measure.ValueType.INT) { failWithMessage( "Expected Measure to have an int value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.INT, actual.getValueType()); } if (actual.getIntValue() != expected) { failWithMessage("Expected value of Measure to be <%s> but was <%s>", expected, actual.getIntValue()); } return this; } public MeasureAssert hasValue(long expected) { isNotNull(); if (actual.getValueType() != Measure.ValueType.LONG) { failWithMessage( "Expected Measure to have a long value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.LONG, actual.getValueType()); } if (actual.getLongValue() != expected) { failWithMessage("Expected value of Measure to be <%s> but was <%s>", expected, actual.getLongValue()); } return this; } public MeasureAssert hasValue(double expected) { isNotNull(); if (actual.getValueType() != Measure.ValueType.DOUBLE) { failWithMessage( "Expected Measure to have a double value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.DOUBLE, actual.getValueType()); } if (actual.getDoubleValue() != expected) { failWithMessage("Expected value of Measure to be <%s> but was <%s>", expected, actual.getDoubleValue()); } return this; } public MeasureAssert hasValue(double expected, Offset<Double> offset) { isNotNull(); if (actual.getValueType() != Measure.ValueType.DOUBLE) { failWithMessage( "Expected Measure to have a double value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.DOUBLE, actual.getValueType()); } double value = actual.getDoubleValue(); if (abs(expected - value) > offset.value) { failWithMessage( "Expected value of Measure to be close to <%s> by less than <%s> but was <%s>", expected, offset.value, value); } return this; } public MeasureAssert hasValue(boolean expected) { isNotNull(); if (actual.getValueType() != Measure.ValueType.BOOLEAN) { failWithMessage( "Expected Measure to have a boolean value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.DOUBLE, actual.getValueType()); } if (actual.getBooleanValue() != expected) { failWithMessage("Expected value of Measure to be <%s> but was <%s>", expected, actual.getBooleanValue()); } return this; } public MeasureAssert hasValue(String expected) { isNotNull(); if (actual.getValueType() != Measure.ValueType.STRING) { failWithMessage( "Expected Measure to have a String value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.DOUBLE, actual.getValueType()); } if (!Objects.equals(actual.getStringValue(), expected)) { failWithMessage("Expected value of Measure to be <%s> but was <%s>", expected, actual.getStringValue()); } return this; } public MeasureAssert hasValue(Measure.Level expected) { isNotNull(); if (actual.getValueType() != Measure.ValueType.LEVEL) { failWithMessage( "Expected Measure to have a Level value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.DOUBLE, actual.getValueType()); } if (actual.getLevelValue() != expected) { failWithMessage("Expected value of Measure to be <%s> but was <%s>", expected, actual.getLevelValue()); } return this; } public MeasureAssert hasNoValue() { isNotNull(); if (actual.getValueType() != Measure.ValueType.NO_VALUE) { failWithMessage( "Expected Measure to have no value and therefore its ValueType to be <%s> but was <%s>", Measure.ValueType.DOUBLE, actual.getValueType()); } return this; } public MeasureAssert hasData(String expected) { isNotNull(); if (!Objects.equals(actual.getData(), expected)) { failWithMessage("Expected data of Measure to be <%s> but was <%s>", expected, actual.getData()); } return this; } public MeasureAssert hasNoData() { isNotNull(); if (actual.getData() == null) { failWithMessage("Expected Measure to have no data but was <%s>", actual.getData()); } return this; } public MeasureAssert hasQualityGateLevel(Measure.Level expected) { isNotNull(); hasQualityGateStatus(); if (actual.getQualityGateStatus().getStatus() != expected) { failWithMessage("Expected Level of QualityGateStatus of Measure to be <%s> but was <%s>", expected, actual.getQualityGateStatus().getStatus()); } return this; } public MeasureAssert hasQualityGateText(String expected) { isNotNull(); hasQualityGateStatus(); if (!Objects.equals(actual.getQualityGateStatus().getText(), expected)) { failWithMessage("Expected text of QualityGateStatus of Measure to be \n<%s>\n but was \n<%s>", expected, actual.getQualityGateStatus().getText()); } return this; } private void hasQualityGateStatus() { if (!actual.hasQualityGateStatus()) { failWithMessage("Expected Measure to have a QualityGateStatus but it did not"); } } public void isAbsent() { if (actual != null) { failWithMessage("Expected measure to be absent"); } } }
7,011
30.164444
152
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepoEntry.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.Map; import java.util.Objects; import java.util.function.Function; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.sonar.ce.task.projectanalysis.component.Component; /** * This class represents a metric key and an associated measure. * It can be used to easily compare the content of the SetMultimap returned by {@link MeasureRepository#getRawMeasures(Component)} * or {@link MeasureRepositoryRule#getAddedRawMeasures(int)}. * <p> * This class is also highly useful to accurately make sure of the SetMultimap content since this * object implements a deep equals of Measure objects (see {@link #deepEquals(Measure, Measure)}), when * {@link Measure#equals(Object)} only care about the ruleId and characteristicId. * </p> * <p> * In order to explore the content of the Map, use {@link #toEntries(Map)} to convert it * to an Iterable of {@link MeasureRepoEntry} and then take benefit of AssertJ API, eg.: * <pre> * assertThat(MeasureRepoEntry.toEntries(measureRepository.getAddedRawMeasures(componentRef))).containsOnly( * MeasureRepoEntry.entryOf(DEVELOPMENT_COST_KEY, newMeasureBuilder().create(Long.toString(expectedDevCost))), * MeasureRepoEntry.entryOf(SQALE_DEBT_RATIO_KEY, newMeasureBuilder().create(expectedDebtRatio)) * ); * </pre> * </p> */ public final class MeasureRepoEntry { private final String metricKey; private final Measure measure; public MeasureRepoEntry(String metricKey, Measure measure) { this.metricKey = metricKey; this.measure = measure; } public static Function<Map.Entry<String, Measure>, MeasureRepoEntry> toMeasureRepoEntry() { return EntryToMeasureRepoEntry.INSTANCE; } public static Iterable<MeasureRepoEntry> toEntries(Map<String, Measure> data) { return data.entrySet().stream().map(toMeasureRepoEntry()).toList(); } public static MeasureRepoEntry entryOf(String metricKey, Measure measure) { return new MeasureRepoEntry(metricKey, measure); } public static boolean deepEquals(Measure measure, Measure measure1) { return measure.getValueType() == measure1.getValueType() && equalsByValue(measure, measure1) && equalsByQualityGateStatus(measure, measure1) && Objects.equals(measure.getData(), measure1.getData()); } private static boolean equalsByValue(Measure measure, Measure measure1) { switch (measure.getValueType()) { case BOOLEAN: return measure.getBooleanValue() == measure1.getBooleanValue(); case INT: return measure.getIntValue() == measure1.getIntValue(); case LONG: return measure.getLongValue() == measure1.getLongValue(); case DOUBLE: return Double.compare(measure.getDoubleValue(), measure1.getDoubleValue()) == 0; case STRING: return measure.getStringValue().equals(measure1.getStringValue()); case LEVEL: return measure.getLevelValue() == measure1.getLevelValue(); case NO_VALUE: return true; default: throw new IllegalArgumentException("Unsupported ValueType " + measure.getValueType()); } } private static boolean equalsByQualityGateStatus(Measure measure, Measure measure1) { if (measure.hasQualityGateStatus() != measure1.hasQualityGateStatus()) { return false; } if (!measure.hasQualityGateStatus()) { return true; } return Objects.equals(measure.getQualityGateStatus(), measure1.getQualityGateStatus()); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } MeasureRepoEntry that = (MeasureRepoEntry) o; return Objects.equals(metricKey, that.metricKey) && deepEquals(measure, that.measure); } @Override public int hashCode() { return Objects.hash(metricKey, measure); } @Override public String toString() { return "<" + metricKey + ", " + measure + '>'; } private enum EntryToMeasureRepoEntry implements Function<Map.Entry<String, Measure>, MeasureRepoEntry> { INSTANCE; @Nullable @Override public MeasureRepoEntry apply(@Nonnull Map.Entry<String, Measure> input) { return new MeasureRepoEntry(input.getKey(), input.getValue()); } } }
5,189
35.808511
130
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/measure/MeasureRepositoryRule.java
/* * SonarQube * Copyright (C) 2009-2023 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.measure; import com.google.common.base.Predicate; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; import javax.annotation.CheckForNull; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.junit.rules.ExternalResource; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.ce.task.projectanalysis.component.ComponentProvider; import org.sonar.ce.task.projectanalysis.component.NoComponentProvider; import org.sonar.ce.task.projectanalysis.component.TreeComponentProvider; import org.sonar.ce.task.projectanalysis.component.TreeRootHolder; import org.sonar.ce.task.projectanalysis.component.TreeRootHolderComponentProvider; import org.sonar.ce.task.projectanalysis.metric.Metric; import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.FluentIterable.from; import static com.google.common.collect.Maps.filterKeys; import static java.lang.String.format; import static java.util.Objects.requireNonNull; /** * An implementation of MeasureRepository as a JUnit rule which provides add methods for raw measures and extra add * methods that takes component ref and metric keys thanks to the integration with various Component and Metric * providers. */ public class MeasureRepositoryRule extends ExternalResource implements MeasureRepository { private final ComponentProvider componentProvider; @CheckForNull private final MetricRepositoryRule metricRepositoryRule; private final Map<InternalKey, Measure> baseMeasures = new HashMap<>(); private final Map<InternalKey, Measure> rawMeasures = new HashMap<>(); private final Map<InternalKey, Measure> initialRawMeasures = new HashMap<>(); private final Predicate<Map.Entry<InternalKey, Measure>> isAddedMeasure = input -> !initialRawMeasures.containsKey(input.getKey()) || !MeasureRepoEntry.deepEquals(input.getValue(), initialRawMeasures.get(input.getKey())); private MeasureRepositoryRule(ComponentProvider componentProvider, @Nullable MetricRepositoryRule metricRepositoryRule) { this.componentProvider = componentProvider; this.metricRepositoryRule = metricRepositoryRule; } @Override protected void after() { componentProvider.reset(); baseMeasures.clear(); rawMeasures.clear(); } public static MeasureRepositoryRule create() { return new MeasureRepositoryRule(NoComponentProvider.INSTANCE, null); } public static MeasureRepositoryRule create(TreeRootHolder treeRootHolder, MetricRepositoryRule metricRepositoryRule) { return new MeasureRepositoryRule(new TreeRootHolderComponentProvider(treeRootHolder), requireNonNull(metricRepositoryRule)); } public static MeasureRepositoryRule create(Component treeRoot, MetricRepositoryRule metricRepositoryRule) { return new MeasureRepositoryRule(new TreeComponentProvider(treeRoot), requireNonNull(metricRepositoryRule)); } public MeasureRepositoryRule addBaseMeasure(int componentRef, String metricKey, Measure measure) { checkAndInitProvidersState(); InternalKey internalKey = new InternalKey(componentProvider.getByRef(componentRef), metricRepositoryRule.getByKey(metricKey)); checkState(!baseMeasures.containsKey(internalKey), format("Can not add a BaseMeasure twice for a Component (ref=%s) and Metric (key=%s)", componentRef, metricKey)); baseMeasures.put(internalKey, measure); return this; } public Map<String, Measure> getRawMeasures(int componentRef) { return getRawMeasures(componentProvider.getByRef(componentRef)); } /** * Return measures that were added by the step (using {@link #add(Component, Metric, Measure)}). * It does not contain the one added in the test by {@link #addRawMeasure(int, String, Measure)} */ public Map<String, Measure> getAddedRawMeasures(int componentRef) { checkAndInitProvidersState(); return getAddedRawMeasures(componentProvider.getByRef(componentRef)); } /** * Return a measure that were added by the step (using {@link #add(Component, Metric, Measure)}). * It does not contain the one added in the test by {@link #addRawMeasure(int, String, Measure)} */ public Optional<Measure> getAddedRawMeasure(Component component, String metricKey) { return getAddedRawMeasure(component.getReportAttributes().getRef(), metricKey); } /** * Return a measure that were added by the step (using {@link #add(Component, Metric, Measure)}). * It does not contain the one added in the test by {@link #addRawMeasure(int, String, Measure)} */ public Optional<Measure> getAddedRawMeasure(int componentRef, String metricKey) { checkAndInitProvidersState(); Measure measure = getAddedRawMeasures(componentProvider.getByRef(componentRef)).get(metricKey); return Optional.ofNullable(measure); } /** * Return measures that were added by the step (using {@link #add(Component, Metric, Measure)}). * It does not contain the one added in the test by {@link #addRawMeasure(int, String, Measure)} */ public Map<String, Measure> getAddedRawMeasures(Component component) { checkAndInitProvidersState(); Map<String, Measure> builder = new HashMap<>(); for (Map.Entry<InternalKey, Measure> entry : from(filterKeys(rawMeasures, hasComponentRef(component)).entrySet()).filter(isAddedMeasure)) { builder.put(entry.getKey().getMetricKey(), entry.getValue()); } return builder; } public MeasureRepositoryRule addRawMeasure(int componentRef, String metricKey, Measure measure) { checkAndInitProvidersState(); InternalKey internalKey = new InternalKey(componentProvider.getByRef(componentRef), metricRepositoryRule.getByKey(metricKey)); checkState(!rawMeasures.containsKey(internalKey), format( "A measure can only be set once for Component (ref=%s), Metric (key=%s)", componentRef, metricKey)); rawMeasures.put(internalKey, measure); initialRawMeasures.put(internalKey, measure); return this; } @Override public Optional<Measure> getBaseMeasure(Component component, Metric metric) { return Optional.ofNullable(baseMeasures.get(new InternalKey(component, metric))); } @Override public Optional<Measure> getRawMeasure(Component component, Metric metric) { return Optional.ofNullable(rawMeasures.get(new InternalKey(component, metric))); } @Override public Map<String, Measure> getRawMeasures(Component component) { return filterKeys(rawMeasures, hasComponentRef(component)).entrySet().stream() .collect(Collectors.toMap(k -> k.getKey().getMetricKey(), Map.Entry::getValue)); } private HasComponentRefPredicate hasComponentRef(Component component) { return new HasComponentRefPredicate(component); } @Override public void add(Component component, Metric metric, Measure measure) { String ref = getRef(component); InternalKey internalKey = new InternalKey(ref, metric.getKey()); if (rawMeasures.containsKey(internalKey)) { throw new UnsupportedOperationException(format( "A measure can only be set once for Component (ref=%s), Metric (key=%s)", ref, metric.getKey())); } rawMeasures.put(internalKey, measure); } @Override public void update(Component component, Metric metric, Measure measure) { String componentRef = getRef(component); InternalKey internalKey = new InternalKey(componentRef, metric.getKey()); if (!rawMeasures.containsKey(internalKey)) { throw new UnsupportedOperationException(format( "A measure can only be updated if it has been added first for Component (ref=%s), Metric (key=%s)", componentRef, metric.getKey())); } rawMeasures.put(internalKey, measure); } private void checkAndInitProvidersState() { checkState(metricRepositoryRule != null, "Can not add a measure by metric key if MeasureRepositoryRule has not been created for a MetricRepository"); componentProvider.ensureInitialized(); } public boolean isEmpty() { return rawMeasures.isEmpty(); } private static final class InternalKey { private final String componentRef; private final String metricKey; public InternalKey(Component component, Metric metric) { this(getRef(component), metric.getKey()); } private InternalKey(String componentRef, String metricKey) { this.componentRef = componentRef; this.metricKey = metricKey; } public String getComponentRef() { return componentRef; } public String getMetricKey() { return metricKey; } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InternalKey that = (InternalKey) o; return Objects.equals(componentRef, that.componentRef) && Objects.equals(metricKey, that.metricKey); } @Override public int hashCode() { return Objects.hash(componentRef, metricKey); } @Override public String toString() { return "InternalKey{" + "component=" + componentRef + ", metric='" + metricKey + '\'' + '}'; } } private static class HasComponentRefPredicate implements Predicate<InternalKey> { private final String componentRef; public HasComponentRefPredicate(Component component) { this.componentRef = getRef(component); } @Override public boolean apply(@Nonnull InternalKey input) { return input.getComponentRef().equals(this.componentRef); } } private static String getRef(Component component) { return component.getType().isReportType() ? String.valueOf(component.getReportAttributes().getRef()) : component.getKey(); } }
10,778
37.913357
168
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/metric/MetricRepositoryRule.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 java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import org.junit.rules.ExternalResource; import static com.google.common.base.Preconditions.checkState; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public class MetricRepositoryRule extends ExternalResource implements MetricRepository { private final Map<String, Metric> metricsByKey = new HashMap<>(); private final Map<String, Metric> metricsByUuid = new HashMap<>(); /** * Convenience method to add a {@link Metric} to the repository created from a {@link org.sonar.api.measures.Metric}, * most of the time it will be a constant of the {@link org.sonar.api.measures.CoreMetrics} class. * <p> * For the id of the created metric, this method uses the hashCode of the metric's key. If you want to specify * the id of the create {@link Metric}, use {@link #add(String, org.sonar.api.measures.Metric)} * </p> */ public MetricRepositoryRule add(org.sonar.api.measures.Metric<?> coreMetric) { add(from(coreMetric)); return this; } /** * Convenience method to add a {@link Metric} to the repository created from a {@link org.sonar.api.measures.Metric} * and with the specified id, most of the time it will be a constant of the {@link org.sonar.api.measures.CoreMetrics} * class. */ public MetricRepositoryRule add(String uuid, org.sonar.api.measures.Metric<?> coreMetric) { add(from(uuid, coreMetric)); return this; } private static Metric from(org.sonar.api.measures.Metric<?> coreMetric) { return from(Long.toString(coreMetric.getKey().hashCode()), coreMetric); } private static Metric from(String uuid, org.sonar.api.measures.Metric<?> coreMetric) { return new MetricImpl( uuid, coreMetric.getKey(), coreMetric.getName(), convert(coreMetric.getType()), coreMetric.getDecimalScale(), coreMetric.getBestValue(), coreMetric.isOptimizedBestValue(), coreMetric.getDeleteHistoricalData()); } private static Metric.MetricType convert(org.sonar.api.measures.Metric.ValueType coreMetricType) { return Metric.MetricType.valueOf(coreMetricType.name()); } public MetricRepositoryRule add(Metric metric) { requireNonNull(metric.getKey(), "key can not be null"); checkState(!metricsByKey.containsKey(metric.getKey()), format("Repository already contains a metric for key %s", metric.getKey())); checkState(!metricsByUuid.containsKey(metric.getUuid()), format("Repository already contains a metric for id %s", metric.getUuid())); metricsByKey.put(metric.getKey(), metric); metricsByUuid.put(metric.getUuid(), metric); return this; } @Override protected void after() { this.metricsByUuid.clear(); this.metricsByUuid.clear(); } @Override public Metric getByKey(String key) { Metric res = metricsByKey.get(key); checkState(res != null, format("No Metric can be found for key %s", key)); return res; } @Override public Metric getByUuid(String uuid) { Metric res = metricsByUuid.get(uuid); checkState(res != null, format("No Metric can be found for uuid %s", uuid)); return res; } @Override public Optional<Metric> getOptionalByUuid(String uuid) { return Optional.of(metricsByUuid.get(uuid)); } @Override public Iterable<Metric> getAll() { return metricsByKey.values(); } @Override public List<Metric> getMetricsByType(Metric.MetricType type) { return metricsByKey.values().stream().filter(m -> m.getType() == type).toList(); } }
4,481
35.737705
137
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/step/BaseStepTest.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.step.ComputationStep; import static org.assertj.core.api.Assertions.assertThat; /** * Temporary solution to test metadata. Should be replaced by a medium test of * all computation stack */ public abstract class BaseStepTest { protected abstract ComputationStep step(); @Test public void test_metadata() { assertThat(step().toString()).isNotEmpty(); assertThat(step().getDescription()).isNotEmpty(); } }
1,366
32.341463
78
java
sonarqube
sonarqube-master/server/sonar-ce-task-projectanalysis/src/testFixtures/java/org/sonar/ce/task/projectanalysis/task/ListTaskContainer.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.task; import com.google.common.collect.Iterables; import java.util.ArrayList; import java.util.List; import java.util.Optional; import org.sonar.ce.task.container.TaskContainer; import org.sonar.core.platform.Module; import org.sonar.core.platform.SpringComponentContainer; public class ListTaskContainer implements TaskContainer { private final List<Object> addedComponents = new ArrayList<>(); @Override public SpringComponentContainer add(Object... objects) { for (Object o : objects) { if (o instanceof Module) { ((Module) o).configure(this); } else if (o instanceof Iterable) { add(Iterables.toArray((Iterable<?>) o, Object.class)); } else { this.addedComponents.add(o); } } // not used anyway return null; } public List<Object> getAddedComponents() { return addedComponents; } @Override public SpringComponentContainer getParent() { throw new UnsupportedOperationException("getParent is not implemented"); } @Override public void bootup() { throw new UnsupportedOperationException("bootup is not implemented"); } @Override public void close() { throw new UnsupportedOperationException("close is not implemented"); } @Override public <T> T getComponentByType(Class<T> type) { throw new UnsupportedOperationException("getParent is not implemented"); } @Override public <T> Optional<T> getOptionalComponentByType(Class<T> type) { throw new UnsupportedOperationException("getParent is not implemented"); } @Override public <T> List<T> getComponentsByType(final Class<T> type) { throw new UnsupportedOperationException("getParent is not implemented"); } }
2,590
30.987654
78
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/it/java/org/sonar/ce/task/log/CeTaskMessagesImplIT.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.log; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Random; import java.util.stream.IntStream; import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.sonar.api.utils.System2; import org.sonar.ce.task.CeTask; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import static java.util.stream.Collectors.toList; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.tuple; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class CeTaskMessagesImplIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private DbClient dbClient = dbTester.getDbClient(); private UuidFactory uuidFactory = mock(UuidFactory.class); private String taskUuid = randomAlphabetic(12); private CeTask ceTask = new CeTask.Builder() .setUuid(taskUuid) .setType(randomAlphabetic(5)) .build(); private CeTaskMessagesImpl underTest = new CeTaskMessagesImpl(dbClient, uuidFactory, ceTask); @Test public void add_fails_with_NPE_if_arg_is_null() { assertThatThrownBy(() -> underTest.add(null)) .isInstanceOf(NullPointerException.class) .hasMessage("message can't be null"); } @Test public void add_persist_message_to_DB() { CeTaskMessages.Message message = new CeTaskMessages.Message(randomAlphabetic(20), 2_999L); String uuid = randomAlphanumeric(40); when(uuidFactory.create()).thenReturn(uuid); underTest.add(message); assertThat(dbTester.select("select uuid as \"UUID\", task_uuid as \"TASK_UUID\", message as \"MESSAGE\", created_at as \"CREATED_AT\" from ce_task_message")) .extracting(t -> t.get("UUID"), t -> t.get("TASK_UUID"), t -> t.get("MESSAGE"), t -> t.get("CREATED_AT")) .containsOnly(tuple(uuid, taskUuid, message.getText(), message.getTimestamp())); } @Test public void addAll_fails_with_NPE_if_arg_is_null() { assertThatThrownBy(() -> underTest.addAll(null)) .isInstanceOf(NullPointerException.class); } @Test public void addAll_fails_with_NPE_if_any_message_in_list_is_null() { Random random = new Random(); List<CeTaskMessages.Message> messages = Stream.of( // some (or none) non null Message before null one IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(randomAlphabetic(3) + "_i", 1_999L + i)), Stream.of((CeTaskMessages.Message) null), // some (or none) non null Message after null one IntStream.range(0, random.nextInt(5)).mapToObj(i -> new CeTaskMessages.Message(randomAlphabetic(3) + "_i", 1_999L + i))) .flatMap(t -> t) .collect(toList()); assertThatThrownBy(() -> underTest.addAll(messages)) .isInstanceOf(NullPointerException.class) .hasMessage("message can't be null"); } @Test public void addAll_has_no_effect_if_arg_is_empty() { DbClient dbClientMock = mock(DbClient.class); UuidFactory uuidFactoryMock = mock(UuidFactory.class); CeTask ceTaskMock = mock(CeTask.class); CeTaskMessagesImpl underTest = new CeTaskMessagesImpl(dbClientMock, uuidFactoryMock, ceTaskMock); underTest.addAll(Collections.emptyList()); verifyNoInteractions(dbClientMock, uuidFactoryMock, ceTaskMock); } @Test public void addAll_persists_all_messages_to_DB() { int messageCount = 5; String[] uuids = IntStream.range(0, messageCount).mapToObj(i -> "UUId_" + i).toArray(String[]::new); CeTaskMessages.Message[] messages = IntStream.range(0, messageCount) .mapToObj(i -> new CeTaskMessages.Message("message_" + i, 2_999L + i)) .toArray(CeTaskMessages.Message[]::new); when(uuidFactory.create()).thenAnswer(new Answer<String>() { int i = 0; @Override public String answer(InvocationOnMock invocation) { return uuids[i++]; } }); underTest.addAll(Arrays.stream(messages).toList()); assertThat(dbTester.select("select uuid as \"UUID\", task_uuid as \"TASK_UUID\", message as \"MESSAGE\", created_at as \"CREATED_AT\" from ce_task_message")) .extracting(t -> t.get("UUID"), t -> t.get("TASK_UUID"), t -> t.get("MESSAGE"), t -> t.get("CREATED_AT")) .containsOnly( tuple(uuids[0], taskUuid, messages[0].getText(), messages[0].getTimestamp()), tuple(uuids[1], taskUuid, messages[1].getText(), messages[1].getTimestamp()), tuple(uuids[2], taskUuid, messages[2].getText(), messages[2].getTimestamp()), tuple(uuids[3], taskUuid, messages[3].getText(), messages[3].getTimestamp()), tuple(uuids[4], taskUuid, messages[4].getText(), messages[4].getTimestamp())); } }
5,968
39.883562
161
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTask.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; import com.google.common.base.MoreObjects; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Optional; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Strings.emptyToNull; import static java.util.Collections.emptyMap; import static java.util.Collections.unmodifiableMap; import static java.util.Objects.requireNonNull; @Immutable public class CeTask { private final String type; private final String uuid; private final Component component; private final Component entity; private final User submitter; private final Map<String, String> characteristics; private CeTask(Builder builder) { this.uuid = requireNonNull(emptyToNull(builder.uuid), "uuid can't be null nor empty"); this.type = requireNonNull(emptyToNull(builder.type), "type can't be null nor empty"); checkArgument((builder.component == null) == (builder.entity == null), "None or both component and entity must be non null"); this.component = builder.component; this.entity = builder.entity; this.submitter = builder.submitter; if (builder.characteristics == null) { this.characteristics = emptyMap(); } else { this.characteristics = unmodifiableMap(new HashMap<>(builder.characteristics)); } } public record User(String uuid, String login) { public User(String uuid, @Nullable String login) { this.uuid = requireNonNull(uuid); this.login = emptyToNull(login); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User other = (User) o; return uuid.equals(other.uuid); } @Override public String toString() { return "User{" + "uuid='" + uuid + '\'' + ", login='" + login + '\'' + '}'; } @Override public int hashCode() { return uuid.hashCode(); } } public String getUuid() { return uuid; } public String getType() { return type; } public Optional<Component> getComponent() { return Optional.ofNullable(component); } public Optional<Component> getEntity() { return Optional.ofNullable(entity); } @CheckForNull public User getSubmitter() { return submitter; } public Map<String, String> getCharacteristics() { return characteristics; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("type", type) .add("uuid", uuid) .add("component", component) .add("entity", entity) .add("submitter", submitter) .toString(); } @Override public boolean equals(@Nullable Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CeTask ceTask = (CeTask) o; return uuid.equals(ceTask.uuid); } @Override public int hashCode() { return uuid.hashCode(); } public static final class Builder { private String uuid; private String type; private Component component; private Component entity; private User submitter; private Map<String, String> characteristics; public Builder setUuid(String uuid) { this.uuid = uuid; return this; } public Builder setType(String type) { this.type = type; return this; } public Builder setComponent(@Nullable Component component) { this.component = component; return this; } public Builder setEntity(@Nullable Component entity) { this.entity = entity; return this; } public Builder setSubmitter(@Nullable User s) { this.submitter = s; return this; } public Builder setCharacteristics(@Nullable Map<String, String> m) { this.characteristics = m; return this; } public CeTask build() { return new CeTask(this); } } public static final class Component { private final String uuid; @CheckForNull private final String key; @CheckForNull private final String name; public Component(String uuid, @Nullable String key, @Nullable String name) { this.uuid = requireNonNull(emptyToNull(uuid), "uuid can't be null nor empty"); this.key = emptyToNull(key); this.name = emptyToNull(name); } public String getUuid() { return uuid; } public Optional<String> getKey() { return Optional.ofNullable(key); } public Optional<String> getName() { return Optional.ofNullable(name); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Component component = (Component) o; return Objects.equals(uuid, component.uuid) && Objects.equals(key, component.key) && Objects.equals(name, component.name); } @Override public int hashCode() { return Objects.hash(uuid, key, name); } @Override public String toString() { return "Component{" + "uuid='" + uuid + '\'' + ", key='" + key + '\'' + ", name='" + name + '\'' + '}'; } } }
6,307
24.852459
90
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTaskCanceledException.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; import org.sonar.db.ce.CeActivityDto; import static java.lang.String.format; public final class CeTaskCanceledException extends CeTaskInterruptedException { public CeTaskCanceledException(Thread thread) { super(format("CeWorker executing in Thread '%s' has been interrupted", thread.getName()), CeActivityDto.Status.CANCELED); } }
1,218
37.09375
93
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTaskInterruptedException.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; import java.util.Optional; import org.sonar.db.ce.CeActivityDto; import static java.util.Objects.requireNonNull; public abstract class CeTaskInterruptedException extends RuntimeException { private final CeActivityDto.Status status; protected CeTaskInterruptedException(String message, CeActivityDto.Status status) { super(message); this.status = requireNonNull(status, "status can't be null"); } public CeActivityDto.Status getStatus() { return status; } public static Optional<CeTaskInterruptedException> isTaskInterruptedException(Throwable e) { if (e instanceof CeTaskInterruptedException ceTaskInterruptedException) { return Optional.of(ceTaskInterruptedException); } return isCauseInterruptedException(e); } private static Optional<CeTaskInterruptedException> isCauseInterruptedException(Throwable e) { Throwable cause = e.getCause(); if (cause == null || cause == e) { return Optional.empty(); } if (cause instanceof CeTaskInterruptedException ceTaskInterruptedException) { return Optional.of(ceTaskInterruptedException); } return isCauseInterruptedException(cause); } }
2,038
34.77193
96
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTaskInterrupter.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; /** * Method {@link #check(Thread)} of the {@link CeTaskInterrupter} can be called during the processing of a * {@link CeTask} to check whether processing of this task must be interrupted. * <p> * Interruption cause may be user cancelling the task, operator stopping the Compute Engine, execution running for * too long, ... */ public interface CeTaskInterrupter { /** * @throws CeTaskInterruptedException if the execution of the task must be interrupted */ void check(Thread currentThread) throws CeTaskInterruptedException; /** * Lets the interrupter know that the processing of the specified task has started. */ void onStart(CeTask ceTask); /** * Lets the interrupter know that the processing of the specified task has ended. */ void onEnd(CeTask ceTask); }
1,671
36.155556
114
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTaskResult.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; import java.util.Optional; /** * Represents the result of the processing of a {@link CeTask}. */ @FunctionalInterface public interface CeTaskResult { /** * The UUID of the analysis created, if any, for the Component in {@link CeTask} */ Optional<String> getAnalysisUuid(); }
1,159
33.117647
82
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/CeTaskTimeoutException.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; import org.sonar.db.ce.CeActivityDto; /** * This exception will stop the task and make it be archived with the {@link CeActivityDto.Status#FAILED FAILED} * status and the error type {@code TIMEOUT}. * <p> * This exception has no stacktrace: * <ul> * <li>it's irrelevant to the end user</li> * <li>we don't want to leak any implementation detail</li> * </ul> */ public final class CeTaskTimeoutException extends CeTaskInterruptedException implements TypedException { public CeTaskTimeoutException(String message) { super(message, CeActivityDto.Status.FAILED); } @Override public String getType() { return "TIMEOUT"; } /** * Does not fill in the stack trace * * @see Throwable#fillInStackTrace() */ @Override public synchronized Throwable fillInStackTrace() { return this; } }
1,705
30.018182
112
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/TypedException.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; /** * This interface is implemented by the exceptions * that provide a type of error when failing * a Compute Engine task. * The error type is persisted and available in * the tasks returned by the web services api/ce. */ public interface TypedException { String getType(); }
1,157
33.058824
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task; import javax.annotation.ParametersAreNonnullByDefault;
957
38.916667
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/container/EagerStart.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.container; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Components with this annotation will be eagerly started when loaded into the {@link TaskContainerImpl}. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface EagerStart { }
1,253
35.882353
106
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/container/LazyUnlessEagerAnnotationStrategy.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.container; import javax.annotation.Nullable; import org.sonar.core.platform.SpringInitStrategy; import org.springframework.beans.factory.config.BeanDefinition; public class LazyUnlessEagerAnnotationStrategy extends SpringInitStrategy { @Override protected boolean isLazyInit(BeanDefinition beanDefinition, @Nullable Class<?> clazz) { return clazz == null || clazz.getAnnotation(EagerStart.class) == null; } }
1,290
39.34375
89
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/container/TaskContainer.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.container; import org.sonar.ce.task.CeTask; import org.sonar.core.platform.Container; import org.sonar.core.platform.ExtensionContainer; /** * The Compute Engine task container. Created for a specific parent {@link ExtensionContainer} and a specific {@link CeTask}. */ public interface TaskContainer extends Container, AutoCloseable { ExtensionContainer getParent(); /** * Starts task container, starting any startable component in it. */ void bootup(); /** * Cleans up resources after process has been called and has returned. */ @Override void close(); }
1,457
32.136364
125
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/container/TaskContainerImpl.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.container; import org.slf4j.LoggerFactory; import org.sonar.core.platform.ContainerPopulator; import org.sonar.core.platform.SpringComponentContainer; import static java.util.Objects.requireNonNull; public class TaskContainerImpl extends SpringComponentContainer implements TaskContainer { public TaskContainerImpl(SpringComponentContainer parent, ContainerPopulator<TaskContainer> populator) { super(parent, new LazyUnlessEagerAnnotationStrategy()); populateContainer(requireNonNull(populator)); } private void populateContainer(ContainerPopulator<TaskContainer> populator) { populator.populateContainer(this); } @Override public void bootup() { startComponents(); } @Override public String toString() { return "TaskContainerImpl"; } @Override public void close() { try { stopComponents(); } catch (Throwable t) { LoggerFactory.getLogger(TaskContainerImpl.class).error("Cleanup of container failed", t); } } }
1,858
31.051724
106
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/container/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.container; import javax.annotation.ParametersAreNonnullByDefault;
967
39.333333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/log/CeTaskLogging.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.log; import org.slf4j.MDC; import org.sonar.ce.task.CeTask; public class CeTaskLogging { public static final String MDC_CE_TASK_UUID = "ceTaskUuid"; public void initForTask(CeTask task) { MDC.put(MDC_CE_TASK_UUID, task.getUuid()); } public void clearForTask() { MDC.remove(MDC_CE_TASK_UUID); } }
1,189
30.315789
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/log/CeTaskMessages.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.log; import java.util.Collection; import java.util.Objects; import javax.annotation.concurrent.Immutable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.db.ce.CeTaskMessageType; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; /** * Provides the ability to record message attached to the current task. */ @ComputeEngineSide public interface CeTaskMessages { /** * Add a single message */ void add(Message message); /** * Add multiple messages. Use this method over {@link #add(Message)} if you have more than one message to add, you'll * allow implementation to batch persistence if possible. */ void addAll(Collection<Message> messages); @Immutable class Message { private final String text; private final long timestamp; private final CeTaskMessageType type; public Message(String text, long timestamp, CeTaskMessageType type) { requireNonNull(text, "Text can't be null"); checkArgument(!text.isEmpty(), "Text can't be empty"); checkArgument(timestamp >= 0, "Timestamp can't be less than 0"); this.text = text; this.timestamp = timestamp; this.type = type; } public Message(String text, long timestamp) { this(text, timestamp, CeTaskMessageType.GENERIC); } public String getText() { return text; } public long getTimestamp() { return timestamp; } public CeTaskMessageType getType() { return type; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Message message1 = (Message) o; return timestamp == message1.timestamp && Objects.equals(text, message1.text); } @Override public int hashCode() { return Objects.hash(text, timestamp); } @Override public String toString() { return "Message{" + "text='" + text + '\'' + ", timestamp=" + timestamp + ", type=" + type + '}'; } } }
3,012
27.158879
119
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/log/CeTaskMessagesImpl.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.log; import java.util.Collection; import org.sonar.ce.task.CeTask; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbClient; import org.sonar.db.DbSession; import org.sonar.db.ce.CeTaskMessageDto; import static java.util.Objects.requireNonNull; /** * Implementation of {@link CeTaskMessages} to made available into a task's container. * <p> * Messages are persisted as the are recorded. */ public class CeTaskMessagesImpl implements CeTaskMessages { private final DbClient dbClient; private final UuidFactory uuidFactory; private final CeTask ceTask; public CeTaskMessagesImpl(DbClient dbClient, UuidFactory uuidFactory, CeTask ceTask) { this.dbClient = dbClient; this.uuidFactory = uuidFactory; this.ceTask = ceTask; } @Override public void add(Message message) { checkMessage(message); try (DbSession dbSession = dbClient.openSession(false)) { insert(dbSession, message); dbSession.commit(); } } @Override public void addAll(Collection<Message> messages) { if (messages.isEmpty()) { return; } messages.forEach(CeTaskMessagesImpl::checkMessage); // TODO: commit every X messages? try (DbSession dbSession = dbClient.openSession(true)) { messages.forEach(message -> insert(dbSession, message)); dbSession.commit(); } } public void insert(DbSession dbSession, Message message) { dbClient.ceTaskMessageDao().insert(dbSession, new CeTaskMessageDto() .setUuid(uuidFactory.create()) .setTaskUuid(ceTask.getUuid()) .setMessage(message.getText()) .setType(message.getType()) .setCreatedAt(message.getTimestamp())); } private static void checkMessage(Message message) { requireNonNull(message, "message can't be null"); } }
2,658
30.282353
88
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/log/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.log; import javax.annotation.ParametersAreNonnullByDefault;
961
39.083333
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/setting/SettingsLoader.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.setting; import org.sonar.api.Startable; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.config.internal.Settings; import org.sonar.ce.task.container.EagerStart; import org.sonar.ce.task.container.TaskContainerImpl; import org.sonar.server.setting.ThreadLocalSettings; /** * Add this class as the first components in the {@link TaskContainerImpl} * to trigger loading of Thread local specific {@link Settings} in {@link ThreadLocalSettings}. */ @EagerStart @ComputeEngineSide public class SettingsLoader implements Startable { private final ThreadLocalSettings threadLocalSettings; public SettingsLoader(ThreadLocalSettings threadLocalSettings) { this.threadLocalSettings = threadLocalSettings; } @Override public void start() { threadLocalSettings.load(); } @Override public void stop() { threadLocalSettings.unload(); } }
1,747
32.615385
95
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/setting/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.setting; import javax.annotation.ParametersAreNonnullByDefault;
965
39.25
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/step/ComputationStep.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.step; /** * A way of splitting the processing of a task into smaller items which can be executed sequentially * by {@link ComputationStepExecutor}. */ public interface ComputationStep { /** * Statistics are displayed in the step ending log. They help * understanding the runtime context and potential performance hotspots. * * <p/> * Example: * <code> * statistics.add("inserts", 200); * statistics.add("updates", 50); * </code> * adds two parameters to the log: * <code> * 2018.07.26 10:22:58 DEBUG ce[AWTVrwb-KZf9YbDx-laU][o.s.s.c.t.s.ComputationStepExecutor] Persist issues | inserts=200 | updates=50 | time=30ms * </code> * * <p/> * Statistics are logged in the order of insertion. */ interface Statistics { /** * @return this * @throws NullPointerException if key or value is null * @throws IllegalArgumentException if key has already been set * @throws IllegalArgumentException if key is "time", to avoid conflict with the profiler field with same name */ Statistics add(String key, Object value); } interface Context { Statistics getStatistics(); } void execute(Context context); String getDescription(); }
2,097
31.78125
146
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/step/ComputationStepExecutor.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.step; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.sonar.ce.task.CeTaskInterrupter; import org.sonar.core.util.logs.Profiler; import org.springframework.beans.factory.annotation.Autowired; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.String.format; import static java.util.Objects.requireNonNull; public final class ComputationStepExecutor { private static final Logger LOGGER = LoggerFactory.getLogger(ComputationStepExecutor.class); private final ComputationSteps steps; private final CeTaskInterrupter taskInterrupter; @CheckForNull private final Listener listener; public ComputationStepExecutor(ComputationSteps steps, CeTaskInterrupter taskInterrupter) { this(steps, taskInterrupter, null); } @Autowired public ComputationStepExecutor(ComputationSteps steps, CeTaskInterrupter taskInterrupter, @Nullable Listener listener) { this.steps = steps; this.taskInterrupter = taskInterrupter; this.listener = listener; } public void execute() { Profiler stepProfiler = Profiler.create(LOGGER).logTimeLast(true); boolean allStepsExecuted = false; try { executeSteps(stepProfiler); allStepsExecuted = true; } finally { if (listener != null) { executeListener(allStepsExecuted); } } } private void executeSteps(Profiler stepProfiler) { StepStatisticsImpl statistics = new StepStatisticsImpl(stepProfiler); ComputationStep.Context context = new StepContextImpl(statistics); for (ComputationStep step : steps.instances()) { executeStep(stepProfiler, context, step); } } private void executeStep(Profiler stepProfiler, ComputationStep.Context context, ComputationStep step) { String status = "FAILED"; stepProfiler.start(); try { taskInterrupter.check(Thread.currentThread()); step.execute(context); status = "SUCCESS"; } finally { stepProfiler.addContext("status", status); stepProfiler.stopInfo(step.getDescription()); } } private void executeListener(boolean allStepsExecuted) { try { listener.finished(allStepsExecuted); } catch (Throwable e) { // any Throwable throws by the listener going up the stack might hide an Exception/Error thrown by the step and // cause it be swallowed. We don't wan't that => we catch Throwable LOGGER.error("Execution of listener failed", e); } } @FunctionalInterface public interface Listener { void finished(boolean allStepsExecuted); } private static class StepStatisticsImpl implements ComputationStep.Statistics { private final Profiler profiler; private StepStatisticsImpl(Profiler profiler) { this.profiler = profiler; } @Override public ComputationStep.Statistics add(String key, Object value) { requireNonNull(key, "Statistic has null key"); requireNonNull(value, () -> format("Statistic with key [%s] has null value", key)); checkArgument(!key.equalsIgnoreCase("time"), "Statistic with key [time] is not accepted"); checkArgument(!profiler.hasContext(key), "Statistic with key [%s] is already present", key); profiler.addContext(key, value); return this; } } private static class StepContextImpl implements ComputationStep.Context { private final ComputationStep.Statistics statistics; private StepContextImpl(ComputationStep.Statistics statistics) { this.statistics = statistics; } @Override public ComputationStep.Statistics getStatistics() { return statistics; } } }
4,565
33.330827
122
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/step/ComputationSteps.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.step; import java.util.List; /** * Ordered list of steps classes and instances to be executed in a Compute Engine process. */ public interface ComputationSteps { /** * List of all {@link ComputationStep}, * ordered by execution sequence. */ List<Class<? extends ComputationStep>> orderedStepClasses(); /** * List of all {@link ComputationStep}, * ordered by execution sequence. */ Iterable<ComputationStep> instances(); }
1,322
32.075
90
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/step/ExecuteStatelessInitExtensionsStep.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.step; import org.sonar.api.ce.ComputeEngineSide; import org.springframework.beans.factory.annotation.Autowired; /** * Execute {@link StatelessInitExtension} instances in no specific order. * If an extension fails (throws an exception), consecutive extensions * won't be called. */ @ComputeEngineSide public class ExecuteStatelessInitExtensionsStep implements ComputationStep { private final StatelessInitExtension[] extensions; @Autowired(required = false) public ExecuteStatelessInitExtensionsStep(StatelessInitExtension[] extensions) { this.extensions = extensions; } /** * Used when zero {@link StatelessInitExtension} are registered into container. */ @Autowired(required = false) public ExecuteStatelessInitExtensionsStep() { this(new StatelessInitExtension[0]); } @Override public void execute(Context context) { for (StatelessInitExtension extension : extensions) { extension.onInit(); } } @Override public String getDescription() { return "Initialize"; } }
1,905
30.766667
82
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/step/StatelessInitExtension.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.step; import org.sonar.api.ExtensionPoint; import org.sonar.api.ce.ComputeEngineSide; /** * Extension point that is called during processing of a task * by {@link ExecuteStatelessInitExtensionsStep}. * It is stateless, the same instance is reused for all tasks. * As a consequence Compute Engine task components can't be injected * as dependencies. */ @ComputeEngineSide @ExtensionPoint public interface StatelessInitExtension { /** * This method can make the task fail by throwing a {@link RuntimeException} */ void onInit(); }
1,418
32.785714
78
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/step/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.step; import javax.annotation.ParametersAreNonnullByDefault;
962
39.125
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/taskprocessor/CeTaskProcessor.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.taskprocessor; import java.util.Set; import javax.annotation.CheckForNull; import org.sonar.api.ce.ComputeEngineSide; import org.sonar.api.server.ServerSide; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; /** * This interface is used to provide the processing code for {@link CeTask}s of one or more type to be called by the * Compute Engine. */ @ComputeEngineSide @ServerSide public interface CeTaskProcessor { /** * The {@link CeTask#getType()} for which this {@link CeTaskProcessor} provides the processing code. * <p> * The match of type is done using {@link String#equals(Object)} and if more than one {@link CeTaskProcessor} declares * itself had handler for the same {@link CeTask#getType()}, an error will be raised at startup and startup will * fail. * </p> * <p> * If an empty {@link Set} is returned, the {@link CeTaskProcessor} will be ignored. * </p> */ Set<String> getHandledCeTaskTypes(); /** * Calls the processing code for a specific {@link CeTask} which will optionally return a {@link CeTaskResult} * holding information to be persisted in the processing history of the Compute Engine (currently the {@code CE_ACTIVITY} table). * <p> * The specified is guaranteed to be non {@code null} and its {@link CeTask#getType()} to be one of the values * of {@link #getHandledCeTaskTypes()}. * </p> * * @throws RuntimeException when thrown, it will be caught and logged by the Compute Engine and the processing of the * specified {@link CeTask} will be flagged as failed. */ @CheckForNull CeTaskResult process(CeTask task); }
2,515
38.3125
131
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolder.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.taskprocessor; import org.sonar.ce.task.CeTaskResult; public interface MutableTaskResultHolder extends TaskResultHolder { /** * @throws NullPointerException if {@code taskResult} is {@code null} * @throws IllegalStateException if a {@link CeTaskResult} has already been set in the holder */ void setResult(CeTaskResult taskResult); }
1,218
38.322581
95
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolderImpl.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.taskprocessor; import javax.annotation.CheckForNull; import org.sonar.ce.task.CeTaskResult; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; public class MutableTaskResultHolderImpl implements MutableTaskResultHolder { @CheckForNull private CeTaskResult result; @Override public CeTaskResult getResult() { checkState(this.result != null, "No CeTaskResult has been set in the holder"); return this.result; } @Override public void setResult(CeTaskResult taskResult) { requireNonNull(taskResult, "taskResult can not be null"); checkState(this.result == null, "CeTaskResult has already been set in the holder"); this.result = taskResult; } }
1,610
34.8
87
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/taskprocessor/TaskResultHolder.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.taskprocessor; import org.sonar.ce.task.CeTaskResult; public interface TaskResultHolder { /** * @throws IllegalStateException if holder holds no CeTaskResult */ CeTaskResult getResult(); }
1,070
34.7
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/taskprocessor/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.taskprocessor; import javax.annotation.ParametersAreNonnullByDefault;
971
39.5
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/util/InitializedProperty.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.util; import javax.annotation.CheckForNull; import javax.annotation.Nullable; public class InitializedProperty<E> { private E property; private boolean initialized = false; public InitializedProperty<E> setProperty(@Nullable E property) { this.property = property; this.initialized = true; return this; } @CheckForNull public E getProperty() { return property; } public boolean isInitialized() { return initialized; } }
1,332
29.295455
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/main/java/org/sonar/ce/task/util/package-info.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. */ @ParametersAreNonnullByDefault package org.sonar.ce.task.util; import javax.annotation.ParametersAreNonnullByDefault;
963
37.56
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskCanceledExceptionTest.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; import org.junit.Test; import org.sonar.db.ce.CeActivityDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; public class CeTaskCanceledExceptionTest { @Test public void message_is_based_on_specified_thread_name() { Thread t = new Thread(); t.setName(randomAlphabetic(29)); CeTaskCanceledException underTest = new CeTaskCanceledException(t); assertThat(underTest.getMessage()).isEqualTo("CeWorker executing in Thread '" + t.getName() + "' has been interrupted"); } @Test public void getStatus_returns_CANCELED() { CeTaskCanceledException underTest = new CeTaskCanceledException(new Thread()); assertThat(underTest.getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); } }
1,670
35.326087
124
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskComponentTest.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; 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.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @RunWith(DataProviderRunner.class) public class CeTaskComponentTest { @Test @UseDataProvider("nullOrEmpty") public void constructor_fails_with_NPE_if_uuid_is_null_or_empty(String str) { assertThatThrownBy(() -> new CeTask.Component(str, "foo", "bar")) .isInstanceOf(NullPointerException.class) .hasMessage("uuid can't be null nor empty"); } @Test @UseDataProvider("nullOrEmpty") public void constructor_considers_empty_as_null_and_accept_it_for_key(String str) { CeTask.Component underTest = new CeTask.Component("foo", str, "bar"); assertThat(underTest.getKey()).isEmpty(); } @Test @UseDataProvider("nullOrEmpty") public void constructor_considers_empty_as_null_and_accept_it_for_name(String str) { CeTask.Component underTest = new CeTask.Component("foo", "bar", str); assertThat(underTest.getName()).isEmpty(); } @Test public void equals_is_based_on_all_fields() { String uuid = randomAlphabetic(2); String key = randomAlphabetic(3); String name = randomAlphabetic(4); String somethingElse = randomAlphabetic(5); CeTask.Component underTest = new CeTask.Component(uuid, key, name); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new CeTask.Component(uuid, key, name)) .isNotNull() .isNotEqualTo(new Object()) .isNotEqualTo(new CeTask.Component(somethingElse, key, name)) .isNotEqualTo(new CeTask.Component(uuid, somethingElse, name)) .isNotEqualTo(new CeTask.Component(uuid, key, somethingElse)) .isNotEqualTo(new CeTask.Component(uuid, key, null)); } @Test public void hashcode_is_based_on_all_fields() { String uuid = randomAlphabetic(2); String key = randomAlphabetic(3); String name = randomAlphabetic(4); String somethingElse = randomAlphabetic(5); CeTask.Component underTest = new CeTask.Component(uuid, key, name); assertThat(underTest) .hasSameHashCodeAs(underTest) .hasSameHashCodeAs(new CeTask.Component(uuid, key, name)); assertThat(underTest.hashCode()) .isNotEqualTo(new Object().hashCode()) .isNotEqualTo(new CeTask.Component(somethingElse, key, name).hashCode()) .isNotEqualTo(new CeTask.Component(uuid, somethingElse, name).hashCode()) .isNotEqualTo(new CeTask.Component(uuid, key, somethingElse).hashCode()) .isNotEqualTo(new CeTask.Component(uuid, key, null).hashCode()); } @DataProvider public static Object[][] nullOrEmpty() { return new Object[][] { {null}, {""}, }; } }
3,854
35.714286
86
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskInterruptedExceptionTest.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; import java.util.Random; import org.junit.Test; import org.sonar.db.ce.CeActivityDto; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.ce.task.CeTaskInterruptedException.isTaskInterruptedException; public class CeTaskInterruptedExceptionTest { @Test public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass() { String message = randomAlphabetic(50); CeActivityDto.Status status = randomStatus(); CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) { }; CeTaskInterruptedException e2 = new CeTaskInterruptedExceptionSubclass(message, status); assertThat(isTaskInterruptedException(e1)).contains(e1); assertThat(isTaskInterruptedException(e2)).contains(e2); assertThat(isTaskInterruptedException(new RuntimeException())).isEmpty(); assertThat(isTaskInterruptedException(new Exception())).isEmpty(); } @Test public void isCauseInterruptedException_returns_CeTaskInterruptedException_or_subclass_in_cause_chain() { String message = randomAlphabetic(50); CeActivityDto.Status status = randomStatus(); CeTaskInterruptedException e1 = new CeTaskInterruptedException(message, status) { }; CeTaskInterruptedException e2 = new CeTaskInterruptedExceptionSubclass(message, status); assertThat(isTaskInterruptedException(new RuntimeException(e1))).contains(e1); assertThat(isTaskInterruptedException(new Exception(new RuntimeException(e2)))).contains(e2); } private static CeActivityDto.Status randomStatus() { return CeActivityDto.Status.values()[new Random().nextInt(CeActivityDto.Status.values().length)]; } private static class CeTaskInterruptedExceptionSubclass extends CeTaskInterruptedException { public CeTaskInterruptedExceptionSubclass(String message, CeActivityDto.Status status) { super(message, status); } } }
2,859
39.28169
107
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTest.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; import com.google.common.collect.ImmutableMap; 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; @RunWith(DataProviderRunner.class) public class CeTaskTest { private CeTask.Builder underTest = new CeTask.Builder(); @Test @UseDataProvider("oneAndOnlyOneOfComponentAndEntity") public void build_fails_with_IAE_if_only_one_of_component_and_main_component_is_non_null(CeTask.Component component, CeTask.Component entity) { underTest.setType("TYPE_1"); underTest.setUuid("UUID_1"); underTest.setComponent(component); underTest.setEntity(entity); assertThatThrownBy(() -> underTest.build()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("None or both component and entity must be non null"); } @DataProvider public static Object[][] oneAndOnlyOneOfComponentAndEntity() { CeTask.Component component = new CeTask.Component("COMPONENT_UUID_1", "COMPONENT_KEY_1", "The component"); return new Object[][] { {component, null}, {null, component} }; } @Test public void verify_getters() { CeTask.Component component = new CeTask.Component("COMPONENT_UUID_1", "COMPONENT_KEY_1", "The component"); CeTask.Component entity = new CeTask.Component("ENTITY_UUID_1", "ENTITY_KEY_1", "The entity"); CeTask.User submitter = new CeTask.User("UUID_USER_1", "LOGIN_1"); underTest.setType("TYPE_1"); underTest.setUuid("UUID_1"); underTest.setSubmitter(submitter); underTest.setComponent(component); underTest.setEntity(entity); underTest.setCharacteristics(ImmutableMap.of("k1", "v1", "k2", "v2")); CeTask task = underTest.build(); assertThat(task.getUuid()).isEqualTo("UUID_1"); assertThat(task.getType()).isEqualTo("TYPE_1"); assertThat(task.getSubmitter()).isEqualTo(submitter); assertThat(task.getComponent()).contains(component); assertThat(task.getEntity()).contains(entity); assertThat(task.getCharacteristics()) .hasSize(2) .containsEntry("k1", "v1") .containsEntry("k2", "v2"); } @Test public void verify_toString() { CeTask.Component component = new CeTask.Component("COMPONENT_UUID_1", "COMPONENT_KEY_1", "The component"); CeTask.Component entity = new CeTask.Component("ENTITY_UUID_1", "ENTITY_KEY_1", "The entity"); underTest.setType("TYPE_1"); underTest.setUuid("UUID_1"); underTest.setComponent(component); underTest.setEntity(entity); underTest.setSubmitter(new CeTask.User("UUID_USER_1", "LOGIN_1")); underTest.setCharacteristics(ImmutableMap.of("k1", "v1", "k2", "v2")); CeTask task = underTest.build(); System.out.println(task.toString()); assertThat(task).hasToString("CeTask{" + "type=TYPE_1, " + "uuid=UUID_1, " + "component=Component{uuid='COMPONENT_UUID_1', key='COMPONENT_KEY_1', name='The component'}, " + "entity=Component{uuid='ENTITY_UUID_1', key='ENTITY_KEY_1', name='The entity'}, " + "submitter=User{uuid='UUID_USER_1', login='LOGIN_1'}" + "}"); } @Test public void empty_in_submitterLogin_is_considered_as_null() { CeTask ceTask = underTest.setUuid("uuid").setType("type") .setSubmitter(new CeTask.User("USER_ID", "")) .build(); assertThat(ceTask.getSubmitter().login()).isNull(); } @Test public void equals_and_hashCode_on_uuid() { underTest.setType("TYPE_1").setUuid("UUID_1"); CeTask task1 = underTest.build(); CeTask task1bis = underTest.build(); CeTask task2 = new CeTask.Builder().setType("TYPE_1").setUuid("UUID_2").build(); assertThat(task1.equals(task1)).isTrue(); assertThat(task1.equals(task1bis)).isTrue(); assertThat(task1.equals(task2)).isFalse(); assertThat(task1) .hasSameHashCodeAs(task1) .hasSameHashCodeAs(task1bis); } @Test public void setCharacteristics_null_is_considered_as_empty() { CeTask task = underTest.setType("TYPE_1").setUuid("UUID_1") .setCharacteristics(null) .build(); assertThat(task.getCharacteristics()).isEmpty(); } @Test public void verify_submitter_getters() { CeTask.User user = new CeTask.User("UUID", "LOGIN"); assertThat(user.uuid()).isEqualTo("UUID"); assertThat(user.login()).isEqualTo("LOGIN"); } @Test public void submitter_equals_and_hashCode_on_uuid() { CeTask.User user1 = new CeTask.User("UUID_1", null); CeTask.User user1bis = new CeTask.User("UUID_1", null); CeTask.User user2 = new CeTask.User("UUID_2", null); CeTask.User user1_diff_login = new CeTask.User("UUID_1", "LOGIN"); assertThat(user1.equals(null)).isFalse(); assertThat(user1) .isEqualTo(user1) .isEqualTo(user1bis) .isNotEqualTo(user2) .hasSameHashCodeAs(user1) .hasSameHashCodeAs(user1bis) .hasSameHashCodeAs(user1_diff_login); } }
6,002
35.603659
145
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/CeTaskTimeoutExceptionTest.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; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.commons.lang.RandomStringUtils; import org.junit.Test; import org.sonar.db.ce.CeActivityDto; import static org.assertj.core.api.Assertions.assertThat; public class CeTaskTimeoutExceptionTest { private String message = RandomStringUtils.randomAlphabetic(50); private CeTaskTimeoutException underTest = new CeTaskTimeoutException(message); @Test public void verify_message_and_type() { assertThat(underTest.getMessage()).isEqualTo(message); assertThat(underTest.getType()).isEqualTo("TIMEOUT"); } @Test public void getStatus_returns_FAILED() { assertThat(underTest.getStatus()).isEqualTo(CeActivityDto.Status.FAILED); } @Test public void noStacktrace() { StringWriter stacktrace = new StringWriter(); underTest.printStackTrace(new PrintWriter(stacktrace)); assertThat(stacktrace.toString()) .isEqualTo(CeTaskTimeoutException.class.getCanonicalName() + ": " + message + System.lineSeparator()); } }
1,900
34.203704
108
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/container/TaskContainerImplTest.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.container; import org.junit.Before; import org.junit.Test; import org.sonar.api.Startable; import org.sonar.core.platform.ContainerPopulator; import org.sonar.core.platform.SpringComponentContainer; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; public class TaskContainerImplTest { private final SpringComponentContainer parent = new SpringComponentContainer(); private final ContainerPopulator<TaskContainer> populator = spy(new DummyContainerPopulator()); @Before public void before() { parent.startComponents(); } @Test public void constructor_fails_fast_on_null_container() { assertThatThrownBy(() -> new TaskContainerImpl(null, populator)) .isInstanceOf(NullPointerException.class); } @Test public void constructor_fails_fast_on_null_item() { SpringComponentContainer c = new SpringComponentContainer(); assertThatThrownBy(() -> new TaskContainerImpl(c, null)) .isInstanceOf(NullPointerException.class); } @Test public void calls_method_populateContainer_of_passed_in_populator() { TaskContainerImpl ceContainer = new TaskContainerImpl(parent, populator); verify(populator).populateContainer(ceContainer); } @Test public void bootup_starts_components_lazily_unless_they_are_annotated_with_EagerStart() { DefaultStartable defaultStartable = new DefaultStartable(); EagerStartable eagerStartable = new EagerStartable(); TaskContainerImpl ceContainer = new TaskContainerImpl(parent, container -> { container.add(defaultStartable); container.add(eagerStartable); }); ceContainer.bootup(); assertThat(defaultStartable.startCalls).isZero(); assertThat(defaultStartable.stopCalls).isZero(); assertThat(eagerStartable.startCalls).isOne(); assertThat(eagerStartable.stopCalls).isZero(); } @Test public void close_stops_started_components() { final DefaultStartable defaultStartable = new DefaultStartable(); final EagerStartable eagerStartable = new EagerStartable(); TaskContainerImpl ceContainer = new TaskContainerImpl(parent, container -> { container.add(defaultStartable); container.add(eagerStartable); }); ceContainer.bootup(); ceContainer.close(); assertThat(defaultStartable.startCalls).isZero(); assertThat(defaultStartable.stopCalls).isZero(); assertThat(eagerStartable.startCalls).isOne(); assertThat(eagerStartable.stopCalls).isOne(); } public static class DefaultStartable implements Startable { protected int startCalls = 0; protected int stopCalls = 0; @Override public void start() { startCalls++; } @Override public void stop() { stopCalls++; } } @EagerStart public static class EagerStartable extends DefaultStartable { } private static class DummyContainerPopulator implements ContainerPopulator<TaskContainer> { @Override public void populateContainer(TaskContainer container) { } } }
3,996
31.495935
97
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskLoggingTest.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.log; import ch.qos.logback.core.joran.spi.JoranException; import org.junit.After; import org.junit.Test; import org.mockito.Mockito; import org.slf4j.MDC; import org.sonar.ce.task.CeTask; import org.sonar.process.logging.LogbackHelper; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.when; import static org.sonar.ce.task.log.CeTaskLogging.MDC_CE_TASK_UUID; public class CeTaskLoggingTest { private LogbackHelper helper = new LogbackHelper(); private CeTaskLogging underTest = new CeTaskLogging(); @After public void resetLogback() throws JoranException { helper.resetFromXml("/logback-test.xml"); } @After public void cleanMDC() { MDC.clear(); } @Test public void initForTask_stores_task_uuid_in_MDC() { String uuid = "ce_task_uuid"; underTest.initForTask(createCeTask(uuid)); assertThat(MDC.get(MDC_CE_TASK_UUID)).isEqualTo(uuid); } private CeTask createCeTask(String uuid) { CeTask ceTask = Mockito.mock(CeTask.class); when(ceTask.getUuid()).thenReturn(uuid); return ceTask; } @Test public void clearForTask_removes_task_uuid_from_MDC() { MDC.put(MDC_CE_TASK_UUID, "some_value"); underTest.clearForTask(); assertThat(MDC.get(MDC_CE_TASK_UUID)).isNull(); } }
2,165
27.88
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/log/CeTaskMessagesMessageTest.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.log; import org.junit.Test; import org.sonar.ce.task.log.CeTaskMessages.Message; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; public class CeTaskMessagesMessageTest { @Test public void constructor_throws_IAE_if_text_is_null() { assertThatThrownBy(() -> new Message(null, 12L)) .isInstanceOf(NullPointerException.class) .hasMessage("Text can't be null"); } @Test public void constructor_throws_IAE_if_text_is_empty() { assertThatThrownBy(() -> new Message("", 12L)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Text can't be empty"); } @Test public void constructor_throws_IAE_if_timestamp_is_less_than_0() { assertThatThrownBy(() -> new Message("bar", -1)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Timestamp can't be less than 0"); } @Test public void equals_is_based_on_text_and_timestamp() { long timestamp = 10_000_000_000L; String text = randomAlphabetic(23); Message underTest = new Message(text, timestamp); assertThat(underTest) .isEqualTo(underTest) .isEqualTo(new Message(text, timestamp)) .isNotEqualTo(new Message(text + "ç", timestamp)) .isNotEqualTo(new Message(text, timestamp + 10_999L)) .isNotNull() .isNotEqualTo(new Object()); } @Test public void hashsode_is_based_on_text_and_timestamp() { long timestamp = 10_000_000_000L; String text = randomAlphabetic(23); Message underTest = new Message(text, timestamp); assertThat(underTest.hashCode()) .isEqualTo(underTest.hashCode()) .isEqualTo(new Message(text, timestamp).hashCode()) .isNotEqualTo(new Message(text + "ç", timestamp).hashCode()) .isNotEqualTo(new Message(text, timestamp + 10_999L).hashCode()) .isNotEqualTo(new Object().hashCode()); } }
2,857
34.283951
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/setting/SettingsLoaderTest.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.setting; import org.junit.Test; import org.sonar.server.setting.ThreadLocalSettings; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; public class SettingsLoaderTest { private ThreadLocalSettings threadLocalSettings = mock(ThreadLocalSettings.class); private SettingsLoader underTest = new SettingsLoader(threadLocalSettings); @Test public void start_calls_ThreadLocalSettings_load() { underTest.start(); verify(threadLocalSettings).load(); verifyNoMoreInteractions(threadLocalSettings); } @Test public void stop_calls_ThreadLocalSettings_remove() { underTest.stop(); verify(threadLocalSettings).unload(); verifyNoMoreInteractions(threadLocalSettings); } }
1,666
33.020408
84
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ComputationStepExecutorTest.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.step; import java.util.Arrays; import java.util.List; import org.junit.Rule; import org.junit.Test; import org.mockito.InOrder; import org.slf4j.event.Level; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.ce.task.CeTaskInterrupter; import org.sonar.ce.task.ChangeLogLevel; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; public class ComputationStepExecutorTest { @Rule public LogTester logTester = new LogTester(); private final ComputationStepExecutor.Listener listener = mock(ComputationStepExecutor.Listener.class); private final CeTaskInterrupter taskInterrupter = mock(CeTaskInterrupter.class); private final ComputationStep computationStep1 = mockComputationStep("step1"); private final ComputationStep computationStep2 = mockComputationStep("step2"); private final ComputationStep computationStep3 = mockComputationStep("step3"); @Test public void execute_call_execute_on_each_ComputationStep_in_order_returned_by_instances_method() { new ComputationStepExecutor(mockComputationSteps(computationStep1, computationStep2, computationStep3), taskInterrupter) .execute(); InOrder inOrder = inOrder(computationStep1, computationStep2, computationStep3); inOrder.verify(computationStep1).execute(any()); inOrder.verify(computationStep1).getDescription(); inOrder.verify(computationStep2).execute(any()); inOrder.verify(computationStep2).getDescription(); inOrder.verify(computationStep3).execute(any()); inOrder.verify(computationStep3).getDescription(); inOrder.verifyNoMoreInteractions(); } @Test public void execute_let_exception_thrown_by_ComputationStep_go_up_as_is() { String message = "Exception should go up"; ComputationStep computationStep = mockComputationStep("step1"); doThrow(new RuntimeException(message)) .when(computationStep) .execute(any()); ComputationStepExecutor computationStepExecutor = new ComputationStepExecutor(mockComputationSteps(computationStep), taskInterrupter); assertThatThrownBy(computationStepExecutor::execute) .isInstanceOf(RuntimeException.class) .hasMessage(message); } @Test public void execute_logs_end_timing_and_statistics_for_each_ComputationStep_in_INFO_level() { ComputationStep step1 = new StepWithStatistics("Step One", "foo", "100", "bar", "20"); ComputationStep step2 = new StepWithStatistics("Step Two", "foo", "50", "baz", "10"); ComputationStep step3 = new StepWithStatistics("Step Three"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO); ChangeLogLevel logLevel1 = new ChangeLogLevel(step1.getClass(), LoggerLevel.INFO); ChangeLogLevel logLevel2 = new ChangeLogLevel(step2.getClass(), LoggerLevel.INFO); ChangeLogLevel logLevel3 = new ChangeLogLevel(step3.getClass(), LoggerLevel.INFO)) { new ComputationStepExecutor(mockComputationSteps(step1, step2, step3), taskInterrupter).execute(); List<String> infoLogs = logTester.logs(Level.INFO); assertThat(infoLogs).hasSize(3); assertThat(infoLogs.get(0)).contains("Step One | foo=100 | bar=20 | status=SUCCESS | time="); assertThat(infoLogs.get(1)).contains("Step Two | foo=50 | baz=10 | status=SUCCESS | time="); assertThat(infoLogs.get(2)).contains("Step Three | status=SUCCESS | time="); } } @Test public void execute_logs_end_timing_and_statistics_for_each_ComputationStep_in_INFO_level_even_if_failed() { RuntimeException expected = new RuntimeException("faking step failing with RuntimeException"); ComputationStep step1 = new StepWithStatistics("Step One", "foo", "100", "bar", "20"); ComputationStep step2 = new StepWithStatistics("Step Two", "foo", "50", "baz", "10"); ComputationStep step3 = new StepWithStatistics("Step Three", "donut", "crash") { @Override public void execute(Context context) { super.execute(context); throw expected; } }; try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO); ChangeLogLevel logLevel1 = new ChangeLogLevel(step1.getClass(), LoggerLevel.INFO); ChangeLogLevel logLevel2 = new ChangeLogLevel(step2.getClass(), LoggerLevel.INFO); ChangeLogLevel logLevel3 = new ChangeLogLevel(step3.getClass(), LoggerLevel.INFO)) { try { new ComputationStepExecutor(mockComputationSteps(step1, step2, step3), taskInterrupter).execute(); fail("a RuntimeException should have been thrown"); } catch (RuntimeException e) { List<String> infoLogs = logTester.logs(Level.INFO); assertThat(infoLogs).hasSize(3); assertThat(infoLogs.get(0)).contains("Step One | foo=100 | bar=20 | status=SUCCESS | time="); assertThat(infoLogs.get(1)).contains("Step Two | foo=50 | baz=10 | status=SUCCESS | time="); assertThat(infoLogs.get(2)).contains("Step Three | donut=crash | status=FAILED | time="); } } } @Test public void execute_throws_IAE_if_step_adds_time_statistic() { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "time", "20"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Statistic with key [time] is not accepted"); } } @Test public void execute_throws_IAE_if_step_adds_statistic_multiple_times() { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "foo", "20"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Statistic with key [foo] is already present"); } } @Test public void execute_throws_NPE_if_step_adds_statistic_with_null_key() { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", null, "bar"); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) .isInstanceOf(NullPointerException.class) .hasMessage("Statistic has null key"); } } @Test public void execute_throws_NPE_if_step_adds_statistic_with_null_value() { ComputationStep step = new StepWithStatistics("A Step", "foo", "100", "bar", null); try (ChangeLogLevel executor = new ChangeLogLevel(ComputationStepExecutor.class, LoggerLevel.INFO)) { assertThatThrownBy(() -> new ComputationStepExecutor(mockComputationSteps(step), taskInterrupter).execute()) .isInstanceOf(NullPointerException.class) .hasMessage("Statistic with key [bar] has null value"); } } @Test public void execute_calls_listener_finished_method_with_all_step_runs() { new ComputationStepExecutor(mockComputationSteps(computationStep1, computationStep2), taskInterrupter, listener) .execute(); verify(listener).finished(true); verifyNoMoreInteractions(listener); } @Test public void execute_calls_listener_finished_method_even_if_a_step_throws_an_exception() { RuntimeException toBeThrown = new RuntimeException("simulating failing execute Step method"); doThrow(toBeThrown) .when(computationStep1) .execute(any()); try { new ComputationStepExecutor(mockComputationSteps(computationStep1, computationStep2), taskInterrupter, listener) .execute(); fail("exception toBeThrown should have been raised"); } catch (RuntimeException e) { assertThat(e).isSameAs(toBeThrown); verify(listener).finished(false); verifyNoMoreInteractions(listener); } } @Test public void execute_does_not_fail_if_listener_throws_Throwable() { ComputationStepExecutor.Listener listener = mock(ComputationStepExecutor.Listener.class); doThrow(new Error("Facking error thrown by Listener")) .when(listener) .finished(anyBoolean()); new ComputationStepExecutor(mockComputationSteps(computationStep1), taskInterrupter, listener).execute(); } @Test public void execute_fails_with_exception_thrown_by_interrupter() throws Throwable { executeFailsWithExceptionThrownByInterrupter(); reset(computationStep1, computationStep2, computationStep3, taskInterrupter); runInOtherThread(this::executeFailsWithExceptionThrownByInterrupter); } private void executeFailsWithExceptionThrownByInterrupter() { Thread currentThread = Thread.currentThread(); ComputationStepExecutor underTest = new ComputationStepExecutor(mockComputationSteps(computationStep1, computationStep2, computationStep3), taskInterrupter); RuntimeException exception = new RuntimeException("mocking fail of method check()"); doNothing() .doNothing() .doThrow(exception) .when(taskInterrupter) .check(currentThread); try { underTest.execute(); fail("execute should have thrown an exception"); } catch (Exception e) { assertThat(e).isSameAs(exception); } } @Test public void execute_calls_interrupter_with_current_thread_before_each_step() throws Throwable { executeCallsInterrupterWithCurrentThreadBeforeEachStep(); reset(computationStep1, computationStep2, computationStep3, taskInterrupter); runInOtherThread(this::executeCallsInterrupterWithCurrentThreadBeforeEachStep); } private void executeCallsInterrupterWithCurrentThreadBeforeEachStep() { InOrder inOrder = inOrder(computationStep1, computationStep2, computationStep3, taskInterrupter); ComputationStepExecutor underTest = new ComputationStepExecutor(mockComputationSteps(computationStep1, computationStep2, computationStep3), taskInterrupter); underTest.execute(); inOrder.verify(taskInterrupter).check(Thread.currentThread()); inOrder.verify(computationStep1).execute(any()); inOrder.verify(computationStep1).getDescription(); inOrder.verify(taskInterrupter).check(Thread.currentThread()); inOrder.verify(computationStep2).execute(any()); inOrder.verify(computationStep2).getDescription(); inOrder.verify(taskInterrupter).check(Thread.currentThread()); inOrder.verify(computationStep3).execute(any()); inOrder.verify(computationStep3).getDescription(); inOrder.verifyNoMoreInteractions(); } private void runInOtherThread(Runnable r) throws Throwable { Throwable[] otherThreadException = new Throwable[1]; Thread t = new Thread(() -> { try { r.run(); } catch (Throwable e) { otherThreadException[0] = e; } }); t.start(); t.join(); if (otherThreadException[0] != null) { throw otherThreadException[0]; } } private static ComputationSteps mockComputationSteps(ComputationStep... computationSteps) { ComputationSteps steps = mock(ComputationSteps.class); when(steps.instances()).thenReturn(Arrays.asList(computationSteps)); return steps; } private static ComputationStep mockComputationStep(String desc) { ComputationStep mock = mock(ComputationStep.class); when(mock.getDescription()).thenReturn(desc); return mock; } private static class StepWithStatistics implements ComputationStep { private final String description; private final String[] statistics; private StepWithStatistics(String description, String... statistics) { this.description = description; this.statistics = statistics; } @Override public void execute(Context context) { for (int i = 0; i < statistics.length; i += 2) { context.getStatistics().add(statistics[i], statistics[i + 1]); } } @Override public String getDescription() { return description; } } }
13,583
41.055728
161
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/step/ExecuteStatelessInitExtensionsStepTest.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.step; import org.junit.Test; import org.mockito.InOrder; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; public class ExecuteStatelessInitExtensionsStepTest { @Test public void test_getDescription() { ExecuteStatelessInitExtensionsStep underTest = new ExecuteStatelessInitExtensionsStep(); assertThat(underTest.getDescription()).isEqualTo("Initialize"); } @Test public void do_nothing_if_no_extensions() { ExecuteStatelessInitExtensionsStep underTest = new ExecuteStatelessInitExtensionsStep(); // no failure underTest.execute(new TestComputationStepContext()); } @Test public void execute_extensions() { StatelessInitExtension ext1 = mock(StatelessInitExtension.class); StatelessInitExtension ext2 = mock(StatelessInitExtension.class); ExecuteStatelessInitExtensionsStep underTest = new ExecuteStatelessInitExtensionsStep( new StatelessInitExtension[] {ext1, ext2}); underTest.execute(new TestComputationStepContext()); InOrder inOrder = inOrder(ext1, ext2); inOrder.verify(ext1).onInit(); inOrder.verify(ext2).onInit(); } @Test public void fail_if_an_extension_throws_an_exception() { StatelessInitExtension ext1 = mock(StatelessInitExtension.class); StatelessInitExtension ext2 = mock(StatelessInitExtension.class); doThrow(new IllegalStateException("BOOM")).when(ext2).onInit(); StatelessInitExtension ext3 = mock(StatelessInitExtension.class); ExecuteStatelessInitExtensionsStep underTest = new ExecuteStatelessInitExtensionsStep( new StatelessInitExtension[] {ext1, ext2, ext3}); try { underTest.execute(new TestComputationStepContext()); fail(); } catch (IllegalStateException e) { assertThat(e).hasMessage("BOOM"); verify(ext1).onInit(); verify(ext3, never()).onInit(); } } }
2,970
33.546512
92
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/test/java/org/sonar/ce/task/taskprocessor/MutableTaskResultHolderImplTest.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.taskprocessor; import org.assertj.core.api.Assertions; import org.junit.Test; import org.sonar.ce.task.CeTaskResult; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; public class MutableTaskResultHolderImplTest { private MutableTaskResultHolder underTest = new MutableTaskResultHolderImpl(); @Test public void getResult_throws_ISE_if_no_CeTaskResult_is_set() { assertThatThrownBy(() -> underTest.getResult()) .isInstanceOf(IllegalStateException.class) .hasMessage("No CeTaskResult has been set in the holder"); } @Test public void getResult_returns_object_set_with_setResult() { CeTaskResult taskResult = mock(CeTaskResult.class); underTest.setResult(taskResult); Assertions.assertThat(underTest.getResult()).isSameAs(taskResult); } @Test public void setResult_throws_NPE_if_CeTaskResult_argument_is_null() { assertThatThrownBy(() -> underTest.setResult(null)) .isInstanceOf(NullPointerException.class) .hasMessage("taskResult can not be null"); } @Test public void setResult_throws_ISE_if_called_twice() { underTest.setResult(mock(CeTaskResult.class)); assertThatThrownBy(() -> underTest.setResult(mock(CeTaskResult.class))) .isInstanceOf(IllegalStateException.class) .hasMessage("CeTaskResult has already been set in the holder"); } }
2,264
33.846154
80
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/testFixtures/java/org/sonar/ce/task/ChangeLogLevel.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; import org.sonar.api.utils.log.Logger; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.api.utils.log.Loggers; public final class ChangeLogLevel implements AutoCloseable { private final Logger logger; private final LoggerLevel previous; public ChangeLogLevel(Class<?> clazz, LoggerLevel newLevel) { this.logger = Loggers.get(clazz); this.previous = logger.getLevel(); logger.setLevel(newLevel); } @Override public void close() { logger.setLevel(previous); } }
1,376
32.585366
75
java
sonarqube
sonarqube-master/server/sonar-ce-task/src/testFixtures/java/org/sonar/ce/task/step/TestComputationStepContext.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.step; import java.util.HashMap; import java.util.Map; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkArgument; import static java.util.Objects.requireNonNull; import static org.assertj.core.api.Assertions.assertThat; /** * Implementation of {@link ComputationStep.Context} for unit tests. */ public class TestComputationStepContext implements ComputationStep.Context { private final TestStatistics statistics = new TestStatistics(); @Override public TestStatistics getStatistics() { return statistics; } public static class TestStatistics implements ComputationStep.Statistics { private final Map<String, Object> map = new HashMap<>(); @Override public ComputationStep.Statistics add(String key, Object value) { requireNonNull(key, "Statistic has null key"); requireNonNull(value, () -> String.format("Statistic with key [%s] has null value", key)); checkArgument(!key.equalsIgnoreCase("time"), "Statistic with key [time] is not accepted"); checkArgument(!map.containsKey(key), "Statistic with key [%s] is already present", key); map.put(key, value); return this; } public Map<String, Object> getAll() { return map; } public Object get(String key) { return requireNonNull(map.get(key)); } public TestStatistics assertValue(String key, @Nullable Object expectedValue) { if (expectedValue == null) { assertThat(map.get(key)).as(key).isNull(); } else { assertThat(map.get(key)).as(key).isEqualTo(expectedValue); } return this; } } }
2,498
33.232877
96
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/analysis/cache/cleaning/AnalysisCacheCleaningSchedulerImplIT.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.analysis.cache.cleaning; import java.io.ByteArrayInputStream; import java.time.LocalDateTime; import java.time.ZoneOffset; import org.junit.Rule; import org.junit.Test; import org.sonar.api.platform.Server; import org.sonar.api.utils.System2; import org.sonar.core.util.SequenceUuidFactory; import org.sonar.core.util.UuidFactory; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.component.SnapshotDto; import org.sonar.db.scannercache.ScannerAnalysisCacheDao; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.SECONDS; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; public class AnalysisCacheCleaningSchedulerImplIT { private System2 system2 = mock(System2.class); private final static UuidFactory uuidFactory = new SequenceUuidFactory(); @Rule public DbTester dbTester = DbTester.create(system2); private DbSession dbSession = dbTester.getSession(); private ScannerAnalysisCacheDao scannerAnalysisCacheDao = dbTester.getDbClient().scannerAnalysisCacheDao(); AnalysisCacheCleaningExecutorService executorService = mock(AnalysisCacheCleaningExecutorService.class); AnalysisCacheCleaningSchedulerImpl underTest = new AnalysisCacheCleaningSchedulerImpl(executorService, dbTester.getDbClient()); @Test public void startSchedulingOnServerStart() { underTest.onServerStart(mock(Server.class)); verify(executorService, times(1)).scheduleAtFixedRate(any(Runnable.class), anyLong(), eq(DAYS.toSeconds(1)), eq(SECONDS)); } @Test public void clean_data_older_than_7_days() { var snapshotDao = dbTester.getDbClient().snapshotDao(); var snapshot1 = createSnapshot(LocalDateTime.now().minusDays(1).toInstant(ZoneOffset.UTC).toEpochMilli()); snapshotDao.insert(dbSession, snapshot1); scannerAnalysisCacheDao.insert(dbSession, snapshot1.getRootComponentUuid(), new ByteArrayInputStream("data".getBytes())); var snapshot2 = createSnapshot(LocalDateTime.now().minusDays(6).toInstant(ZoneOffset.UTC).toEpochMilli()); snapshotDao.insert(dbSession, snapshot2); scannerAnalysisCacheDao.insert(dbSession, snapshot2.getRootComponentUuid(), new ByteArrayInputStream("data".getBytes())); var snapshot3 = createSnapshot(LocalDateTime.now().minusDays(8).toInstant(ZoneOffset.UTC).toEpochMilli()); snapshotDao.insert(dbSession, snapshot3); scannerAnalysisCacheDao.insert(dbSession, snapshot3.getRootComponentUuid(), new ByteArrayInputStream("data".getBytes())); var snapshot4 = createSnapshot(LocalDateTime.now().minusDays(30).toInstant(ZoneOffset.UTC).toEpochMilli()); snapshotDao.insert(dbSession, snapshot4); scannerAnalysisCacheDao.insert(dbSession, snapshot4.getRootComponentUuid(), new ByteArrayInputStream("data".getBytes())); assertThat(dbTester.countRowsOfTable("scanner_analysis_cache")).isEqualTo(4); underTest.clean(); assertThat(dbTester.countRowsOfTable("scanner_analysis_cache")).isEqualTo(2); assertThat(scannerAnalysisCacheDao.selectData(dbSession, snapshot1.getRootComponentUuid())).isNotNull(); assertThat(scannerAnalysisCacheDao.selectData(dbSession, snapshot2.getRootComponentUuid())).isNotNull(); assertThat(scannerAnalysisCacheDao.selectData(dbSession, snapshot3.getRootComponentUuid())).isNull(); assertThat(scannerAnalysisCacheDao.selectData(dbSession, snapshot4.getRootComponentUuid())).isNull(); } private static SnapshotDto createSnapshot(long buildtime) { return new SnapshotDto() .setUuid(uuidFactory.create()) .setRootComponentUuid(uuidFactory.create()) .setStatus("P") .setLast(true) .setProjectVersion("2.1-SNAPSHOT") .setPeriodMode("days1") .setPeriodParam("30") .setPeriodDate(buildtime) .setBuildDate(buildtime); } }
4,936
46.019048
129
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/container/ComputeEngineContainerImplIT.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.container; import com.google.common.collect.ImmutableSet; import java.io.File; import java.io.IOException; import java.util.Date; import java.util.Locale; import java.util.Properties; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang.StringUtils; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.sonar.api.CoreProperties; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.core.extension.ServiceLoaderWrapper; import org.sonar.db.DbTester; import org.sonar.db.property.PropertyDto; import org.sonar.process.ProcessId; import org.sonar.process.ProcessProperties; import org.sonar.process.Props; import org.sonar.server.property.InternalProperties; import org.springframework.context.annotation.AnnotationConfigApplicationContext; import static java.lang.String.valueOf; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.process.ProcessEntryPoint.PROPERTY_PROCESS_INDEX; import static org.sonar.process.ProcessEntryPoint.PROPERTY_SHARED_PATH; import static org.sonar.process.ProcessProperties.Property.JDBC_PASSWORD; import static org.sonar.process.ProcessProperties.Property.JDBC_URL; import static org.sonar.process.ProcessProperties.Property.JDBC_USERNAME; import static org.sonar.process.ProcessProperties.Property.PATH_DATA; import static org.sonar.process.ProcessProperties.Property.PATH_HOME; import static org.sonar.process.ProcessProperties.Property.PATH_TEMP; public class ComputeEngineContainerImplIT { @Rule public TemporaryFolder tempFolder = new TemporaryFolder(); @Rule public DbTester db = DbTester.create(System2.INSTANCE); private final ServiceLoaderWrapper serviceLoaderWrapper = mock(ServiceLoaderWrapper.class); private final ProcessProperties processProperties = new ProcessProperties(serviceLoaderWrapper); private final ComputeEngineContainerImpl underTest = new ComputeEngineContainerImpl(); @Before public void setUp() { when(serviceLoaderWrapper.load()).thenReturn(ImmutableSet.of()); underTest.setComputeEngineStatus(mock(ComputeEngineStatus.class)); } @Test public void constructor_does_not_create_container() { assertThat(underTest.getComponentContainer()).isNull(); } @Test public void test_real_start() throws IOException { Properties properties = getProperties(); // required persisted properties insertProperty(CoreProperties.SERVER_ID, "a_server_id"); insertProperty(CoreProperties.SERVER_STARTTIME, DateUtils.formatDateTime(new Date())); insertInternalProperty(InternalProperties.SERVER_ID_CHECKSUM, DigestUtils.sha256Hex("a_server_id|" + cleanJdbcUrl())); underTest.start(new Props(properties)); AnnotationConfigApplicationContext context = underTest.getComponentContainer().context(); try { assertThat(context.getBeanDefinitionNames()).hasSizeGreaterThan(1); assertThat(context.getParent().getBeanDefinitionNames()).hasSizeGreaterThan(1); assertThat(context.getParent().getParent().getBeanDefinitionNames()).hasSizeGreaterThan(1); assertThat(context.getParent().getParent().getParent().getBeanDefinitionNames()).hasSizeGreaterThan(1); assertThat(context.getParent().getParent().getParent().getParent()).isNull(); } finally { underTest.stop(); } assertThat(context.isActive()).isFalse(); } private String cleanJdbcUrl() { return StringUtils.lowerCase(StringUtils.substringBefore(db.getUrl(), "?"), Locale.ENGLISH); } private Properties getProperties() throws IOException { Properties properties = new Properties(); Props props = new Props(properties); processProperties.completeDefaults(props); properties = props.rawProperties(); File homeDir = tempFolder.newFolder(); File dataDir = new File(homeDir, "data"); dataDir.mkdirs(); File tmpDir = new File(homeDir, "tmp"); tmpDir.mkdirs(); properties.setProperty(PATH_HOME.getKey(), homeDir.getAbsolutePath()); properties.setProperty(PATH_DATA.getKey(), dataDir.getAbsolutePath()); properties.setProperty(PATH_TEMP.getKey(), tmpDir.getAbsolutePath()); properties.setProperty(PROPERTY_PROCESS_INDEX, valueOf(ProcessId.COMPUTE_ENGINE.getIpcIndex())); properties.setProperty(PROPERTY_SHARED_PATH, tmpDir.getAbsolutePath()); properties.setProperty(JDBC_URL.getKey(), db.getUrl()); properties.setProperty(JDBC_USERNAME.getKey(), "sonar"); properties.setProperty(JDBC_PASSWORD.getKey(), "sonar"); return properties; } private void insertProperty(String key, String value) { PropertyDto dto = new PropertyDto().setKey(key).setValue(value); db.getDbClient().propertiesDao().saveProperty(db.getSession(), dto, null, null, null, null); db.commit(); } private void insertInternalProperty(String key, String value) { db.getDbClient().internalPropertiesDao().save(db.getSession(), key, value); db.commit(); } }
5,955
40.65035
122
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/monitoring/CeDatabaseMBeanImplIT.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.monitoring; import java.lang.management.ManagementFactory; import javax.annotation.CheckForNull; import javax.management.InstanceNotFoundException; import javax.management.ObjectInstance; import javax.management.ObjectName; import org.junit.BeforeClass; import org.junit.Rule; import org.junit.Test; import org.sonar.api.utils.System2; import org.sonar.db.DbTester; import org.sonar.process.Jmx; import org.sonar.process.systeminfo.protobuf.ProtobufSystemInfo; import static org.assertj.core.api.Assertions.assertThat; public class CeDatabaseMBeanImplIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final CeDatabaseMBeanImpl underTest = new CeDatabaseMBeanImpl(dbTester.getDbClient()); @BeforeClass public static void beforeClass() { // if any other class starts a container where CeDatabaseMBeanImpl is added, it will have been registered Jmx.unregister("SonarQube:name=ComputeEngineDatabaseConnection"); } @Test public void register_and_unregister() throws Exception { assertThat(getMBean()).isNull(); underTest.start(); assertThat(getMBean()).isNotNull(); underTest.stop(); assertThat(getMBean()).isNull(); } @Test public void export_system_info() { ProtobufSystemInfo.Section section = underTest.toProtobuf(); assertThat(section.getName()).isEqualTo("Compute Engine Database Connection"); assertThat(section.getAttributesCount()).isEqualTo(7); assertThat(section.getAttributes(0).getKey()).isEqualTo("Pool Total Connections"); assertThat(section.getAttributes(0).getLongValue()).isPositive(); } @CheckForNull private ObjectInstance getMBean() throws Exception { try { return ManagementFactory.getPlatformMBeanServer().getObjectInstance(new ObjectName("SonarQube:name=ComputeEngineDatabaseConnection")); } catch (InstanceNotFoundException e) { return null; } } }
2,776
34.151899
140
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/notification/ReportAnalysisFailureNotificationExecutionListenerIT.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.notification; import java.time.Duration; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Optional; import java.util.Random; import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.sonar.api.notifications.Notification; import org.sonar.api.resources.Qualifiers; import org.sonar.api.utils.System2; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotification; import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotificationBuilder; import org.sonar.ce.task.projectanalysis.notification.ReportAnalysisFailureNotificationSerializer; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.RowNotFoundException; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ComponentTesting; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.server.notification.NotificationService; import static java.util.Collections.singleton; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.db.component.ComponentTesting.newDirectory; public class ReportAnalysisFailureNotificationExecutionListenerIT { @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); private final Random random = new Random(); private final DbClient dbClient = dbTester.getDbClient(); private final NotificationService notificationService = mock(NotificationService.class); private final ReportAnalysisFailureNotificationSerializer serializer = mock(ReportAnalysisFailureNotificationSerializer.class); private final System2 system2 = mock(System2.class); private final DbClient dbClientMock = mock(DbClient.class); private final CeTask ceTaskMock = mock(CeTask.class); private final Throwable throwableMock = mock(Throwable.class); private final CeTaskResult ceTaskResultMock = mock(CeTaskResult.class); private final ReportAnalysisFailureNotificationExecutionListener fullMockedUnderTest = new ReportAnalysisFailureNotificationExecutionListener( notificationService, dbClientMock, serializer, system2); private final ReportAnalysisFailureNotificationExecutionListener underTest = new ReportAnalysisFailureNotificationExecutionListener( notificationService, dbClient, serializer, system2); @Test public void onStart_has_no_effect() { CeTask mockedCeTask = mock(CeTask.class); fullMockedUnderTest.onStart(mockedCeTask); verifyNoInteractions(mockedCeTask, notificationService, dbClientMock, serializer, system2); } @Test public void onEnd_has_no_effect_if_status_is_SUCCESS() { fullMockedUnderTest.onEnd(ceTaskMock, CeActivityDto.Status.SUCCESS, randomDuration(), ceTaskResultMock, throwableMock); verifyNoInteractions(ceTaskMock, ceTaskResultMock, throwableMock, notificationService, dbClientMock, serializer, system2); } @Test public void onEnd_has_no_effect_if_CeTask_type_is_not_report() { when(ceTaskMock.getType()).thenReturn(randomAlphanumeric(12)); fullMockedUnderTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); verifyNoInteractions(ceTaskResultMock, throwableMock, notificationService, dbClientMock, serializer, system2); } @Test public void onEnd_has_no_effect_if_CeTask_has_no_component_uuid() { when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); fullMockedUnderTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); verifyNoInteractions(ceTaskResultMock, throwableMock, notificationService, dbClientMock, serializer, system2); } @Test public void onEnd_has_no_effect_if_there_is_no_subscriber_for_ReportAnalysisFailureNotification_type() { ProjectData projectData = dbTester.components().insertPrivateProject(); when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(projectData.getMainBranchDto().getUuid(), null, null))); when(notificationService.hasProjectSubscribersForTypes(projectData.projectUuid(), singleton(ReportAnalysisFailureNotification.class))) .thenReturn(false); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); verifyNoInteractions(ceTaskResultMock, throwableMock, serializer, system2); } @Test public void onEnd_fails_with_ISE_if_project_does_not_exist_in_DB() { BranchDto branchDto = dbTester.components().insertProjectBranch(new ProjectDto().setUuid("uuid").setKee("kee").setName("name")); String componentUuid = branchDto.getUuid(); when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(componentUuid, null, null))); when(notificationService.hasProjectSubscribersForTypes(branchDto.getProjectUuid(), singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); Duration randomDuration = randomDuration(); assertThatThrownBy(() -> underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration, ceTaskResultMock, throwableMock)) .isInstanceOf(IllegalStateException.class) .hasMessage("Could not find project uuid " + branchDto.getProjectUuid()); } @Test public void onEnd_fails_with_ISE_if_branch_does_not_exist_in_DB() { String componentUuid = randomAlphanumeric(6); ProjectDto project = new ProjectDto().setUuid(componentUuid).setKey(randomAlphanumeric(5)).setQualifier(Qualifiers.PROJECT); dbTester.getDbClient().projectDao().insert(dbTester.getSession(), project); dbTester.getSession().commit(); when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(componentUuid, null, null))); when(notificationService.hasProjectSubscribersForTypes(componentUuid, singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); Duration randomDuration = randomDuration(); assertThatThrownBy(() -> underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration, ceTaskResultMock, throwableMock)) .isInstanceOf(IllegalStateException.class) .hasMessage("Could not find a branch with uuid " + componentUuid); } @Test public void onEnd_fails_with_IAE_if_component_is_not_a_branch() { when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); ComponentDto mainBranch = dbTester.components().insertPrivateProject().getMainBranchComponent(); ComponentDto directory = dbTester.components().insertComponent(newDirectory(mainBranch, randomAlphanumeric(12))); ComponentDto file = dbTester.components().insertComponent(ComponentTesting.newFileDto(mainBranch)); ComponentDto view = dbTester.components().insertComponent(ComponentTesting.newPortfolio()); ComponentDto subView = dbTester.components().insertComponent(ComponentTesting.newSubPortfolio(view)); ComponentDto projectCopy = dbTester.components().insertComponent(ComponentTesting.newProjectCopy(mainBranch, subView)); ComponentDto application = dbTester.components().insertComponent(ComponentTesting.newApplication()); Arrays.asList(directory, file, view, subView, projectCopy, application) .forEach(component -> { when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(component.uuid(), null, null))); when(notificationService.hasProjectSubscribersForTypes(component.uuid(), singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); Duration randomDuration = randomDuration(); try { underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration, ceTaskResultMock, throwableMock); fail("An IllegalArgumentException should have been thrown for component " + component); } catch (IllegalStateException e) { assertThat(e.getMessage()).isIn("Could not find project uuid " + component.uuid(), "Could not find a branch with uuid " + component.uuid()); } }); } @Test public void onEnd_fails_with_RowNotFoundException_if_activity_for_task_does_not_exist_in_DB() { ProjectData projectData = dbTester.components().insertPrivateProject(); ComponentDto mainBranch = projectData.getMainBranchComponent(); String taskUuid = randomAlphanumeric(6); when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); when(ceTaskMock.getUuid()).thenReturn(taskUuid); when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(mainBranch.uuid(), null, null))); when(notificationService.hasProjectSubscribersForTypes(projectData.projectUuid(), singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); Duration randomDuration = randomDuration(); assertThatThrownBy(() -> underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration, ceTaskResultMock, throwableMock)) .isInstanceOf(RowNotFoundException.class) .hasMessage("CeActivity with uuid '" + taskUuid + "' not found"); } @Test public void onEnd_creates_notification_with_data_from_activity_and_project_and_deliver_it() { String taskUuid = randomAlphanumeric(12); int createdAt = random.nextInt(999_999); long executedAt = random.nextInt(999_999); ProjectData project = initMocksToPassConditions(taskUuid, createdAt, executedAt); Notification notificationMock = mockSerializer(); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); verify(notificationService).deliver(same(notificationMock)); ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); ReportAnalysisFailureNotificationBuilder.Project notificationProject = reportAnalysisFailureNotificationBuilder.project(); assertThat(notificationProject.name()).isEqualTo(project.getProjectDto().getName()); assertThat(notificationProject.key()).isEqualTo(project.getProjectDto().getKey()); assertThat(notificationProject.uuid()).isEqualTo(project.getProjectDto().getUuid()); assertThat(notificationProject.branchName()).isNull(); ReportAnalysisFailureNotificationBuilder.Task notificationTask = reportAnalysisFailureNotificationBuilder.task(); assertThat(notificationTask.uuid()).isEqualTo(taskUuid); assertThat(notificationTask.createdAt()).isEqualTo(createdAt); assertThat(notificationTask.failedAt()).isEqualTo(executedAt); } @Test public void onEnd_shouldCreateNotificationWithDataFromActivity_whenNonMainBranchIsFailing() { String taskUuid = randomAlphanumeric(12); int createdAt = random.nextInt(999_999); long executedAt = random.nextInt(999_999); ProjectData project = random.nextBoolean() ? dbTester.components().insertPrivateProject() : dbTester.components().insertPublicProject(); ComponentDto branchComponent = dbTester.components().insertProjectBranch(project.getMainBranchComponent(), b->b.setKey("otherbranch")); initMocksToPassConditionsForBranch(branchComponent, project, taskUuid, createdAt, executedAt); Notification notificationMock = mockSerializer(); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); verify(notificationService).deliver(same(notificationMock)); ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); ReportAnalysisFailureNotificationBuilder.Project notificationProject = reportAnalysisFailureNotificationBuilder.project(); assertThat(notificationProject.name()).isEqualTo(project.getProjectDto().getName()); assertThat(notificationProject.key()).isEqualTo(project.getProjectDto().getKey()); assertThat(notificationProject.uuid()).isEqualTo(project.getProjectDto().getUuid()); assertThat(notificationProject.branchName()).isEqualTo("otherbranch"); ReportAnalysisFailureNotificationBuilder.Task notificationTask = reportAnalysisFailureNotificationBuilder.task(); assertThat(notificationTask.uuid()).isEqualTo(taskUuid); assertThat(notificationTask.createdAt()).isEqualTo(createdAt); assertThat(notificationTask.failedAt()).isEqualTo(executedAt); } @Test public void onEnd_creates_notification_with_error_message_from_Throwable_argument_message() { initMocksToPassConditions(randomAlphanumeric(12), random.nextInt(999_999), (long) random.nextInt(999_999)); String message = randomAlphanumeric(66); when(throwableMock.getMessage()).thenReturn(message); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, throwableMock); ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); assertThat(reportAnalysisFailureNotificationBuilder.errorMessage()).isEqualTo(message); } @Test public void onEnd_creates_notification_with_null_error_message_if_Throwable_is_null() { String taskUuid = randomAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999)); Notification notificationMock = mockSerializer(); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, null); verify(notificationService).deliver(same(notificationMock)); ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); ReportAnalysisFailureNotificationBuilder reportAnalysisFailureNotificationBuilder = notificationCaptor.getValue(); assertThat(reportAnalysisFailureNotificationBuilder.errorMessage()).isNull(); } @Test public void onEnd_ignores_null_CeTaskResult_argument() { String taskUuid = randomAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999)); Notification notificationMock = mockSerializer(); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), null, null); verify(notificationService).deliver(same(notificationMock)); } @Test public void onEnd_ignores_CeTaskResult_argument() { String taskUuid = randomAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), (long) random.nextInt(999_999)); Notification notificationMock = mockSerializer(); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, null); verify(notificationService).deliver(same(notificationMock)); verifyNoInteractions(ceTaskResultMock); } @Test public void onEnd_uses_system_data_as_failedAt_if_task_has_no_executedAt() { String taskUuid = randomAlphanumeric(12); initMocksToPassConditions(taskUuid, random.nextInt(999_999), null); long now = random.nextInt(999_999); when(system2.now()).thenReturn(now); Notification notificationMock = mockSerializer(); underTest.onEnd(ceTaskMock, CeActivityDto.Status.FAILED, randomDuration(), ceTaskResultMock, null); verify(notificationService).deliver(same(notificationMock)); ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = verifyAndCaptureSerializedNotification(); assertThat(notificationCaptor.getValue().task().failedAt()).isEqualTo(now); } private ReportAnalysisFailureNotification mockSerializer() { ReportAnalysisFailureNotification notificationMock = mock(ReportAnalysisFailureNotification.class); when(serializer.toNotification(any(ReportAnalysisFailureNotificationBuilder.class))).thenReturn(notificationMock); return notificationMock; } private ProjectData initMocksToPassConditions(String taskUuid, int createdAt, @Nullable Long executedAt) { ProjectData projectData = random.nextBoolean() ? dbTester.components().insertPrivateProject() : dbTester.components().insertPublicProject(); mockCeTask(taskUuid, createdAt, executedAt, projectData, projectData.getMainBranchComponent()); return projectData; } private ComponentDto initMocksToPassConditionsForBranch(ComponentDto branchComponent, ProjectData projectData, String taskUuid, int createdAt, @Nullable Long executedAt) { mockCeTask(taskUuid, createdAt, executedAt, projectData, branchComponent); return branchComponent; } private void mockCeTask(String taskUuid, int createdAt, @org.jetbrains.annotations.Nullable Long executedAt, ProjectData projectData, ComponentDto branchComponent) { when(ceTaskMock.getType()).thenReturn(CeTaskTypes.REPORT); when(ceTaskMock.getComponent()).thenReturn(Optional.of(new CeTask.Component(branchComponent.uuid(), null, null))); when(ceTaskMock.getUuid()).thenReturn(taskUuid); when(notificationService.hasProjectSubscribersForTypes(projectData.projectUuid(), singleton(ReportAnalysisFailureNotification.class))) .thenReturn(true); insertActivityDto(taskUuid, createdAt, executedAt, branchComponent); } private void insertActivityDto(String taskUuid, int createdAt, @Nullable Long executedAt, ComponentDto branch) { dbClient.ceActivityDao().insert(dbTester.getSession(), new CeActivityDto(new CeQueueDto() .setUuid(taskUuid) .setTaskType(CeTaskTypes.REPORT) .setComponentUuid(branch.uuid()) .setCreatedAt(createdAt)) .setExecutedAt(executedAt) .setStatus(CeActivityDto.Status.FAILED)); dbTester.getSession().commit(); } private ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> verifyAndCaptureSerializedNotification() { ArgumentCaptor<ReportAnalysisFailureNotificationBuilder> notificationCaptor = ArgumentCaptor.forClass(ReportAnalysisFailureNotificationBuilder.class); verify(serializer).toNotification(notificationCaptor.capture()); return notificationCaptor; } private Duration randomDuration() { return Duration.of(random.nextLong(), ChronoUnit.MILLIS); } }
19,978
51.71504
173
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/queue/InternalCeQueueImplIT.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.queue; import com.google.common.collect.ImmutableSet; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.ce.container.ComputeEngineStatus; import org.sonar.ce.monitoring.CEQueueStatus; import org.sonar.ce.monitoring.CEQueueStatusImpl; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; import org.sonar.ce.task.TypedException; import org.sonar.core.util.UuidFactory; import org.sonar.core.util.UuidFactoryImpl; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeQueueTesting; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.BranchDto; import org.sonar.db.component.ComponentDto; import org.sonar.db.component.ProjectData; import org.sonar.db.project.ProjectDto; import org.sonar.db.user.UserDto; import org.sonar.server.platform.NodeInformation; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; import static org.sonar.ce.container.ComputeEngineStatus.Status.STARTED; import static org.sonar.ce.container.ComputeEngineStatus.Status.STOPPING; public class InternalCeQueueImplIT { private static final String AN_ANALYSIS_UUID = "U1"; private static final String WORKER_UUID_1 = "worker uuid 1"; private static final String WORKER_UUID_2 = "worker uuid 2"; private static final String NODE_NAME = "nodeName1"; private final System2 system2 = new AlwaysIncreasingSystem2(); @Rule public DbTester db = DbTester.create(system2); private final DbSession session = db.getSession(); private final UuidFactory uuidFactory = UuidFactoryImpl.INSTANCE; private final CEQueueStatus queueStatus = new CEQueueStatusImpl(db.getDbClient(), mock(System2.class)); private final ComputeEngineStatus computeEngineStatus = mock(ComputeEngineStatus.class); private final Configuration config = mock(Configuration.class); private final NextPendingTaskPicker nextPendingTaskPicker = new NextPendingTaskPicker(config, db.getDbClient()); private final NodeInformation nodeInformation = mock(NodeInformation.class); private final InternalCeQueue underTest = new InternalCeQueueImpl(system2, db.getDbClient(), uuidFactory, queueStatus, computeEngineStatus, nextPendingTaskPicker, nodeInformation); @Before public void setUp() { when(config.getBoolean(any())).thenReturn(Optional.of(false)); when(computeEngineStatus.getStatus()).thenReturn(STARTED); when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME)); } @Test public void submit_returns_task_populated_from_CeTaskSubmit_and_creates_CeQueue_row() { CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, "entity", "component", "rob"); CeTask task = underTest.submit(taskSubmit); UserDto userDto = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit.getSubmitterUuid()); verifyCeTask(taskSubmit, task, null, userDto); verifyCeQueueDtoForTaskSubmit(taskSubmit); } @Test public void submit_populates_component_name_and_key_of_CeTask_if_component_exists() { ProjectData projectData = newProject("PROJECT_1"); CeTaskSubmit taskSubmit = createTaskSubmit(CeTaskTypes.REPORT, projectData, null); CeTask task = underTest.submit(taskSubmit); verifyCeTask(taskSubmit, task, projectData.getMainBranchComponent(), null); } @Test public void submit_returns_task_without_component_info_when_submit_has_none() { CeTaskSubmit taskSubmit = createTaskSubmit("not cpt related"); CeTask task = underTest.submit(taskSubmit); verifyCeTask(taskSubmit, task, null, null); } @Test public void massSubmit_returns_tasks_for_each_CeTaskSubmit_populated_from_CeTaskSubmit_and_creates_CeQueue_row_for_each() { CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, "entity", "component", "rob"); CeTaskSubmit taskSubmit2 = createTaskSubmit("some type"); List<CeTask> tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2)); UserDto userDto1 = db.getDbClient().userDao().selectByUuid(db.getSession(), taskSubmit1.getSubmitterUuid()); assertThat(tasks).hasSize(2); verifyCeTask(taskSubmit1, tasks.get(0), null, userDto1); verifyCeTask(taskSubmit2, tasks.get(1), null, null); verifyCeQueueDtoForTaskSubmit(taskSubmit1); verifyCeQueueDtoForTaskSubmit(taskSubmit2); } @Test public void massSubmit_populates_component_name_and_key_of_CeTask_if_component_exists() { ProjectData project = newProject("PROJECT_1"); CeTaskSubmit taskSubmit1 = createTaskSubmit(CeTaskTypes.REPORT, project, null); CeTaskSubmit taskSubmit2 = createTaskSubmit("something", project.projectUuid(), "non-existing", null); List<CeTask> tasks = underTest.massSubmit(asList(taskSubmit1, taskSubmit2)); assertThat(tasks).hasSize(2); verifyCeTask(taskSubmit1, tasks.get(0), project.getMainBranchComponent(), null); verifyCeTask(taskSubmit2, tasks.get(1), null, null); } @Test public void peek_throws_NPE_if_workerUUid_is_null() { assertThatThrownBy(() -> underTest.peek(null, true)) .isInstanceOf(NullPointerException.class) .hasMessage("workerUuid can't be null"); } @Test public void test_remove() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); underTest.remove(peek.get(), CeActivityDto.Status.SUCCESS, null, null); // queue is empty assertThat(db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid())).isNotPresent(); assertThat(underTest.peek(WORKER_UUID_2, true)).isNotPresent(); // available in history Optional<CeActivityDto> history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(history).isPresent(); assertThat(history.get().getStatus()).isEqualTo(CeActivityDto.Status.SUCCESS); assertThat(history.get().getIsLast()).isTrue(); assertThat(history.get().getAnalysisUuid()).isNull(); } @Test public void remove_throws_IAE_if_exception_is_provided_but_status_is_SUCCESS() { assertThatThrownBy(() -> underTest.remove(mock(CeTask.class), CeActivityDto.Status.SUCCESS, null, new RuntimeException("Some error"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Error can be provided only when status is FAILED"); } @Test public void remove_throws_IAE_if_exception_is_provided_but_status_is_CANCELED() { assertThatThrownBy(() -> underTest.remove(mock(CeTask.class), CeActivityDto.Status.CANCELED, null, new RuntimeException("Some error"))) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Error can be provided only when status is FAILED"); } @Test public void remove_does_not_set_analysisUuid_in_CeActivity_when_CeTaskResult_has_no_analysis_uuid() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); underTest.remove(peek.get(), CeActivityDto.Status.SUCCESS, newTaskResult(null), null); // available in history Optional<CeActivityDto> history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(history).isPresent(); assertThat(history.get().getAnalysisUuid()).isNull(); } @Test public void remove_sets_analysisUuid_in_CeActivity_when_CeTaskResult_has_analysis_uuid() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_2, true); underTest.remove(peek.get(), CeActivityDto.Status.SUCCESS, newTaskResult(AN_ANALYSIS_UUID), null); // available in history Optional<CeActivityDto> history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(history).isPresent(); assertThat(history.get().getAnalysisUuid()).isEqualTo("U1"); } @Test public void remove_sets_nodeName_in_CeActivity_when_nodeInformation_defines_node_name() { when(nodeInformation.getNodeName()).thenReturn(Optional.of(NODE_NAME)); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_2, true); underTest.remove(peek.get(), CeActivityDto.Status.SUCCESS, newTaskResult(AN_ANALYSIS_UUID), null); Optional<CeActivityDto> history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(history).isPresent(); assertThat(history.get().getNodeName()).isEqualTo(NODE_NAME); } @Test public void remove_do_not_set_nodeName_in_CeActivity_when_nodeInformation_does_not_define_node_name() { when(nodeInformation.getNodeName()).thenReturn(Optional.empty()); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_2, true); underTest.remove(peek.get(), CeActivityDto.Status.SUCCESS, newTaskResult(AN_ANALYSIS_UUID), null); Optional<CeActivityDto> history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(history).isPresent(); assertThat(history.get().getNodeName()).isNull(); } @Test public void remove_saves_error_message_and_stacktrace_when_exception_is_provided() { Throwable error = new NullPointerException("Fake NPE to test persistence to DB"); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); underTest.remove(peek.get(), CeActivityDto.Status.FAILED, null, error); Optional<CeActivityDto> activityDto = db.getDbClient().ceActivityDao().selectByUuid(session, task.getUuid()); assertThat(activityDto).isPresent(); assertThat(activityDto.get().getErrorMessage()).isEqualTo(error.getMessage()); assertThat(activityDto.get().getErrorStacktrace()).isEqualToIgnoringWhitespace(stacktraceToString(error)); assertThat(activityDto.get().getErrorType()).isNull(); } @Test public void remove_saves_error_when_TypedMessageException_is_provided() { Throwable error = new TypedExceptionImpl("aType", "aMessage"); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); underTest.remove(peek.get(), CeActivityDto.Status.FAILED, null, error); CeActivityDto activityDto = db.getDbClient().ceActivityDao().selectByUuid(session, task.getUuid()).get(); assertThat(activityDto.getErrorType()).isEqualTo("aType"); assertThat(activityDto.getErrorMessage()).isEqualTo("aMessage"); assertThat(activityDto.getErrorStacktrace()).isEqualToIgnoringWhitespace(stacktraceToString(error)); } @Test public void remove_updates_queueStatus_success_even_if_task_does_not_exist_in_DB() { CEQueueStatus queueStatus = mock(CEQueueStatus.class); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); db.getDbClient().ceQueueDao().deleteByUuid(db.getSession(), task.getUuid()); db.commit(); InternalCeQueueImpl underTest = new InternalCeQueueImpl(system2, db.getDbClient(), null, queueStatus, null, null, nodeInformation); try { underTest.remove(task, CeActivityDto.Status.SUCCESS, null, null); fail("remove should have thrown a IllegalStateException"); } catch (IllegalStateException e) { verify(queueStatus).addSuccess(anyLong()); } } @Test public void remove_updates_queueStatus_failure_even_if_task_does_not_exist_in_DB() { CEQueueStatus queueStatusMock = mock(CEQueueStatus.class); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); db.getDbClient().ceQueueDao().deleteByUuid(db.getSession(), task.getUuid()); db.commit(); InternalCeQueueImpl underTest = new InternalCeQueueImpl(system2, db.getDbClient(), null, queueStatusMock, null, null, nodeInformation); try { underTest.remove(task, CeActivityDto.Status.FAILED, null, null); fail("remove should have thrown a IllegalStateException"); } catch (IllegalStateException e) { verify(queueStatusMock).addError(anyLong()); } } @Test public void cancelWornOuts_does_not_update_queueStatus() { CEQueueStatus queueStatusMock = mock(CEQueueStatus.class); CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); db.executeUpdateSql("update ce_queue set status = 'PENDING', started_at = 123 where uuid = '" + task.getUuid() + "'"); db.commit(); InternalCeQueueImpl underTest = new InternalCeQueueImpl(system2, db.getDbClient(), null, queueStatusMock, null, null, nodeInformation); underTest.cancelWornOuts(); Optional<CeActivityDto> ceActivityDto = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(ceActivityDto).isPresent(); assertThat(ceActivityDto.get().getNodeName()).isEqualTo(NODE_NAME); verifyNoInteractions(queueStatusMock); } private static class TypedExceptionImpl extends RuntimeException implements TypedException { private final String type; private TypedExceptionImpl(String type, String message) { super(message); this.type = type; } @Override public String getType() { return type; } } @Test public void remove_copies_workerUuid() { CeQueueDto ceQueueDto = db.getDbClient().ceQueueDao().insert(session, new CeQueueDto() .setUuid("uuid") .setTaskType("foo") .setStatus(CeQueueDto.Status.PENDING)); makeInProgress(ceQueueDto, "Dustin"); db.commit(); underTest.remove(new CeTask.Builder() .setUuid("uuid") .setType("bar") .build(), CeActivityDto.Status.SUCCESS, null, null); CeActivityDto dto = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), "uuid").get(); assertThat(dto.getWorkerUuid()).isEqualTo("Dustin"); } @Test public void fail_to_remove_if_not_in_queue() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); underTest.remove(task, CeActivityDto.Status.SUCCESS, null, null); assertThatThrownBy(() -> underTest.remove(task, CeActivityDto.Status.SUCCESS, null, null)) .isInstanceOf(IllegalStateException.class); } @Test public void test_peek() { ProjectData projectData = newProject("PROJECT_1"); ComponentDto mainBranchComponent = projectData.getMainBranchComponent(); CeTask task = submit(CeTaskTypes.REPORT, projectData); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); assertThat(peek).isPresent(); assertThat(peek.get().getUuid()).isEqualTo(task.getUuid()); assertThat(peek.get().getType()).isEqualTo(CeTaskTypes.REPORT); assertThat(peek.get().getComponent()).contains(new CeTask.Component(mainBranchComponent.uuid(), mainBranchComponent.getKey(), mainBranchComponent.name())); assertThat(peek.get().getEntity()).contains(new CeTask.Component(projectData.getProjectDto().getUuid(), projectData.getProjectDto().getKey(), projectData.getProjectDto().getName())); // no more pending tasks peek = underTest.peek(WORKER_UUID_2, true); assertThat(peek).isEmpty(); } @Test public void peek_populates_name_and_key_for_existing_component_and_main_component() { ProjectDto project = db.components().insertPrivateProject().getProjectDto(); BranchDto branch = db.components().insertProjectBranch(project); CeTask task = submit(CeTaskTypes.REPORT, branch); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); assertThat(peek).isPresent(); assertThat(peek.get().getUuid()).isEqualTo(task.getUuid()); assertThat(peek.get().getType()).isEqualTo(CeTaskTypes.REPORT); assertThat(peek.get().getComponent()).contains(new CeTask.Component(branch.getUuid(), project.getKey(), project.getName())); assertThat(peek.get().getEntity()).contains(new CeTask.Component(project.getUuid(), project.getKey(), project.getName())); // no more pending tasks peek = underTest.peek(WORKER_UUID_2, true); assertThat(peek).isEmpty(); } @Test public void peek_is_paused_then_resumed() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); underTest.pauseWorkers(); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); assertThat(peek).isEmpty(); underTest.resumeWorkers(); peek = underTest.peek(WORKER_UUID_1, true); assertThat(peek).isPresent(); assertThat(peek.get().getUuid()).isEqualTo(task.getUuid()); } @Test public void peek_ignores_in_progress_tasks() { CeQueueDto dto = db.getDbClient().ceQueueDao().insert(session, new CeQueueDto() .setUuid("uuid") .setTaskType("foo") .setStatus(CeQueueDto.Status.PENDING)); makeInProgress(dto, "foo"); db.commit(); assertThat(underTest.peek(WORKER_UUID_1, true)).isEmpty(); } @Test public void peek_nothing_if_application_status_stopping() { submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); when(computeEngineStatus.getStatus()).thenReturn(STOPPING); Optional<CeTask> peek = underTest.peek(WORKER_UUID_1, true); assertThat(peek).isEmpty(); } @Test public void peek_peeks_pending_task() { db.getDbClient().ceQueueDao().insert(session, new CeQueueDto() .setUuid("uuid") .setTaskType("foo") .setStatus(CeQueueDto.Status.PENDING)); db.commit(); assertThat(underTest.peek(WORKER_UUID_1, true).get().getUuid()).isEqualTo("uuid"); } @Test public void peek_resets_to_pending_any_task_in_progress_for_specified_worker_uuid_and_updates_updatedAt() { insertPending("u0"); // add a pending one that will be picked so that u1 isn't peek and status reset is visible in DB CeQueueDto u1 = insertPending("u1");// will be picked-because older than any of the reset ones CeQueueDto u2 = insertInProgress("u2", WORKER_UUID_1);// will be reset assertThat(underTest.peek(WORKER_UUID_1, true).get().getUuid()).isEqualTo("u0"); verifyUnmodifiedTask(u1); verifyResetTask(u2); } @Test public void peek_resets_to_pending_any_task_in_progress_for_specified_worker_uuid_and_only_this_uuid() { insertPending("u0"); // add a pending one that will be picked so that u1 isn't peek and status reset is visible in DB CeQueueDto u1 = insertInProgress("u1", WORKER_UUID_1); CeQueueDto u2 = insertInProgress("u2", WORKER_UUID_2); CeQueueDto u3 = insertInProgress("u3", WORKER_UUID_1); CeQueueDto u4 = insertInProgress("u4", WORKER_UUID_2); assertThat(underTest.peek(WORKER_UUID_1, true).get().getUuid()).isEqualTo("u0"); verifyResetTask(u1); verifyUnmodifiedTask(u2); verifyResetTask(u3); verifyUnmodifiedTask(u4); } private void verifyResetTask(CeQueueDto originalDto) { CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(session, originalDto.getUuid()).get(); assertThat(dto.getStatus()).isEqualTo(CeQueueDto.Status.PENDING); assertThat(dto.getCreatedAt()).isEqualTo(originalDto.getCreatedAt()); assertThat(dto.getUpdatedAt()).isGreaterThan(originalDto.getUpdatedAt()); } private void verifyUnmodifiedTask(CeQueueDto originalDto) { CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(session, originalDto.getUuid()).get(); assertThat(dto.getStatus()).isEqualTo(originalDto.getStatus()); assertThat(dto.getCreatedAt()).isEqualTo(originalDto.getCreatedAt()); assertThat(dto.getUpdatedAt()).isEqualTo(originalDto.getUpdatedAt()); } private CeQueueDto insertInProgress(String uuid, String workerUuid) { CeQueueDto dto = new CeQueueDto() .setUuid(uuid) .setTaskType("foo") .setStatus(CeQueueDto.Status.PENDING); db.getDbClient().ceQueueDao().insert(session, dto); makeInProgress(dto, workerUuid); db.commit(); return db.getDbClient().ceQueueDao().selectByUuid(session, uuid).get(); } private CeQueueDto insertPending(String uuid) { CeQueueDto dto = new CeQueueDto() .setUuid(uuid) .setTaskType("foo") .setStatus(CeQueueDto.Status.PENDING); db.getDbClient().ceQueueDao().insert(session, dto); db.commit(); return dto; } @Test public void cancel_pending() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); underTest.cancel(db.getSession(), queueDto); Optional<CeActivityDto> activity = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), task.getUuid()); assertThat(activity).isPresent(); assertThat(activity.get().getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); } @Test public void fail_to_cancel_if_in_progress() { CeTask task = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); underTest.peek(WORKER_UUID_2, true); CeQueueDto queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), task.getUuid()).get(); assertThatThrownBy(() -> underTest.cancel(db.getSession(), queueDto)) .isInstanceOf(IllegalStateException.class) .hasMessageContaining("Task is in progress and can't be canceled"); } @Test public void cancelAll_pendings_but_not_in_progress() { CeTask inProgressTask = submit(CeTaskTypes.REPORT, newProject("PROJECT_1")); CeTask pendingTask1 = submit(CeTaskTypes.REPORT, newProject("PROJECT_2")); CeTask pendingTask2 = submit(CeTaskTypes.REPORT, newProject("PROJECT_3")); underTest.peek(WORKER_UUID_2, true); int canceledCount = underTest.cancelAll(); assertThat(canceledCount).isEqualTo(2); Optional<CeActivityDto> history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), pendingTask1.getUuid()); assertThat(history.get().getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), pendingTask2.getUuid()); assertThat(history.get().getStatus()).isEqualTo(CeActivityDto.Status.CANCELED); history = db.getDbClient().ceActivityDao().selectByUuid(db.getSession(), inProgressTask.getUuid()); assertThat(history).isEmpty(); } @Test public void resetTasksWithUnknownWorkerUUIDs_reset_only_in_progress_tasks() { CeQueueDto u1 = insertCeQueueDto("u1"); CeQueueDto u2 = insertCeQueueDto("u2"); CeQueueDto u6 = insertInProgress("u6", "worker1"); CeQueueDto u7 = insertInProgress("u7", "worker2"); CeQueueDto u8 = insertInProgress("u8", "worker3"); underTest.resetTasksWithUnknownWorkerUUIDs(ImmutableSet.of("worker2", "worker3")); // Pending tasks must not be modified even if a workerUUID is not present verifyUnmodified(u1); verifyUnmodified(u2); // Unknown worker : null, "worker1" verifyReset(u6); // Known workers : "worker2", "worker3" verifyUnmodified(u7); verifyUnmodified(u8); } @Test public void resetTasksWithUnknownWorkerUUIDs_with_empty_set_will_reset_all_in_progress_tasks() { CeQueueDto u1 = insertCeQueueDto("u1"); CeQueueDto u2 = insertCeQueueDto("u2"); CeQueueDto u6 = insertInProgress("u6", "worker1"); CeQueueDto u7 = insertInProgress("u7", "worker2"); CeQueueDto u8 = insertInProgress("u8", "worker3"); underTest.resetTasksWithUnknownWorkerUUIDs(ImmutableSet.of()); // Pending tasks must not be modified even if a workerUUID is not present verifyUnmodified(u1); verifyUnmodified(u2); // Unknown worker : null, "worker1" verifyReset(u6); verifyReset(u7); verifyReset(u8); } @Test public void resetTasksWithUnknownWorkerUUIDs_with_worker_without_tasks_will_reset_all_in_progress_tasks() { CeQueueDto u1 = insertCeQueueDto("u1"); CeQueueDto u2 = insertCeQueueDto("u2"); CeQueueDto u6 = insertInProgress("u6", "worker1"); CeQueueDto u7 = insertInProgress("u7", "worker2"); CeQueueDto u8 = insertInProgress("u8", "worker3"); underTest.resetTasksWithUnknownWorkerUUIDs(ImmutableSet.of("worker1000", "worker1001")); // Pending tasks must not be modified even if a workerUUID is not present verifyUnmodified(u1); verifyUnmodified(u2); // Unknown worker : null, "worker1" verifyReset(u6); verifyReset(u7); verifyReset(u8); } private void verifyReset(CeQueueDto original) { CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), original.getUuid()).get(); // We do not touch CreatedAt assertThat(dto.getCreatedAt()).isEqualTo(original.getCreatedAt()); // Status must have changed to PENDING and must not be equal to previous status assertThat(dto.getStatus()).isEqualTo(CeQueueDto.Status.PENDING).isNotEqualTo(original.getStatus()); // UpdatedAt must have been updated assertThat(dto.getUpdatedAt()).isNotEqualTo(original.getUpdatedAt()); assertThat(dto.getStartedAt()).isEqualTo(original.getStartedAt()); // WorkerUuid must be null assertThat(dto.getWorkerUuid()).isNull(); } private void verifyUnmodified(CeQueueDto original) { CeQueueDto dto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), original.getUuid()).get(); assertThat(dto.getStatus()).isEqualTo(original.getStatus()); assertThat(dto.getCreatedAt()).isEqualTo(original.getCreatedAt()); assertThat(dto.getUpdatedAt()).isEqualTo(original.getUpdatedAt()); } private CeQueueDto insertCeQueueDto(String uuid) { CeQueueDto dto = new CeQueueDto() .setUuid(uuid) .setTaskType("foo") .setStatus(CeQueueDto.Status.PENDING); db.getDbClient().ceQueueDao().insert(db.getSession(), dto); db.commit(); return dto; } private void verifyCeTask(CeTaskSubmit taskSubmit, CeTask task, @Nullable ComponentDto componentDto, @Nullable UserDto userDto) { assertThat(task.getUuid()).isEqualTo(taskSubmit.getUuid()); assertThat(task.getType()).isEqualTo(taskSubmit.getType()); if (componentDto != null) { CeTask.Component component = task.getComponent().get(); assertThat(component.getUuid()).isEqualTo(componentDto.uuid()); assertThat(component.getKey()).contains(componentDto.getKey()); assertThat(component.getName()).contains(componentDto.name()); } else if (taskSubmit.getComponent().isPresent()) { assertThat(task.getComponent()).contains(new CeTask.Component(taskSubmit.getComponent().get().getUuid(), null, null)); } else { assertThat(task.getComponent()).isEmpty(); } if (taskSubmit.getSubmitterUuid() != null) { if (userDto == null) { assertThat(task.getSubmitter().uuid()).isEqualTo(taskSubmit.getSubmitterUuid()); assertThat(task.getSubmitter().login()).isNull(); } else { assertThat(task.getSubmitter().uuid()).isEqualTo(userDto.getUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); assertThat(task.getSubmitter().uuid()).isEqualTo(userDto.getLogin()); } } } private void verifyCeQueueDtoForTaskSubmit(CeTaskSubmit taskSubmit) { Optional<CeQueueDto> queueDto = db.getDbClient().ceQueueDao().selectByUuid(db.getSession(), taskSubmit.getUuid()); assertThat(queueDto).isPresent(); CeQueueDto dto = queueDto.get(); assertThat(dto.getTaskType()).isEqualTo(taskSubmit.getType()); Optional<CeTaskSubmit.Component> component = taskSubmit.getComponent(); if (component.isPresent()) { assertThat(dto.getEntityUuid()).isEqualTo(component.get().getEntityUuid()); assertThat(dto.getComponentUuid()).isEqualTo(component.get().getUuid()); } else { assertThat(dto.getEntityUuid()).isNull(); assertThat(dto.getComponentUuid()).isNull(); } assertThat(dto.getSubmitterUuid()).isEqualTo(taskSubmit.getSubmitterUuid()); assertThat(dto.getCreatedAt()).isEqualTo(dto.getUpdatedAt()); } private ProjectData newProject(String uuid) { return db.components().insertPublicProject(uuid); } private CeTask submit(String reportType, BranchDto branchDto) { return underTest.submit(createTaskSubmit(reportType, branchDto.getProjectUuid(), branchDto.getUuid(), null)); } private CeTask submit(String reportType, ProjectData projectData) { return underTest.submit(createTaskSubmit(reportType, projectData.getProjectDto().getUuid(), projectData.getMainBranchDto().getUuid(), null)); } private CeTaskSubmit createTaskSubmit(String type) { return createTaskSubmit(type, null, null, null); } private CeTaskSubmit createTaskSubmit(String type, ProjectData projectData, @Nullable String submitterUuid) { return createTaskSubmit(type, projectData.projectUuid(), projectData.getMainBranchDto().getUuid(), submitterUuid); } private CeTaskSubmit createTaskSubmit(String type, @Nullable String entityUuid, @Nullable String componentUuid, @Nullable String submitterUuid) { CeTaskSubmit.Builder builder = underTest.prepareSubmit() .setType(type) .setSubmitterUuid(submitterUuid) .setCharacteristics(emptyMap()); if (componentUuid != null && entityUuid != null) { builder.setComponent(CeTaskSubmit.Component.fromDto(componentUuid, entityUuid)); } return builder.build(); } private CeTaskResult newTaskResult(@Nullable String analysisUuid) { CeTaskResult taskResult = mock(CeTaskResult.class); when(taskResult.getAnalysisUuid()).thenReturn(java.util.Optional.ofNullable(analysisUuid)); return taskResult; } private CeQueueDto makeInProgress(CeQueueDto ceQueueDto, String workerUuid) { CeQueueTesting.makeInProgress(session, workerUuid, system2.now(), ceQueueDto); return db.getDbClient().ceQueueDao().selectByUuid(session, ceQueueDto.getUuid()).get(); } private static String stacktraceToString(Throwable error) { ByteArrayOutputStream out = new ByteArrayOutputStream(); error.printStackTrace(new PrintStream(out)); return out.toString(); } }
31,449
41.730978
186
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/queue/NextPendingTaskPickerIT.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.queue; import java.util.Optional; import java.util.UUID; import java.util.function.Consumer; import javax.annotation.Nullable; import org.jetbrains.annotations.NotNull; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.sonar.api.config.Configuration; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; import org.sonar.api.utils.System2; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.core.config.ComputeEngineProperties; import org.sonar.db.DbTester; import org.sonar.db.ce.CeQueueDto; import org.sonar.db.ce.CeTaskCharacteristicDto; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.component.ComponentDto; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.ce.CeQueueDto.Status.IN_PROGRESS; import static org.sonar.db.ce.CeQueueDto.Status.PENDING; import static org.sonar.db.ce.CeTaskCharacteristicDto.BRANCH_KEY; import static org.sonar.db.ce.CeTaskCharacteristicDto.PULL_REQUEST; public class NextPendingTaskPickerIT { private final System2 alwaysIncreasingSystem2 = new AlwaysIncreasingSystem2(1L, 1); private final Configuration config = mock(Configuration.class); @Rule public LogTester logTester = new LogTester(); private NextPendingTaskPicker underTest; @Rule public DbTester db = DbTester.create(alwaysIncreasingSystem2); @Before public void before() { underTest = new NextPendingTaskPicker(config, db.getDbClient()); when(config.getBoolean(ComputeEngineProperties.CE_PARALLEL_PROJECT_TASKS_ENABLED)).thenReturn(Optional.of(true)); } @Test public void findPendingTask_whenNoTasksPending_returnsEmpty() { Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isEmpty(); } @Test public void findPendingTask_whenTwoTasksPending_returnsTheOlderOne() { // both the 'eligibleTask' and 'parallelEligibleTask' will point to this one insertPending("1"); insertPending("2"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("1"); } @Test public void findPendingTask_whenTwoTasksPendingWithSameCreationDate_returnsLowestUuid() { insertPending("d", c -> c.setCreatedAt(1L).setUpdatedAt(1L)); insertPending("c", c -> c.setCreatedAt(1L).setUpdatedAt(1L)); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("c"); } @Test public void findPendingTask_givenBranchInProgressAndPropertySet_returnQueuedPR() { insertInProgress("1"); insertPendingPullRequest("2"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("2"); assertThat(logTester.logs()).contains("Task [uuid = " + ceQueueDto.get().getUuid() + "] will be run concurrently with other tasks for the same project"); } @Test public void findPendingTask_givenBranchInProgressAndPropertyNotSet_dontReturnQueuedPR() { when(config.getBoolean(ComputeEngineProperties.CE_PARALLEL_PROJECT_TASKS_ENABLED)).thenReturn(Optional.of(false)); insertInProgress("1"); insertPendingPullRequest("2"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isEmpty(); } @Test public void findPendingTask_given2PRsQueued_returnBothQueuedPR() { insertPendingPullRequest("1"); insertPendingPullRequest("2"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); Optional<CeQueueDto> ceQueueDto2 = underTest.findPendingTask("workerUuid2", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto2).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("1"); assertThat(ceQueueDto.get().getStatus()).isEqualTo(IN_PROGRESS); assertThat(ceQueueDto2.get().getStatus()).isEqualTo(IN_PROGRESS); } @Test public void findPendingTask_given1MainBranch_2PRsQueued_returnMainBranchAndPRs() { insertPending("1"); insertPendingPullRequest("2"); insertPendingPullRequest("3"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); Optional<CeQueueDto> ceQueueDto2 = underTest.findPendingTask("workerUuid2", db.getSession(), true); Optional<CeQueueDto> ceQueueDto3 = underTest.findPendingTask("workerUuid3", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto2).isPresent(); assertThat(ceQueueDto3).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("1"); assertThat(ceQueueDto.get().getStatus()).isEqualTo(IN_PROGRESS); assertThat(ceQueueDto2.get().getUuid()).isEqualTo("2"); assertThat(ceQueueDto2.get().getStatus()).isEqualTo(IN_PROGRESS); assertThat(ceQueueDto3.get().getUuid()).isEqualTo("3"); assertThat(ceQueueDto3.get().getStatus()).isEqualTo(IN_PROGRESS); } @Test public void findPendingTask_given1MainBranch_2BranchesQueued_returnOnyMainBranch() { insertPending("1", null); insertPendingBranch("2"); insertPendingBranch("3"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); Optional<CeQueueDto> ceQueueDto2 = underTest.findPendingTask("workerUuid2", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto2).isEmpty(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("1"); assertThat(ceQueueDto.get().getStatus()).isEqualTo(IN_PROGRESS); } @Test public void findPendingTask_given2BranchesQueued_returnOnlyFirstQueuedBranch() { insertPending("1"); insertPendingBranch("2"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); Optional<CeQueueDto> ceQueueDto2 = underTest.findPendingTask("workerUuid2", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto2).isEmpty(); assertThat(ceQueueDto.get().getStatus()).isEqualTo(IN_PROGRESS); } @Test public void findPendingTask_given2SamePRsQueued_returnOnlyFirstQueuedPR() { insertPendingPullRequest("1", c -> c.setComponentUuid("pr1")); insertPendingPullRequest("2", c -> c.setComponentUuid("pr1")); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); Optional<CeQueueDto> ceQueueDto2 = underTest.findPendingTask("workerUuid2", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto2).isEmpty(); assertThat(ceQueueDto.get().getStatus()).isEqualTo(IN_PROGRESS); } @Test public void findPendingTask_givenBranchInTheQueueOlderThanPrInTheQueue_dontJumpAheadOfBranch() { // we have branch task in progress. Next branch task needs to wait for this one to finish. We dont allow PRs to jump ahead of this branch insertInProgress("1"); insertPending("2"); insertPendingPullRequest("3"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isEmpty(); } @Test public void findPendingTask_givenDifferentProjectAndPrInTheQueue_dontJumpAheadOfDifferentProject() { // we have branch task in progress. insertInProgress("1"); // The PR can run in parallel, but needs to wait for this other project to finish. We dont allow PRs to jump ahead insertPending("2", c -> c.setEntityUuid("different project")); insertPendingPullRequest("3"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("2"); } @Test public void findPendingTask_givenDifferentProjectAndPrInTheQueue_prCanRunFirst() { // we have branch task in progress. insertInProgress("1"); // The PR can run in parallel and is ahead of the other project insertPendingPullRequest("2"); insertPending("3", c -> c.setEntityUuid("different project")); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("2"); } @Test public void findPendingTask_givenFivePrsInProgress_branchCanBeScheduled() { insertInProgressPullRequest("1"); insertInProgressPullRequest("2"); insertInProgressPullRequest("3"); insertInProgressPullRequest("4"); insertInProgressPullRequest("5"); insertPending("6"); Optional<CeQueueDto> ceQueueDto = underTest.findPendingTask("workerUuid", db.getSession(), true); assertThat(ceQueueDto).isPresent(); assertThat(ceQueueDto.get().getUuid()).isEqualTo("6"); } @Test public void findPendingTask_excludingViewPickUpOrphanBranches() { insertPending("1", dto -> dto .setComponentUuid("1") .setEntityUuid("non-existing-uuid") .setStatus(PENDING) .setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC) .setCreatedAt(100_000L)); Optional<CeQueueDto> peek = underTest.findPendingTask("1", db.getSession(), false); assertThat(peek).isPresent(); assertThat(peek.get().getUuid()).isEqualTo("1"); } @Test public void exclude_portfolios_computation_when_indexing_issues() { String taskUuid1 = "1", taskUuid2 = "2"; String branchUuid = "1"; insertBranch(branchUuid); insertPending(taskUuid1, dto -> dto .setComponentUuid(branchUuid) .setEntityUuid("entity_uuid") .setStatus(PENDING) .setTaskType(CeTaskTypes.BRANCH_ISSUE_SYNC) .setCreatedAt(100_000L)); String view_uuid = "view_uuid"; insertView(view_uuid); insertPending(taskUuid2, dto -> dto .setComponentUuid(view_uuid) .setEntityUuid(view_uuid) .setStatus(PENDING) .setTaskType(CeTaskTypes.REPORT) .setCreatedAt(100_000L)); Optional<CeQueueDto> peek = underTest.findPendingTask("1", db.getSession(), false); assertThat(peek).isPresent(); assertThat(peek.get().getUuid()).isEqualTo(taskUuid1); Optional<CeQueueDto> peek2 = underTest.findPendingTask("1", db.getSession(), false); assertThat(peek2).isPresent(); assertThat(peek2.get().getUuid()).isEqualTo(taskUuid2); } private CeQueueDto insertPending(String uuid) { return insertPending(uuid, null); } private CeQueueDto insertPendingBranch(String uuid) { CeQueueDto queue = insertPending(uuid, null); insertCharacteristics(queue.getUuid(), BRANCH_KEY); return queue; } private CeQueueDto insertPendingPullRequest(String uuid) { return insertPendingPullRequest(uuid, null); } private CeQueueDto insertPendingPullRequest(String uuid, @Nullable Consumer<CeQueueDto> ceQueueDto) { CeQueueDto queue = insertPending(uuid, ceQueueDto); insertCharacteristics(queue.getUuid(), PULL_REQUEST); return queue; } private CeQueueDto insertInProgressPullRequest(String uuid) { CeQueueDto queue = insertInProgress(uuid, null); insertCharacteristics(queue.getUuid(), PULL_REQUEST); return queue; } private CeQueueDto insertInProgress(String uuid) { return insertInProgress(uuid, null); } private CeQueueDto insertInProgress(String uuid, @Nullable Consumer<CeQueueDto> ceQueueDto) { return insertTask(uuid, IN_PROGRESS, ceQueueDto); } private CeQueueDto insertPending(String uuid, @Nullable Consumer<CeQueueDto> ceQueueDto) { return insertTask(uuid, PENDING, ceQueueDto); } private CeTaskCharacteristicDto insertCharacteristics(String taskUuid, String branchType) { var ctcDto = new CeTaskCharacteristicDto(); ctcDto.setUuid(UUID.randomUUID().toString()); ctcDto.setTaskUuid(taskUuid); ctcDto.setKey(branchType); ctcDto.setValue("value"); db.getDbClient().ceTaskCharacteristicsDao().insert(db.getSession(), ctcDto); db.getSession().commit(); return ctcDto; } private CeQueueDto insertTask(String uuid, CeQueueDto.Status status, @Nullable Consumer<CeQueueDto> ceQueueDtoConsumer) { CeQueueDto dto = createCeQueue(uuid, status, ceQueueDtoConsumer); db.getDbClient().ceQueueDao().insert(db.getSession(), dto); db.getSession().commit(); return dto; } @NotNull private static CeQueueDto createCeQueue(String uuid, CeQueueDto.Status status, @Nullable Consumer<CeQueueDto> ceQueueDtoConsumer) { CeQueueDto dto = new CeQueueDto(); dto.setUuid(uuid); dto.setTaskType(CeTaskTypes.REPORT); dto.setStatus(status); dto.setSubmitterUuid("henri"); dto.setComponentUuid(UUID.randomUUID().toString()); dto.setEntityUuid("1"); if (ceQueueDtoConsumer != null) { ceQueueDtoConsumer.accept(dto); } return dto; } private void insertView(String view_uuid) { ComponentDto view = new ComponentDto(); view.setQualifier("VW"); view.setKey(view_uuid + "_key"); view.setUuid(view_uuid); view.setPrivate(false); view.setUuidPath("uuid_path"); view.setBranchUuid(view_uuid); db.components().insertPortfolioAndSnapshot(view); db.commit(); } private void insertBranch(String uuid) { ComponentDto branch = new ComponentDto(); branch.setQualifier("TRK"); branch.setKey(uuid + "_key"); branch.setUuid(uuid); branch.setPrivate(false); branch.setUuidPath("uuid_path"); branch.setBranchUuid(uuid); db.components().insertComponent(branch); db.commit(); } }
14,705
37.197403
157
java
sonarqube
sonarqube-master/server/sonar-ce/src/it/java/org/sonar/ce/taskprocessor/CeWorkerImplIT.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.taskprocessor; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; import javax.annotation.Nullable; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.InOrder; import org.mockito.stubbing.Answer; import org.slf4j.event.Level; import org.sonar.api.impl.utils.TestSystem2; import org.sonar.api.testfixtures.log.LogAndArguments; import org.sonar.api.testfixtures.log.LogTester; import org.sonar.api.utils.MessageException; import org.sonar.api.utils.System2; import org.sonar.api.utils.log.LoggerLevel; import org.sonar.ce.queue.InternalCeQueue; import org.sonar.ce.task.CeTask; import org.sonar.ce.task.CeTaskResult; import org.sonar.ce.task.projectanalysis.taskprocessor.ReportTaskProcessor; import org.sonar.ce.task.taskprocessor.CeTaskProcessor; import org.sonar.db.DbSession; import org.sonar.db.DbTester; import org.sonar.db.ce.CeActivityDto; import org.sonar.db.ce.CeTaskTypes; import org.sonar.db.user.UserDto; import org.sonar.db.user.UserTesting; 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.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.reset; 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.taskprocessor.CeWorker.Result.DISABLED; import static org.sonar.ce.taskprocessor.CeWorker.Result.NO_TASK; import static org.sonar.ce.taskprocessor.CeWorker.Result.TASK_PROCESSED; public class CeWorkerImplIT { private System2 system2 = new TestSystem2().setNow(1_450_000_000_000L); @Rule public CeTaskProcessorRepositoryRule taskProcessorRepository = new CeTaskProcessorRepositoryRule(); @Rule public LogTester logTester = new LogTester(); @Rule public DbTester db = DbTester.create(system2); private DbSession session = db.getSession(); private InternalCeQueue queue = mock(InternalCeQueue.class); private ReportTaskProcessor taskProcessor = mock(ReportTaskProcessor.class); private CeWorker.ExecutionListener executionListener1 = mock(CeWorker.ExecutionListener.class); private CeWorker.ExecutionListener executionListener2 = mock(CeWorker.ExecutionListener.class); private CeWorkerController ceWorkerController = mock(CeWorkerController.class); private ArgumentCaptor<String> workerUuidCaptor = ArgumentCaptor.forClass(String.class); private int randomOrdinal = new Random().nextInt(50); private String workerUuid = UUID.randomUUID().toString(); private CeWorker underTest = new CeWorkerImpl(randomOrdinal, workerUuid, queue, taskProcessorRepository, ceWorkerController, executionListener1, executionListener2); private CeWorker underTestNoListener = new CeWorkerImpl(randomOrdinal, workerUuid, queue, taskProcessorRepository, ceWorkerController); private InOrder inOrder = inOrder(taskProcessor, queue, executionListener1, executionListener2); private final CeTask.User submitter = new CeTask.User("UUID_USER_1", "LOGIN_1"); @Before public void setUp() { when(ceWorkerController.isEnabled(any(CeWorker.class))).thenReturn(true); } @Test public void constructor_throws_IAE_if_ordinal_is_less_than_zero() { assertThatThrownBy(() -> new CeWorkerImpl(-1 - new Random().nextInt(20), workerUuid, queue, taskProcessorRepository, ceWorkerController)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Ordinal must be >= 0"); } @Test public void getUUID_must_return_the_uuid_of_constructor() { String uuid = UUID.randomUUID().toString(); CeWorker underTest = new CeWorkerImpl(randomOrdinal, uuid, queue, taskProcessorRepository, ceWorkerController); assertThat(underTest.getUUID()).isEqualTo(uuid); } @Test public void worker_disabled() throws Exception { reset(ceWorkerController); when(ceWorkerController.isEnabled(underTest)).thenReturn(false); assertThat(underTest.call()).isEqualTo(DISABLED); verifyNoInteractions(taskProcessor, executionListener1, executionListener2); } @Test public void worker_disabled_no_listener() throws Exception { reset(ceWorkerController); when(ceWorkerController.isEnabled(underTest)).thenReturn(false); assertThat(underTestNoListener.call()).isEqualTo(DISABLED); verifyNoInteractions(taskProcessor, executionListener1, executionListener2); } @Test public void no_pending_tasks_in_queue() throws Exception { when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.empty()); assertThat(underTest.call()).isEqualTo(NO_TASK); verifyNoInteractions(taskProcessor, executionListener1, executionListener2); } @Test public void no_pending_tasks_in_queue_without_listener() throws Exception { when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.empty()); assertThat(underTestNoListener.call()).isEqualTo(NO_TASK); verifyNoInteractions(taskProcessor, executionListener1, executionListener2); } @Test public void fail_when_no_CeTaskProcessor_is_found_in_repository() throws Exception { CeTask task = createCeTask(null); taskProcessorRepository.setNoProcessorForTask(CeTaskTypes.REPORT); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(task)); assertThat(underTest.call()).isEqualTo(TASK_PROCESSED); verifyWorkerUuid(); inOrder.verify(executionListener1).onStart(task); inOrder.verify(executionListener2).onStart(task); inOrder.verify(queue).remove(task, CeActivityDto.Status.FAILED, null, null); inOrder.verify(executionListener1).onEnd(eq(task), eq(CeActivityDto.Status.FAILED), any(), isNull(), isNull()); inOrder.verify(executionListener2).onEnd(eq(task), eq(CeActivityDto.Status.FAILED), any(), isNull(), isNull()); } @Test public void fail_when_no_CeTaskProcessor_is_found_in_repository_without_listener() throws Exception { CeTask task = createCeTask(null); taskProcessorRepository.setNoProcessorForTask(CeTaskTypes.REPORT); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(task)); assertThat(underTestNoListener.call()).isEqualTo(TASK_PROCESSED); verifyWorkerUuid(); inOrder.verify(queue).remove(task, CeActivityDto.Status.FAILED, null, null); inOrder.verifyNoMoreInteractions(); } @Test public void peek_and_process_task() throws Exception { CeTask task = createCeTask(null); taskProcessorRepository.setProcessorForTask(task.getType(), taskProcessor); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(task)); assertThat(underTest.call()).isEqualTo(TASK_PROCESSED); verifyWorkerUuid(); inOrder.verify(executionListener1).onStart(task); inOrder.verify(executionListener2).onStart(task); inOrder.verify(taskProcessor).process(task); inOrder.verify(queue).remove(task, CeActivityDto.Status.SUCCESS, null, null); inOrder.verify(executionListener1).onEnd(eq(task), eq(CeActivityDto.Status.SUCCESS), any(), isNull(), isNull()); inOrder.verify(executionListener2).onEnd(eq(task), eq(CeActivityDto.Status.SUCCESS), any(), isNull(), isNull()); } @Test public void peek_and_process_task_without_listeners() throws Exception { CeTask task = createCeTask(null); taskProcessorRepository.setProcessorForTask(task.getType(), taskProcessor); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(task)); assertThat(underTestNoListener.call()).isEqualTo(TASK_PROCESSED); verifyWorkerUuid(); inOrder.verify(taskProcessor).process(task); inOrder.verify(queue).remove(task, CeActivityDto.Status.SUCCESS, null, null); inOrder.verifyNoMoreInteractions(); } @Test public void fail_to_process_task() throws Exception { CeTask task = createCeTask(null); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(task)); taskProcessorRepository.setProcessorForTask(task.getType(), taskProcessor); Throwable error = makeTaskProcessorFail(task); assertThat(underTest.call()).isEqualTo(TASK_PROCESSED); verifyWorkerUuid(); inOrder.verify(executionListener1).onStart(task); inOrder.verify(executionListener2).onStart(task); inOrder.verify(taskProcessor).process(task); inOrder.verify(queue).remove(task, CeActivityDto.Status.FAILED, null, error); inOrder.verify(executionListener1).onEnd(eq(task), eq(CeActivityDto.Status.FAILED), any(), isNull(), eq(error)); inOrder.verify(executionListener2).onEnd(eq(task), eq(CeActivityDto.Status.FAILED), any(), isNull(), eq(error)); } @Test public void fail_to_process_task_without_listeners() throws Exception { CeTask task = createCeTask(null); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(task)); taskProcessorRepository.setProcessorForTask(task.getType(), taskProcessor); Throwable error = makeTaskProcessorFail(task); assertThat(underTestNoListener.call()).isEqualTo(TASK_PROCESSED); verifyWorkerUuid(); inOrder.verify(taskProcessor).process(task); inOrder.verify(queue).remove(task, CeActivityDto.Status.FAILED, null, error); inOrder.verifyNoMoreInteractions(); } @Test public void log_task_characteristics() throws Exception { when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(createCeTask(null, "pullRequest", "123", "branch", "foo"))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); for (int i = 0; i < 2; i++) { assertThat(logs.get(i)).contains("pullRequest=123"); assertThat(logs.get(i)).contains("branch=foo"); } } @Test public void do_not_log_submitter_param_if_anonymous_and_success() throws Exception { when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(createCeTask(null))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); for (int i = 0; i < 2; i++) { assertThat(logs.get(i)).doesNotContain("submitter="); } } @Test public void do_not_log_submitter_param_if_anonymous_and_error() throws Exception { CeTask ceTask = createCeTask(null); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(ceTask.getType(), taskProcessor); makeTaskProcessorFail(ceTask); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).doesNotContain("submitter="); assertThat(logs.get(1)).doesNotContain("submitter="); logs = logTester.logs(Level.ERROR); assertThat(logs).hasSize(1); assertThat(logs.iterator().next()).doesNotContain("submitter="); assertThat(logTester.logs(Level.DEBUG)).isEmpty(); } @Test public void log_submitter_login_if_authenticated_and_success() throws Exception { UserDto userDto = insertRandomUser(); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(createCeTask(toTaskSubmitter(userDto)))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(String.format("submitter=%s", userDto.getLogin())); assertThat(logs.get(1)).contains(String.format("submitter=%s | status=SUCCESS | time=", userDto.getLogin())); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.DEBUG)).isEmpty(); } @Test public void log_submitterUuid_if_user_matching_submitterUuid_can_not_be_found() throws Exception { when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(createCeTask(new CeTask.User("UUID_USER", null)))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains("submitter=UUID_USER"); assertThat(logs.get(1)).contains("submitter=UUID_USER | status=SUCCESS | time="); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.DEBUG)).isEmpty(); } @Test public void display_submitterLogin_in_logs_when_set_in_case_of_error() throws Exception { UserDto userDto = insertRandomUser(); CeTask ceTask = createCeTask(toTaskSubmitter(userDto)); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(ceTask.getType(), taskProcessor); makeTaskProcessorFail(ceTask); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(String.format("submitter=%s", userDto.getLogin())); assertThat(logs.get(1)).contains(String.format("submitter=%s | status=FAILED | time=", userDto.getLogin())); logs = logTester.logs(Level.ERROR); assertThat(logs).hasSize(1); assertThat(logs.get(0)).isEqualTo("Failed to execute task " + ceTask.getUuid()); } @Test public void display_start_stop_at_debug_level_for_console_if_DEBUG_is_enabled_and_task_successful() throws Exception { logTester.setLevel(LoggerLevel.DEBUG); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(createCeTask(submitter))); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=SUCCESS | time=", submitter.login())); assertThat(logTester.logs(Level.ERROR)).isEmpty(); assertThat(logTester.logs(Level.DEBUG)).isEmpty(); } @Test public void display_start_at_debug_level_stop_at_error_level_for_console_if_DEBUG_is_enabled_and_task_failed() throws Exception { logTester.setLevel(LoggerLevel.DEBUG); CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); makeTaskProcessorFail(ceTask); underTest.call(); verifyWorkerUuid(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); logs = logTester.logs(Level.ERROR); assertThat(logs).hasSize(1); assertThat(logs.iterator().next()).isEqualTo("Failed to execute task " + ceTask.getUuid()); assertThat(logTester.logs(Level.DEBUG)).isEmpty(); } @Test public void call_sets_and_restores_thread_name_with_information_of_worker_when_there_is_no_task_to_process() throws Exception { String threadName = randomAlphabetic(3); when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) .isEqualTo("Worker " + randomOrdinal + " (UUID=" + workerUuid + ") on " + threadName); return Optional.empty(); }); Thread newThread = createThreadNameVerifyingThread(threadName); newThread.start(); newThread.join(); } @Test public void call_sets_and_restores_thread_name_with_information_of_worker_when_a_task_is_processed() throws Exception { String threadName = randomAlphabetic(3); when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) .isEqualTo("Worker " + randomOrdinal + " (UUID=" + workerUuid + ") on " + threadName); return Optional.of(createCeTask(submitter)); }); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); Thread newThread = createThreadNameVerifyingThread(threadName); newThread.start(); newThread.join(); } @Test public void call_sets_and_restores_thread_name_with_information_of_worker_when_an_error_occurs() throws Exception { String threadName = randomAlphabetic(3); CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenAnswer(invocation -> { assertThat(Thread.currentThread().getName()) .isEqualTo("Worker " + randomOrdinal + " (UUID=" + workerUuid + ") on " + threadName); return Optional.of(ceTask); }); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); makeTaskProcessorFail(ceTask); Thread newThread = createThreadNameVerifyingThread(threadName); newThread.start(); newThread.join(); } @Test public void call_sets_and_restores_thread_name_with_information_of_worker_when_worker_is_disabled() throws Exception { reset(ceWorkerController); when(ceWorkerController.isEnabled(underTest)).thenReturn(false); String threadName = randomAlphabetic(3); Thread newThread = createThreadNameVerifyingThread(threadName); newThread.start(); newThread.join(); } @Test public void log_error_when_task_fails_with_not_MessageException() throws Exception { CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); makeTaskProcessorFail(ceTask); underTest.call(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); logs = logTester.logs(Level.ERROR); assertThat(logs).hasSize(1); assertThat(logs.iterator().next()).isEqualTo("Failed to execute task " + ceTask.getUuid()); } @Test public void do_no_log_error_when_task_fails_with_MessageException() throws Exception { CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); makeTaskProcessorFail(ceTask, MessageException.of("simulate MessageException thrown by TaskProcessor#process")); underTest.call(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(1)).contains(" | submitter=" + submitter.login()); assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); assertThat(logTester.logs(Level.ERROR)).isEmpty(); } @Test public void log_error_when_task_was_successful_but_ending_state_can_not_be_persisted_to_db() throws Exception { CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); doThrow(new RuntimeException("Simulate queue#remove failing")).when(queue).remove(ceTask, CeActivityDto.Status.SUCCESS, null, null); underTest.call(); assertThat(logTester.logs(Level.ERROR)).containsOnly("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db"); } @Test public void log_error_when_task_failed_and_ending_state_can_not_be_persisted_to_db() throws Exception { CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); IllegalStateException ex = makeTaskProcessorFail(ceTask); RuntimeException runtimeException = new RuntimeException("Simulate queue#remove failing"); doThrow(runtimeException).when(queue).remove(ceTask, CeActivityDto.Status.FAILED, null, ex); underTest.call(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); List<LogAndArguments> logAndArguments = logTester.getLogs(Level.ERROR); assertThat(logAndArguments).hasSize(2); LogAndArguments executionErrorLog = logAndArguments.get(0); assertThat(executionErrorLog.getFormattedMsg()).isEqualTo("Failed to execute task " + ceTask.getUuid()); LogAndArguments finalizingErrorLog = logAndArguments.get(1); assertThat(finalizingErrorLog.getFormattedMsg()).isEqualTo("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db"); } @Test public void log_error_as_suppressed_when_task_failed_with_MessageException_and_ending_state_can_not_be_persisted_to_db() throws Exception { CeTask ceTask = createCeTask(submitter); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(CeTaskTypes.REPORT, taskProcessor); MessageException ex = makeTaskProcessorFail(ceTask, MessageException.of("simulate MessageException thrown by TaskProcessor#process")); RuntimeException runtimeException = new RuntimeException("Simulate queue#remove failing"); doThrow(runtimeException).when(queue).remove(ceTask, CeActivityDto.Status.FAILED, null, ex); underTest.call(); List<String> logs = logTester.logs(Level.INFO); assertThat(logs).hasSize(2); assertThat(logs.get(0)).contains(" | submitter=" + submitter.login()); assertThat(logs.get(1)).contains(String.format(" | submitter=%s | status=FAILED | time=", submitter.login())); List<LogAndArguments> logAndArguments = logTester.getLogs(Level.ERROR); assertThat(logAndArguments).hasSize(1); assertThat(logAndArguments.get(0).getFormattedMsg()).isEqualTo("Failed to finalize task with uuid '" + ceTask.getUuid() + "' and persist its state to db"); } @Test public void isExecutedBy_returns_false_when_no_interaction_with_instance() { assertThat(underTest.isExecutedBy(Thread.currentThread())).isFalse(); assertThat(underTest.isExecutedBy(new Thread())).isFalse(); } @Test public void isExecutedBy_returns_false_unless_a_thread_is_currently_calling_call() throws InterruptedException { CountDownLatch inCallLatch = new CountDownLatch(1); CountDownLatch assertionsDoneLatch = new CountDownLatch(1); // mock long running peek(String) call => Thread is executing call() but not running a task when(queue.peek(anyString(), anyBoolean())).thenAnswer((Answer<Optional<CeTask>>) invocation -> { inCallLatch.countDown(); try { assertionsDoneLatch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } return Optional.empty(); }); Thread t = callCallInNewThread(underTest); try { t.start(); inCallLatch.await(10, TimeUnit.SECONDS); assertThat(underTest.isExecutedBy(Thread.currentThread())).isFalse(); assertThat(underTest.isExecutedBy(new Thread())).isFalse(); assertThat(underTest.isExecutedBy(t)).isTrue(); } finally { assertionsDoneLatch.countDown(); t.join(); } assertThat(underTest.isExecutedBy(Thread.currentThread())).isFalse(); assertThat(underTest.isExecutedBy(new Thread())).isFalse(); assertThat(underTest.isExecutedBy(t)).isFalse(); } @Test public void isExecutedBy_returns_false_unless_a_thread_is_currently_executing_a_task() throws InterruptedException { CountDownLatch inCallLatch = new CountDownLatch(1); CountDownLatch assertionsDoneLatch = new CountDownLatch(1); String taskType = randomAlphabetic(12); CeTask ceTask = mock(CeTask.class); when(ceTask.getType()).thenReturn(taskType); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(taskType, new SimpleCeTaskProcessor() { @CheckForNull @Override public CeTaskResult process(CeTask task) { inCallLatch.countDown(); try { assertionsDoneLatch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } return null; } }); Thread t = callCallInNewThread(underTest); try { t.start(); inCallLatch.await(10, TimeUnit.SECONDS); assertThat(underTest.isExecutedBy(Thread.currentThread())).isFalse(); assertThat(underTest.isExecutedBy(new Thread())).isFalse(); assertThat(underTest.isExecutedBy(t)).isTrue(); } finally { assertionsDoneLatch.countDown(); t.join(); } assertThat(underTest.isExecutedBy(Thread.currentThread())).isFalse(); assertThat(underTest.isExecutedBy(new Thread())).isFalse(); assertThat(underTest.isExecutedBy(t)).isFalse(); } @Test public void getCurrentTask_returns_empty_when_no_interaction_with_instance() { assertThat(underTest.getCurrentTask()).isEmpty(); } @Test public void do_not_exclude_portfolio_when_indexation_task_lookup_is_disabled() throws Exception { // first call with empty queue to disable indexationTaskLookupEnabled when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.empty()); assertThat(underTest.call()).isEqualTo(NO_TASK); // following calls should not exclude portfolios when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(createCeTask(submitter))); assertThat(underTest.call()).isEqualTo(TASK_PROCESSED); verify(queue, times(2)).peek(anyString(), anyBoolean()); } @Test public void getCurrentTask_returns_empty_when_a_thread_is_currently_calling_call_but_not_executing_a_task() throws InterruptedException { CountDownLatch inCallLatch = new CountDownLatch(1); CountDownLatch assertionsDoneLatch = new CountDownLatch(1); // mock long running peek(String) call => Thread is executing call() but not running a task when(queue.peek(anyString(), anyBoolean())).thenAnswer((Answer<Optional<CeTask>>) invocation -> { inCallLatch.countDown(); try { assertionsDoneLatch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } return Optional.empty(); }); Thread t = callCallInNewThread(underTest); try { t.start(); inCallLatch.await(10, TimeUnit.SECONDS); assertThat(underTest.getCurrentTask()).isEmpty(); } finally { assertionsDoneLatch.countDown(); t.join(); } assertThat(underTest.getCurrentTask()).isEmpty(); } @Test public void getCurrentTask_returns_empty_unless_a_thread_is_currently_executing_a_task() throws InterruptedException { CountDownLatch inCallLatch = new CountDownLatch(1); CountDownLatch assertionsDoneLatch = new CountDownLatch(1); String taskType = randomAlphabetic(12); CeTask ceTask = mock(CeTask.class); when(ceTask.getType()).thenReturn(taskType); when(queue.peek(anyString(), anyBoolean())).thenReturn(Optional.of(ceTask)); taskProcessorRepository.setProcessorForTask(taskType, new SimpleCeTaskProcessor() { @CheckForNull @Override public CeTaskResult process(CeTask task) { inCallLatch.countDown(); try { assertionsDoneLatch.await(10, TimeUnit.SECONDS); } catch (InterruptedException e) { throw new RuntimeException(e); } return null; } }); Thread t = callCallInNewThread(underTest); try { t.start(); inCallLatch.await(10, TimeUnit.SECONDS); assertThat(underTest.getCurrentTask()).contains(ceTask); } finally { assertionsDoneLatch.countDown(); t.join(); } assertThat(underTest.getCurrentTask()).isEmpty(); } private Thread callCallInNewThread(CeWorker underTest) { return new Thread(() -> { try { underTest.call(); } catch (Exception e) { throw new RuntimeException("call to call() failed and this is unexpected. Fix the UT.", e); } }); } private Thread createThreadNameVerifyingThread(String threadName) { return new Thread(() -> { verifyUnchangedThreadName(threadName); try { underTest.call(); } catch (Exception e) { throw new RuntimeException(e); } verifyUnchangedThreadName(threadName); }, threadName); } private void verifyUnchangedThreadName(String threadName) { assertThat(Thread.currentThread().getName()).isEqualTo(threadName); } private void verifyWorkerUuid() { verify(queue, atLeastOnce()).peek(workerUuidCaptor.capture(), anyBoolean()); assertThat(workerUuidCaptor.getValue()).isEqualTo(workerUuid); } private static CeTask createCeTask(@Nullable CeTask.User submitter, String... characteristics) { Map<String, String> characteristicMap = new HashMap<>(); for (int i = 0; i < characteristics.length; i += 2) { characteristicMap.put(characteristics[i], characteristics[i + 1]); } CeTask.Component entity = new CeTask.Component("PROJECT_1", null, null); CeTask.Component component = new CeTask.Component("BRANCH_1", null, null); return new CeTask.Builder() .setUuid("TASK_1").setType(CeTaskTypes.REPORT) .setComponent(component) .setEntity(entity) .setSubmitter(submitter) .setCharacteristics(characteristicMap) .build(); } private UserDto insertRandomUser() { UserDto userDto = UserTesting.newUserDto(); db.getDbClient().userDao().insert(session, userDto); session.commit(); return userDto; } private CeTask.User toTaskSubmitter(UserDto userDto) { return new CeTask.User(userDto.getUuid(), userDto.getLogin()); } private IllegalStateException makeTaskProcessorFail(CeTask task) { return makeTaskProcessorFail(task, new IllegalStateException("simulate exception thrown by TaskProcessor#process")); } private <T extends Throwable> T makeTaskProcessorFail(CeTask task, T t) { doThrow(t).when(taskProcessor).process(task); return t; } private static abstract class SimpleCeTaskProcessor implements CeTaskProcessor { @Override public Set<String> getHandledCeTaskTypes() { throw new UnsupportedOperationException("getHandledCeTaskTypes should not be called"); } } }
32,506
40.46301
159
java
sonarqube
sonarqube-master/server/sonar-ce/src/main/java/org/sonar/ce/CeConfigurationModule.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; import org.sonar.ce.configuration.CeConfigurationImpl; import org.sonar.ce.monitoring.CeDatabaseMBeanImpl; import org.sonar.ce.task.log.CeTaskLogging; import org.sonar.core.platform.Module; import org.sonar.process.systeminfo.JvmPropertiesSection; import org.sonar.process.systeminfo.JvmStateSection; import org.sonar.server.platform.monitoring.LoggingSection; public class CeConfigurationModule extends Module { @Override protected void configureModule() { add( CeConfigurationImpl.class, CeTaskLogging.class, CeDatabaseMBeanImpl.class, new JvmStateSection("Compute Engine JVM State"), new JvmPropertiesSection("Compute Engine JVM Properties"), LoggingSection.class); } }
1,586
36.785714
75
java