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/it/java/org/sonar/ce/task/projectanalysis/source/DbLineHashVersionIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.source.LineHashVersion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class DbLineHashVersionIT {
@Rule
public DbTester db = DbTester.create();
private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class);
private final DbLineHashVersion underTest = new DbLineHashVersion(db.getDbClient(), analysisMetadataHolder, referenceBranchComponentUuids);
@Test
public void hasLineHashWithSignificantCode_should_return_true() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
db.fileSources().insertFileSource(file, dto -> dto.setLineHashesVersion(LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue()));
Component component = ReportComponent.builder(Component.Type.FILE, 1).setKey("key").setUuid(file.uuid()).build();
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isTrue();
}
@Test
public void hasLineHashWithSignificantCode_should_return_false_if_file_is_not_found() {
Component component = ReportComponent.builder(Component.Type.FILE, 1).setKey("key").setUuid("123").build();
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isFalse();
}
@Test
public void hasLineHashWithSignificantCode_should_return_false_if_pr_reference_doesnt_have_file() {
when(analysisMetadataHolder.isPullRequest()).thenReturn(true);
Component component = ReportComponent.builder(Component.Type.FILE, 1).setKey("key").setUuid("123").build();
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isFalse();
verify(analysisMetadataHolder).isPullRequest();
verify(referenceBranchComponentUuids).getComponentUuid(component.getKey());
}
@Test
public void hasLineHashWithSignificantCode_should_return_false_if_pr_reference_has_file_but_it_is_not_in_db() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
when(analysisMetadataHolder.isPullRequest()).thenReturn(true);
when(referenceBranchComponentUuids.getComponentUuid("key")).thenReturn(file.uuid());
Component component = ReportComponent.builder(Component.Type.FILE, 1).setKey("key").setUuid("123").build();
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isFalse();
verify(analysisMetadataHolder).isPullRequest();
verify(referenceBranchComponentUuids).getComponentUuid(component.getKey());
}
@Test
public void hasLineHashWithSignificantCode_should_return_true_if_pr_reference_has_file_and_it_is_in_db() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
db.fileSources().insertFileSource(file, dto -> dto.setLineHashesVersion(LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue()));
when(analysisMetadataHolder.isPullRequest()).thenReturn(true);
when(referenceBranchComponentUuids.getComponentUuid("key")).thenReturn(file.uuid());
Component component = ReportComponent.builder(Component.Type.FILE, 1).setKey("key").setUuid("123").build();
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isTrue();
verify(analysisMetadataHolder).isPullRequest();
verify(referenceBranchComponentUuids).getComponentUuid(component.getKey());
}
@Test
public void should_cache_line_hash_version_from_db() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(ComponentTesting.newFileDto(project));
db.fileSources().insertFileSource(file, dto -> dto.setLineHashesVersion(LineHashVersion.WITH_SIGNIFICANT_CODE.getDbValue()));
Component component = ReportComponent.builder(Component.Type.FILE, 1).setKey("key").setUuid(file.uuid()).build();
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isTrue();
assertThat(db.countRowsOfTable("file_sources")).isOne();
db.executeUpdateSql("delete from file_sources");
db.commit();
assertThat(db.countRowsOfTable("file_sources")).isZero();
// still true because it uses cache
assertThat(underTest.hasLineHashesWithSignificantCode(component)).isTrue();
}
}
| 6,043 | 48.950413 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/source/PersistFileSourcesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.source;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import org.apache.commons.codec.digest.DigestUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileAttributes;
import org.sonar.ce.task.projectanalysis.component.PreviousSourceHashRepository;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.scm.Changeset;
import org.sonar.ce.task.projectanalysis.step.BaseStepTest;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.protobuf.DbFileSources;
import org.sonar.db.source.FileHashesDto;
import org.sonar.db.source.FileSourceDto;
import org.sonar.db.source.LineHashVersion;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class PersistFileSourcesStepIT extends BaseStepTest {
private static final int FILE1_REF = 3;
private static final String PROJECT_UUID = "PROJECT";
private static final String PROJECT_KEY = "PROJECT_KEY";
private static final String FILE1_UUID = "FILE1";
private static final long NOW = 123456789L;
private static final long PAST = 15000L;
private final System2 system2 = mock(System2.class);
@Rule
public DbTester dbTester = DbTester.create(system2);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
private final SourceLinesHashRepository sourceLinesHashRepository = mock(SourceLinesHashRepository.class);
private final SourceLinesHashRepositoryImpl.LineHashesComputer lineHashesComputer = mock(SourceLinesHashRepositoryImpl.LineHashesComputer.class);
private final FileSourceDataComputer fileSourceDataComputer = mock(FileSourceDataComputer.class);
private final FileSourceDataWarnings fileSourceDataWarnings = mock(FileSourceDataWarnings.class);
private final PreviousSourceHashRepository previousSourceHashRepository = mock(PreviousSourceHashRepository.class);
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession session = dbTester.getSession();
private PersistFileSourcesStep underTest;
@Before
public void setup() {
when(system2.now()).thenReturn(NOW);
when(sourceLinesHashRepository.getLineHashesComputerToPersist(any(Component.class))).thenReturn(lineHashesComputer);
underTest = new PersistFileSourcesStep(dbClient, system2, treeRootHolder, sourceLinesHashRepository, fileSourceDataComputer, fileSourceDataWarnings,
new SequenceUuidFactory(), previousSourceHashRepository);
initBasicReport(1);
}
@Override
protected ComputationStep step() {
return underTest;
}
@Test
public void persist_sources() {
List<String> lineHashes = Arrays.asList("137f72c3708c6bd0de00a0e5a69c699b", "e6251bcf1a7dc3ba5e7933e325bbe605");
String sourceHash = "ee5a58024a155466b43bc559d953e018";
DbFileSources.Data fileSourceData = DbFileSources.Data.newBuilder()
.addAllLines(Arrays.asList(
DbFileSources.Line.newBuilder().setSource("line1").setLine(1).build(),
DbFileSources.Line.newBuilder().setSource("line2").setLine(2).build()))
.build();
when(fileSourceDataComputer.compute(fileComponent().build(), fileSourceDataWarnings))
.thenReturn(new FileSourceDataComputer.Data(fileSourceData, lineHashes, sourceHash, null));
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getProjectUuid()).isEqualTo(PROJECT_UUID);
assertThat(fileSourceDto.getFileUuid()).isEqualTo(FILE1_UUID);
assertThat(fileSourceDto.getBinaryData()).isNotEmpty();
assertThat(fileSourceDto.getDataHash()).isNotEmpty();
assertThat(fileSourceDto.getLineHashesVersion()).isEqualTo(LineHashVersion.WITHOUT_SIGNIFICANT_CODE.getDbValue());
assertThat(fileSourceDto.getLineHashes()).isNotEmpty();
assertThat(fileSourceDto.getCreatedAt()).isEqualTo(NOW);
assertThat(fileSourceDto.getUpdatedAt()).isEqualTo(NOW);
DbFileSources.Data data = fileSourceDto.getSourceData();
assertThat(data.getLinesCount()).isEqualTo(2);
assertThat(data.getLines(0).getLine()).isOne();
assertThat(data.getLines(0).getSource()).isEqualTo("line1");
assertThat(data.getLines(1).getLine()).isEqualTo(2);
assertThat(data.getLines(1).getSource()).isEqualTo("line2");
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void persist_source_hashes() {
List<String> lineHashes = Arrays.asList("137f72c3708c6bd0de00a0e5a69c699b", "e6251bcf1a7dc3ba5e7933e325bbe605");
String sourceHash = "ee5a58024a155466b43bc559d953e018";
setComputedData(DbFileSources.Data.newBuilder().build(), lineHashes, sourceHash, null);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getLineHashes()).containsExactly("137f72c3708c6bd0de00a0e5a69c699b", "e6251bcf1a7dc3ba5e7933e325bbe605");
assertThat(fileSourceDto.getSrcHash()).isEqualTo("ee5a58024a155466b43bc559d953e018");
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void persist_coverage() {
DbFileSources.Data dbData = DbFileSources.Data.newBuilder().addLines(
DbFileSources.Line.newBuilder()
.setConditions(10)
.setCoveredConditions(2)
.setLineHits(1)
.setLine(1)
.build())
.build();
setComputedData(dbData);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getSourceData()).isEqualTo(dbData);
verify(fileSourceDataWarnings).commitWarnings();
}
private ReportComponent.Builder fileComponent() {
return ReportComponent.builder(Component.Type.FILE, FILE1_REF).setUuid(FILE1_UUID).setKey("PROJECT_KEY" + ":src/Foo.java");
}
@Test
public void persist_scm() {
DbFileSources.Data dbData = DbFileSources.Data.newBuilder().addLines(
DbFileSources.Line.newBuilder()
.setScmAuthor("john")
.setScmDate(123456789L)
.setScmRevision("rev-1")
.build())
.build();
setComputedData(dbData);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getSourceData()).isEqualTo(dbData);
assertThat(fileSourceDto.getRevision()).isNull();
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void persist_scm_some_lines() {
DbFileSources.Data dbData = DbFileSources.Data.newBuilder().addAllLines(Arrays.asList(
DbFileSources.Line.newBuilder()
.setScmAuthor("john")
.setScmDate(123456789L)
.setScmRevision("rev-1")
.build(),
DbFileSources.Line.newBuilder()
.setScmDate(223456789L)
.build(),
DbFileSources.Line.newBuilder()
.build()))
.build();
setComputedData(dbData);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
DbFileSources.Data data = fileSourceDto.getSourceData();
assertThat(data.getLinesList()).hasSize(3);
assertThat(data.getLines(0).getScmAuthor()).isEqualTo("john");
assertThat(data.getLines(0).getScmDate()).isEqualTo(123456789L);
assertThat(data.getLines(0).getScmRevision()).isEqualTo("rev-1");
assertThat(data.getLines(1).getScmAuthor()).isEmpty();
assertThat(data.getLines(1).getScmDate()).isEqualTo(223456789L);
assertThat(data.getLines(1).getScmRevision()).isEmpty();
assertThat(data.getLines(2).getScmAuthor()).isEmpty();
assertThat(data.getLines(2).getScmDate()).isZero();
assertThat(data.getLines(2).getScmRevision()).isEmpty();
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void persist_highlighting() {
DbFileSources.Data dbData = DbFileSources.Data.newBuilder().addLines(
DbFileSources.Line.newBuilder()
.setHighlighting("2,4,a")
.build())
.build();
setComputedData(dbData);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
DbFileSources.Data data = fileSourceDto.getSourceData();
assertThat(data).isEqualTo(dbData);
assertThat(data.getLinesList()).hasSize(1);
assertThat(data.getLines(0).getHighlighting()).isEqualTo("2,4,a");
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void persist_symbols() {
DbFileSources.Data dbData = DbFileSources.Data.newBuilder().addAllLines(Arrays.asList(
DbFileSources.Line.newBuilder()
.setSymbols("2,4,1")
.build(),
DbFileSources.Line.newBuilder().build(),
DbFileSources.Line.newBuilder()
.setSymbols("1,3,1")
.build()))
.build();
setComputedData(dbData);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getSourceData()).isEqualTo(dbData);
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void persist_duplication() {
DbFileSources.Data dbData = DbFileSources.Data.newBuilder().addLines(
DbFileSources.Line.newBuilder()
.addDuplication(2)
.build())
.build();
setComputedData(dbData);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getSourceData()).isEqualTo(dbData);
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void save_revision() {
Changeset latest = Changeset.newChangesetBuilder().setDate(0L).setRevision("rev-1").build();
setComputedData(DbFileSources.Data.newBuilder().build(), Collections.singletonList("lineHashes"), "srcHash", latest);
underTest.execute(new TestComputationStepContext());
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getRevision()).isEqualTo("rev-1");
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void not_save_revision() {
setComputedData(DbFileSources.Data.newBuilder().build());
underTest.execute(new TestComputationStepContext());
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getRevision()).isNull();
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void not_update_sources_when_nothing_has_changed() {
setPastAnalysisHashes();
dbClient.fileSourceDao().insert(dbTester.getSession(), createDto());
dbTester.getSession().commit();
Changeset changeset = Changeset.newChangesetBuilder().setDate(1L).setRevision("rev-1").build();
setComputedData(DbFileSources.Data.newBuilder().build(), Collections.singletonList("lineHash"), "sourceHash", changeset);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getSrcHash()).isEqualTo("sourceHash");
assertThat(fileSourceDto.getLineHashes()).isEqualTo(Collections.singletonList("lineHash"));
assertThat(fileSourceDto.getCreatedAt()).isEqualTo(PAST);
assertThat(fileSourceDto.getUpdatedAt()).isEqualTo(PAST);
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void update_sources_when_source_updated() {
// Existing sources
long past = 150000L;
FileSourceDto dbFileSources = new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE1_UUID)
.setSrcHash("5b4bd9815cdb17b8ceae19eb1810c34c")
.setLineHashes(Collections.singletonList("6438c669e0d0de98e6929c2cc0fac474"))
.setDataHash("6cad150e3d065976c230cddc5a09efaa")
.setSourceData(DbFileSources.Data.newBuilder()
.addLines(DbFileSources.Line.newBuilder()
.setLine(1)
.setSource("old line")
.build())
.build())
.setCreatedAt(past)
.setUpdatedAt(past)
.setRevision("rev-0");
dbClient.fileSourceDao().insert(dbTester.getSession(), dbFileSources);
dbTester.getSession().commit();
setPastAnalysisHashes(dbFileSources);
DbFileSources.Data newSourceData = DbFileSources.Data.newBuilder()
.addLines(DbFileSources.Line.newBuilder()
.setLine(1)
.setSource("old line")
.setScmDate(123456789L)
.setScmRevision("rev-1")
.setScmAuthor("john")
.build())
.build();
Changeset changeset = Changeset.newChangesetBuilder().setDate(1L).setRevision("rev-1").build();
setComputedData(newSourceData, Collections.singletonList("6438c669e0d0de98e6929c2cc0fac474"), "5b4bd9815cdb17b8ceae19eb1810c34c", changeset);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getCreatedAt()).isEqualTo(past);
assertThat(fileSourceDto.getUpdatedAt()).isEqualTo(NOW);
assertThat(fileSourceDto.getRevision()).isEqualTo("rev-1");
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void update_sources_when_src_hash_is_missing() {
FileSourceDto dbFileSources = createDto(dto -> dto.setSrcHash(null));
dbClient.fileSourceDao().insert(dbTester.getSession(), dbFileSources);
dbTester.getSession().commit();
setPastAnalysisHashes(dbFileSources);
DbFileSources.Data sourceData = DbFileSources.Data.newBuilder().build();
setComputedData(sourceData, Collections.singletonList("lineHash"), "newSourceHash", null);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getCreatedAt()).isEqualTo(PAST);
assertThat(fileSourceDto.getUpdatedAt()).isEqualTo(NOW);
assertThat(fileSourceDto.getSrcHash()).isEqualTo("newSourceHash");
verify(fileSourceDataWarnings).commitWarnings();
}
@Test
public void update_sources_when_revision_is_missing() {
DbFileSources.Data sourceData = DbFileSources.Data.newBuilder()
.addLines(DbFileSources.Line.newBuilder()
.setLine(1)
.setSource("line")
.build())
.build();
FileSourceDto dbFileSources = createDto(dto -> dto.setRevision(null));
dbClient.fileSourceDao().insert(dbTester.getSession(), dbFileSources);
dbTester.getSession().commit();
setPastAnalysisHashes(dbFileSources);
Changeset changeset = Changeset.newChangesetBuilder().setDate(1L).setRevision("revision").build();
setComputedData(sourceData, Collections.singletonList("137f72c3708c6bd0de00a0e5a69c699b"), "29f25900140c94db38035128cb6de6a2", changeset);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("file_sources")).isOne();
FileSourceDto fileSourceDto = dbClient.fileSourceDao().selectByFileUuid(session, FILE1_UUID);
assertThat(fileSourceDto.getCreatedAt()).isEqualTo(PAST);
assertThat(fileSourceDto.getUpdatedAt()).isEqualTo(NOW);
assertThat(fileSourceDto.getRevision()).isEqualTo("revision");
verify(fileSourceDataWarnings).commitWarnings();
}
private FileSourceDto createDto() {
return createDto(dto -> {
});
}
private FileSourceDto createDto(Consumer<FileSourceDto> modifier) {
DbFileSources.Data sourceData = DbFileSources.Data.newBuilder().build();
byte[] data = FileSourceDto.encodeSourceData(sourceData);
String dataHash = DigestUtils.md5Hex(data);
FileSourceDto dto = new FileSourceDto()
.setUuid(Uuids.createFast())
.setProjectUuid(PROJECT_UUID)
.setFileUuid(FILE1_UUID)
.setSrcHash("sourceHash")
.setLineHashes(Collections.singletonList("lineHash"))
.setDataHash(dataHash)
.setRevision("rev-1")
.setSourceData(sourceData)
.setCreatedAt(PAST)
.setUpdatedAt(PAST);
modifier.accept(dto);
return dto;
}
private void setPastAnalysisHashes() {
DbFileSources.Data sourceData = DbFileSources.Data.newBuilder().build();
byte[] data = FileSourceDto.encodeSourceData(sourceData);
String dataHash = DigestUtils.md5Hex(data);
FileHashesDto fileHashesDto = new FileHashesDto()
.setSrcHash("sourceHash")
.setDataHash(dataHash)
.setRevision("rev-1");
setPastAnalysisHashes(fileHashesDto);
}
private void setPastAnalysisHashes(FileHashesDto fileHashesDto) {
when(previousSourceHashRepository.getDbFile(any(Component.class))).thenReturn(Optional.of(fileHashesDto));
}
private void setComputedData(DbFileSources.Data data, List<String> lineHashes, String sourceHash, Changeset latestChangeWithRevision) {
FileSourceDataComputer.Data computedData = new FileSourceDataComputer.Data(data, lineHashes, sourceHash, latestChangeWithRevision);
when(fileSourceDataComputer.compute(fileComponent().build(), fileSourceDataWarnings)).thenReturn(computedData);
}
private void setComputedData(DbFileSources.Data data) {
FileSourceDataComputer.Data computedData = new FileSourceDataComputer.Data(data, Collections.emptyList(), "", null);
when(fileSourceDataComputer.compute(fileComponent().build(), fileSourceDataWarnings)).thenReturn(computedData);
}
private void initBasicReport(int numberOfLines) {
ReportComponent root = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(PROJECT_UUID).setKey(PROJECT_KEY).addChildren(
fileComponent().setFileAttributes(new FileAttributes(false, null, numberOfLines)).build())
.build();
treeRootHolder.setRoots(root, root);
}
}
| 20,356 | 41.146998 | 152 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/BuildComponentTreeStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl;
import org.sonar.ce.task.projectanalysis.component.MutableTreeRootHolderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType;
import org.sonar.scanner.protocol.output.ScannerReport.Component.FileStatus;
import org.sonar.server.project.Project;
import static java.util.Optional.ofNullable;
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.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.ComponentTesting.newDirectory;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.SnapshotTesting.newAnalysis;
import static org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType.FILE;
import static org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType.PROJECT;
@RunWith(DataProviderRunner.class)
public class BuildComponentTreeStepIT {
private static final String NO_SCANNER_PROJECT_VERSION = null;
private static final String NO_SCANNER_BUILD_STRING = null;
private static final int ROOT_REF = 1;
private static final int FILE_1_REF = 4;
private static final int FILE_2_REF = 5;
private static final int FILE_3_REF = 7;
private static final int UNCHANGED_FILE_REF = 10;
private static final String REPORT_PROJECT_KEY = "REPORT_PROJECT_KEY";
private static final String REPORT_DIR_PATH_1 = "src/main/java/dir1";
private static final String REPORT_FILE_PATH_1 = "src/main/java/dir1/File1.java";
private static final String REPORT_FILE_NAME_1 = "File1.java";
private static final String REPORT_DIR_PATH_2 = "src/main/java/dir2";
private static final String REPORT_FILE_PATH_2 = "src/main/java/dir2/File2.java";
private static final String REPORT_FILE_PATH_3 = "src/main/java/dir2/File3.java";
private static final String REPORT_UNCHANGED_FILE_PATH = "src/main/File3.java";
private static final long ANALYSIS_DATE = 123456789L;
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule().setMetadata(createReportMetadata(NO_SCANNER_PROJECT_VERSION, NO_SCANNER_BUILD_STRING));
@Rule
public MutableTreeRootHolderRule treeRootHolder = new MutableTreeRootHolderRule();
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
private DbClient dbClient = dbTester.getDbClient();
private BuildComponentTreeStep underTest = new BuildComponentTreeStep(dbClient, reportReader, treeRootHolder, analysisMetadataHolder);
@Test
public void fails_if_root_component_does_not_exist_in_reportReader() {
setAnalysisMetadataHolder();
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(NullPointerException.class);
}
@Test
public void verify_tree_is_correctly_built() {
setAnalysisMetadataHolder();
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF, FILE_2_REF, FILE_3_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
reportReader.putComponent(componentWithPath(FILE_2_REF, FILE, REPORT_FILE_PATH_2));
reportReader.putComponent(componentWithPath(FILE_3_REF, FILE, REPORT_FILE_PATH_3));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
Component root = treeRootHolder.getRoot();
assertThat(root).isNotNull();
verifyComponent(root, Component.Type.PROJECT, ROOT_REF, 1);
Component dir = root.getChildren().iterator().next();
verifyComponent(dir, Component.Type.DIRECTORY, null, 2);
Component dir1 = dir.getChildren().get(0);
verifyComponent(dir1, Component.Type.DIRECTORY, null, 1);
verifyComponent(dir1.getChildren().get(0), Component.Type.FILE, FILE_1_REF, 0);
Component dir2 = dir.getChildren().get(1);
verifyComponent(dir2, Component.Type.DIRECTORY, null, 2);
verifyComponent(dir2.getChildren().get(0), Component.Type.FILE, FILE_2_REF, 0);
verifyComponent(dir2.getChildren().get(1), Component.Type.FILE, FILE_3_REF, 0);
context.getStatistics().assertValue("components", 7);
}
@Test
public void verify_tree_is_correctly_built_in_prs() {
setAnalysisMetadataHolder(true);
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF, FILE_2_REF, FILE_3_REF, UNCHANGED_FILE_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
reportReader.putComponent(componentWithPath(FILE_2_REF, FILE, REPORT_FILE_PATH_2));
reportReader.putComponent(componentWithPath(FILE_3_REF, FILE, REPORT_FILE_PATH_3));
reportReader.putComponent(unchangedComponentWithPath(UNCHANGED_FILE_REF, FILE, REPORT_UNCHANGED_FILE_PATH));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
// modified root
Component mRoot = treeRootHolder.getRoot();
verifyComponent(mRoot, Component.Type.PROJECT, ROOT_REF, 1);
Component mDir = mRoot.getChildren().get(0);
assertThat(mDir.getName()).isEqualTo("src/main/java");
verifyComponent(mDir, Component.Type.DIRECTORY, null, 2);
Component mDir1 = mDir.getChildren().get(0);
assertThat(mDir1.getName()).isEqualTo("src/main/java/dir1");
verifyComponent(mDir1, Component.Type.DIRECTORY, null, 1);
verifyComponent(mDir1.getChildren().get(0), Component.Type.FILE, FILE_1_REF, 0);
Component mDir2 = mDir.getChildren().get(1);
assertThat(mDir2.getName()).isEqualTo("src/main/java/dir2");
verifyComponent(mDir2, Component.Type.DIRECTORY, null, 2);
verifyComponent(mDir2.getChildren().get(0), Component.Type.FILE, FILE_2_REF, 0);
verifyComponent(mDir2.getChildren().get(1), Component.Type.FILE, FILE_3_REF, 0);
// root
Component root = treeRootHolder.getReportTreeRoot();
verifyComponent(root, Component.Type.PROJECT, ROOT_REF, 1);
Component dir = root.getChildren().get(0);
assertThat(dir.getName()).isEqualTo("src/main");
verifyComponent(dir, Component.Type.DIRECTORY, null, 2);
Component dir1 = dir.getChildren().get(0);
assertThat(dir1.getName()).isEqualTo("src/main/java");
verifyComponent(dir1, Component.Type.DIRECTORY, null, 2);
verifyComponent(dir1.getChildren().get(0), Component.Type.DIRECTORY, null, 1);
verifyComponent(dir1.getChildren().get(1), Component.Type.DIRECTORY, null, 2);
Component dir2 = dir1.getChildren().get(0);
assertThat(dir2.getName()).isEqualTo("src/main/java/dir1");
verifyComponent(dir2, Component.Type.DIRECTORY, null, 1);
verifyComponent(dir2.getChildren().get(0), Component.Type.FILE, FILE_1_REF, 0);
Component dir3 = dir1.getChildren().get(1);
assertThat(dir3.getName()).isEqualTo("src/main/java/dir2");
verifyComponent(dir3, Component.Type.DIRECTORY, null, 2);
verifyComponent(dir3.getChildren().get(0), Component.Type.FILE, FILE_2_REF, 0);
verifyComponent(dir3.getChildren().get(1), Component.Type.FILE, FILE_3_REF, 0);
context.getStatistics().assertValue("components", 7);
}
/**
* SONAR-13262
*/
@Test
public void verify_tree_is_correctly_built_in_prs_with_repeated_names() {
setAnalysisMetadataHolder(true);
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_PROJECT_KEY + "/file.js"));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
// modified root
Component mRoot = treeRootHolder.getRoot();
verifyComponent(mRoot, Component.Type.PROJECT, ROOT_REF, 1);
Component dir = mRoot.getChildren().get(0);
assertThat(dir.getName()).isEqualTo(REPORT_PROJECT_KEY);
assertThat(dir.getShortName()).isEqualTo(REPORT_PROJECT_KEY);
verifyComponent(dir, Component.Type.DIRECTORY, null, 1);
}
@Test
public void compute_keys_and_uuids() {
setAnalysisMetadataHolder();
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, REPORT_PROJECT_KEY, analysisMetadataHolder.getProject().getName());
verifyComponentByKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_1, REPORT_DIR_PATH_1);
verifyComponentByRef(FILE_1_REF, REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_1, REPORT_FILE_NAME_1);
}
@Test
public void return_existing_uuids() {
setAnalysisMetadataHolder();
ComponentDto mainBranch = dbTester.components().insertPrivateProject("ABCD", p -> p.setKey(REPORT_PROJECT_KEY)).getMainBranchComponent();
ComponentDto directory = newDirectory(mainBranch, "CDEF", REPORT_DIR_PATH_1);
insertComponent(directory.setKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_1));
insertComponent(newFileDto(mainBranch, directory, "DEFG")
.setKey(REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_1)
.setPath(REPORT_FILE_PATH_1));
// new structure, without modules
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, REPORT_PROJECT_KEY, analysisMetadataHolder.getProject().getName(), mainBranch.uuid());
verifyComponentByKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_1, REPORT_DIR_PATH_1, "CDEF");
verifyComponentByRef(FILE_1_REF, REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_1, REPORT_FILE_NAME_1, "DEFG");
}
@Test
public void generate_keys_when_using_new_branch() {
Branch branch = mock(Branch.class);
when(branch.getName()).thenReturn("origin/feature");
when(branch.isMain()).thenReturn(false);
when(branch.generateKey(any(), any())).thenReturn("generated");
analysisMetadataHolder.setRootComponentRef(ROOT_REF)
.setAnalysisDate(ANALYSIS_DATE)
.setProject(Project.from(newPrivateProjectDto().setKey(REPORT_PROJECT_KEY)))
.setBranch(branch);
BuildComponentTreeStep underTest = new BuildComponentTreeStep(dbClient, reportReader, treeRootHolder, analysisMetadataHolder);
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, "generated", analysisMetadataHolder.getProject().getName(), null);
verifyComponentByRef(FILE_1_REF, "generated", REPORT_FILE_NAME_1, null);
}
@Test
public void generate_keys_when_using_existing_branch() {
ComponentDto projectDto = dbTester.components().insertPublicProject().getMainBranchComponent();
String branchName = randomAlphanumeric(248);
ComponentDto componentDto = dbTester.components().insertProjectBranch(projectDto, b -> b.setKey(branchName));
Branch branch = mock(Branch.class);
when(branch.getName()).thenReturn(branchName);
when(branch.isMain()).thenReturn(false);
when(branch.generateKey(any(), any())).thenReturn(componentDto.getKey());
analysisMetadataHolder.setRootComponentRef(ROOT_REF)
.setAnalysisDate(ANALYSIS_DATE)
.setProject(Project.from(projectDto))
.setBranch(branch);
BuildComponentTreeStep underTest = new BuildComponentTreeStep(dbClient, reportReader, treeRootHolder, analysisMetadataHolder);
reportReader.putComponent(component(ROOT_REF, PROJECT, componentDto.getKey()));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, componentDto.getKey(), analysisMetadataHolder.getProject().getName(), componentDto.uuid());
}
@Test
public void generate_keys_when_using_main_branch() {
setAnalysisMetadataHolder();
BuildComponentTreeStep underTest = new BuildComponentTreeStep(dbClient, reportReader, treeRootHolder, analysisMetadataHolder);
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, REPORT_PROJECT_KEY, analysisMetadataHolder.getProject().getName(), null);
verifyComponentByKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_1, REPORT_DIR_PATH_1);
verifyComponentByRef(FILE_1_REF, REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_1, REPORT_FILE_NAME_1, null);
}
@Test
public void compute_keys_and_uuids_on_project_having_module_and_directory() {
setAnalysisMetadataHolder();
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF, FILE_2_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
reportReader.putComponent(componentWithPath(FILE_2_REF, FILE, REPORT_FILE_PATH_2));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, REPORT_PROJECT_KEY, analysisMetadataHolder.getProject().getName());
verifyComponentByKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_1, "dir1");
verifyComponentByRef(FILE_1_REF, REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_1, REPORT_FILE_NAME_1);
verifyComponentByKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_2, "dir2");
verifyComponentByRef(FILE_2_REF, REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_2, "File2.java");
}
@Test
public void compute_keys_and_uuids_on_multi_modules() {
setAnalysisMetadataHolder();
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY, FILE_1_REF));
reportReader.putComponent(componentWithPath(FILE_1_REF, FILE, REPORT_FILE_PATH_1));
underTest.execute(new TestComputationStepContext());
verifyComponentByRef(ROOT_REF, REPORT_PROJECT_KEY, analysisMetadataHolder.getProject().getName());
verifyComponentByKey(REPORT_PROJECT_KEY + ":" + REPORT_DIR_PATH_1, REPORT_DIR_PATH_1);
verifyComponentByRef(FILE_1_REF, REPORT_PROJECT_KEY + ":" + REPORT_FILE_PATH_1, REPORT_FILE_NAME_1);
}
@Test
public void set_no_base_project_snapshot_when_no_snapshot() {
setAnalysisMetadataHolder();
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.isFirstAnalysis()).isTrue();
}
@Test
public void set_no_base_project_snapshot_when_no_last_snapshot() {
setAnalysisMetadataHolder();
ComponentDto project = insertComponent(newPrivateProjectDto("ABCD").setKey(REPORT_PROJECT_KEY));
insertSnapshot(newAnalysis(project).setLast(false));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.isFirstAnalysis()).isTrue();
}
@Test
public void set_base_project_snapshot_when_last_snapshot_exist() {
setAnalysisMetadataHolder();
ComponentDto project = dbTester.components().insertPrivateProject("ABCD", p -> p.setKey(REPORT_PROJECT_KEY)).getMainBranchComponent();
insertSnapshot(newAnalysis(project).setLast(true));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.isFirstAnalysis()).isFalse();
}
@Test
public void set_projectVersion_to_not_provided_when_not_set_on_first_analysis() {
setAnalysisMetadataHolder();
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(treeRootHolder.getReportTreeRoot().getProjectAttributes().getProjectVersion()).isEqualTo("not provided");
}
@Test
@UseDataProvider("oneParameterNullNonNullCombinations")
public void set_projectVersion_to_previous_analysis_when_not_set(@Nullable String previousAnalysisProjectVersion) {
setAnalysisMetadataHolder();
ComponentDto project = dbTester.components().insertPrivateProject("ABCD", p -> p.setKey(REPORT_PROJECT_KEY)).getMainBranchComponent();
insertSnapshot(newAnalysis(project).setProjectVersion(previousAnalysisProjectVersion).setLast(true));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
String projectVersion = treeRootHolder.getReportTreeRoot().getProjectAttributes().getProjectVersion();
if (previousAnalysisProjectVersion == null) {
assertThat(projectVersion).isEqualTo("not provided");
} else {
assertThat(projectVersion).isEqualTo(previousAnalysisProjectVersion);
}
}
@Test
public void set_projectVersion_when_it_is_set_on_first_analysis() {
String scannerProjectVersion = randomAlphabetic(12);
setAnalysisMetadataHolder();
reportReader.setMetadata(createReportMetadata(scannerProjectVersion, NO_SCANNER_BUILD_STRING));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(treeRootHolder.getReportTreeRoot().getProjectAttributes().getProjectVersion())
.isEqualTo(scannerProjectVersion);
}
@Test
@UseDataProvider("oneParameterNullNonNullCombinations")
public void set_projectVersion_when_it_is_set_on_later_analysis(@Nullable String previousAnalysisProjectVersion) {
String scannerProjectVersion = randomAlphabetic(12);
setAnalysisMetadataHolder();
reportReader.setMetadata(createReportMetadata(scannerProjectVersion, NO_SCANNER_BUILD_STRING));
ComponentDto project = insertComponent(newPrivateProjectDto("ABCD").setKey(REPORT_PROJECT_KEY));
insertSnapshot(newAnalysis(project).setProjectVersion(previousAnalysisProjectVersion).setLast(true));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(treeRootHolder.getReportTreeRoot().getProjectAttributes().getProjectVersion())
.isEqualTo(scannerProjectVersion);
}
@Test
@UseDataProvider("oneParameterNullNonNullCombinations")
public void set_buildString(@Nullable String buildString) {
String projectVersion = randomAlphabetic(7);
setAnalysisMetadataHolder();
reportReader.setMetadata(createReportMetadata(projectVersion, buildString));
reportReader.putComponent(component(ROOT_REF, PROJECT, REPORT_PROJECT_KEY));
underTest.execute(new TestComputationStepContext());
assertThat(treeRootHolder.getReportTreeRoot().getProjectAttributes().getBuildString()).isEqualTo(Optional.ofNullable(buildString));
}
@DataProvider
public static Object[][] oneParameterNullNonNullCombinations() {
return new Object[][] {
{null},
{randomAlphabetic(7)}
};
}
private void verifyComponent(Component component, Component.Type type, @Nullable Integer componentRef, int size) {
assertThat(component.getType()).isEqualTo(type);
assertThat(component.getReportAttributes().getRef()).isEqualTo(componentRef);
assertThat(component.getChildren()).hasSize(size);
}
private void verifyComponentByRef(int ref, String key, String shortName) {
verifyComponentByRef(ref, key, shortName, null);
}
private void verifyComponentByKey(String key, String shortName) {
verifyComponentByKey(key, shortName, null);
}
private void verifyComponentByKey(String key, String shortName, @Nullable String uuid) {
Map<String, Component> componentsByKey = indexAllComponentsInTreeByKey(treeRootHolder.getRoot());
Component component = componentsByKey.get(key);
assertThat(component.getKey()).isEqualTo(key);
assertThat(component.getReportAttributes().getRef()).isNull();
assertThat(component.getShortName()).isEqualTo(shortName);
if (uuid != null) {
assertThat(component.getUuid()).isEqualTo(uuid);
} else {
assertThat(component.getUuid()).isNotNull();
}
}
private void verifyComponentByRef(int ref, String key, String shortName, @Nullable String uuid) {
Map<Integer, Component> componentsByRef = indexAllComponentsInTreeByRef(treeRootHolder.getRoot());
Component component = componentsByRef.get(ref);
assertThat(component.getKey()).isEqualTo(key);
assertThat(component.getShortName()).isEqualTo(shortName);
if (uuid != null) {
assertThat(component.getUuid()).isEqualTo(uuid);
} else {
assertThat(component.getUuid()).isNotNull();
}
}
private static ScannerReport.Component component(int componentRef, ComponentType componentType, String key, int... children) {
return component(componentRef, componentType, key, FileStatus.CHANGED, null, children);
}
private static ScannerReport.Component unchangedComponentWithPath(int componentRef, ComponentType componentType, String path, int... children) {
return component(componentRef, componentType, REPORT_PROJECT_KEY + ":" + path, FileStatus.SAME, path, children);
}
private static ScannerReport.Component componentWithPath(int componentRef, ComponentType componentType, String path, int... children) {
return component(componentRef, componentType, REPORT_PROJECT_KEY + ":" + path, FileStatus.CHANGED, path, children);
}
private static ScannerReport.Component component(int componentRef, ComponentType componentType, String key, FileStatus status, @Nullable String path, int... children) {
ScannerReport.Component.Builder builder = ScannerReport.Component.newBuilder()
.setType(componentType)
.setRef(componentRef)
.setName(key)
.setStatus(status)
.setLines(1)
.setKey(key);
if (path != null) {
builder.setProjectRelativePath(path);
}
for (int child : children) {
builder.addChildRef(child);
}
return builder.build();
}
private static Map<Integer, Component> indexAllComponentsInTreeByRef(Component root) {
Map<Integer, Component> componentsByRef = new HashMap<>();
feedComponentByRef(root, componentsByRef);
return componentsByRef;
}
private static Map<String, Component> indexAllComponentsInTreeByKey(Component root) {
Map<String, Component> componentsByKey = new HashMap<>();
feedComponentByKey(root, componentsByKey);
return componentsByKey;
}
private static void feedComponentByKey(Component component, Map<String, Component> map) {
map.put(component.getKey(), component);
for (Component child : component.getChildren()) {
feedComponentByKey(child, map);
}
}
private static void feedComponentByRef(Component component, Map<Integer, Component> map) {
if (component.getReportAttributes().getRef() != null) {
map.put(component.getReportAttributes().getRef(), component);
}
for (Component child : component.getChildren()) {
feedComponentByRef(child, map);
}
}
private ComponentDto insertComponent(ComponentDto component) {
return dbTester.components().insertComponent(component);
}
private SnapshotDto insertSnapshot(SnapshotDto snapshot) {
dbClient.snapshotDao().insert(dbTester.getSession(), snapshot);
dbTester.getSession().commit();
return snapshot;
}
private void setAnalysisMetadataHolder() {
setAnalysisMetadataHolder(false);
}
private void setAnalysisMetadataHolder(boolean isPr) {
Branch branch = isPr ? new PrBranch(DEFAULT_MAIN_BRANCH_NAME) : new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME);
analysisMetadataHolder.setRootComponentRef(ROOT_REF)
.setAnalysisDate(ANALYSIS_DATE)
.setBranch(branch)
.setProject(Project.from(newPrivateProjectDto().setKey(REPORT_PROJECT_KEY).setName(REPORT_PROJECT_KEY)));
}
public static ScannerReport.Metadata createReportMetadata(@Nullable String projectVersion, @Nullable String buildString) {
ScannerReport.Metadata.Builder builder = ScannerReport.Metadata.newBuilder()
.setProjectKey(REPORT_PROJECT_KEY)
.setRootComponentRef(ROOT_REF);
ofNullable(projectVersion).ifPresent(builder::setProjectVersion);
ofNullable(buildString).ifPresent(builder::setBuildString);
return builder.build();
}
private static class PrBranch extends DefaultBranchImpl {
public PrBranch(String branch) {
super(branch);
}
@Override
public BranchType getType() {
return BranchType.PULL_REQUEST;
}
}
}
| 26,949 | 44.911414 | 170 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/CleanIssueChangesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.issue.IssueChangesToDeleteRepository;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import static java.util.Collections.singleton;
import static org.assertj.core.api.Assertions.assertThat;
public class CleanIssueChangesStepIT {
@Rule
public DbTester db = DbTester.create();
private final IssueChangesToDeleteRepository repository = new IssueChangesToDeleteRepository();
private final CleanIssueChangesStep cleanIssueChangesStep = new CleanIssueChangesStep(repository, db.getDbClient());
private final TestComputationStepContext context = new TestComputationStepContext();
@Test
public void steps_deletes_all_changes_in_repository() {
IssueDto issue1 = db.issues().insert();
IssueChangeDto change1 = db.issues().insertChange(issue1);
IssueChangeDto change2 = db.issues().insertChange(issue1);
repository.add(change1.getUuid());
cleanIssueChangesStep.execute(context);
assertThat(db.getDbClient().issueChangeDao().selectByIssueKeys(db.getSession(), singleton(issue1.getKey())))
.extracting(IssueChangeDto::getUuid)
.containsOnly(change2.getUuid());
}
@Test
public void steps_does_nothing_if_no_uuid() {
IssueDto issue1 = db.issues().insert();
IssueChangeDto change1 = db.issues().insertChange(issue1);
IssueChangeDto change2 = db.issues().insertChange(issue1);
cleanIssueChangesStep.execute(context);
assertThat(db.getDbClient().issueChangeDao().selectByIssueKeys(db.getSession(), singleton(issue1.getKey())))
.extracting(IssueChangeDto::getUuid)
.containsOnly(change1.getUuid(), change2.getUuid());
}
}
| 2,699 | 39.298507 | 118 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/EnableAnalysisStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotTesting;
import static org.assertj.core.api.Assertions.assertThat;
public class EnableAnalysisStepIT {
private static final ReportComponent REPORT_PROJECT = ReportComponent.builder(Component.Type.PROJECT, 1).build();
private static final String PREVIOUS_ANALYSIS_UUID = "ANALYSIS_1";
private static final String CURRENT_ANALYSIS_UUID = "ANALYSIS_2";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
private EnableAnalysisStep underTest = new EnableAnalysisStep(db.getDbClient(), treeRootHolder, analysisMetadataHolder);
@Test
public void switch_islast_flag_and_mark_analysis_as_processed() {
ComponentDto project = ComponentTesting.newPrivateProjectDto(REPORT_PROJECT.getUuid());
db.components().insertComponent(project);
insertAnalysis(project, PREVIOUS_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, true);
insertAnalysis(project, CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_UNPROCESSED, false);
db.commit();
treeRootHolder.setRoot(REPORT_PROJECT);
analysisMetadataHolder.setUuid(CURRENT_ANALYSIS_UUID);
underTest.execute(new TestComputationStepContext());
verifyAnalysis(PREVIOUS_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, false);
verifyAnalysis(CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, true);
}
@Test
public void set_islast_flag_and_mark_as_processed_if_no_previous_analysis() {
ComponentDto project = ComponentTesting.newPrivateProjectDto(REPORT_PROJECT.getUuid());
db.components().insertComponent(project);
insertAnalysis(project, CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_UNPROCESSED, false);
db.commit();
treeRootHolder.setRoot(REPORT_PROJECT);
analysisMetadataHolder.setUuid(CURRENT_ANALYSIS_UUID);
underTest.execute(new TestComputationStepContext());
verifyAnalysis(CURRENT_ANALYSIS_UUID, SnapshotDto.STATUS_PROCESSED, true);
}
private void verifyAnalysis(String uuid, String expectedStatus, boolean expectedLastFlag) {
Optional<SnapshotDto> analysis = db.getDbClient().snapshotDao().selectByUuid(db.getSession(), uuid);
assertThat(analysis.get().getStatus()).isEqualTo(expectedStatus);
assertThat(analysis.get().getLast()).isEqualTo(expectedLastFlag);
}
private void insertAnalysis(ComponentDto project, String uuid, String status, boolean isLastFlag) {
SnapshotDto snapshot = SnapshotTesting.newAnalysis(project)
.setLast(isLastFlag)
.setStatus(status)
.setUuid(uuid);
db.getDbClient().snapshotDao().insert(db.getSession(), snapshot);
}
}
| 4,275 | 41.76 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ExtractReportStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.impl.utils.JUnitTempFolder;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.api.utils.ZipUtils;
import org.sonar.api.utils.log.LoggerLevel;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.batch.BatchReportDirectoryHolderImpl;
import org.sonar.ce.task.projectanalysis.batch.MutableBatchReportDirectoryHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.ce.CeTaskTypes;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExtractReportStepIT {
private static final String TASK_UUID = "1";
@Rule
public JUnitTempFolder tempFolder = new JUnitTempFolder();
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private MutableBatchReportDirectoryHolder reportDirectoryHolder = new BatchReportDirectoryHolderImpl();
private CeTask ceTask = new CeTask.Builder()
.setType(CeTaskTypes.REPORT)
.setUuid(TASK_UUID)
.build();
private ExtractReportStep underTest = new ExtractReportStep(dbTester.getDbClient(), ceTask, tempFolder, reportDirectoryHolder);
@Test
public void fail_if_report_zip_does_not_exist() {
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(MessageException.class)
.hasMessage("Analysis report 1 is missing in database");
}
@Test
public void unzip_report() throws Exception {
logTester.setLevel(LoggerLevel.DEBUG);
File reportFile = generateReport();
try (InputStream input = FileUtils.openInputStream(reportFile)) {
dbTester.getDbClient().ceTaskInputDao().insert(dbTester.getSession(), TASK_UUID, input);
}
dbTester.getSession().commit();
dbTester.getSession().close();
underTest.execute(new TestComputationStepContext());
// directory contains the uncompressed report (which contains only metadata.pb in this test)
File unzippedDir = reportDirectoryHolder.getDirectory();
assertThat(unzippedDir).isDirectory().exists();
assertThat(unzippedDir.listFiles()).hasSize(1);
assertThat(new File(unzippedDir, "metadata.pb")).hasContent("{metadata}");
assertThat(logTester.logs(Level.DEBUG)).anyMatch(log -> log.matches("Analysis report is \\d+ bytes uncompressed"));
}
@Test
public void unzip_report_should_fail_if_unzip_size_exceed_threshold() throws Exception {
logTester.setLevel(LoggerLevel.DEBUG);
URL zipBombFile = getClass().getResource("/org/sonar/ce/task/projectanalysis/step/ExtractReportStepIT/zip-bomb.zip");
try (InputStream input = zipBombFile.openStream()) {
dbTester.getDbClient().ceTaskInputDao().insert(dbTester.getSession(), TASK_UUID, input);
}
dbTester.getSession().commit();
dbTester.getSession().close();
TestComputationStepContext testComputationStepContext = new TestComputationStepContext();
assertThatThrownBy(() -> underTest.execute(testComputationStepContext))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Decompression failed because unzipped size reached threshold: 4000000000 bytes");
}
private File generateReport() throws IOException {
File zipDir = tempFolder.newDir();
File metadataFile = new File(zipDir, "metadata.pb");
FileUtils.write(metadataFile, "{metadata}");
File zip = tempFolder.newFile();
ZipUtils.zipDir(zipDir, zip);
return zip;
}
}
| 4,722 | 38.033058 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/IndexAnalysisStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Set;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileStatuses;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.component.ViewsComponent;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDao;
import org.sonar.server.es.AnalysisIndexer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW;
public class IndexAnalysisStepIT extends BaseStepTest {
private static final String PROJECT_KEY = "PROJECT_KEY";
private static final String PROJECT_UUID = "PROJECT_UUID";
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
private final DbClient dbClient = mock(DbClient.class);
private final FileStatuses fileStatuses = mock(FileStatuses.class);
private final AnalysisIndexer analysisIndexer = mock(AnalysisIndexer.class);
private final DbSession dbSession = mock(DbSession.class);
private final BranchDao branchDao = mock(BranchDao.class);
private final IndexAnalysisStep underTest = new IndexAnalysisStep(treeRootHolder, fileStatuses, dbClient, analysisIndexer);
private TestComputationStepContext testComputationStepContext;
@Before
public void init() {
testComputationStepContext = new TestComputationStepContext();
when(dbClient.openSession(false)).thenReturn(dbSession);
when(dbClient.branchDao()).thenReturn(branchDao);
}
@Test
public void call_indexByProjectUuid_of_indexer_for_project() {
Component project = ReportComponent.builder(PROJECT, 1).setUuid(PROJECT_UUID).setKey(PROJECT_KEY).build();
treeRootHolder.setRoot(project);
underTest.execute(testComputationStepContext);
verify(analysisIndexer).indexOnAnalysis(PROJECT_UUID, Set.of());
}
@Test
public void call_indexByProjectUuid_of_indexer_for_view() {
Component view = ViewsComponent.builder(VIEW, PROJECT_KEY).setUuid(PROJECT_UUID).build();
treeRootHolder.setRoot(view);
underTest.execute(testComputationStepContext);
verify(analysisIndexer).indexOnAnalysis(PROJECT_UUID, Set.of());
}
@Test
public void execute_whenMarkAsUnchangedFlagActivated_shouldCallIndexOnAnalysisWithChangedComponents() {
Component project = ReportComponent.builder(PROJECT, 1).setUuid(PROJECT_UUID).setKey(PROJECT_KEY).build();
treeRootHolder.setRoot(project);
Set<String> anyUuids = Set.of("any-uuid");
when(fileStatuses.getFileUuidsMarkedAsUnchanged()).thenReturn(anyUuids);
underTest.execute(testComputationStepContext);
verify(analysisIndexer).indexOnAnalysis(PROJECT_UUID, anyUuids);
}
@Test
public void execute_whenBranchIsNeedIssueSync_shouldReindexEverything() {
Component project = ReportComponent.builder(PROJECT, 1).setUuid(PROJECT_UUID).setKey(PROJECT_KEY).build();
treeRootHolder.setRoot(project);
when(branchDao.isBranchNeedIssueSync(dbSession, PROJECT_UUID)).thenReturn(true);
underTest.execute(testComputationStepContext);
verify(analysisIndexer).indexOnAnalysis(PROJECT_UUID);
}
@Override
protected ComputationStep step() {
return underTest;
}
}
| 4,705 | 38.216667 | 125 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadCrossProjectDuplicationsRepositoryStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileAttributes;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.duplication.CrossProjectDuplicationStatusHolder;
import org.sonar.ce.task.projectanalysis.duplication.IntegrateCrossProjectDuplications;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotTesting;
import org.sonar.db.duplication.DuplicationUnitDto;
import org.sonar.duplications.block.Block;
import org.sonar.duplications.block.ByteArray;
import org.sonar.scanner.protocol.output.ScannerReport;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
public class LoadCrossProjectDuplicationsRepositoryStepIT {
private static final String XOO_LANGUAGE = "xoo";
private static final int PROJECT_REF = 1;
private static final int FILE_REF = 2;
private static final String CURRENT_FILE_KEY = "FILE_KEY";
private static final Component CURRENT_FILE = ReportComponent.builder(FILE, FILE_REF)
.setKey(CURRENT_FILE_KEY)
.setFileAttributes(new FileAttributes(false, XOO_LANGUAGE, 1))
.build();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(
ReportComponent.builder(PROJECT, PROJECT_REF)
.addChildren(CURRENT_FILE).build());
@Rule
public BatchReportReaderRule batchReportReader = new BatchReportReaderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
private CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder = mock(CrossProjectDuplicationStatusHolder.class);
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private DbClient dbClient = dbTester.getDbClient();
private DbSession dbSession = dbTester.getSession();
private IntegrateCrossProjectDuplications integrateCrossProjectDuplications = mock(IntegrateCrossProjectDuplications.class);
private Analysis baseProjectAnalysis;
private ComputationStep underTest = new LoadCrossProjectDuplicationsRepositoryStep(treeRootHolder, batchReportReader, analysisMetadataHolder, crossProjectDuplicationStatusHolder,
integrateCrossProjectDuplications, dbClient);
@Before
public void setUp() {
ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
SnapshotDto projectSnapshot = SnapshotTesting.newAnalysis(project);
dbClient.snapshotDao().insert(dbSession, projectSnapshot);
dbSession.commit();
baseProjectAnalysis = new Analysis.Builder()
.setUuid(projectSnapshot.getUuid())
.setCreatedAt(projectSnapshot.getCreatedAt())
.build();
}
@Test
public void call_compute_cpd_on_one_duplication() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis);
ComponentDto otherProject = createProject("OTHER_PROJECT_KEY");
SnapshotDto otherProjectSnapshot = createProjectSnapshot(otherProject);
ComponentDto otherFile = createFile("OTHER_FILE_KEY", otherProject);
String hash = "a8998353e96320ec";
DuplicationUnitDto duplicate = new DuplicationUnitDto()
.setHash(hash)
.setStartLine(40)
.setEndLine(55)
.setIndexInFile(0)
.setAnalysisUuid(otherProjectSnapshot.getUuid())
.setComponentUuid(otherFile.uuid());
dbClient.duplicationDao().insert(dbSession, duplicate);
dbSession.commit();
ScannerReport.CpdTextBlock originBlock = ScannerReport.CpdTextBlock.newBuilder()
.setHash(hash)
.setStartLine(30)
.setEndLine(45)
.setStartTokenIndex(0)
.setEndTokenIndex(10)
.build();
batchReportReader.putDuplicationBlocks(FILE_REF, singletonList(originBlock));
underTest.execute(new TestComputationStepContext());
verify(integrateCrossProjectDuplications).computeCpd(CURRENT_FILE,
singletonList(
new Block.Builder()
.setResourceId(CURRENT_FILE_KEY)
.setBlockHash(new ByteArray(hash))
.setIndexInFile(0)
.setLines(originBlock.getStartLine(), originBlock.getEndLine())
.setUnit(originBlock.getStartTokenIndex(), originBlock.getEndTokenIndex())
.build()),
singletonList(
new Block.Builder()
.setResourceId(otherFile.getKey())
.setBlockHash(new ByteArray(hash))
.setIndexInFile(duplicate.getIndexInFile())
.setLines(duplicate.getStartLine(), duplicate.getEndLine())
.build()));
}
@Test
public void call_compute_cpd_on_many_duplication() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis);
ComponentDto otherProject = createProject("OTHER_PROJECT_KEY");
SnapshotDto otherProjectSnapshot = createProjectSnapshot(otherProject);
ComponentDto otherFile = createFile("OTHER_FILE_KEY", otherProject);
ScannerReport.CpdTextBlock originBlock1 = ScannerReport.CpdTextBlock.newBuilder()
.setHash("a8998353e96320ec")
.setStartLine(30)
.setEndLine(45)
.setStartTokenIndex(0)
.setEndTokenIndex(10)
.build();
ScannerReport.CpdTextBlock originBlock2 = ScannerReport.CpdTextBlock.newBuilder()
.setHash("b1234353e96320ff")
.setStartLine(10)
.setEndLine(25)
.setStartTokenIndex(5)
.setEndTokenIndex(15)
.build();
batchReportReader.putDuplicationBlocks(FILE_REF, asList(originBlock1, originBlock2));
DuplicationUnitDto duplicate1 = new DuplicationUnitDto()
.setHash(originBlock1.getHash())
.setStartLine(40)
.setEndLine(55)
.setIndexInFile(0)
.setAnalysisUuid(otherProjectSnapshot.getUuid())
.setComponentUuid(otherFile.uuid());
DuplicationUnitDto duplicate2 = new DuplicationUnitDto()
.setHash(originBlock2.getHash())
.setStartLine(20)
.setEndLine(35)
.setIndexInFile(1)
.setAnalysisUuid(otherProjectSnapshot.getUuid())
.setComponentUuid(otherFile.uuid());
dbClient.duplicationDao().insert(dbSession, duplicate1);
dbClient.duplicationDao().insert(dbSession, duplicate2);
dbSession.commit();
underTest.execute(new TestComputationStepContext());
ArgumentCaptor<List<Block>> originBlocks = ArgumentCaptor.forClass(List.class);
ArgumentCaptor<List<Block>> duplicationBlocks = ArgumentCaptor.forClass(List.class);
verify(integrateCrossProjectDuplications).computeCpd(eq(CURRENT_FILE), originBlocks.capture(), duplicationBlocks.capture());
Map<Integer, Block> originBlocksByIndex = blocksByIndexInFile(originBlocks.getValue());
assertThat(originBlocksByIndex).containsExactly(
Map.entry(0, new Block.Builder()
.setResourceId(CURRENT_FILE_KEY)
.setBlockHash(new ByteArray(originBlock1.getHash()))
.setIndexInFile(0)
.setLines(originBlock1.getStartLine(), originBlock1.getEndLine())
.setUnit(originBlock1.getStartTokenIndex(), originBlock1.getEndTokenIndex())
.build()),
Map.entry(1, new Block.Builder()
.setResourceId(CURRENT_FILE_KEY)
.setBlockHash(new ByteArray(originBlock2.getHash()))
.setIndexInFile(1)
.setLines(originBlock2.getStartLine(), originBlock2.getEndLine())
.setUnit(originBlock2.getStartTokenIndex(), originBlock2.getEndTokenIndex())
.build()));
Map<Integer, Block> duplicationBlocksByIndex = blocksByIndexInFile(duplicationBlocks.getValue());
assertThat(duplicationBlocksByIndex).containsExactly(
Map.entry(0, new Block.Builder()
.setResourceId(otherFile.getKey())
.setBlockHash(new ByteArray(originBlock1.getHash()))
.setIndexInFile(duplicate1.getIndexInFile())
.setLines(duplicate1.getStartLine(), duplicate1.getEndLine())
.build()),
Map.entry(1, new Block.Builder()
.setResourceId(otherFile.getKey())
.setBlockHash(new ByteArray(originBlock2.getHash()))
.setIndexInFile(duplicate2.getIndexInFile())
.setLines(duplicate2.getStartLine(), duplicate2.getEndLine())
.build()));
}
@Test
public void nothing_to_do_when_cross_project_duplication_is_disabled() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(false);
analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis);
ComponentDto otherProject = createProject("OTHER_PROJECT_KEY");
SnapshotDto otherProjectSnapshot = createProjectSnapshot(otherProject);
ComponentDto otherFIle = createFile("OTHER_FILE_KEY", otherProject);
String hash = "a8998353e96320ec";
DuplicationUnitDto duplicate = new DuplicationUnitDto()
.setHash(hash)
.setStartLine(40)
.setEndLine(55)
.setIndexInFile(0)
.setAnalysisUuid(otherProjectSnapshot.getUuid())
.setComponentUuid(otherFIle.uuid());
dbClient.duplicationDao().insert(dbSession, duplicate);
dbSession.commit();
ScannerReport.CpdTextBlock originBlock = ScannerReport.CpdTextBlock.newBuilder()
.setHash(hash)
.setStartLine(30)
.setEndLine(45)
.setStartTokenIndex(0)
.setEndTokenIndex(10)
.build();
batchReportReader.putDuplicationBlocks(FILE_REF, singletonList(originBlock));
underTest.execute(new TestComputationStepContext());
verifyNoInteractions(integrateCrossProjectDuplications);
}
@Test
public void nothing_to_do_when_no_cpd_text_blocks_found() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis);
batchReportReader.putDuplicationBlocks(FILE_REF, Collections.emptyList());
underTest.execute(new TestComputationStepContext());
verifyNoInteractions(integrateCrossProjectDuplications);
}
@Test
public void nothing_to_do_when_cpd_text_blocks_exists_but_no_duplicated_found() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
analysisMetadataHolder.setBaseAnalysis(baseProjectAnalysis);
ScannerReport.CpdTextBlock originBlock = ScannerReport.CpdTextBlock.newBuilder()
.setHash("a8998353e96320ec")
.setStartLine(30)
.setEndLine(45)
.setStartTokenIndex(0)
.setEndTokenIndex(10)
.build();
batchReportReader.putDuplicationBlocks(FILE_REF, singletonList(originBlock));
underTest.execute(new TestComputationStepContext());
verifyNoInteractions(integrateCrossProjectDuplications);
}
private ComponentDto createProject(String projectKey) {
return dbTester.components().insertPrivateProject(p->p.setKey(projectKey)).getMainBranchComponent();
}
private SnapshotDto createProjectSnapshot(ComponentDto project) {
SnapshotDto projectSnapshot = SnapshotTesting.newAnalysis(project);
dbClient.snapshotDao().insert(dbSession, projectSnapshot);
dbSession.commit();
return projectSnapshot;
}
private ComponentDto createFile(String fileKey, ComponentDto project) {
ComponentDto file = ComponentTesting.newFileDto(project)
.setKey(fileKey)
.setLanguage(XOO_LANGUAGE);
dbClient.componentDao().insert(dbSession, file, false);
dbSession.commit();
return file;
}
private static Map<Integer, Block> blocksByIndexInFile(List<Block> blocks) {
Map<Integer, Block> blocksByIndexInFile = new HashMap<>();
for (Block block : blocks) {
blocksByIndexInFile.put(block.getIndexInFile(), block);
}
return blocksByIndexInFile;
}
}
| 13,740 | 38.828986 | 180 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadFileHashesAndStatusStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.ArrayList;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileStatusesImpl;
import org.sonar.ce.task.projectanalysis.component.PreviousSourceHashRepositoryImpl;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.source.FileHashesDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class LoadFileHashesAndStatusStepIT {
@Rule
public DbTester db = DbTester.create();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
public PreviousSourceHashRepositoryImpl previousFileHashesRepository = new PreviousSourceHashRepositoryImpl();
public FileStatusesImpl fileStatuses = mock(FileStatusesImpl.class);
public AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
private final LoadFileHashesAndStatusStep underTest = new LoadFileHashesAndStatusStep(db.getDbClient(), previousFileHashesRepository, fileStatuses,
db.getDbClient().fileSourceDao(), treeRootHolder);
@Before
public void before() {
when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false);
}
@Test
public void initialized_file_statuses() {
Component project = ReportComponent.builder(Component.Type.PROJECT, 1, "project").build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
verify(fileStatuses).initialize();
}
@Test
public void loads_file_hashes_for_project_branch() {
ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto project2 = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto dbFile1 = db.components().insertComponent(ComponentTesting.newFileDto(project1));
ComponentDto dbFile2 = db.components().insertComponent(ComponentTesting.newFileDto(project1));
insertFileSources(dbFile1, dbFile2);
Component reportFile1 = ReportComponent.builder(Component.Type.FILE, 2, dbFile1.getKey()).setUuid(dbFile1.uuid()).build();
Component reportFile2 = ReportComponent.builder(Component.Type.FILE, 3, dbFile2.getKey()).setUuid(dbFile2.uuid()).build();
Component reportFile3 = ReportComponent.builder(Component.Type.FILE, 4, dbFile2.getKey()).build();
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1, project1.getKey()).setUuid(project1.uuid())
.addChildren(reportFile1, reportFile2, reportFile3).build());
underTest.execute(new TestComputationStepContext());
assertThat(previousFileHashesRepository.getMap()).hasSize(2);
assertThat(previousFileHashesRepository.getDbFile(reportFile1).get())
.extracting(FileHashesDto::getSrcHash, FileHashesDto::getRevision, FileHashesDto::getDataHash)
.containsOnly("srcHash" + dbFile1.getKey(), "revision" + dbFile1.getKey(), "dataHash" + dbFile1.getKey());
assertThat(previousFileHashesRepository.getDbFile(reportFile2).get())
.extracting(FileHashesDto::getSrcHash, FileHashesDto::getRevision, FileHashesDto::getDataHash)
.containsOnly("srcHash" + dbFile2.getKey(), "revision" + dbFile2.getKey(), "dataHash" + dbFile2.getKey());
assertThat(previousFileHashesRepository.getDbFile(reportFile3)).isEmpty();
}
@Test
public void loads_high_number_of_files() {
ComponentDto project1 = db.components().insertPublicProject().getMainBranchComponent();
List<Component> files = new ArrayList<>(2000);
for (int i = 0; i < 2000; i++) {
ComponentDto dbFile = db.components().insertComponent(ComponentTesting.newFileDto(project1));
insertFileSources(dbFile);
files.add(ReportComponent.builder(Component.Type.FILE, 2, dbFile.getKey()).setUuid(dbFile.uuid()).build());
}
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1, project1.getKey()).setUuid(project1.uuid())
.addChildren(files.toArray(Component[]::new)).build());
underTest.execute(new TestComputationStepContext());
assertThat(previousFileHashesRepository.getMap()).hasSize(2000);
for (Component file : files) {
assertThat(previousFileHashesRepository.getDbFile(file)).isPresent();
}
}
private void insertFileSources(ComponentDto... files) {
for (ComponentDto file : files) {
db.fileSources().insertFileSource(file, f -> f
.setSrcHash("srcHash" + file.getKey())
.setRevision("revision" + file.getKey())
.setDataHash("dataHash" + file.getKey()));
}
}
}
| 5,950 | 45.858268 | 149 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadPeriodsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.event.Level;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.ce.task.log.CeTaskMessages;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.period.NewCodePeriodResolver;
import org.sonar.ce.task.projectanalysis.period.Period;
import org.sonar.ce.task.projectanalysis.period.PeriodHolderImpl;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventTesting;
import org.sonar.db.newcodeperiod.NewCodePeriodDao;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.server.project.Project;
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.assertj.core.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED;
import static org.sonar.db.event.EventDto.CATEGORY_VERSION;
import static org.sonar.db.event.EventTesting.newEvent;
@RunWith(DataProviderRunner.class)
public class LoadPeriodsStepIT extends BaseStepTest {
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public LogTester logTester = new LogTester();
private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
private final PeriodHolderImpl periodsHolder = new PeriodHolderImpl();
private final System2 system2Mock = mock(System2.class);
private final NewCodePeriodDao dao = new NewCodePeriodDao(system2Mock, new SequenceUuidFactory());
private final NewCodePeriodResolver newCodePeriodResolver = new NewCodePeriodResolver(dbTester.getDbClient(), analysisMetadataHolder);
private final ZonedDateTime analysisDate = ZonedDateTime.of(2019, 3, 20, 5, 30, 40, 0, ZoneId.systemDefault());
private final CeTaskMessages ceTaskMessages = mock(CeTaskMessages.class);
private final LoadPeriodsStep underTest = new LoadPeriodsStep(analysisMetadataHolder, dao, treeRootHolder, periodsHolder, dbTester.getDbClient(), newCodePeriodResolver,
ceTaskMessages, system2Mock);
private ComponentDto project;
@Override
protected ComputationStep step() {
return underTest;
}
@Before
public void setUp() {
logTester.setLevel(Level.TRACE);
project = dbTester.components().insertPublicProject().getMainBranchComponent();
when(analysisMetadataHolder.isBranch()).thenReturn(true);
when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(false);
when(analysisMetadataHolder.getAnalysisDate()).thenReturn(analysisDate.toInstant().toEpochMilli());
}
@Test
public void no_period_on_first_analysis() {
setupRoot(project);
when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true);
underTest.execute(new TestComputationStepContext());
verify(analysisMetadataHolder).isFirstAnalysis();
verify(analysisMetadataHolder).isBranch();
verify(analysisMetadataHolder).getProject();
verify(analysisMetadataHolder).getNewCodeReferenceBranch();
assertThat(periodsHolder.hasPeriod()).isFalse();
verifyNoMoreInteractions(analysisMetadataHolder);
}
@Test
public void no_period_date_if_not_branch() {
when(analysisMetadataHolder.isBranch()).thenReturn(false);
underTest.execute(new TestComputationStepContext());
verify(analysisMetadataHolder).isBranch();
assertThat(periodsHolder.hasPeriod()).isFalse();
verifyNoMoreInteractions(analysisMetadataHolder);
}
@Test
public void load_default_if_nothing_defined() {
setupRoot(project);
SnapshotDto analysis = dbTester.components().insertSnapshot(project,
snapshot -> snapshot.setCreatedAt(milisSinceEpoch(2019, 3, 15, 0)));
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.PREVIOUS_VERSION, null, analysis.getCreatedAt());
verifyDebugLogs("Resolving first analysis as new code period as there is only one existing version");
}
@Test
public void load_number_of_days_global() {
setGlobalPeriod(NewCodePeriodType.NUMBER_OF_DAYS, "10");
testNumberOfDays(project);
}
@Test
public void load_number_of_days_on_project() {
setGlobalPeriod(NewCodePeriodType.PREVIOUS_VERSION, null);
setProjectPeriod(project.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, "10");
testNumberOfDays(project);
}
@Test
public void load_number_of_days_on_branch() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
setGlobalPeriod(NewCodePeriodType.PREVIOUS_VERSION, null);
setProjectPeriod(project.uuid(), NewCodePeriodType.PREVIOUS_VERSION, null);
setBranchPeriod(project.uuid(), branch.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, "10");
testNumberOfDays(branch);
verifyNoInteractions(ceTaskMessages);
}
@Test
public void load_reference_branch() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
setupRoot(branch);
setProjectPeriod(project.uuid(), NewCodePeriodType.REFERENCE_BRANCH, "master");
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.REFERENCE_BRANCH, "master", null);
verifyNoInteractions(ceTaskMessages);
}
@Test
public void scanner_overrides_branch_new_code_reference_branch() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
setupRoot(branch);
setBranchPeriod(project.uuid(), branch.uuid(), NewCodePeriodType.REFERENCE_BRANCH, "master");
String newCodeReferenceBranch = "newCodeReferenceBranch";
when(analysisMetadataHolder.getNewCodeReferenceBranch()).thenReturn(Optional.of(newCodeReferenceBranch));
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.REFERENCE_BRANCH, newCodeReferenceBranch, null);
verify(ceTaskMessages).add(any(CeTaskMessages.Message.class));
}
@Test
public void scanner_defines_new_code_reference_branch() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
setupRoot(branch);
String newCodeReferenceBranch = "newCodeReferenceBranch";
when(analysisMetadataHolder.getNewCodeReferenceBranch()).thenReturn(Optional.of(newCodeReferenceBranch));
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.REFERENCE_BRANCH, newCodeReferenceBranch, null);
verifyNoInteractions(ceTaskMessages);
}
@Test
public void scanner_overrides_project_new_code_reference_branch() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
setupRoot(branch);
setProjectPeriod(project.uuid(), NewCodePeriodType.REFERENCE_BRANCH, "master");
String newCodeReferenceBranch = "newCodeReferenceBranch";
when(analysisMetadataHolder.getNewCodeReferenceBranch()).thenReturn(Optional.of(newCodeReferenceBranch));
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.REFERENCE_BRANCH, newCodeReferenceBranch, null);
verifyNoInteractions(ceTaskMessages);
}
@Test
public void load_reference_branch_without_fork_date_in_report() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
setupRoot(branch);
setProjectPeriod(project.uuid(), NewCodePeriodType.REFERENCE_BRANCH, "master");
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.REFERENCE_BRANCH, "master", null);
verifyNoInteractions(ceTaskMessages);
}
private void testNumberOfDays(ComponentDto projectOrBranch) {
setupRoot(projectOrBranch);
SnapshotDto analysis = dbTester.components().insertSnapshot(projectOrBranch,
snapshot -> snapshot.setCreatedAt(milisSinceEpoch(2019, 3, 15, 0)));
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.NUMBER_OF_DAYS, "10", analysis.getCreatedAt());
verifyDebugLogs("Resolving new code period by 10 days: 2019-03-10");
}
@Test
public void load_specific_analysis() {
ComponentDto branch = dbTester.components().insertProjectBranch(project);
SnapshotDto selectedAnalysis = dbTester.components().insertSnapshot(branch);
SnapshotDto aVersionAnalysis = dbTester.components().insertSnapshot(branch, snapshot -> snapshot.setCreatedAt(milisSinceEpoch(2019, 3, 12, 0)).setLast(false));
dbTester.events().insertEvent(EventTesting.newEvent(aVersionAnalysis).setName("a_version").setCategory(CATEGORY_VERSION));
dbTester.components().insertSnapshot(branch, snapshot -> snapshot.setCreatedAt(milisSinceEpoch(2019, 3, 15, 0)).setLast(true));
setBranchPeriod(project.uuid(), branch.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, selectedAnalysis.getUuid());
setupRoot(branch);
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.SPECIFIC_ANALYSIS, selectedAnalysis.getUuid(), selectedAnalysis.getCreatedAt());
verifyDebugLogs("Resolving new code period with a specific analysis");
verifyNoInteractions(ceTaskMessages);
}
@Test
public void throw_ISE_if_no_analysis_found_for_number_of_days() {
setProjectPeriod(project.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, "10");
setupRoot(project);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Attempting to resolve period while no analysis exist");
}
@Test
public void throw_ISE_if_no_analysis_found_with_default() {
setupRoot(project);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Attempting to resolve period while no analysis exist");
}
@Test
public void ignore_unprocessed_snapshots() {
SnapshotDto analysis1 = dbTester.components()
.insertSnapshot(project, snapshot -> snapshot.setStatus(STATUS_UNPROCESSED).setCreatedAt(milisSinceEpoch(2019, 3, 12, 0)).setLast(false));
SnapshotDto analysis2 = dbTester.components().insertSnapshot(project,
snapshot -> snapshot.setStatus(STATUS_PROCESSED).setProjectVersion("not provided").setCreatedAt(milisSinceEpoch(2019, 3, 15, 0)).setLast(false));
dbTester.events().insertEvent(newEvent(analysis1).setName("not provided").setCategory(CATEGORY_VERSION).setDate(analysis1.getCreatedAt()));
dbTester.events().insertEvent(newEvent(analysis2).setName("not provided").setCategory(CATEGORY_VERSION).setDate(analysis2.getCreatedAt()));
setupRoot(project);
setProjectPeriod(project.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, "10");
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.NUMBER_OF_DAYS, "10", analysis2.getCreatedAt());
verifyDebugLogs("Resolving new code period by 10 days: 2019-03-10");
}
@Test
public void throw_ISE_when_specific_analysis_is_set_but_does_not_exist_in_DB() {
ComponentDto project = dbTester.components().insertPublicProject().getMainBranchComponent();
setProjectPeriod(project.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, "nonexistent");
setupRoot(project, project.uuid(), "any-string");
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis 'nonexistent' of project '" + project.uuid() + "' defined as the baseline does not exist");
}
@Test
public void throw_ISE_when_specific_analysis_is_set_but_does_not_belong_to_current_project() {
ComponentDto otherProject = dbTester.components().insertPublicProject().getMainBranchComponent();
SnapshotDto otherProjectAnalysis = dbTester.components().insertSnapshot(otherProject);
setBranchPeriod(project.uuid(), project.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, otherProjectAnalysis.getUuid());
setupRoot(project);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis '" + otherProjectAnalysis.getUuid() + "' of project '" + project.uuid() + "' defined as the baseline does not exist");
}
@Test
public void throw_ISE_when_specific_analysis_is_set_but_does_not_belong_to_current_branch() {
ComponentDto otherBranch = dbTester.components().insertProjectBranch(project);
SnapshotDto otherBranchAnalysis = dbTester.components().insertSnapshot(otherBranch);
setBranchPeriod(project.uuid(), project.uuid(), NewCodePeriodType.SPECIFIC_ANALYSIS, otherBranchAnalysis.getUuid());
setupRoot(project);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis '" + otherBranchAnalysis.getUuid() + "' of project '" + project.uuid() + "' defined as the baseline does not exist");
}
@Test
public void load_previous_version() {
SnapshotDto analysis1 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226379600000L).setProjectVersion("0.9").setLast(false)); // 2008-11-11
SnapshotDto analysis2 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226494680000L).setProjectVersion("1.0").setLast(false)); // 2008-11-12
SnapshotDto analysis3 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227157200000L).setProjectVersion("1.1").setLast(false)); // 2008-11-20
SnapshotDto analysis4 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227358680000L).setProjectVersion("1.1").setLast(false)); // 2008-11-22
SnapshotDto analysis5 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227934800000L).setProjectVersion("1.1").setLast(true)); // 2008-11-29
dbTester.events().insertEvent(newEvent(analysis1).setName("0.9").setCategory(CATEGORY_VERSION).setDate(analysis1.getCreatedAt()));
dbTester.events().insertEvent(newEvent(analysis2).setName("1.0").setCategory(CATEGORY_VERSION).setDate(analysis2.getCreatedAt()));
dbTester.events().insertEvent(newEvent(analysis5).setName("1.1").setCategory(CATEGORY_VERSION).setDate(analysis5.getCreatedAt()));
setupRoot(project, "1.1");
setProjectPeriod(project.uuid(), NewCodePeriodType.PREVIOUS_VERSION, null);
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.PREVIOUS_VERSION, "1.0", analysis2.getCreatedAt());
verifyDebugLogs("Resolving new code period by previous version: 1.0");
}
@Test
public void load_previous_version_when_version_is_changing() {
SnapshotDto analysis1 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226379600000L).setProjectVersion("0.9").setLast(false)); // 2008-11-11
SnapshotDto analysis2 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226494680000L).setProjectVersion("0.9").setLast(true)); // 2008-11-12
dbTester.events().insertEvent(newEvent(analysis2).setName("0.9").setCategory(CATEGORY_VERSION).setDate(analysis2.getCreatedAt()));
setupRoot(project, "1.0");
setProjectPeriod(project.uuid(), NewCodePeriodType.PREVIOUS_VERSION, null);
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.PREVIOUS_VERSION, "0.9", analysis2.getCreatedAt());
verifyDebugLogs("Resolving new code period by previous version: 0.9");
}
@Test
@UseDataProvider("zeroOrLess")
public void fail_with_MessageException_if_period_is_0_or_less(int zeroOrLess) {
setupRoot(project);
setProjectPeriod(project.uuid(), NewCodePeriodType.NUMBER_OF_DAYS, String.valueOf(zeroOrLess));
verifyFailWithInvalidValueMessageException(String.valueOf(zeroOrLess),
"Invalid code period '" + zeroOrLess + "': number of days is <= 0");
}
@Test
public void load_previous_version_with_previous_version_deleted() {
SnapshotDto analysis1 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226379600000L).setProjectVersion("0.9").setLast(false)); // 2008-11-11
SnapshotDto analysis2 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226494680000L).setProjectVersion("1.0").setLast(false)); // 2008-11-12
SnapshotDto analysis3 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227157200000L).setProjectVersion("1.1").setLast(true)); // 2008-11-20
dbTester.events().insertEvent(newEvent(analysis1).setName("0.9").setCategory(CATEGORY_VERSION));
// The "1.0" version was deleted from the history
setupRoot(project, "1.1");
underTest.execute(new TestComputationStepContext());
// Analysis form 2008-11-11
assertPeriod(NewCodePeriodType.PREVIOUS_VERSION, "0.9", analysis1.getCreatedAt());
}
@Test
public void load_previous_version_with_first_analysis_when_no_previous_version_found() {
SnapshotDto analysis1 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226379600000L).setProjectVersion("1.1").setLast(false)); // 2008-11-11
SnapshotDto analysis2 = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227934800000L).setProjectVersion("1.1").setLast(true)); // 2008-11-29
dbTester.events().insertEvent(newEvent(analysis2).setName("1.1").setCategory(CATEGORY_VERSION));
setupRoot(project, "1.1");
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.PREVIOUS_VERSION, null, analysis1.getCreatedAt());
verifyDebugLogs("Resolving first analysis as new code period as there is only one existing version");
}
@Test
public void load_previous_version_with_first_analysis_when_previous_snapshot_is_the_last_one() {
SnapshotDto analysis = dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226379600000L).setProjectVersion("0.9").setLast(true)); // 2008-11-11
dbTester.events().insertEvent(newEvent(analysis).setName("0.9").setCategory(CATEGORY_VERSION));
setupRoot(project, "1.1");
dbTester.newCodePeriods().insert(NewCodePeriodType.PREVIOUS_VERSION, null);
underTest.execute(new TestComputationStepContext());
assertPeriod(NewCodePeriodType.PREVIOUS_VERSION, "0.9", analysis.getCreatedAt());
verifyDebugLogs("Resolving new code period by previous version: 0.9");
}
@Test
@UseDataProvider("anyValidLeakPeriodSettingValue")
public void leak_period_setting_is_ignored_for_PR(NewCodePeriodType type, @Nullable String value) {
when(analysisMetadataHolder.isBranch()).thenReturn(false);
dbTester.newCodePeriods().insert(type, value);
underTest.execute(new TestComputationStepContext());
assertThat(periodsHolder.hasPeriod()).isFalse();
}
private void verifyFailWithInvalidValueMessageException(String propertyValue, String debugLog, String... otherDebugLogs) {
try {
underTest.execute(new TestComputationStepContext());
fail("a Message Exception should have been thrown");
} catch (MessageException e) {
verifyInvalidValueMessage(e, propertyValue);
verifyDebugLogs(debugLog, otherDebugLogs);
}
}
@DataProvider
public static Object[][] zeroOrLess() {
return new Object[][] {
{0},
{-1 - new Random().nextInt(30)}
};
}
@DataProvider
public static Object[][] stringConsideredAsVersions() {
return new Object[][] {
{randomAlphabetic(5)},
{"1,3"},
{"1.3"},
{"0 1"},
{"1-SNAPSHOT"},
{"01-12-2018"}, // unsupported date format
};
}
@DataProvider
public static Object[][] projectVersionNullOrNot() {
return new Object[][] {
{null},
{randomAlphabetic(15)},
};
}
@DataProvider
public static Object[][] anyValidLeakPeriodSettingValue() {
return new Object[][] {
// days
{NewCodePeriodType.NUMBER_OF_DAYS, "100"},
// previous_version
{NewCodePeriodType.PREVIOUS_VERSION, null}
};
}
private List<SnapshotDto> createSnapshots(ComponentDto project) {
ArrayList<SnapshotDto> list = new ArrayList<>();
list.add(dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226379600000L).setLast(false))); // 2008-11-11
list.add(dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1226494680000L).setLast(false))); // 2008-11-12
list.add(dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227157200000L).setLast(false))); // 2008-11-20
list.add(dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227358680000L).setLast(false))); // 2008-11-22
list.add(dbTester.components().insertSnapshot(project, snapshot -> snapshot.setCreatedAt(1227934800000L).setLast(true))); // 2008-11-29
return list;
}
private long milisSinceEpoch(int year, int month, int day, int hour) {
return ZonedDateTime.of(year, month, day, hour, 0, 0, 0, ZoneId.systemDefault())
.toInstant().toEpochMilli();
}
private void setProjectPeriod(String projectUuid, NewCodePeriodType type, @Nullable String value) {
dbTester.newCodePeriods().insert(projectUuid, type, value);
}
private void setBranchPeriod(String projectUuid, String branchUuid, NewCodePeriodType type, @Nullable String value) {
dbTester.newCodePeriods().insert(projectUuid, branchUuid, type, value);
}
private void setGlobalPeriod(NewCodePeriodType type, @Nullable String value) {
dbTester.newCodePeriods().insert(type, value);
}
private void assertPeriod(NewCodePeriodType type, @Nullable String value, @Nullable Long date) {
Period period = periodsHolder.getPeriod();
assertThat(period).isNotNull();
assertThat(period.getMode()).isEqualTo(type.name());
assertThat(period.getModeParameter()).isEqualTo(value);
assertThat(period.getDate()).isEqualTo(date);
}
private void verifyDebugLogs(String log, String... otherLogs) {
assertThat(logTester.logs(Level.DEBUG))
.contains(Stream.concat(Stream.of(log), Arrays.stream(otherLogs)).toArray(String[]::new));
}
private void setupRoot(ComponentDto branchComponent) {
setupRoot(branchComponent, "any-string");
}
private void setupRoot(ComponentDto branchComponent, String projectUuid, String version) {
treeRootHolder.setRoot(ReportComponent
.builder(Component.Type.PROJECT, 1)
.setUuid(branchComponent.uuid())
.setKey(branchComponent.getKey())
.setProjectVersion(version)
.build());
Project project = mock(Project.class);
when(project.getUuid()).thenReturn(projectUuid);
when(analysisMetadataHolder.getProject()).thenReturn(project);
}
private void setupRoot(ComponentDto branchComponent, String version) {
setupRoot(branchComponent, project.uuid(), version);
}
private static void verifyInvalidValueMessage(MessageException e, String propertyValue) {
assertThat(e).hasMessage("Invalid new code period. '" + propertyValue
+ "' is not one of: integer > 0, date before current analysis j, \"previous_version\", or version string that exists in the project' \n" +
"Please contact a project administrator to correct this setting");
}
}
| 25,632 | 44.529307 | 179 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/LoadReportAnalysisMetadataHolderStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.assertj.core.api.Assertions;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.Plugin;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.ScannerPlugin;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.BranchLoader;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.platform.PluginInfo;
import org.sonar.core.platform.PluginRepository;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.project.DefaultBranchNameResolver;
import org.sonar.server.project.Project;
import static java.util.Arrays.stream;
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.when;
@RunWith(DataProviderRunner.class)
public class LoadReportAnalysisMetadataHolderStepIT {
private static final String PROJECT_KEY = "project_key";
private static final long ANALYSIS_DATE = 123456789L;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
private final DbClient dbClient = db.getDbClient();
private final TestPluginRepository pluginRepository = new TestPluginRepository();
private ProjectDto project;
private ComputationStep underTest;
@Before
public void setUp() {
CeTask defaultOrgCeTask = createCeTask(PROJECT_KEY);
underTest = createStep(defaultOrgCeTask);
project = db.components().insertPublicProject(p -> p.setKey(PROJECT_KEY)).getProjectDto();
}
@Test
public void set_root_component_ref() {
reportReader.setMetadata(
newBatchReportBuilder()
.setRootComponentRef(1)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.getRootComponentRef()).isOne();
}
@Test
public void set_analysis_date() {
reportReader.setMetadata(
newBatchReportBuilder()
.setAnalysisDate(ANALYSIS_DATE)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.getAnalysisDate()).isEqualTo(ANALYSIS_DATE);
}
@Test
public void set_new_code_reference_branch() {
String newCodeReferenceBranch = "newCodeReferenceBranch";
reportReader.setMetadata(
newBatchReportBuilder()
.setNewCodeReferenceBranch(newCodeReferenceBranch)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.getNewCodeReferenceBranch()).hasValue(newCodeReferenceBranch);
}
@Test
public void set_project_from_dto() {
reportReader.setMetadata(
newBatchReportBuilder()
.setRootComponentRef(1)
.build());
underTest.execute(new TestComputationStepContext());
Project project = analysisMetadataHolder.getProject();
assertThat(project.getUuid()).isEqualTo(this.project.getUuid());
assertThat(project.getKey()).isEqualTo(this.project.getKey());
assertThat(project.getName()).isEqualTo(this.project.getName());
assertThat(project.getDescription()).isEqualTo(this.project.getDescription());
}
@Test
public void set_cross_project_duplication_to_true() {
reportReader.setMetadata(
newBatchReportBuilder()
.setCrossProjectDuplicationActivated(true)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.isCrossProjectDuplicationEnabled()).isTrue();
}
@Test
public void set_cross_project_duplication_to_false() {
reportReader.setMetadata(
newBatchReportBuilder()
.setCrossProjectDuplicationActivated(false)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.isCrossProjectDuplicationEnabled()).isFalse();
}
@Test
public void set_cross_project_duplication_to_false_when_nothing_in_the_report() {
reportReader.setMetadata(
newBatchReportBuilder()
.build());
underTest.execute(new TestComputationStepContext());
assertThat(analysisMetadataHolder.isCrossProjectDuplicationEnabled()).isFalse();
}
@Test
public void execute_fails_with_ISE_if_component_is_null_in_CE_task() {
CeTask res = mock(CeTask.class);
when(res.getComponent()).thenReturn(Optional.empty());
reportReader.setMetadata(ScannerReport.Metadata.newBuilder().build());
ComputationStep underTest = createStep(res);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("component missing on ce task");
}
@Test
public void execute_fails_with_MessageException_if_main_projectKey_is_null_in_CE_task() {
CeTask res = mock(CeTask.class);
Optional<CeTask.Component> component = Optional.of(new CeTask.Component("main_prj_uuid", null, null));
when(res.getComponent()).thenReturn(component);
when(res.getEntity()).thenReturn(component);
reportReader.setMetadata(ScannerReport.Metadata.newBuilder().build());
ComputationStep underTest = createStep(res);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(MessageException.class)
.hasMessage("Compute Engine task entity key is null. Project with UUID main_prj_uuid must have been deleted since report was uploaded. Can not proceed.");
}
@Test
public void execute_fails_with_MessageException_if_projectKey_is_null_in_CE_task() {
CeTask res = mock(CeTask.class);
Optional<CeTask.Component> component = Optional.of(new CeTask.Component("prj_uuid", null, null));
when(res.getComponent()).thenReturn(component);
when(res.getEntity()).thenReturn(Optional.of(new CeTask.Component("main_prj_uuid", "main_prj_key", null)));
reportReader.setMetadata(ScannerReport.Metadata.newBuilder().build());
ComputationStep underTest = createStep(res);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(MessageException.class)
.hasMessage("Compute Engine task component key is null. Project with UUID prj_uuid must have been deleted since report was uploaded. Can not proceed.");
}
@Test
public void execute_fails_with_MessageException_when_projectKey_in_report_is_different_from_componentKey_in_CE_task() {
ComponentDto otherProject = db.components().insertPublicProject().getMainBranchComponent();
reportReader.setMetadata(
ScannerReport.Metadata.newBuilder()
.setProjectKey(otherProject.getKey())
.build());
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(MessageException.class)
.hasMessage("ProjectKey in report (" + otherProject.getKey() + ") is not consistent with projectKey under which the report has been submitted (" + PROJECT_KEY + ")");
}
@Test
public void execute_sets_branch_even_if_MessageException_is_thrown_because_projectKey_in_report_is_different_from_componentKey_in_CE_task() {
ComponentDto otherProject = db.components().insertPublicProject().getMainBranchComponent();
reportReader.setMetadata(
ScannerReport.Metadata.newBuilder()
.setProjectKey(otherProject.getKey())
.build());
try {
underTest.execute(new TestComputationStepContext());
} catch (MessageException e) {
assertThat(analysisMetadataHolder.getBranch()).isNotNull();
}
}
@Test
public void execute_sets_analysis_date_even_if_MessageException_is_thrown_because_projectKey_is_different_from_componentKey_in_CE_task() {
ComponentDto otherProject = db.components().insertPublicProject().getMainBranchComponent();
reportReader.setMetadata(
ScannerReport.Metadata.newBuilder()
.setProjectKey(otherProject.getKey())
.setAnalysisDate(ANALYSIS_DATE)
.build());
try {
underTest.execute(new TestComputationStepContext());
} catch (MessageException e) {
assertThat(analysisMetadataHolder.getAnalysisDate()).isEqualTo(ANALYSIS_DATE);
}
}
@Test
public void execute_does_not_fail_when_report_has_a_quality_profile_that_does_not_exist_anymore() {
ComponentDto project = db.components().insertPublicProject().getMainBranchComponent();
ScannerReport.Metadata.Builder metadataBuilder = newBatchReportBuilder();
metadataBuilder
.setProjectKey(project.getKey());
metadataBuilder.putQprofilesPerLanguage("js", ScannerReport.Metadata.QProfile.newBuilder().setKey("p1").setName("Sonar way").setLanguage("js").build());
reportReader.setMetadata(metadataBuilder.build());
ComputationStep underTest = createStep(createCeTask(project.getKey()));
underTest.execute(new TestComputationStepContext());
}
@Test
public void execute_read_plugins_from_report() {
// the installed plugins
pluginRepository.add(
new PluginInfo("java"),
new PluginInfo("customjava").setBasePlugin("java"),
new PluginInfo("php"));
// the plugins sent by scanner
ScannerReport.Metadata.Builder metadataBuilder = newBatchReportBuilder();
metadataBuilder.putPluginsByKey("java", ScannerReport.Metadata.Plugin.newBuilder().setKey("java").setUpdatedAt(10L).build());
metadataBuilder.putPluginsByKey("php", ScannerReport.Metadata.Plugin.newBuilder().setKey("php").setUpdatedAt(20L).build());
metadataBuilder.putPluginsByKey("customjava", ScannerReport.Metadata.Plugin.newBuilder().setKey("customjava").setUpdatedAt(30L).build());
metadataBuilder.putPluginsByKey("uninstalled", ScannerReport.Metadata.Plugin.newBuilder().setKey("uninstalled").setUpdatedAt(40L).build());
reportReader.setMetadata(metadataBuilder.build());
underTest.execute(new TestComputationStepContext());
Assertions.assertThat(analysisMetadataHolder.getScannerPluginsByKey().values()).extracting(ScannerPlugin::getKey, ScannerPlugin::getBasePluginKey, ScannerPlugin::getUpdatedAt)
.containsExactlyInAnyOrder(
tuple("java", null, 10L),
tuple("php", null, 20L),
tuple("customjava", "java", 30L),
tuple("uninstalled", null, 40L));
}
private LoadReportAnalysisMetadataHolderStep createStep(CeTask ceTask) {
return new LoadReportAnalysisMetadataHolderStep(ceTask, reportReader, analysisMetadataHolder,
dbClient, new BranchLoader(analysisMetadataHolder, mock(DefaultBranchNameResolver.class)), pluginRepository);
}
private static ScannerReport.Metadata.Builder newBatchReportBuilder() {
return ScannerReport.Metadata.newBuilder()
.setProjectKey(PROJECT_KEY);
}
private CeTask createCeTask(String projectKey) {
CeTask res = mock(CeTask.class);
Optional<CeTask.Component> entity = Optional.of(new CeTask.Component(projectKey + "_uuid", projectKey, projectKey + "_name"));
Optional<CeTask.Component> component = Optional.of(new CeTask.Component(projectKey + "branch_uuid", projectKey, projectKey + "_name"));
when(res.getComponent()).thenReturn(component);
when(res.getEntity()).thenReturn(entity);
return res;
}
private static class TestPluginRepository implements PluginRepository {
private final Map<String, PluginInfo> pluginsMap = new HashMap<>();
void add(PluginInfo... plugins) {
stream(plugins).forEach(p -> pluginsMap.put(p.getKey(), p));
}
@Override
public Collection<PluginInfo> getPluginInfos() {
return pluginsMap.values();
}
@Override
public PluginInfo getPluginInfo(String key) {
if (!pluginsMap.containsKey(key)) {
throw new IllegalArgumentException();
}
return pluginsMap.get(key);
}
@Override
public Plugin getPluginInstance(String key) {
throw new UnsupportedOperationException();
}
@Override
public Collection<Plugin> getPluginInstances() {
throw new UnsupportedOperationException();
}
@Override
public boolean hasPlugin(String key) {
return pluginsMap.containsKey(key);
}
}
}
| 13,789 | 37.84507 | 179 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistAdHocRulesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.issue.AdHocRuleCreator;
import org.sonar.ce.task.projectanalysis.issue.NewAdHocRule;
import org.sonar.ce.task.projectanalysis.issue.RuleRepositoryImpl;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.SequenceUuidFactory;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.rule.RuleDao;
import org.sonar.db.rule.RuleDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.es.EsTester;
import org.sonar.server.rule.index.RuleIndexDefinition;
import org.sonar.server.rule.index.RuleIndexer;
import static org.assertj.core.api.Assertions.assertThat;
public class PersistAdHocRulesStepIT extends BaseStepTest {
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private DbClient dbClient = db.getDbClient();
private ComputationStep underTest;
private RuleRepositoryImpl ruleRepository;
@org.junit.Rule
public EsTester es = EsTester.create();
private RuleIndexer indexer = new RuleIndexer(es.client(), dbClient);
private AdHocRuleCreator adHocRuleCreator = new AdHocRuleCreator(dbClient, System2.INSTANCE, indexer, new SequenceUuidFactory());
@Override
protected ComputationStep step() {
return underTest;
}
@Before
public void setup() {
ruleRepository = new RuleRepositoryImpl(adHocRuleCreator, dbClient);
underTest = new PersistAdHocRulesStep(dbClient, ruleRepository);
}
@Test
public void persist_and_index_new_ad_hoc_rules() {
RuleKey ruleKey = RuleKey.of("external_eslint", "no-cond-assign");
ruleRepository.addOrUpdateAddHocRuleIfNeeded(ruleKey,
() -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build()));
underTest.execute(new TestComputationStepContext());
RuleDao ruleDao = dbClient.ruleDao();
Optional<RuleDto> ruleDefinitionDtoOptional = ruleDao.selectByKey(dbClient.openSession(false), ruleKey);
assertThat(ruleDefinitionDtoOptional).isPresent();
RuleDto reloaded = ruleDefinitionDtoOptional.get();
assertThat(reloaded.getRuleKey()).isEqualTo("no-cond-assign");
assertThat(reloaded.getRepositoryKey()).isEqualTo("external_eslint");
assertThat(reloaded.isExternal()).isTrue();
assertThat(reloaded.isAdHoc()).isTrue();
assertThat(reloaded.getType()).isZero();
assertThat(reloaded.getSeverity()).isNull();
assertThat(reloaded.getName()).isEqualTo("eslint:no-cond-assign");
assertThat(es.countDocuments(RuleIndexDefinition.TYPE_RULE)).isOne();
assertThat(es.getDocuments(RuleIndexDefinition.TYPE_RULE).iterator().next().getId()).isEqualTo(reloaded.getUuid());
}
@Test
public void do_not_persist_existing_external_rules() {
RuleKey ruleKey = RuleKey.of("eslint", "no-cond-assign");
db.rules().insert(ruleKey, r -> r.setIsExternal(true));
ruleRepository.addOrUpdateAddHocRuleIfNeeded(ruleKey,
() -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build()));
underTest.execute(new TestComputationStepContext());
RuleDao ruleDao = dbClient.ruleDao();
assertThat(ruleDao.selectAll(dbClient.openSession(false))).hasSize(1);
assertThat(es.countDocuments(RuleIndexDefinition.TYPE_RULE)).isZero();
}
}
| 4,451 | 38.75 | 131 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistAnalysisPropertiesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.ImmutableList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.CloseableIterator;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbTester;
import org.sonar.db.component.AnalysisPropertyDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PersistAnalysisPropertiesStepIT {
private static final String SNAPSHOT_UUID = randomAlphanumeric(40);
private static final String SMALL_VALUE1 = randomAlphanumeric(50);
private static final String SMALL_VALUE2 = randomAlphanumeric(50);
private static final String SMALL_VALUE3 = randomAlphanumeric(50);
private static final String BIG_VALUE = randomAlphanumeric(5000);
private static final String VALUE_PREFIX_FOR_PR_PROPERTIES = "pr_";
private static final List<ScannerReport.ContextProperty> PROPERTIES = Arrays.asList(
newContextProperty("key1", "value1"),
newContextProperty("key2", "value1"),
newContextProperty("sonar.analysis", SMALL_VALUE1),
newContextProperty("sonar.analysis.branch", SMALL_VALUE2),
newContextProperty("sonar.analysis.empty_string", ""),
newContextProperty("sonar.analysis.big_value", BIG_VALUE),
newContextProperty("sonar.analysis.", SMALL_VALUE3),
newContextProperty("sonar.pullrequest", VALUE_PREFIX_FOR_PR_PROPERTIES + SMALL_VALUE1),
newContextProperty("sonar.pullrequest.branch", VALUE_PREFIX_FOR_PR_PROPERTIES + SMALL_VALUE2),
newContextProperty("sonar.pullrequest.empty_string", ""),
newContextProperty("sonar.pullrequest.big_value", VALUE_PREFIX_FOR_PR_PROPERTIES + BIG_VALUE),
newContextProperty("sonar.pullrequest.", VALUE_PREFIX_FOR_PR_PROPERTIES + SMALL_VALUE3));
private static final String SCM_REV_ID = "sha1";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private BatchReportReader batchReportReader = mock(BatchReportReader.class);
private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
private PersistAnalysisPropertiesStep underTest = new PersistAnalysisPropertiesStep(dbTester.getDbClient(), analysisMetadataHolder, batchReportReader,
UuidFactoryFast.getInstance());
@Test
public void persist_should_stores_sonarDotAnalysisDot_and_sonarDotPullRequestDot_properties() {
when(batchReportReader.readContextProperties()).thenReturn(CloseableIterator.from(PROPERTIES.iterator()));
when(analysisMetadataHolder.getUuid()).thenReturn(SNAPSHOT_UUID);
when(analysisMetadataHolder.getScmRevision()).thenReturn(Optional.of(SCM_REV_ID));
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("analysis_properties")).isEqualTo(8);
List<AnalysisPropertyDto> propertyDtos = dbTester.getDbClient()
.analysisPropertiesDao().selectByAnalysisUuid(dbTester.getSession(), SNAPSHOT_UUID);
assertThat(propertyDtos)
.extracting(AnalysisPropertyDto::getAnalysisUuid, AnalysisPropertyDto::getKey, AnalysisPropertyDto::getValue)
.containsExactlyInAnyOrder(
tuple(SNAPSHOT_UUID, "sonar.analysis.branch", SMALL_VALUE2),
tuple(SNAPSHOT_UUID, "sonar.analysis.empty_string", ""),
tuple(SNAPSHOT_UUID, "sonar.analysis.big_value", BIG_VALUE),
tuple(SNAPSHOT_UUID, "sonar.analysis.", SMALL_VALUE3),
tuple(SNAPSHOT_UUID, "sonar.pullrequest.branch", VALUE_PREFIX_FOR_PR_PROPERTIES + SMALL_VALUE2),
tuple(SNAPSHOT_UUID, "sonar.pullrequest.empty_string", ""),
tuple(SNAPSHOT_UUID, "sonar.pullrequest.big_value", VALUE_PREFIX_FOR_PR_PROPERTIES + BIG_VALUE),
tuple(SNAPSHOT_UUID, "sonar.pullrequest.", VALUE_PREFIX_FOR_PR_PROPERTIES + SMALL_VALUE3));
}
@Test
public void persist_filtering_of_properties_is_case_sensitive() {
when(analysisMetadataHolder.getScmRevision()).thenReturn(Optional.of(SCM_REV_ID));
when(batchReportReader.readContextProperties()).thenReturn(CloseableIterator.from(ImmutableList.of(
newContextProperty("sonar.ANALYSIS.foo", "foo"),
newContextProperty("sonar.anaLysis.bar", "bar"),
newContextProperty("sonar.anaLYSIS.doo", "doh"),
newContextProperty("sonar.PULLREQUEST.foo", "foo"),
newContextProperty("sonar.pullRequest.bar", "bar"),
newContextProperty("sonar.pullREQUEST.doo", "doh")).iterator()));
when(analysisMetadataHolder.getUuid()).thenReturn(SNAPSHOT_UUID);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("analysis_properties")).isZero();
}
@Test
public void persist_should_store_nothing_if_there_are_no_context_properties() {
when(analysisMetadataHolder.getScmRevision()).thenReturn(Optional.of(SCM_REV_ID));
when(batchReportReader.readContextProperties()).thenReturn(CloseableIterator.emptyCloseableIterator());
when(analysisMetadataHolder.getUuid()).thenReturn(SNAPSHOT_UUID);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("analysis_properties")).isZero();
}
@Test
public void verify_description_value() {
assertThat(underTest.getDescription()).isEqualTo("Persist analysis properties");
}
private static ScannerReport.ContextProperty newContextProperty(String key, String value) {
return ScannerReport.ContextProperty.newBuilder()
.setKey(key)
.setValue(value)
.build();
}
}
| 6,832 | 48.158273 | 152 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistCrossProjectDuplicationIndexStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.Analysis;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.duplication.CrossProjectDuplicationStatusHolder;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.scanner.protocol.output.ScannerReport;
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 PersistCrossProjectDuplicationIndexStepIT {
private static final int FILE_1_REF = 2;
private static final int FILE_2_REF = 3;
private static final String FILE_2_UUID = "file2";
private static final Component FILE_1 = ReportComponent.builder(Component.Type.FILE, FILE_1_REF).build();
private static final Component FILE_2 = ReportComponent.builder(Component.Type.FILE, FILE_2_REF)
.setStatus(Component.Status.SAME).setUuid(FILE_2_UUID).build();
private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, 1)
.addChildren(FILE_1)
.addChildren(FILE_2)
.build();
private static final ScannerReport.CpdTextBlock CPD_TEXT_BLOCK = ScannerReport.CpdTextBlock.newBuilder()
.setHash("a8998353e96320ec")
.setStartLine(30)
.setEndLine(45)
.build();
private static final String ANALYSIS_UUID = "analysis uuid";
private static final String BASE_ANALYSIS_UUID = "base analysis uuid";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT);
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
private CrossProjectDuplicationStatusHolder crossProjectDuplicationStatusHolder = mock(CrossProjectDuplicationStatusHolder.class);
private Analysis baseAnalysis = mock(Analysis.class);
private DbClient dbClient = dbTester.getDbClient();
private ComputationStep underTest;
@Before
public void setUp() {
when(baseAnalysis.getUuid()).thenReturn(BASE_ANALYSIS_UUID);
analysisMetadataHolder.setUuid(ANALYSIS_UUID);
analysisMetadataHolder.setBaseAnalysis(baseAnalysis);
underTest = new PersistCrossProjectDuplicationIndexStep(crossProjectDuplicationStatusHolder, dbClient, treeRootHolder, analysisMetadataHolder, reportReader);
}
@Test
public void persist_cpd_text_block() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
reportReader.putDuplicationBlocks(FILE_1_REF, singletonList(CPD_TEXT_BLOCK));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
Map<String, Object> dto = dbTester.selectFirst("select HASH, START_LINE, END_LINE, INDEX_IN_FILE, COMPONENT_UUID, ANALYSIS_UUID from duplications_index");
assertThat(dto)
.containsEntry("HASH", CPD_TEXT_BLOCK.getHash())
.containsEntry("START_LINE", 30L)
.containsEntry("END_LINE", 45L)
.containsEntry("INDEX_IN_FILE", 0L)
.containsEntry("COMPONENT_UUID", FILE_1.getUuid())
.containsEntry("ANALYSIS_UUID", ANALYSIS_UUID);
context.getStatistics().assertValue("inserts", 1);
}
@Test
public void persist_many_cpd_text_blocks() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
reportReader.putDuplicationBlocks(FILE_1_REF, Arrays.asList(
CPD_TEXT_BLOCK,
ScannerReport.CpdTextBlock.newBuilder()
.setHash("b1234353e96320ff")
.setStartLine(20)
.setEndLine(15)
.build()));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
List<Map<String, Object>> dtos = dbTester.select("select HASH, START_LINE, END_LINE, INDEX_IN_FILE, COMPONENT_UUID, ANALYSIS_UUID from duplications_index");
assertThat(dtos).extracting("HASH").containsOnly(CPD_TEXT_BLOCK.getHash(), "b1234353e96320ff");
assertThat(dtos).extracting("START_LINE").containsOnly(30L, 20L);
assertThat(dtos).extracting("END_LINE").containsOnly(45L, 15L);
assertThat(dtos).extracting("INDEX_IN_FILE").containsOnly(0L, 1L);
assertThat(dtos).extracting("COMPONENT_UUID").containsOnly(FILE_1.getUuid());
assertThat(dtos).extracting("ANALYSIS_UUID").containsOnly(ANALYSIS_UUID);
context.getStatistics().assertValue("inserts", 2);
}
@Test
public void nothing_to_persist_when_no_cpd_text_blocks_in_report() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(true);
reportReader.putDuplicationBlocks(FILE_1_REF, Collections.emptyList());
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
assertThat(dbTester.countRowsOfTable("duplications_index")).isZero();
context.getStatistics().assertValue("inserts", 0);
}
@Test
public void nothing_to_do_when_cross_project_duplication_is_disabled() {
when(crossProjectDuplicationStatusHolder.isEnabled()).thenReturn(false);
reportReader.putDuplicationBlocks(FILE_1_REF, singletonList(CPD_TEXT_BLOCK));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
assertThat(dbTester.countRowsOfTable("duplications_index")).isZero();
context.getStatistics().assertValue("inserts", null);
}
}
| 6,963 | 41.987654 | 161 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistDuplicationDataStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.duplication.DuplicationRepositoryRule;
import org.sonar.ce.task.projectanalysis.duplication.TextBlock;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.measures.CoreMetrics.DUPLICATIONS_DATA_KEY;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
public class PersistDuplicationDataStepIT extends BaseStepTest {
private static final int ROOT_REF = 1;
private static final String PROJECT_KEY = "PROJECT_KEY";
private static final String PROJECT_UUID = "u1";
private static final int FILE_1_REF = 2;
private static final String FILE_1_KEY = "FILE_1_KEY";
private static final String FILE_1_UUID = "u2";
private static final int FILE_2_REF = 3;
private static final String FILE_2_KEY = "FILE_2_KEY";
private static final String FILE_2_UUID = "u3";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule()
.setRoot(
builder(PROJECT, ROOT_REF).setKey(PROJECT_KEY).setUuid(PROJECT_UUID)
.addChildren(
builder(FILE, FILE_1_REF).setKey(FILE_1_KEY).setUuid(FILE_1_UUID)
.build(),
builder(FILE, FILE_2_REF).setKey(FILE_2_KEY).setUuid(FILE_2_UUID)
.build())
.build());
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
@Rule
public DuplicationRepositoryRule duplicationRepository = DuplicationRepositoryRule.create(treeRootHolder);
@Rule
public MetricRepositoryRule metricRepository = new MetricRepositoryRule();
@Before
public void setUp() {
MetricDto metric = db.measures().insertMetric(m -> m.setKey(DUPLICATIONS_DATA_KEY).setValueType(Metric.ValueType.STRING.name()));
insertComponent(PROJECT_KEY, PROJECT_UUID);
insertComponent(FILE_1_KEY, FILE_1_UUID);
insertComponent(FILE_2_KEY, FILE_2_UUID);
db.commit();
metricRepository.add(metric.getUuid(), new Metric.Builder(DUPLICATIONS_DATA_KEY, DUPLICATIONS_DATA_KEY, Metric.ValueType.STRING).create());
}
@Override
protected ComputationStep step() {
return underTest();
}
@Test
public void nothing_to_persist_when_no_duplication() {
TestComputationStepContext context = new TestComputationStepContext();
underTest().execute(context);
assertThatNothingPersisted();
verifyStatistics(context, 0);
}
@Test
public void compute_duplications_on_same_file() {
duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(1, 5), new TextBlock(6, 10));
TestComputationStepContext context = new TestComputationStepContext();
underTest().execute(context);
assertThat(selectMeasureData(FILE_1_UUID)).hasValue("<duplications><g><b s=\"1\" l=\"5\" t=\"false\" r=\"" + FILE_1_KEY + "\"/><b s=\"6\" l=\"5\" t=\"false\" r=\""
+ FILE_1_KEY + "\"/></g></duplications>");
assertThat(selectMeasureData(FILE_2_UUID)).isEmpty();
assertThat(selectMeasureData(PROJECT_UUID)).isEmpty();
}
@Test
public void compute_duplications_on_different_files() {
duplicationRepository.addDuplication(FILE_1_REF, new TextBlock(1, 5), FILE_2_REF, new TextBlock(6, 10));
TestComputationStepContext context = new TestComputationStepContext();
underTest().execute(context);
assertThat(selectMeasureData(FILE_1_UUID)).hasValue(
"<duplications><g><b s=\"1\" l=\"5\" t=\"false\" r=\"" + FILE_1_KEY + "\"/><b s=\"6\" l=\"5\" t=\"false\" r=\""
+ FILE_2_KEY + "\"/></g></duplications>");
assertThat(selectMeasureData(FILE_2_UUID)).isEmpty();
assertThat(selectMeasureData(PROJECT_UUID)).isEmpty();
}
@Test
public void compute_duplications_on_unchanged_file() {
duplicationRepository.addExtendedProjectDuplication(FILE_1_REF, new TextBlock(1, 5), FILE_2_REF, new TextBlock(6, 10));
TestComputationStepContext context = new TestComputationStepContext();
underTest().execute(context);
assertThat(selectMeasureData(FILE_1_UUID)).hasValue(
"<duplications><g><b s=\"1\" l=\"5\" t=\"false\" r=\"" + FILE_1_KEY + "\"/><b s=\"6\" l=\"5\" t=\"true\" r=\""
+ FILE_2_KEY + "\"/></g></duplications>");
assertThat(selectMeasureData(FILE_2_UUID)).isEmpty();
assertThat(selectMeasureData(PROJECT_UUID)).isEmpty();
}
@Test
public void compute_duplications_on_different_projects() {
String fileKeyFromOtherProject = "PROJECT2_KEY:file2";
duplicationRepository.addCrossProjectDuplication(FILE_1_REF, new TextBlock(1, 5), fileKeyFromOtherProject, new TextBlock(6, 10));
TestComputationStepContext context = new TestComputationStepContext();
underTest().execute(context);
assertThat(selectMeasureData(FILE_1_UUID)).hasValue(
"<duplications><g><b s=\"1\" l=\"5\" t=\"false\" r=\"" + FILE_1_KEY + "\"/><b s=\"6\" l=\"5\" t=\"false\" r=\""
+ fileKeyFromOtherProject + "\"/></g></duplications>");
assertThat(selectMeasureData(FILE_2_UUID)).isEmpty();
assertThat(selectMeasureData(PROJECT_UUID)).isEmpty();
}
private PersistDuplicationDataStep underTest() {
return new PersistDuplicationDataStep(db.getDbClient(), treeRootHolder, metricRepository, duplicationRepository,
new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder));
}
private void assertThatNothingPersisted() {
assertThat(db.countRowsOfTable(db.getSession(), "live_measures")).isZero();
}
private Optional<String> selectMeasureData(String componentUuid) {
return db.getDbClient().liveMeasureDao().selectMeasure(db.getSession(), componentUuid, "duplications_data")
.map(LiveMeasureDto::getTextValue);
}
private ComponentDto insertComponent(String key, String uuid) {
ComponentDto componentDto = new ComponentDto()
.setKey(key)
.setUuid(uuid)
.setUuidPath(uuid + ".")
.setBranchUuid(uuid);
db.components().insertComponent(componentDto);
return componentDto;
}
private static void verifyStatistics(TestComputationStepContext context, int expectedInsertsOrUpdates) {
context.getStatistics().assertValue("insertsOrUpdates", expectedInsertsOrUpdates);
}
}
| 7,980 | 41.005263 | 167 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistEventsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.ImmutableList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.event.Event;
import org.sonar.ce.task.projectanalysis.event.EventRepository;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.event.EventDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.db.event.EventDto.CATEGORY_ALERT;
import static org.sonar.db.event.EventDto.CATEGORY_PROFILE;
import static org.sonar.db.event.EventDto.CATEGORY_VERSION;
public class PersistEventsStepIT extends BaseStepTest {
private static final long NOW = 1225630680000L;
private static final ReportComponent ROOT = builder(PROJECT, 1)
.setUuid("ABCD")
.setProjectVersion("version_1")
.addChildren(
builder(DIRECTORY, 2)
.setUuid("BCDE")
.addChildren(
builder(DIRECTORY, 3)
.setUuid("Q")
.addChildren(
builder(FILE, 4)
.setUuid("Z")
.build())
.build())
.build())
.build();
private static final String ANALYSIS_UUID = "uuid_1";
System2 system2 = mock(System2.class);
@Rule
public DbTester dbTester = DbTester.create(system2);
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
private Date someDate = new Date(150000000L);
private EventRepository eventRepository = mock(EventRepository.class);
private UuidFactory uuidFactory = UuidFactoryImpl.INSTANCE;
private PersistEventsStep underTest;
@Before
public void setup() {
analysisMetadataHolder.setAnalysisDate(someDate.getTime()).setUuid(ANALYSIS_UUID);
underTest = new PersistEventsStep(dbTester.getDbClient(), system2, treeRootHolder, analysisMetadataHolder, eventRepository, uuidFactory);
when(eventRepository.getEvents()).thenReturn(Collections.emptyList());
}
@Override
protected ComputationStep step() {
return underTest;
}
@Test
public void create_version_event() {
when(system2.now()).thenReturn(NOW);
Component project = builder(PROJECT, 1)
.setUuid("ABCD")
.setProjectVersion("1.0")
.addChildren(
builder(DIRECTORY, 2)
.setUuid("BCDE")
.addChildren(
builder(DIRECTORY, 3)
.setUuid("Q")
.addChildren(
builder(FILE, 4)
.setUuid("Z")
.build())
.build())
.build())
.build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isOne();
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos).hasSize(1);
EventDto eventDto = eventDtos.iterator().next();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo("1.0");
assertThat(eventDto.getDescription()).isNull();
assertThat(eventDto.getCategory()).isEqualTo(CATEGORY_VERSION);
assertThat(eventDto.getData()).isNull();
assertThat(eventDto.getDate()).isEqualTo(analysisMetadataHolder.getAnalysisDate());
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
}
@Test
public void persist_alert_events_on_root() {
when(system2.now()).thenReturn(NOW);
treeRootHolder.setRoot(ROOT);
Event alert = Event.createAlert("Failed", null, "Open issues > 0");
when(eventRepository.getEvents()).thenReturn(ImmutableList.of(alert));
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(2);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos)
.extracting(EventDto::getCategory)
.containsOnly(CATEGORY_ALERT, CATEGORY_VERSION);
EventDto eventDto = eventDtos.stream().filter(t -> CATEGORY_ALERT.equals(t.getCategory())).findAny().get();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo(alert.getName());
assertThat(eventDto.getDescription()).isEqualTo(alert.getDescription());
assertThat(eventDto.getCategory()).isEqualTo(CATEGORY_ALERT);
assertThat(eventDto.getData()).isNull();
assertThat(eventDto.getDate()).isEqualTo(analysisMetadataHolder.getAnalysisDate());
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
}
@Test
public void persist_profile_events_on_root() {
when(system2.now()).thenReturn(NOW);
treeRootHolder.setRoot(ROOT);
Event profile = Event.createProfile("foo", null, "bar");
when(eventRepository.getEvents()).thenReturn(ImmutableList.of(profile));
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(2);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), ROOT.getUuid());
assertThat(eventDtos)
.extracting(EventDto::getCategory)
.containsOnly(CATEGORY_PROFILE, CATEGORY_VERSION);
EventDto eventDto = eventDtos.stream().filter(t -> CATEGORY_PROFILE.equals(t.getCategory())).findAny().get();
assertThat(eventDto.getComponentUuid()).isEqualTo(ROOT.getUuid());
assertThat(eventDto.getName()).isEqualTo(profile.getName());
assertThat(eventDto.getDescription()).isEqualTo(profile.getDescription());
assertThat(eventDto.getCategory()).isEqualTo(EventDto.CATEGORY_PROFILE);
assertThat(eventDto.getData()).isNull();
assertThat(eventDto.getDate()).isEqualTo(analysisMetadataHolder.getAnalysisDate());
assertThat(eventDto.getCreatedAt()).isEqualTo(NOW);
}
@Test
public void keep_one_event_by_version() {
ComponentDto projectDto = dbTester.components().insertPublicProject().getMainBranchComponent();
EventDto[] existingEvents = new EventDto[] {
dbTester.events().insertEvent(newVersionEventDto(projectDto, 120_000_000L, "1.3-SNAPSHOT")),
dbTester.events().insertEvent(newVersionEventDto(projectDto, 130_000_000L, "1.4")),
dbTester.events().insertEvent(newVersionEventDto(projectDto, 140_000_000L, "1.5-SNAPSHOT"))
};
Component project = builder(PROJECT, 1)
.setUuid(projectDto.uuid())
.setProjectVersion("1.5-SNAPSHOT")
.addChildren(
builder(DIRECTORY, 2)
.setUuid("BCDE")
.addChildren(
builder(DIRECTORY, 3)
.setUuid("Q")
.addChildren(
builder(FILE, 4)
.setUuid("Z")
.build())
.build())
.build())
.build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable(dbTester.getSession(), "events")).isEqualTo(3);
List<EventDto> eventDtos = dbTester.getDbClient().eventDao().selectByComponentUuid(dbTester.getSession(), projectDto.uuid());
assertThat(eventDtos).hasSize(3);
assertThat(eventDtos)
.extracting(EventDto::getName)
.containsOnly("1.3-SNAPSHOT", "1.4", "1.5-SNAPSHOT");
assertThat(eventDtos)
.extracting(EventDto::getUuid)
.contains(existingEvents[0].getUuid(), existingEvents[1].getUuid())
.doesNotContain(existingEvents[2].getUuid());
}
private EventDto newVersionEventDto(ComponentDto project, long date, String name) {
return new EventDto().setUuid(uuidFactory.create()).setComponentUuid(project.uuid())
.setAnalysisUuid("analysis_uuid")
.setCategory(CATEGORY_VERSION)
.setName(name).setDate(date).setCreatedAt(date);
}
}
| 9,838 | 40.514768 | 141 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistIssuesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentCaptor;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.issue.AdHocRuleCreator;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.issue.RuleRepositoryImpl;
import org.sonar.ce.task.projectanalysis.issue.UpdateConflictResolver;
import org.sonar.ce.task.projectanalysis.period.Period;
import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule;
import org.sonar.ce.task.projectanalysis.util.cache.DiskCache;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.core.issue.DefaultIssueComment;
import org.sonar.core.issue.FieldDiffs;
import org.sonar.core.util.UuidFactoryImpl;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.issue.IssueMapper;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleTesting;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.issue.IssueStorage;
import static java.util.Collections.singletonList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.data.MapEntry.entry;
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.issue.Issue.RESOLUTION_FIXED;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.rule.Severity.BLOCKER;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.issue.IssueTesting.newCodeReferenceIssue;
public class PersistIssuesStepIT extends BaseStepTest {
private static final long NOW = 1_400_000_000_000L;
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
@Rule
public PeriodHolderRule periodHolder = new PeriodHolderRule();
private System2 system2 = mock(System2.class);
private DbSession session = db.getSession();
private DbClient dbClient = db.getDbClient();
private UpdateConflictResolver conflictResolver = mock(UpdateConflictResolver.class);
private ProtoIssueCache protoIssueCache;
private ComputationStep underTest;
private AdHocRuleCreator adHocRuleCreator = mock(AdHocRuleCreator.class);
@Override
protected ComputationStep step() {
return underTest;
}
@Before
public void setup() throws Exception {
periodHolder.setPeriod(new Period(NewCodePeriodType.NUMBER_OF_DAYS.name(), "10", 1000L));
protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
reportReader.setMetadata(ScannerReport.Metadata.getDefaultInstance());
underTest = new PersistIssuesStep(dbClient, system2, conflictResolver, new RuleRepositoryImpl(adHocRuleCreator, dbClient), periodHolder,
protoIssueCache, new IssueStorage(), UuidFactoryImpl.INSTANCE);
}
@After
public void tearDown() {
session.close();
}
@Test
public void insert_copied_issue() {
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
when(system2.now()).thenReturn(NOW);
String issueKey = "ISSUE-1";
protoIssueCache.newAppender().append(new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setTags(singletonList("test"))
.setNew(false)
.setCopied(true)
.setType(RuleType.BUG)
.setCreationDate(new Date(NOW))
.setSelectedAt(NOW)
.addComment(new DefaultIssueComment()
.setKey("COMMENT")
.setIssueKey(issueKey)
.setUserUuid("john_uuid")
.setMarkdownText("Some text")
.setCreatedAt(new Date(NOW))
.setUpdatedAt(new Date(NOW))
.setNew(true))
.setCurrentChange(
new FieldDiffs()
.setIssueKey(issueKey)
.setUserUuid("john_uuid")
.setDiff("technicalDebt", null, 1L)
.setCreationDate(new Date(NOW))))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.getKey()).isEqualTo(issueKey);
assertThat(result.getRuleKey()).isEqualTo(rule.getKey());
assertThat(result.getComponentUuid()).isEqualTo(file.uuid());
assertThat(result.getProjectUuid()).isEqualTo(project.uuid());
assertThat(result.getSeverity()).isEqualTo(BLOCKER);
assertThat(result.getStatus()).isEqualTo(STATUS_OPEN);
assertThat(result.getType()).isEqualTo(RuleType.BUG.getDbConstant());
assertThat(result.getTags()).containsExactlyInAnyOrder("test");
assertThat(result.isNewCodeReferenceIssue()).isFalse();
List<IssueChangeDto> changes = dbClient.issueChangeDao().selectByIssueKeys(session, Arrays.asList(issueKey));
assertThat(changes).extracting(IssueChangeDto::getChangeType).containsExactly(IssueChangeDto.TYPE_COMMENT, IssueChangeDto.TYPE_FIELD_CHANGE);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "1"), entry("updates", "0"), entry("merged", "0"));
}
@Test
public void insert_copied_issue_with_minimal_info() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
when(system2.now()).thenReturn(NOW);
String issueKey = "ISSUE-2";
protoIssueCache.newAppender().append(new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setNew(false)
.setCopied(true)
.setType(RuleType.BUG)
.setCreationDate(new Date(NOW))
.setSelectedAt(NOW))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.getKey()).isEqualTo(issueKey);
assertThat(result.getRuleKey()).isEqualTo(rule.getKey());
assertThat(result.getComponentUuid()).isEqualTo(file.uuid());
assertThat(result.getProjectUuid()).isEqualTo(project.uuid());
assertThat(result.getSeverity()).isEqualTo(BLOCKER);
assertThat(result.getStatus()).isEqualTo(STATUS_OPEN);
assertThat(result.getType()).isEqualTo(RuleType.BUG.getDbConstant());
assertThat(result.getTags()).isEmpty();
assertThat(result.isNewCodeReferenceIssue()).isFalse();
assertThat(dbClient.issueChangeDao().selectByIssueKeys(session, Arrays.asList(issueKey))).isEmpty();
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "1"), entry("updates", "0"), entry("merged", "0"));
}
@Test
public void insert_merged_issue() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
when(system2.now()).thenReturn(NOW);
String issueKey = "ISSUE-3";
protoIssueCache.newAppender().append(new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setNew(true)
.setIsOnChangedLine(true)
.setCopied(true)
.setType(RuleType.BUG)
.setCreationDate(new Date(NOW))
.setSelectedAt(NOW)
.addComment(new DefaultIssueComment()
.setKey("COMMENT")
.setIssueKey(issueKey)
.setUserUuid("john_uuid")
.setMarkdownText("Some text")
.setUpdatedAt(new Date(NOW))
.setCreatedAt(new Date(NOW))
.setNew(true))
.setCurrentChange(new FieldDiffs()
.setIssueKey(issueKey)
.setUserUuid("john_uuid")
.setDiff("technicalDebt", null, 1L)
.setCreationDate(new Date(NOW))))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.getKey()).isEqualTo(issueKey);
assertThat(result.getRuleKey()).isEqualTo(rule.getKey());
assertThat(result.getComponentUuid()).isEqualTo(file.uuid());
assertThat(result.getProjectUuid()).isEqualTo(project.uuid());
assertThat(result.getSeverity()).isEqualTo(BLOCKER);
assertThat(result.getStatus()).isEqualTo(STATUS_OPEN);
assertThat(result.getType()).isEqualTo(RuleType.BUG.getDbConstant());
assertThat(result.isNewCodeReferenceIssue()).isTrue();
List<IssueChangeDto> changes = dbClient.issueChangeDao().selectByIssueKeys(session, Arrays.asList(issueKey));
assertThat(changes).extracting(IssueChangeDto::getChangeType).containsExactly(IssueChangeDto.TYPE_COMMENT, IssueChangeDto.TYPE_FIELD_CHANGE);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "1"), entry("updates", "0"), entry("merged", "0"));
}
@Test
public void update_conflicting_issue() {
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
.setCreatedAt(NOW - 1_000_000_000L)
// simulate the issue has been updated after the analysis ran
.setUpdatedAt(NOW + 1_000_000_000L));
issue = dbClient.issueDao().selectByKey(db.getSession(), issue.getKey()).get();
DiskCache.CacheAppender issueCacheAppender = protoIssueCache.newAppender();
when(system2.now()).thenReturn(NOW);
DefaultIssue defaultIssue = issue.toDefaultIssue()
.setStatus(STATUS_CLOSED)
.setResolution(RESOLUTION_FIXED)
.setSelectedAt(NOW)
.setNew(false)
.setChanged(true);
issueCacheAppender.append(defaultIssue).close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
ArgumentCaptor<IssueDto> issueDtoCaptor = ArgumentCaptor.forClass(IssueDto.class);
verify(conflictResolver).resolve(eq(defaultIssue), issueDtoCaptor.capture(), any(IssueMapper.class));
assertThat(issueDtoCaptor.getValue().getKey()).isEqualTo(issue.getKey());
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "1"), entry("merged", "1"));
}
@Test
public void insert_new_issue() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
session.commit();
String issueKey = "ISSUE-4";
protoIssueCache.newAppender().append(new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setCreationDate(new Date(NOW))
.setNew(true)
.setIsOnChangedLine(true)
.setType(RuleType.BUG)).close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.getKey()).isEqualTo(issueKey);
assertThat(result.getRuleKey()).isEqualTo(rule.getKey());
assertThat(result.getComponentUuid()).isEqualTo(file.uuid());
assertThat(result.getProjectUuid()).isEqualTo(project.uuid());
assertThat(result.getSeverity()).isEqualTo(BLOCKER);
assertThat(result.getStatus()).isEqualTo(STATUS_OPEN);
assertThat(result.getType()).isEqualTo(RuleType.BUG.getDbConstant());
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "1"), entry("updates", "0"), entry("merged", "0"));
assertThat(result.isNewCodeReferenceIssue()).isTrue();
}
@Test
public void close_issue() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
.setCreatedAt(NOW - 1_000_000_000L)
.setUpdatedAt(NOW - 1_000_000_000L));
DiskCache.CacheAppender issueCacheAppender = protoIssueCache.newAppender();
issueCacheAppender.append(
issue.toDefaultIssue()
.setStatus(STATUS_CLOSED)
.setResolution(RESOLUTION_FIXED)
.setSelectedAt(NOW)
.setNew(false)
.setChanged(true))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueDto issueReloaded = db.getDbClient().issueDao().selectByKey(db.getSession(), issue.getKey()).get();
assertThat(issueReloaded.getStatus()).isEqualTo(STATUS_CLOSED);
assertThat(issueReloaded.getResolution()).isEqualTo(RESOLUTION_FIXED);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "1"), entry("merged", "0"));
}
@Test
public void handle_no_longer_new_issue() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
when(system2.now()).thenReturn(NOW);
String issueKey = "ISSUE-5";
DefaultIssue defaultIssue = new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setNew(true)
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(true)
.setIsNoLongerNewCodeReferenceIssue(false)
.setCopied(false)
.setType(RuleType.BUG)
.setCreationDate(new Date(NOW))
.setSelectedAt(NOW);
IssueDto issueDto = IssueDto.toDtoForComputationInsert(defaultIssue, rule.getUuid(), NOW);
dbClient.issueDao().insert(session, issueDto);
dbClient.issueDao().insertAsNewCodeOnReferenceBranch(session, newCodeReferenceIssue(issueDto));
session.commit();
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.isNewCodeReferenceIssue()).isTrue();
protoIssueCache.newAppender().append(defaultIssue.setNew(false)
.setIsOnChangedLine(false)
.setIsNewCodeReferenceIssue(false)
.setIsNoLongerNewCodeReferenceIssue(true))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "1"), entry("merged", "0"));
result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.isNewCodeReferenceIssue()).isFalse();
}
@Test
public void handle_existing_new_code_issue_migration() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
when(system2.now()).thenReturn(NOW);
String issueKey = "ISSUE-6";
DefaultIssue defaultIssue = new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setNew(true)
.setCopied(false)
.setType(RuleType.BUG)
.setCreationDate(new Date(NOW))
.setSelectedAt(NOW);
IssueDto issueDto = IssueDto.toDtoForComputationInsert(defaultIssue, rule.getUuid(), NOW);
dbClient.issueDao().insert(session, issueDto);
session.commit();
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.isNewCodeReferenceIssue()).isFalse();
protoIssueCache.newAppender().append(defaultIssue.setNew(false)
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(false)
.setIsNoLongerNewCodeReferenceIssue(false))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "1"), entry("merged", "0"));
result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.isNewCodeReferenceIssue()).isTrue();
}
@Test
public void handle_existing_without_need_for_new_code_issue_migration() {
periodHolder.setPeriod(new Period(NewCodePeriodType.REFERENCE_BRANCH.name(), "master", null));
RuleDto rule = RuleTesting.newRule(RuleKey.of("xoo", "S01"));
db.rules().insert(rule);
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
when(system2.now()).thenReturn(NOW);
String issueKey = "ISSUE-7";
DefaultIssue defaultIssue = new DefaultIssue()
.setKey(issueKey)
.setType(RuleType.CODE_SMELL)
.setRuleKey(rule.getKey())
.setComponentUuid(file.uuid())
.setComponentKey(file.getKey())
.setProjectUuid(project.uuid())
.setProjectKey(project.getKey())
.setSeverity(BLOCKER)
.setStatus(STATUS_OPEN)
.setNew(true)
.setIsOnChangedLine(true)
.setIsNewCodeReferenceIssue(true)
.setIsNoLongerNewCodeReferenceIssue(false)
.setCopied(false)
.setType(RuleType.BUG)
.setCreationDate(new Date(NOW))
.setSelectedAt(NOW);
IssueDto issueDto = IssueDto.toDtoForComputationInsert(defaultIssue, rule.getUuid(), NOW);
dbClient.issueDao().insert(session, issueDto);
dbClient.issueDao().insertAsNewCodeOnReferenceBranch(session, newCodeReferenceIssue(issueDto));
session.commit();
IssueDto result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.isNewCodeReferenceIssue()).isTrue();
protoIssueCache.newAppender().append(defaultIssue.setNew(false)
.setIsOnChangedLine(false)
.setIsNewCodeReferenceIssue(true)
.setIsOnChangedLine(true)
.setIsNoLongerNewCodeReferenceIssue(false))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "0"), entry("merged", "0"));
result = dbClient.issueDao().selectOrFailByKey(session, issueKey);
assertThat(result.isNewCodeReferenceIssue()).isTrue();
}
@Test
public void add_comment() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
.setCreatedAt(NOW - 1_000_000_000L)
.setUpdatedAt(NOW - 1_000_000_000L));
DiskCache.CacheAppender issueCacheAppender = protoIssueCache.newAppender();
issueCacheAppender.append(
issue.toDefaultIssue()
.setStatus(STATUS_CLOSED)
.setResolution(RESOLUTION_FIXED)
.setSelectedAt(NOW)
.setNew(false)
.setChanged(true)
.addComment(new DefaultIssueComment()
.setKey("COMMENT")
.setIssueKey(issue.getKey())
.setUserUuid("john_uuid")
.setMarkdownText("Some text")
.setCreatedAt(new Date(NOW))
.setUpdatedAt(new Date(NOW))
.setNew(true)))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueChangeDto issueChangeDto = db.getDbClient().issueChangeDao().selectByIssueKeys(db.getSession(), singletonList(issue.getKey())).get(0);
assertThat(issueChangeDto)
.extracting(IssueChangeDto::getChangeType, IssueChangeDto::getUserUuid, IssueChangeDto::getChangeData, IssueChangeDto::getIssueKey,
IssueChangeDto::getIssueChangeCreationDate)
.containsOnly(IssueChangeDto.TYPE_COMMENT, "john_uuid", "Some text", issue.getKey(), NOW);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "1"), entry("merged", "0"));
}
@Test
public void add_change() {
ComponentDto project = db.components().insertPrivateProject().getMainBranchComponent();
ComponentDto file = db.components().insertComponent(newFileDto(project));
RuleDto rule = db.rules().insert();
IssueDto issue = db.issues().insert(rule, project, file,
i -> i.setStatus(STATUS_OPEN)
.setResolution(null)
.setCreatedAt(NOW - 1_000_000_000L)
.setUpdatedAt(NOW - 1_000_000_000L));
DiskCache.CacheAppender issueCacheAppender = protoIssueCache.newAppender();
issueCacheAppender.append(
issue.toDefaultIssue()
.setStatus(STATUS_CLOSED)
.setResolution(RESOLUTION_FIXED)
.setSelectedAt(NOW)
.setNew(false)
.setChanged(true)
.setIsOnChangedLine(false)
.setIsNewCodeReferenceIssue(false)
.setCurrentChange(new FieldDiffs()
.setIssueKey("ISSUE")
.setUserUuid("john_uuid")
.setDiff("technicalDebt", null, 1L)
.setCreationDate(new Date(NOW))))
.close();
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
IssueChangeDto issueChangeDto = db.getDbClient().issueChangeDao().selectByIssueKeys(db.getSession(), singletonList(issue.getKey())).get(0);
assertThat(issueChangeDto)
.extracting(IssueChangeDto::getChangeType, IssueChangeDto::getUserUuid, IssueChangeDto::getChangeData, IssueChangeDto::getIssueKey,
IssueChangeDto::getIssueChangeCreationDate)
.containsOnly(IssueChangeDto.TYPE_FIELD_CHANGE, "john_uuid", "technicalDebt=1", issue.getKey(), NOW);
assertThat(context.getStatistics().getAll()).contains(
entry("inserts", "0"), entry("updates", "1"), entry("merged", "0"));
}
}
| 26,419 | 40.803797 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistLiveMeasuresStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.FileStatuses;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.component.ViewsComponent;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.LiveMeasureDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.server.project.Project;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.CoreMetrics.BUGS;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
import static org.sonar.db.measure.MeasureTesting.newLiveMeasure;
public class PersistLiveMeasuresStepIT extends BaseStepTest {
private static final Metric STRING_METRIC = new Metric.Builder("string-metric", "String metric", Metric.ValueType.STRING).create();
private static final Metric INT_METRIC = new Metric.Builder("int-metric", "int metric", Metric.ValueType.INT).create();
private static final Metric METRIC_WITH_BEST_VALUE = new Metric.Builder("best-value-metric", "best value metric", Metric.ValueType.INT)
.setBestValue(0.0)
.setOptimizedBestValue(true)
.create();
private static final int REF_1 = 1;
private static final int REF_2 = 2;
private static final int REF_3 = 3;
private static final int REF_4 = 4;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public MetricRepositoryRule metricRepository = new MetricRepositoryRule();
@Rule
public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository);
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
private final FileStatuses fileStatuses = mock(FileStatuses.class);
private final DbClient dbClient = db.getDbClient();
private final TestComputationStepContext context = new TestComputationStepContext();
@Before
public void setUp() {
MetricDto stringMetricDto = db.measures().insertMetric(m -> m.setKey(STRING_METRIC.getKey()).setValueType(Metric.ValueType.STRING.name()));
MetricDto intMetricDto = db.measures().insertMetric(m -> m.setKey(INT_METRIC.getKey()).setValueType(Metric.ValueType.INT.name()));
MetricDto bestValueMMetricDto = db.measures()
.insertMetric(m -> m.setKey(METRIC_WITH_BEST_VALUE.getKey()).setValueType(Metric.ValueType.INT.name()).setOptimizedBestValue(true).setBestValue(0.0));
MetricDto bugs = db.measures().insertMetric(m -> m.setKey(BUGS.getKey()));
metricRepository.add(stringMetricDto.getUuid(), STRING_METRIC);
metricRepository.add(intMetricDto.getUuid(), INT_METRIC);
metricRepository.add(bestValueMMetricDto.getUuid(), METRIC_WITH_BEST_VALUE);
metricRepository.add(bugs.getUuid(), BUGS);
}
@Test
public void persist_live_measures_of_project_analysis() {
prepareProject();
// the computed measures
measureRepository.addRawMeasure(REF_1, STRING_METRIC.getKey(), newMeasureBuilder().create("project-value"));
measureRepository.addRawMeasure(REF_3, STRING_METRIC.getKey(), newMeasureBuilder().create("dir-value"));
measureRepository.addRawMeasure(REF_4, STRING_METRIC.getKey(), newMeasureBuilder().create("file-value"));
step().execute(context);
// all measures are persisted, from project to file
assertThat(db.countRowsOfTable("live_measures")).isEqualTo(3);
assertThat(selectMeasure("project-uuid", STRING_METRIC).get().getDataAsString()).isEqualTo("project-value");
assertThat(selectMeasure("dir-uuid", STRING_METRIC).get().getDataAsString()).isEqualTo("dir-value");
assertThat(selectMeasure("file-uuid", STRING_METRIC).get().getDataAsString()).isEqualTo("file-value");
verifyStatistics(context, 3);
}
@Test
public void measures_without_value_are_not_persisted() {
prepareProject();
measureRepository.addRawMeasure(REF_1, STRING_METRIC.getKey(), newMeasureBuilder().createNoValue());
measureRepository.addRawMeasure(REF_1, INT_METRIC.getKey(), newMeasureBuilder().createNoValue());
step().execute(context);
assertThatMeasureIsNotPersisted("project-uuid", STRING_METRIC);
assertThatMeasureIsNotPersisted("project-uuid", INT_METRIC);
verifyStatistics(context, 0);
}
@Test
public void measures_on_new_code_period_are_persisted() {
prepareProject();
measureRepository.addRawMeasure(REF_1, INT_METRIC.getKey(), newMeasureBuilder().create(42.0));
step().execute(context);
LiveMeasureDto persistedMeasure = selectMeasure("project-uuid", INT_METRIC).get();
assertThat(persistedMeasure.getValue()).isEqualTo(42.0);
verifyStatistics(context, 1);
}
@Test
public void delete_measures_from_db_if_no_longer_computed() {
prepareProject();
// measure to be updated
LiveMeasureDto measureOnFileInProject = insertMeasure("file-uuid", "project-uuid", INT_METRIC);
// measure to be deleted because not computed anymore
LiveMeasureDto otherMeasureOnFileInProject = insertMeasure("file-uuid", "project-uuid", STRING_METRIC);
// measure in another project, not touched
LiveMeasureDto measureInOtherProject = insertMeasure("other-file-uuid", "other-project-uuid", INT_METRIC);
db.commit();
measureRepository.addRawMeasure(REF_4, INT_METRIC.getKey(), newMeasureBuilder().create(42));
step().execute(context);
assertThatMeasureHasValue(measureOnFileInProject, 42);
assertThatMeasureDoesNotExist(otherMeasureOnFileInProject);
assertThatMeasureHasValue(measureInOtherProject, (int) measureInOtherProject.getValue().doubleValue());
verifyStatistics(context, 1);
}
@Test
public void do_not_persist_file_measures_with_best_value() {
prepareProject();
// measure to be deleted because new value matches the metric best value
LiveMeasureDto oldMeasure = insertMeasure("file-uuid", "project-uuid", INT_METRIC);
db.commit();
// project measure with metric best value -> persist with value 0
measureRepository.addRawMeasure(REF_1, METRIC_WITH_BEST_VALUE.getKey(), newMeasureBuilder().create(0));
// file measure with metric best value -> do not persist
measureRepository.addRawMeasure(REF_4, METRIC_WITH_BEST_VALUE.getKey(), newMeasureBuilder().create(0));
step().execute(context);
assertThatMeasureDoesNotExist(oldMeasure);
assertThatMeasureHasValue("project-uuid", METRIC_WITH_BEST_VALUE, 0);
verifyStatistics(context, 1);
}
@Test
public void keep_measures_for_unchanged_files() {
prepareProject();
LiveMeasureDto oldMeasure = insertMeasure("file-uuid", "project-uuid", BUGS);
db.commit();
when(fileStatuses.isDataUnchanged(any(Component.class))).thenReturn(true);
// this new value won't be persisted
measureRepository.addRawMeasure(REF_4, BUGS.getKey(), newMeasureBuilder().create(oldMeasure.getValue() + 1, 0));
step().execute(context);
assertThat(selectMeasure("file-uuid", BUGS).get().getValue()).isEqualTo(oldMeasure.getValue());
}
@Test
public void dont_keep_measures_for_unchanged_files() {
prepareProject();
LiveMeasureDto oldMeasure = insertMeasure("file-uuid", "project-uuid", BUGS);
db.commit();
when(fileStatuses.isDataUnchanged(any(Component.class))).thenReturn(false);
// this new value will be persisted
measureRepository.addRawMeasure(REF_4, BUGS.getKey(), newMeasureBuilder().create(oldMeasure.getValue() + 1, 0));
step().execute(context);
assertThat(selectMeasure("file-uuid", BUGS).get().getValue()).isEqualTo(oldMeasure.getValue() + 1);
}
@Test
public void persist_live_measures_of_portfolio_analysis() {
preparePortfolio();
// the computed measures
measureRepository.addRawMeasure(REF_1, STRING_METRIC.getKey(), newMeasureBuilder().create("view-value"));
measureRepository.addRawMeasure(REF_2, STRING_METRIC.getKey(), newMeasureBuilder().create("subview-value"));
measureRepository.addRawMeasure(REF_3, STRING_METRIC.getKey(), newMeasureBuilder().create("project-value"));
step().execute(context);
assertThat(db.countRowsOfTable("live_measures")).isEqualTo(3);
assertThat(selectMeasure("view-uuid", STRING_METRIC).get().getDataAsString()).isEqualTo("view-value");
assertThat(selectMeasure("subview-uuid", STRING_METRIC).get().getDataAsString()).isEqualTo("subview-value");
assertThat(selectMeasure("project-uuid", STRING_METRIC).get().getDataAsString()).isEqualTo("project-value");
verifyStatistics(context, 3);
}
private LiveMeasureDto insertMeasure(String componentUuid, String projectUuid, Metric metric) {
LiveMeasureDto measure = newLiveMeasure()
.setComponentUuid(componentUuid)
.setProjectUuid(projectUuid)
.setMetricUuid(metricRepository.getByKey(metric.getKey()).getUuid());
dbClient.liveMeasureDao().insertOrUpdate(db.getSession(), measure);
return measure;
}
private void assertThatMeasureHasValue(LiveMeasureDto template, int expectedValue) {
Optional<LiveMeasureDto> persisted = dbClient.liveMeasureDao().selectMeasure(db.getSession(),
template.getComponentUuid(), metricRepository.getByUuid(template.getMetricUuid()).getKey());
assertThat(persisted).isPresent();
assertThat(persisted.get().getValue()).isEqualTo(expectedValue);
}
private void assertThatMeasureHasValue(String componentUuid, Metric metric, int expectedValue) {
Optional<LiveMeasureDto> persisted = dbClient.liveMeasureDao().selectMeasure(db.getSession(),
componentUuid, metric.getKey());
assertThat(persisted).isPresent();
assertThat(persisted.get().getValue()).isEqualTo(expectedValue);
}
private void assertThatMeasureDoesNotExist(LiveMeasureDto template) {
assertThat(dbClient.liveMeasureDao().selectMeasure(db.getSession(),
template.getComponentUuid(), metricRepository.getByUuid(template.getMetricUuid()).getKey()))
.isEmpty();
}
private void prepareProject() {
// tree of components as defined by scanner report
Component project = ReportComponent.builder(PROJECT, REF_1).setUuid("project-uuid")
.addChildren(
ReportComponent.builder(DIRECTORY, REF_3).setUuid("dir-uuid")
.addChildren(
ReportComponent.builder(FILE, REF_4).setUuid("file-uuid")
.build())
.build())
.build();
treeRootHolder.setRoot(project);
analysisMetadataHolder.setProject(new Project(project.getUuid(), project.getKey(), project.getName(), project.getDescription(), emptyList()));
// components as persisted in db
ComponentDto projectDto = insertComponent("project-key", "project-uuid");
ComponentDto dirDto = insertComponent("dir-key", "dir-uuid");
ComponentDto fileDto = insertComponent("file-key", "file-uuid");
}
private void preparePortfolio() {
// tree of components
Component portfolio = ViewsComponent.builder(VIEW, REF_1).setUuid("view-uuid")
.addChildren(
ViewsComponent.builder(SUBVIEW, REF_2).setUuid("subview-uuid")
.addChildren(
ViewsComponent.builder(PROJECT_VIEW, REF_3).setUuid("project-uuid")
.build())
.build())
.build();
treeRootHolder.setRoot(portfolio);
// components as persisted in db
ComponentDto portfolioDto = insertComponent("view-key", "view-uuid");
ComponentDto subViewDto = insertComponent("subview-key", "subview-uuid");
ComponentDto projectDto = insertComponent("project-key", "project-uuid");
analysisMetadataHolder.setProject(Project.from(portfolioDto));
}
private void assertThatMeasureIsNotPersisted(String componentUuid, Metric metric) {
assertThat(selectMeasure(componentUuid, metric)).isEmpty();
}
private Optional<LiveMeasureDto> selectMeasure(String componentUuid, Metric metric) {
return dbClient.liveMeasureDao().selectMeasure(db.getSession(), componentUuid, metric.getKey());
}
private ComponentDto insertComponent(String key, String uuid) {
ComponentDto componentDto = new ComponentDto()
.setKey(key)
.setUuid(uuid)
.setUuidPath(uuid + ".")
.setBranchUuid(uuid);
db.components().insertComponent(componentDto);
return componentDto;
}
@Override
protected ComputationStep step() {
return new PersistLiveMeasuresStep(dbClient, metricRepository, new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder), treeRootHolder, measureRepository,
Optional.of(fileStatuses));
}
private static void verifyStatistics(TestComputationStepContext context, int expectedInsertsOrUpdates) {
context.getStatistics().assertValue("insertsOrUpdates", expectedInsertsOrUpdates);
}
}
| 15,026 | 45.37963 | 166 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistMeasuresStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.measures.Metric;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.component.ViewsComponent;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule;
import org.sonar.ce.task.projectanalysis.measure.MeasureToMeasureDto;
import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT_VIEW;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.SUBVIEW;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.VIEW;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
public class PersistMeasuresStepIT extends BaseStepTest {
private static final Metric STRING_METRIC = new Metric.Builder("string-metric", "String metric", Metric.ValueType.STRING).create();
private static final Metric INT_METRIC = new Metric.Builder("int-metric", "int metric", Metric.ValueType.INT).create();
private static final Metric NON_HISTORICAL_METRIC = new Metric.Builder("nh-metric", "nh metric", Metric.ValueType.INT).setDeleteHistoricalData(true).create();
private static final String ANALYSIS_UUID = "a1";
private static final int REF_1 = 1;
private static final int REF_2 = 2;
private static final int REF_3 = 3;
private static final int REF_4 = 4;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public MetricRepositoryRule metricRepository = new MetricRepositoryRule();
@Rule
public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository);
@Rule
public MutableAnalysisMetadataHolderRule analysisMetadataHolder = new MutableAnalysisMetadataHolderRule();
private DbClient dbClient = db.getDbClient();
@Before
public void setUp() {
analysisMetadataHolder.setUuid(ANALYSIS_UUID);
MetricDto stringMetricDto = db.measures().insertMetric(m -> m.setKey(STRING_METRIC.getKey()).setValueType(Metric.ValueType.STRING.name()));
MetricDto intMetricDto = db.measures().insertMetric(m -> m.setKey(INT_METRIC.getKey()).setValueType(Metric.ValueType.INT.name()));
MetricDto nhMetricDto = db.measures().insertMetric(m -> m.setKey(NON_HISTORICAL_METRIC.getKey()).setValueType(Metric.ValueType.INT.name()));
metricRepository.add(stringMetricDto.getUuid(), STRING_METRIC);
metricRepository.add(intMetricDto.getUuid(), INT_METRIC);
metricRepository.add(nhMetricDto.getUuid(), NON_HISTORICAL_METRIC);
}
@Test
public void measures_on_non_historical_metrics_are_not_persisted() {
prepareProject();
measureRepository.addRawMeasure(REF_1, NON_HISTORICAL_METRIC.getKey(), newMeasureBuilder().create(1));
measureRepository.addRawMeasure(REF_1, INT_METRIC.getKey(), newMeasureBuilder().create(2));
TestComputationStepContext context = execute();
assertThatMeasureIsNotPersisted("project-uuid", NON_HISTORICAL_METRIC);
MeasureDto persistedMeasure = selectMeasure("project-uuid", INT_METRIC).get();
assertThat(persistedMeasure.getValue()).isEqualTo(2);
assertNbOfInserts(context, 1);
}
@Test
public void persist_measures_of_project_analysis_excluding_directories() {
prepareProject();
// the computed measures
measureRepository.addRawMeasure(REF_1, STRING_METRIC.getKey(), newMeasureBuilder().create("project-value"));
measureRepository.addRawMeasure(REF_3, STRING_METRIC.getKey(), newMeasureBuilder().create("dir-value"));
measureRepository.addRawMeasure(REF_4, STRING_METRIC.getKey(), newMeasureBuilder().create("file-value"));
TestComputationStepContext context = execute();
// project and dir measures are persisted, but not file measures
assertThat(db.countRowsOfTable("project_measures")).isOne();
assertThat(selectMeasure("project-uuid", STRING_METRIC).get().getData()).isEqualTo("project-value");
assertThatMeasuresAreNotPersisted("dir-uuid");
assertThatMeasuresAreNotPersisted("file-uuid");
assertNbOfInserts(context, 1);
}
@Test
public void measures_without_value_are_not_persisted() {
prepareProject();
measureRepository.addRawMeasure(REF_1, STRING_METRIC.getKey(), newMeasureBuilder().createNoValue());
measureRepository.addRawMeasure(REF_1, INT_METRIC.getKey(), newMeasureBuilder().createNoValue());
TestComputationStepContext context = execute();
assertThatMeasureIsNotPersisted("project-uuid", STRING_METRIC);
assertThatMeasureIsNotPersisted("project-uuid", INT_METRIC);
assertNbOfInserts(context, 0);
}
@Test
public void measures_on_new_code_period_are_persisted() {
prepareProject();
measureRepository.addRawMeasure(REF_1, INT_METRIC.getKey(), newMeasureBuilder().create(42.0));
TestComputationStepContext context = execute();
MeasureDto persistedMeasure = selectMeasure("project-uuid", INT_METRIC).get();
assertThat(persistedMeasure.getValue()).isEqualTo(42.0);
assertNbOfInserts(context, 1);
}
@Test
public void persist_all_measures_of_portfolio_analysis() {
preparePortfolio();
// the computed measures
measureRepository.addRawMeasure(REF_1, STRING_METRIC.getKey(), newMeasureBuilder().create("view-value"));
measureRepository.addRawMeasure(REF_2, STRING_METRIC.getKey(), newMeasureBuilder().create("subview-value"));
measureRepository.addRawMeasure(REF_3, STRING_METRIC.getKey(), newMeasureBuilder().create("project-value"));
TestComputationStepContext context = execute();
assertThat(db.countRowsOfTable("project_measures")).isEqualTo(2);
assertThat(selectMeasure("view-uuid", STRING_METRIC).get().getData()).isEqualTo("view-value");
assertThat(selectMeasure("subview-uuid", STRING_METRIC).get().getData()).isEqualTo("subview-value");
assertNbOfInserts(context, 2);
}
private void prepareProject() {
// tree of components as defined by scanner report
Component project = ReportComponent.builder(PROJECT, REF_1).setUuid("project-uuid")
.addChildren(
ReportComponent.builder(DIRECTORY, REF_3).setUuid("dir-uuid")
.addChildren(
ReportComponent.builder(FILE, REF_4).setUuid("file-uuid")
.build())
.build())
.build();
treeRootHolder.setRoot(project);
// components as persisted in db
ComponentDto projectDto = insertComponent("project-key", "project-uuid");
ComponentDto dirDto = insertComponent("dir-key", "dir-uuid");
ComponentDto fileDto = insertComponent("file-key", "file-uuid");
db.components().insertSnapshot(projectDto, s -> s.setUuid(ANALYSIS_UUID));
}
private void preparePortfolio() {
// tree of components
Component portfolio = ViewsComponent.builder(VIEW, REF_1).setUuid("view-uuid")
.addChildren(
ViewsComponent.builder(SUBVIEW, REF_2).setUuid("subview-uuid")
.addChildren(
ViewsComponent.builder(PROJECT_VIEW, REF_3).setUuid("project-uuid")
.build())
.build())
.build();
treeRootHolder.setRoot(portfolio);
// components as persisted in db
ComponentDto viewDto = insertComponent("view-key", "view-uuid");
ComponentDto subViewDto = insertComponent("subview-key", "subview-uuid");
ComponentDto projectDto = insertComponent("project-key", "project-uuid");
db.components().insertSnapshot(viewDto, s -> s.setUuid(ANALYSIS_UUID));
}
private void assertThatMeasureIsNotPersisted(String componentUuid, Metric metric) {
assertThat(selectMeasure(componentUuid, metric)).isEmpty();
}
private void assertThatMeasuresAreNotPersisted(String componentUuid) {
assertThatMeasureIsNotPersisted(componentUuid, STRING_METRIC);
assertThatMeasureIsNotPersisted(componentUuid, INT_METRIC);
}
private TestComputationStepContext execute() {
TestComputationStepContext context = new TestComputationStepContext();
new PersistMeasuresStep(dbClient, metricRepository, new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder), treeRootHolder, measureRepository)
.execute(context);
return context;
}
private Optional<MeasureDto> selectMeasure(String componentUuid, Metric metric) {
return dbClient.measureDao().selectMeasure(db.getSession(), ANALYSIS_UUID, componentUuid, metric.getKey());
}
private ComponentDto insertComponent(String key, String uuid) {
ComponentDto componentDto = new ComponentDto()
.setKey(key)
.setUuid(uuid)
.setUuidPath(uuid + ".")
.setBranchUuid(uuid);
db.components().insertComponent(componentDto);
return componentDto;
}
private static void assertNbOfInserts(TestComputationStepContext context, int expected) {
context.getStatistics().assertValue("inserts", expected);
}
@Override
protected ComputationStep step() {
return new PersistMeasuresStep(dbClient, metricRepository, new MeasureToMeasureDto(analysisMetadataHolder, treeRootHolder), treeRootHolder, measureRepository);
}
}
| 10,914 | 44.103306 | 163 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistProjectLinksStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.Mockito;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolder;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.UuidFactory;
import org.sonar.core.util.UuidFactoryFast;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType;
import org.sonar.server.project.Project;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType.CI;
import static org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType.HOME;
import static org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType.ISSUE;
import static org.sonar.scanner.protocol.output.ScannerReport.ComponentLink.ComponentLinkType.SCM;
public class PersistProjectLinksStepIT extends BaseStepTest {
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
private ProjectData project;
private PersistProjectLinksStep underTest = new PersistProjectLinksStep(analysisMetadataHolder, db.getDbClient(), treeRootHolder, reportReader, UuidFactoryFast.getInstance());
@Override
protected ComputationStep step() {
return underTest;
}
@Before
public void setup(){
this.project = db.components().insertPrivateProject();
analysisMetadataHolder.setProject(Project.fromProjectDtoWithTags(project.getProjectDto()));
}
@Test
public void no_effect_if_branch_is_not_main() {
DbClient dbClient = mock(DbClient.class);
TreeRootHolder treeRootHolder = mock(TreeRootHolder.class);
BatchReportReader reportReader = mock(BatchReportReader.class);
UuidFactory uuidFactory = mock(UuidFactory.class);
mockBranch(false);
PersistProjectLinksStep underTest = new PersistProjectLinksStep(analysisMetadataHolder, dbClient, treeRootHolder, reportReader, uuidFactory);
underTest.execute(new TestComputationStepContext());
verifyNoInteractions(uuidFactory, reportReader, treeRootHolder, dbClient);
}
@Test
public void add_links_on_project() {
mockBranch(true);
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
// project
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.addChildRef(2)
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.addLink(ScannerReport.ComponentLink.newBuilder().setType(SCM).setHref("https://github.com/SonarSource/sonar").build())
.addLink(ScannerReport.ComponentLink.newBuilder().setType(ISSUE).setHref("http://jira.sonarsource.com/").build())
.addLink(ScannerReport.ComponentLink.newBuilder().setType(CI).setHref("http://bamboo.ci.codehaus.org/browse/SONAR").build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.getDbClient().projectLinkDao().selectByProjectUuid(db.getSession(), project.projectUuid()))
.extracting(ProjectLinkDto::getType, ProjectLinkDto::getHref, ProjectLinkDto::getName)
.containsExactlyInAnyOrder(
tuple("homepage", "http://www.sonarqube.org", null),
tuple("scm", "https://github.com/SonarSource/sonar", null),
tuple("issue", "http://jira.sonarsource.com/", null),
tuple("ci", "http://bamboo.ci.codehaus.org/browse/SONAR", null));
}
@Test
public void nothing_to_do_when_link_already_exists() {
mockBranch(true);
db.projectLinks().insertProvidedLink(project.getProjectDto(), l -> l.setType("homepage").setName("Home").setHref("http://www.sonarqube.org"));
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.getDbClient().projectLinkDao().selectByProjectUuid(db.getSession(), project.projectUuid()))
.extracting(ProjectLinkDto::getType, ProjectLinkDto::getHref)
.containsExactlyInAnyOrder(tuple("homepage", "http://www.sonarqube.org"));
}
@Test
public void do_not_add_links_on_module() {
mockBranch(true);
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.addChildRef(2)
.build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(2)
.setType(ComponentType.MODULE)
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("project_links")).isZero();
}
@Test
public void do_not_add_links_on_file() {
mockBranch(true);
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).addChildren(
ReportComponent.builder(Component.Type.FILE, 2).setUuid("BCDE").build())
.build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.addChildRef(2)
.build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(2)
.setType(ComponentType.FILE)
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("project_links")).isZero();
}
@Test
public void update_link() {
mockBranch(true);
analysisMetadataHolder.setProject(Project.fromProjectDtoWithTags(project.getProjectDto()));
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.getDbClient().projectLinkDao().selectByProjectUuid(db.getSession(), project.getProjectDto().getUuid()))
.extracting(ProjectLinkDto::getType, ProjectLinkDto::getHref)
.containsExactlyInAnyOrder(tuple("homepage", "http://www.sonarqube.org"));
}
@Test
public void delete_link() {
mockBranch(true);
db.projectLinks().insertProvidedLink(project.getProjectDto(), l -> l.setType("homepage").setName("Home").setHref("http://www.sonar.org"));
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("project_links")).isZero();
}
@Test
public void not_delete_custom_link() {
mockBranch(true);
db.projectLinks().insertCustomLink(project.getProjectDto());
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("project_links")).isOne();
}
@Test
public void fail_when_trying_to_add_same_link_type_multiple_times() {
mockBranch(true);
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid(project.getMainBranchComponent().uuid()).build());
reportReader.putComponent(ScannerReport.Component.newBuilder()
.setRef(1)
.setType(ComponentType.PROJECT)
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.addLink(ScannerReport.ComponentLink.newBuilder().setType(HOME).setHref("http://www.sonarqube.org").build())
.build());
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Link of type 'homepage' has already been declared on component '%s'".formatted(project.projectUuid()));
}
private void mockBranch(boolean isMain) {
Branch branch = Mockito.mock(Branch.class);
when(branch.isMain()).thenReturn(isMain);
analysisMetadataHolder.setBranch(branch);
}
}
| 11,358 | 42.190114 | 177 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistPushEventsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.io.IOException;
import java.util.Date;
import java.util.Optional;
import java.util.stream.IntStream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.MutableTreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.pushevent.PushEventFactory;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbTester;
import org.sonar.db.pushevent.PushEventDto;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatCode;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PersistPushEventsStepIT {
private final TestSystem2 system2 = new TestSystem2().setNow(1L);
@Rule
public DbTester db = DbTester.create(system2);
public final PushEventFactory pushEventFactory = mock(PushEventFactory.class);
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public MutableTreeRootHolderRule treeRootHolder = new MutableTreeRootHolderRule();
private ProtoIssueCache protoIssueCache;
private PersistPushEventsStep underTest;
@Before
public void before() throws IOException {
protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
buildComponentTree();
underTest = new PersistPushEventsStep(db.getDbClient(), protoIssueCache, pushEventFactory, treeRootHolder);
}
@Test
public void description() {
assertThat(underTest.getDescription()).isEqualTo("Publishing taint vulnerabilities and security hotspots events");
}
@Test
public void do_nothing_if_no_issues() {
underTest.execute(mock(ComputationStep.Context.class));
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isZero();
}
@Test
public void resilient_to_failure() {
protoIssueCache.newAppender().append(
createIssue("key1").setType(RuleType.VULNERABILITY))
.close();
when(pushEventFactory.raiseEventOnIssue(any(), any())).thenThrow(new RuntimeException("I have a bad feelings about this"));
assertThatCode(() -> underTest.execute(mock(ComputationStep.Context.class)))
.doesNotThrowAnyException();
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isZero();
}
@Test
public void skip_persist_if_no_push_events() {
protoIssueCache.newAppender().append(
createIssue("key1").setType(RuleType.VULNERABILITY))
.close();
underTest.execute(mock(ComputationStep.Context.class));
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isZero();
}
@Test
public void do_nothing_if_issue_does_not_have_component() {
protoIssueCache.newAppender().append(
createIssue("key1").setType(RuleType.VULNERABILITY)
.setComponentUuid(null))
.close();
underTest.execute(mock(ComputationStep.Context.class));
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isZero();
}
@Test
public void store_push_events() {
protoIssueCache.newAppender()
.append(createIssue("key1").setType(RuleType.VULNERABILITY)
.setComponentUuid("cu1")
.setComponentKey("ck1"))
.append(createIssue("key2").setType(RuleType.VULNERABILITY)
.setComponentUuid("cu2")
.setComponentKey("ck2"))
.close();
when(pushEventFactory.raiseEventOnIssue(eq("uuid_1"), any(DefaultIssue.class))).thenReturn(
Optional.of(createPushEvent()),
Optional.of(createPushEvent()));
underTest.execute(mock(ComputationStep.Context.class));
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isEqualTo(2);
}
@Test
public void store_push_events_for_branch() {
var project = db.components().insertPrivateProject().getProjectDto();
db.components().insertProjectBranch(project, b -> b.setUuid("uuid_1"));
protoIssueCache.newAppender()
.append(createIssue("key1").setType(RuleType.VULNERABILITY)
.setComponentUuid("cu1")
.setComponentKey("ck1"))
.append(createIssue("key2").setType(RuleType.VULNERABILITY)
.setComponentUuid("cu2")
.setComponentKey("ck2"))
.close();
when(pushEventFactory.raiseEventOnIssue(eq(project.getUuid()), any(DefaultIssue.class))).thenReturn(
Optional.of(createPushEvent()),
Optional.of(createPushEvent()));
underTest.execute(mock(ComputationStep.Context.class));
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isEqualTo(2);
}
@Test
public void store_push_events_in_batches() {
var appender = protoIssueCache.newAppender();
IntStream.range(1, 252)
.forEach(value -> {
var defaultIssue = createIssue("key-" + value).setType(RuleType.VULNERABILITY)
.setComponentUuid("cu" + value)
.setComponentKey("ck" + value);
appender.append(defaultIssue);
when(pushEventFactory.raiseEventOnIssue(anyString(), eq(defaultIssue))).thenReturn(Optional.of(createPushEvent()));
});
appender.close();
underTest.execute(mock(ComputationStep.Context.class));
assertThat(db.countSql(db.getSession(), "SELECT count(uuid) FROM push_events")).isEqualTo(251);
}
private DefaultIssue createIssue(String key) {
return new DefaultIssue()
.setKey(key)
.setProjectKey("p")
.setStatus("OPEN")
.setProjectUuid("project-uuid")
.setComponentKey("c")
.setRuleKey(RuleKey.of("r", "r"))
.setCreationDate(new Date());
}
private PushEventDto createPushEvent() {
return new PushEventDto().setProjectUuid("project-uuid").setName("event").setPayload("test".getBytes(UTF_8));
}
private void buildComponentTree() {
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1)
.setUuid("uuid_1")
.addChildren(ReportComponent.builder(Component.Type.FILE, 2)
.setUuid("issue-component-uuid")
.build())
.addChildren(ReportComponent.builder(Component.Type.FILE, 3)
.setUuid("location-component-uuid")
.build())
.build());
}
}
| 7,678 | 34.716279 | 127 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistScannerAnalysisCacheStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import org.apache.commons.io.IOUtils;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.db.DbClient;
import org.sonar.db.DbInputStream;
import org.sonar.db.DbTester;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PersistScannerAnalysisCacheStepIT {
@Rule
public BatchReportReaderRule reader = new BatchReportReaderRule();
@Rule
public DbTester dbTester = DbTester.create();
private final DbClient client = dbTester.getDbClient();
private final TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
private final PersistScannerAnalysisCacheStep step = new PersistScannerAnalysisCacheStep(reader, dbTester.getDbClient(), treeRootHolder);
@Test
public void inserts_cache() throws IOException {
reader.setAnalysisCache("test".getBytes(UTF_8));
Component root = mock(Component.class);
when(root.getUuid()).thenReturn("branch");
treeRootHolder.setRoot(root);
step.execute(mock(ComputationStep.Context.class));
assertThat(dbTester.countRowsOfTable("scanner_analysis_cache")).isOne();
try (DbInputStream data = client.scannerAnalysisCacheDao().selectData(dbTester.getSession(), "branch")) {
assertThat(IOUtils.toString(data, UTF_8)).isEqualTo("test");
}
}
@Test
public void updates_cache() throws IOException {
client.scannerAnalysisCacheDao().insert(dbTester.getSession(), "branch", new ByteArrayInputStream("test".getBytes(UTF_8)));
inserts_cache();
}
@Test
public void do_nothing_if_no_analysis_cache() {
step.execute(mock(ComputationStep.Context.class));
assertThat(dbTester.countRowsOfTable("scanner_analysis_cache")).isZero();
}
}
| 3,009 | 38.605263 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/PersistScannerContextStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.CloseableIterator;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class PersistScannerContextStepIT {
private static final String ANALYSIS_UUID = "UUID";
@ClassRule
public static final DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public BatchReportReaderRule reportReader = new BatchReportReaderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule()
.setUuid(ANALYSIS_UUID);
private DbClient dbClient = dbTester.getDbClient();
private CeTask ceTask = mock(CeTask.class);
private PersistScannerContextStep underTest = new PersistScannerContextStep(reportReader, dbClient, ceTask);
@Test
public void getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Persist scanner context");
}
@Test
public void executes_persist_lines_of_reportReader() {
String taskUuid = "task uuid";
when(ceTask.getUuid()).thenReturn(taskUuid);
reportReader.setScannerLogs(asList("log1", "log2"));
underTest.execute(new TestComputationStepContext());
assertThat(dbClient.ceScannerContextDao().selectScannerContext(dbTester.getSession(), taskUuid))
.contains("log1" + '\n' + "log2");
}
@Test
public void executes_persist_does_not_persist_any_scanner_context_if_iterator_is_empty() {
reportReader.setScannerLogs(emptyList());
underTest.execute(new TestComputationStepContext());
assertThat(dbClient.ceScannerContextDao().selectScannerContext(dbTester.getSession(), ANALYSIS_UUID))
.isEmpty();
}
/**
* SONAR-8306
*/
@Test
public void execute_does_not_fail_if_scanner_context_has_already_been_persisted() {
dbClient.ceScannerContextDao().insert(dbTester.getSession(), ANALYSIS_UUID, CloseableIterator.from(Arrays.asList("a", "b", "c").iterator()));
dbTester.commit();
reportReader.setScannerLogs(asList("1", "2", "3"));
when(ceTask.getUuid()).thenReturn(ANALYSIS_UUID);
underTest.execute(new TestComputationStepContext());
assertThat(dbClient.ceScannerContextDao().selectScannerContext(dbTester.getSession(), ANALYSIS_UUID))
.contains("1" + '\n' + "2" + '\n' + "3");
}
}
| 3,708 | 36.09 | 145 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ProjectNclocComputationStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.server.project.Project;
import static java.util.Collections.emptyList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.sonar.api.measures.Metric.ValueType.INT;
public class ProjectNclocComputationStepIT {
@Rule
public DbTester db = DbTester.create();
private final DbClient dbClient = db.getDbClient();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
private final ProjectNclocComputationStep step = new ProjectNclocComputationStep(analysisMetadataHolder, dbClient);
@Test
public void test_computing_branch_ncloc() {
MetricDto ncloc = db.measures().insertMetric(m -> m.setKey("ncloc").setValueType(INT.toString()));
ProjectDto project = db.components().insertPublicProject().getProjectDto();
BranchDto branch1 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
db.measures().insertLiveMeasure(branch1, ncloc, m -> m.setValue(200d));
BranchDto branch2 = db.components().insertProjectBranch(project, b -> b.setBranchType(BranchType.BRANCH));
db.measures().insertLiveMeasure(branch2, ncloc, m -> m.setValue(10d));
analysisMetadataHolder.setProject(new Project(project.getUuid(), project.getKey(), project.getName(), project.getDescription(), emptyList()));
step.execute(TestComputationStepContext.TestStatistics::new);
assertThat(dbClient.projectDao().getNclocSum(db.getSession())).isEqualTo(200L);
}
@Test
public void description_is_not_missing() {
assertThat(step.getDescription()).isNotBlank();
}
}
| 2,899 | 42.283582 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ReportPersistAnalysisStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import java.util.Optional;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.period.Period;
import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotQuery;
import org.sonar.db.component.SnapshotTesting;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ReportPersistAnalysisStepIT extends BaseStepTest {
private static final String PROJECT_KEY = "PROJECT_KEY";
private static final String ANALYSIS_UUID = "U1";
private static final String REVISION_ID = "5f6432a1";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
@Rule
public PeriodHolderRule periodsHolder = new PeriodHolderRule();
private System2 system2 = mock(System2.class);
private DbClient dbClient = dbTester.getDbClient();
private long analysisDate;
private long now;
private PersistAnalysisStep underTest;
@Before
public void setup() {
analysisDate = DateUtils.parseDateQuietly("2015-06-01").getTime();
analysisMetadataHolder.setUuid(ANALYSIS_UUID);
analysisMetadataHolder.setAnalysisDate(analysisDate);
analysisMetadataHolder.setScmRevision(REVISION_ID);
now = DateUtils.parseDateQuietly("2015-06-02").getTime();
when(system2.now()).thenReturn(now);
underTest = new PersistAnalysisStep(system2, dbClient, treeRootHolder, analysisMetadataHolder, periodsHolder);
// initialize PeriodHolder to empty by default
periodsHolder.setPeriod(null);
}
@Override
protected ComputationStep step() {
return underTest;
}
@Test
public void persist_analysis() {
String projectVersion = randomAlphabetic(10);
ComponentDto projectDto = ComponentTesting.newPrivateProjectDto("ABCD").setKey(PROJECT_KEY).setName("Project");
dbTester.components().insertComponent(projectDto);
ComponentDto directoryDto = ComponentTesting.newDirectory(projectDto, "CDEF", "src/main/java/dir").setKey("PROJECT_KEY:src/main/java/dir");
dbTester.components().insertComponent(directoryDto);
ComponentDto fileDto = ComponentTesting.newFileDto(projectDto, directoryDto, "DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java");
dbTester.components().insertComponent(fileDto);
dbTester.getSession().commit();
Component file = ReportComponent.builder(Component.Type.FILE, 3).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java").build();
Component directory = ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir").addChildren(file).build();
String buildString = Optional.ofNullable(projectVersion).map(v -> randomAlphabetic(7)).orElse(null);
Component project = ReportComponent.builder(Component.Type.PROJECT, 1)
.setUuid("ABCD")
.setKey(PROJECT_KEY)
.setProjectVersion(projectVersion)
.setBuildString(buildString)
.setScmRevisionId(REVISION_ID)
.addChildren(directory)
.build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("snapshots")).isOne();
SnapshotDto projectSnapshot = getUnprocessedSnapshot(projectDto.uuid());
assertThat(projectSnapshot.getUuid()).isEqualTo(ANALYSIS_UUID);
assertThat(projectSnapshot.getRootComponentUuid()).isEqualTo(project.getUuid());
assertThat(projectSnapshot.getProjectVersion()).isEqualTo(projectVersion);
assertThat(projectSnapshot.getBuildString()).isEqualTo(buildString);
assertThat(projectSnapshot.getLast()).isFalse();
assertThat(projectSnapshot.getStatus()).isEqualTo("U");
assertThat(projectSnapshot.getCreatedAt()).isEqualTo(analysisDate);
assertThat(projectSnapshot.getBuildDate()).isEqualTo(now);
assertThat(projectSnapshot.getRevision()).isEqualTo(REVISION_ID);
}
@Test
public void persist_snapshots_with_new_code_period() {
ComponentDto projectDto = ComponentTesting.newPrivateProjectDto("ABCD").setKey(PROJECT_KEY).setName("Project");
dbTester.components().insertComponent(projectDto);
SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(projectDto).setCreatedAt(DateUtils.parseDateQuietly("2015-01-01").getTime());
dbClient.snapshotDao().insert(dbTester.getSession(), snapshotDto);
dbTester.getSession().commit();
periodsHolder.setPeriod(new Period("NUMBER_OF_DAYS", "10", analysisDate));
Component project = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
SnapshotDto projectSnapshot = getUnprocessedSnapshot(projectDto.uuid());
assertThat(projectSnapshot.getPeriodMode()).isEqualTo("NUMBER_OF_DAYS");
assertThat(projectSnapshot.getPeriodDate()).isEqualTo(analysisDate);
assertThat(projectSnapshot.getPeriodModeParameter()).isNotNull();
}
@Test
public void only_persist_snapshots_with_new_code_period_on_project_and_module() {
periodsHolder.setPeriod(new Period("PREVIOUS_VERSION", null, analysisDate));
ComponentDto projectDto = ComponentTesting.newPrivateProjectDto("ABCD").setKey(PROJECT_KEY).setName("Project");
dbTester.components().insertComponent(projectDto);
SnapshotDto projectSnapshot = SnapshotTesting.newAnalysis(projectDto);
dbClient.snapshotDao().insert(dbTester.getSession(), projectSnapshot);
ComponentDto directoryDto = ComponentTesting.newDirectory(projectDto, "CDEF", "MODULE_KEY:src/main/java/dir").setKey("MODULE_KEY:src/main/java/dir");
dbTester.components().insertComponent(directoryDto);
ComponentDto fileDto = ComponentTesting.newFileDto(projectDto, directoryDto, "DEFG").setKey("MODULE_KEY:src/main/java/dir/Foo.java");
dbTester.components().insertComponent(fileDto);
dbTester.getSession().commit();
Component file = ReportComponent.builder(Component.Type.FILE, 3).setUuid("DEFG").setKey("MODULE_KEY:src/main/java/dir/Foo.java").build();
Component directory = ReportComponent.builder(Component.Type.DIRECTORY, 2).setUuid("CDEF").setKey("MODULE_KEY:src/main/java/dir").addChildren(file).build();
Component project = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).addChildren(directory).build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
SnapshotDto newProjectSnapshot = getUnprocessedSnapshot(projectDto.uuid());
assertThat(newProjectSnapshot.getPeriodMode()).isEqualTo("PREVIOUS_VERSION");
}
@Test
public void set_no_period_on_snapshots_when_no_period() {
ComponentDto projectDto = ComponentTesting.newPrivateProjectDto("ABCD").setKey(PROJECT_KEY).setName("Project");
dbTester.components().insertComponent(projectDto);
SnapshotDto snapshotDto = SnapshotTesting.newAnalysis(projectDto);
dbClient.snapshotDao().insert(dbTester.getSession(), snapshotDto);
dbTester.getSession().commit();
Component project = ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).build();
treeRootHolder.setRoot(project);
underTest.execute(new TestComputationStepContext());
SnapshotDto projectSnapshot = getUnprocessedSnapshot(projectDto.uuid());
assertThat(projectSnapshot.getPeriodMode()).isNull();
assertThat(projectSnapshot.getPeriodDate()).isNull();
assertThat(projectSnapshot.getPeriodModeParameter()).isNull();
}
private SnapshotDto getUnprocessedSnapshot(String componentUuid) {
List<SnapshotDto> projectSnapshots = dbClient.snapshotDao().selectAnalysesByQuery(dbTester.getSession(),
new SnapshotQuery().setRootComponentUuid(componentUuid).setIsLast(false).setStatus(SnapshotDto.STATUS_UNPROCESSED));
assertThat(projectSnapshots).hasSize(1);
return projectSnapshots.get(0);
}
}
| 9,772 | 45.985577 | 161 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ReportPersistComponentsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Optional;
import java.util.Set;
import java.util.function.Consumer;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.TestBranch;
import org.sonar.ce.task.projectanalysis.component.BranchPersister;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl;
import org.sonar.ce.task.projectanalysis.component.FileAttributes;
import org.sonar.ce.task.projectanalysis.component.MutableDisabledComponentsHolder;
import org.sonar.ce.task.projectanalysis.component.ProjectPersister;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.server.project.Project;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.DIRECTORY;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.FILE;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.PROJECT;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR;
import static org.sonar.db.component.ComponentTesting.newDirectory;
public class ReportPersistComponentsStepIT extends BaseStepTest {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final String PROJECT_KEY = "PROJECT_KEY";
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
private final System2 system2 = mock(System2.class);
private final DbClient dbClient = db.getDbClient();
private Date now;
private final MutableDisabledComponentsHolder disabledComponentsHolder = mock(MutableDisabledComponentsHolder.class, RETURNS_DEEP_STUBS);
private PersistComponentsStep underTest;
@Before
public void setup() throws Exception {
now = DATE_FORMAT.parse("2015-06-02");
when(system2.now()).thenReturn(now.getTime());
BranchPersister branchPersister = mock(BranchPersister.class);
ProjectPersister projectPersister = mock(ProjectPersister.class);
underTest = new PersistComponentsStep(dbClient, treeRootHolder, system2, disabledComponentsHolder, analysisMetadataHolder, branchPersister, projectPersister);
}
@Override
protected ComputationStep step() {
return underTest;
}
@Test
public void persist_components() {
ComponentDto projectDto = prepareProject();
Component file = builder(FILE, 4).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java")
.setName("src/main/java/dir/Foo.java")
.setShortName("Foo.java")
.setFileAttributes(new FileAttributes(false, "java", 1))
.build();
Component directory = builder(DIRECTORY, 3).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir")
.setName("src/main/java/dir")
.setShortName("dir")
.addChildren(file)
.build();
Component treeRoot = asTreeRoot(projectDto)
.addChildren(directory)
.build();
treeRootHolder.setRoot(treeRoot);
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("components")).isEqualTo(3);
ComponentDto directoryDto = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir").get();
assertThat(directoryDto.name()).isEqualTo("dir");
assertThat(directoryDto.longName()).isEqualTo("src/main/java/dir");
assertThat(directoryDto.description()).isNull();
assertThat(directoryDto.path()).isEqualTo("src/main/java/dir");
assertThat(directoryDto.uuid()).isEqualTo("CDEF");
assertThat(directoryDto.getUuidPath()).isEqualTo(UUID_PATH_SEPARATOR + projectDto.uuid() + UUID_PATH_SEPARATOR);
assertThat(directoryDto.branchUuid()).isEqualTo(projectDto.uuid());
assertThat(directoryDto.qualifier()).isEqualTo("DIR");
assertThat(directoryDto.scope()).isEqualTo("DIR");
assertThat(directoryDto.getCreatedAt()).isEqualTo(now);
ComponentDto fileDto = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java").get();
assertThat(fileDto.name()).isEqualTo("Foo.java");
assertThat(fileDto.longName()).isEqualTo("src/main/java/dir/Foo.java");
assertThat(fileDto.description()).isNull();
assertThat(fileDto.path()).isEqualTo("src/main/java/dir/Foo.java");
assertThat(fileDto.language()).isEqualTo("java");
assertThat(fileDto.uuid()).isEqualTo("DEFG");
assertThat(fileDto.getUuidPath()).isEqualTo(directoryDto.getUuidPath() + directoryDto.uuid() + UUID_PATH_SEPARATOR);
assertThat(fileDto.branchUuid()).isEqualTo(projectDto.uuid());
assertThat(fileDto.qualifier()).isEqualTo("FIL");
assertThat(fileDto.scope()).isEqualTo("FIL");
assertThat(fileDto.getCreatedAt()).isEqualTo(now);
}
@Test
public void persist_components_of_existing_branch() {
ComponentDto branch = prepareBranch("feature/foo");
Component file = builder(FILE, 4).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java")
.setName("src/main/java/dir/Foo.java")
.setShortName("Foo.java")
.setFileAttributes(new FileAttributes(false, "java", 1))
.build();
Component directory = builder(DIRECTORY, 3).setUuid("CDEF")
.setKey("PROJECT_KEY:src/main/java/dir")
.setName("src/main/java/dir")
.setShortName("dir")
.addChildren(file)
.build();
Component treeRoot = asTreeRoot(branch)
.addChildren(directory)
.build();
treeRootHolder.setRoot(treeRoot);
underTest.execute(new TestComputationStepContext());
// 3 in this branch plus the project
assertThat(db.countRowsOfTable("components")).isEqualTo(4);
ComponentDto directoryDto = dbClient.componentDao().selectByKeyAndBranch(db.getSession(), "PROJECT_KEY:src/main/java/dir", "feature/foo").get();
assertThat(directoryDto.name()).isEqualTo("dir");
assertThat(directoryDto.longName()).isEqualTo("src/main/java/dir");
assertThat(directoryDto.description()).isNull();
assertThat(directoryDto.path()).isEqualTo("src/main/java/dir");
assertThat(directoryDto.uuid()).isEqualTo("CDEF");
assertThat(directoryDto.getUuidPath()).isEqualTo(UUID_PATH_SEPARATOR + branch.uuid() + UUID_PATH_SEPARATOR);
assertThat(directoryDto.branchUuid()).isEqualTo(branch.uuid());
assertThat(directoryDto.qualifier()).isEqualTo("DIR");
assertThat(directoryDto.scope()).isEqualTo("DIR");
assertThat(directoryDto.getCreatedAt()).isEqualTo(now);
ComponentDto fileDto = dbClient.componentDao().selectByKeyAndBranch(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java", "feature/foo").get();
assertThat(fileDto.name()).isEqualTo("Foo.java");
assertThat(fileDto.longName()).isEqualTo("src/main/java/dir/Foo.java");
assertThat(fileDto.description()).isNull();
assertThat(fileDto.path()).isEqualTo("src/main/java/dir/Foo.java");
assertThat(fileDto.language()).isEqualTo("java");
assertThat(fileDto.uuid()).isEqualTo("DEFG");
assertThat(fileDto.getUuidPath()).isEqualTo(directoryDto.getUuidPath() + directoryDto.uuid() + UUID_PATH_SEPARATOR);
assertThat(fileDto.branchUuid()).isEqualTo(branch.uuid());
assertThat(fileDto.qualifier()).isEqualTo("FIL");
assertThat(fileDto.scope()).isEqualTo("FIL");
assertThat(fileDto.getCreatedAt()).isEqualTo(now);
}
@Test
public void persist_file_directly_attached_on_root_directory() {
ComponentDto projectDto = prepareProject();
treeRootHolder.setRoot(
asTreeRoot(projectDto)
.addChildren(
builder(FILE, 2).setUuid("DEFG").setKey(projectDto.getKey() + ":pom.xml")
.setName("pom.xml")
.build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(dbClient.componentDao().selectByKey(db.getSession(), projectDto.getKey() + ":/")).isNotPresent();
ComponentDto file = dbClient.componentDao().selectByKey(db.getSession(), projectDto.getKey() + ":pom.xml").get();
assertThat(file.name()).isEqualTo("pom.xml");
assertThat(file.path()).isEqualTo("pom.xml");
}
@Test
public void persist_unit_test() {
ComponentDto projectDto = prepareProject();
treeRootHolder.setRoot(
asTreeRoot(projectDto)
.addChildren(
builder(DIRECTORY, 2).setUuid("CDEF").setKey(PROJECT_KEY + ":src/test/java/dir")
.setName("src/test/java/dir")
.addChildren(
builder(FILE, 3).setUuid("DEFG").setKey(PROJECT_KEY + ":src/test/java/dir/FooTest.java")
.setName("src/test/java/dir/FooTest.java")
.setShortName("FooTest.java")
.setFileAttributes(new FileAttributes(true, null, 1))
.build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
ComponentDto file = dbClient.componentDao().selectByKey(db.getSession(), PROJECT_KEY + ":src/test/java/dir/FooTest.java").get();
assertThat(file.name()).isEqualTo("FooTest.java");
assertThat(file.longName()).isEqualTo("src/test/java/dir/FooTest.java");
assertThat(file.path()).isEqualTo("src/test/java/dir/FooTest.java");
assertThat(file.qualifier()).isEqualTo("UTS");
assertThat(file.scope()).isEqualTo("FIL");
}
@Test
public void update_file_to_directory_change_scope() {
ComponentDto project = prepareProject();
ComponentDto directory = ComponentTesting.newDirectory(project, "src").setUuid("CDEF").setKey("PROJECT_KEY:src");
ComponentDto file = ComponentTesting.newFileDto(project, directory, "DEFG").setPath("src/foo").setName("foo")
.setKey("PROJECT_KEY:src/foo");
dbClient.componentDao().insert(db.getSession(), Set.of(directory, file), true);
db.getSession().commit();
assertThat(dbClient.componentDao().selectByKey(db.getSession(), PROJECT_KEY + ":src/foo").get().scope()).isEqualTo("FIL");
treeRootHolder.setRoot(
asTreeRoot(project)
.addChildren(
builder(DIRECTORY, 2).setUuid("CDEF").setKey(PROJECT_KEY + ":src")
.setName("src")
.addChildren(
builder(DIRECTORY, 3).setUuid("DEFG").setKey(PROJECT_KEY + ":src/foo")
.setName("foo")
.addChildren(
builder(FILE, 4).setUuid("HIJK").setKey(PROJECT_KEY + ":src/foo/FooTest.java")
.setName("src/foo/FooTest.java")
.setShortName("FooTest.java")
.setFileAttributes(new FileAttributes(false, null, 1))
.build())
.build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
// commit the functional transaction
dbClient.componentDao().applyBChangesForBranchUuid(db.getSession(), project.uuid());
db.commit();
assertThat(dbClient.componentDao().selectByKey(db.getSession(), PROJECT_KEY + ":src/foo").get().scope()).isEqualTo("DIR");
}
@Test
public void persist_only_new_components() {
// Project and module already exists
ComponentDto project = prepareProject();
db.getSession().commit();
treeRootHolder.setRoot(
builder(PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey())
.setName("Project")
.addChildren(
builder(DIRECTORY, 3).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir")
.setName("src/main/java/dir")
.addChildren(
builder(FILE, 4).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java")
.setName("src/main/java/dir/Foo.java")
.setShortName("Foo.java")
.build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("components")).isEqualTo(3);
ComponentDto projectReloaded = dbClient.componentDao().selectByKey(db.getSession(), project.getKey()).get();
assertThat(projectReloaded.uuid()).isEqualTo(project.uuid());
assertThat(projectReloaded.getUuidPath()).isEqualTo(UUID_PATH_OF_ROOT);
ComponentDto directory = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir").get();
assertThat(directory.getUuidPath()).isEqualTo(directory.getUuidPath());
assertThat(directory.branchUuid()).isEqualTo(project.uuid());
ComponentDto file = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java").get();
assertThat(file.getUuidPath()).isEqualTo(file.getUuidPath());
assertThat(file.branchUuid()).isEqualTo(project.uuid());
}
@Test
public void nothing_to_persist() {
ComponentDto project = prepareProject();
ComponentDto directory = ComponentTesting.newDirectory(project, "src/main/java/dir").setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir");
ComponentDto file = ComponentTesting.newFileDto(project, directory, "DEFG").setPath("src/main/java/dir/Foo.java").setName("Foo.java")
.setKey("PROJECT_KEY:src/main/java/dir/Foo.java");
dbClient.componentDao().insert(db.getSession(), Set.of(directory, file), true);
db.getSession().commit();
treeRootHolder.setRoot(
builder(PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey())
.setName("Project")
.addChildren(
builder(DIRECTORY, 3).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir")
.setName("src/main/java/dir")
.addChildren(
builder(FILE, 4).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java")
.setName("src/main/java/dir/Foo.java")
.build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("components")).isEqualTo(3);
assertThat(dbClient.componentDao().selectByKey(db.getSession(), project.getKey()).get().uuid()).isEqualTo(project.uuid());
assertThat(dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir").get().uuid()).isEqualTo(directory.uuid());
assertThat(dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java").get().uuid()).isEqualTo(file.uuid());
ComponentDto projectReloaded = dbClient.componentDao().selectByKey(db.getSession(), project.getKey()).get();
assertThat(projectReloaded.uuid()).isEqualTo(project.uuid());
assertThat(projectReloaded.branchUuid()).isEqualTo(project.branchUuid());
ComponentDto directoryReloaded = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir").get();
assertThat(directoryReloaded.uuid()).isEqualTo(directory.uuid());
assertThat(directoryReloaded.getUuidPath()).isEqualTo(directory.getUuidPath());
assertThat(directoryReloaded.branchUuid()).isEqualTo(directory.branchUuid());
assertThat(directoryReloaded.name()).isEqualTo(directory.name());
assertThat(directoryReloaded.path()).isEqualTo(directory.path());
ComponentDto fileReloaded = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java").get();
assertThat(fileReloaded.uuid()).isEqualTo(file.uuid());
assertThat(fileReloaded.getUuidPath()).isEqualTo(file.getUuidPath());
assertThat(fileReloaded.branchUuid()).isEqualTo(file.branchUuid());
assertThat(fileReloaded.name()).isEqualTo(file.name());
assertThat(fileReloaded.path()).isEqualTo(file.path());
}
@Test
public void do_not_update_created_at_on_existing_component() {
Date oldDate = DateUtils.parseDate("2015-01-01");
ComponentDto project = prepareProject(p -> p.setCreatedAt(oldDate));
db.getSession().commit();
treeRootHolder.setRoot(
builder(PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey())
.build());
underTest.execute(new TestComputationStepContext());
Optional<ComponentDto> projectReloaded = dbClient.componentDao().selectByUuid(db.getSession(), project.uuid());
assertThat(projectReloaded.get().getCreatedAt()).isNotEqualTo(now);
}
@Test
public void persist_components_that_were_previously_removed() {
ComponentDto project = prepareProject();
ComponentDto removedDirectory = ComponentTesting.newDirectory(project, "src/main/java/dir")
.setLongName("src/main/java/dir")
.setName("dir")
.setUuid("CDEF")
.setKey("PROJECT_KEY:src/main/java/dir")
.setEnabled(false);
ComponentDto removedFile = ComponentTesting.newFileDto(project, removedDirectory, "DEFG")
.setPath("src/main/java/dir/Foo.java")
.setLongName("src/main/java/dir/Foo.java")
.setName("Foo.java")
.setKey("PROJECT_KEY:src/main/java/dir/Foo.java")
.setEnabled(false);
dbClient.componentDao().insert(db.getSession(), Set.of(removedDirectory, removedFile), true);
db.getSession().commit();
treeRootHolder.setRoot(
builder(PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey())
.setName("Project")
.addChildren(
builder(DIRECTORY, 3).setUuid("CDEF").setKey("PROJECT_KEY:src/main/java/dir")
.setName("src/main/java/dir")
.setShortName("dir")
.addChildren(
builder(FILE, 4).setUuid("DEFG").setKey("PROJECT_KEY:src/main/java/dir/Foo.java")
.setName("src/main/java/dir/Foo.java")
.setShortName("Foo.java")
.build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
assertThat(db.countRowsOfTable("components")).isEqualTo(3);
assertThat(dbClient.componentDao().selectByKey(db.getSession(), project.getKey()).get().uuid()).isEqualTo(project.uuid());
assertThat(dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir").get().uuid()).isEqualTo(removedDirectory.uuid());
assertThat(dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java").get().uuid()).isEqualTo(removedFile.uuid());
assertExistButDisabled(removedDirectory.getKey(), removedFile.getKey());
// commit the functional transaction
dbClient.componentDao().applyBChangesForBranchUuid(db.getSession(), project.uuid());
ComponentDto projectReloaded = dbClient.componentDao().selectByKey(db.getSession(), project.getKey()).get();
assertThat(projectReloaded.uuid()).isEqualTo(project.uuid());
assertThat(projectReloaded.getUuidPath()).isEqualTo(project.getUuidPath());
assertThat(projectReloaded.branchUuid()).isEqualTo(project.branchUuid());
assertThat(projectReloaded.isEnabled()).isTrue();
ComponentDto directoryReloaded = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir").get();
assertThat(directoryReloaded.uuid()).isEqualTo(removedDirectory.uuid());
assertThat(directoryReloaded.getUuidPath()).isEqualTo(removedDirectory.getUuidPath());
assertThat(directoryReloaded.branchUuid()).isEqualTo(removedDirectory.branchUuid());
assertThat(directoryReloaded.name()).isEqualTo(removedDirectory.name());
assertThat(directoryReloaded.longName()).isEqualTo(removedDirectory.longName());
assertThat(directoryReloaded.path()).isEqualTo(removedDirectory.path());
assertThat(directoryReloaded.isEnabled()).isTrue();
ComponentDto fileReloaded = dbClient.componentDao().selectByKey(db.getSession(), "PROJECT_KEY:src/main/java/dir/Foo.java").get();
assertThat(fileReloaded.uuid()).isEqualTo(removedFile.uuid());
assertThat(fileReloaded.getUuidPath()).isEqualTo(removedFile.getUuidPath());
assertThat(fileReloaded.branchUuid()).isEqualTo(removedFile.branchUuid());
assertThat(fileReloaded.name()).isEqualTo(removedFile.name());
assertThat(fileReloaded.path()).isEqualTo(removedFile.path());
assertThat(fileReloaded.isEnabled()).isTrue();
}
private void assertExistButDisabled(String... keys) {
for (String key : keys) {
ComponentDto dto = dbClient.componentDao().selectByKey(db.getSession(), key).get();
assertThat(dto.isEnabled()).isFalse();
}
}
@Test
public void persists_existing_components_with_visibility_of_root_in_db_out_of_functional_transaction() {
ComponentDto project = prepareProject(p -> p.setPrivate(true));
ComponentDto dir = db.components().insertComponent(newDirectory(project, "DEFG", "Directory").setKey("DIR").setPrivate(true));
treeRootHolder.setRoot(createSampleProjectComponentTree(project));
underTest.execute(new TestComputationStepContext());
Stream.of(project.uuid(), dir.uuid())
.forEach(uuid -> assertThat(dbClient.componentDao().selectByUuid(db.getSession(), uuid).get().isPrivate())
.describedAs("for uuid " + uuid)
.isTrue());
}
private ReportComponent createSampleProjectComponentTree(ComponentDto project) {
return createSampleProjectComponentTree(project.uuid(), project.getKey());
}
private ReportComponent createSampleProjectComponentTree(String projectUuid, String projectKey) {
return builder(PROJECT, 1).setUuid(projectUuid).setKey(projectKey)
.setName("Project")
.addChildren(
builder(Component.Type.DIRECTORY, 3).setUuid("DEFG").setKey("DIR")
.setName("Directory")
.addChildren(
builder(FILE, 4).setUuid("CDEF").setKey("FILE")
.setName("file")
.build())
.build())
.build();
}
private ReportComponent.Builder asTreeRoot(ComponentDto project) {
return builder(PROJECT, 1).setUuid(project.uuid()).setKey(project.getKey()).setName(project.name());
}
private ComponentDto prepareProject() {
return prepareProject(defaults());
}
private ComponentDto prepareProject(Consumer<ComponentDto> populators) {
ComponentDto dto = db.components().insertPrivateProject(populators).getMainBranchComponent();
analysisMetadataHolder.setProject(Project.from(dto));
analysisMetadataHolder.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME));
return dto;
}
private ComponentDto prepareBranch(String branchName) {
ComponentDto projectDto = db.components().insertPublicProject().getMainBranchComponent();
ComponentDto branchDto = db.components().insertProjectBranch(projectDto, b -> b.setKey(branchName));
analysisMetadataHolder.setProject(Project.from(projectDto));
analysisMetadataHolder.setBranch(new TestBranch(branchName));
return branchDto;
}
private static <T> Consumer<T> defaults() {
return t -> {
};
}
}
| 24,477 | 46.346228 | 162 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/SendIssueNotificationsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.assertj.core.groups.Tuple;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.sonar.api.notifications.Notification;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rules.RuleType;
import org.sonar.api.utils.Duration;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.issue.ProtoIssueCache;
import org.sonar.ce.task.projectanalysis.notification.NotificationFactory;
import org.sonar.ce.task.projectanalysis.util.cache.DiskCache;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.issue.DefaultIssue;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.user.UserDto;
import org.sonar.server.issue.notification.DistributedMetricStatsInt;
import org.sonar.server.issue.notification.IssuesChangesNotification;
import org.sonar.server.issue.notification.MyNewIssuesNotification;
import org.sonar.server.issue.notification.NewIssuesNotification;
import org.sonar.server.issue.notification.NewIssuesStatistics;
import org.sonar.server.notification.NotificationService;
import org.sonar.server.project.Project;
import static java.util.Arrays.stream;
import static java.util.Collections.emptyList;
import static java.util.Collections.shuffle;
import static java.util.Collections.singleton;
import static java.util.stream.Collectors.toList;
import static java.util.stream.Stream.concat;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.apache.commons.lang.math.RandomUtils.nextInt;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.ArgumentCaptor.forClass;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.ArgumentMatchers.anySet;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
import static org.sonar.ce.task.projectanalysis.component.Component.Type;
import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
import static org.sonar.ce.task.projectanalysis.step.SendIssueNotificationsStep.NOTIF_TYPES;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.BranchType.BRANCH;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
import static org.sonar.db.component.ComponentTesting.newBranchComponent;
import static org.sonar.db.component.ComponentTesting.newBranchDto;
import static org.sonar.db.component.ComponentTesting.newFileDto;
import static org.sonar.db.component.ComponentTesting.newMainBranchDto;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.issue.IssueTesting.newIssue;
import static org.sonar.db.rule.RuleTesting.newRule;
public class SendIssueNotificationsStepIT extends BaseStepTest {
private static final String BRANCH_NAME = "feature";
private static final String PULL_REQUEST_ID = "pr-123";
private static final long ANALYSE_DATE = 123L;
private static final int FIVE_MINUTES_IN_MS = 1000 * 60 * 5;
private static final Duration ISSUE_DURATION = Duration.create(100L);
private static final Component FILE = builder(Type.FILE, 11).build();
private static final Component PROJECT = builder(Type.PROJECT, 1)
.setProjectVersion(randomAlphanumeric(10))
.addChildren(FILE).build();
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule()
.setRoot(PROJECT);
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule()
.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME))
.setAnalysisDate(new Date(ANALYSE_DATE));
@Rule
public TemporaryFolder temp = new TemporaryFolder();
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
private final Random random = new Random();
private final RuleType[] RULE_TYPES_EXCEPT_HOTSPOTS = Stream.of(RuleType.values()).filter(r -> r != SECURITY_HOTSPOT).toArray(RuleType[]::new);
private final RuleType randomRuleType = RULE_TYPES_EXCEPT_HOTSPOTS[random.nextInt(RULE_TYPES_EXCEPT_HOTSPOTS.length)];
@SuppressWarnings("unchecked")
private Class<Map<String, UserDto>> assigneeCacheType = (Class<Map<String, UserDto>>) (Object) Map.class;
@SuppressWarnings("unchecked")
private Class<Set<DefaultIssue>> setType = (Class<Set<DefaultIssue>>) (Class<?>) Set.class;
@SuppressWarnings("unchecked")
private Class<Map<String, UserDto>> mapType = (Class<Map<String, UserDto>>) (Class<?>) Map.class;
private ArgumentCaptor<Map<String, UserDto>> assigneeCacheCaptor = ArgumentCaptor.forClass(assigneeCacheType);
private ArgumentCaptor<Set<DefaultIssue>> issuesSetCaptor = forClass(setType);
private ArgumentCaptor<Map<String, UserDto>> assigneeByUuidCaptor = forClass(mapType);
private NotificationService notificationService = mock(NotificationService.class);
private NotificationFactory notificationFactory = mock(NotificationFactory.class);
private NewIssuesNotification newIssuesNotificationMock = createNewIssuesNotificationMock();
private MyNewIssuesNotification myNewIssuesNotificationMock = createMyNewIssuesNotificationMock();
private ProtoIssueCache protoIssueCache;
private SendIssueNotificationsStep underTest;
@Before
public void setUp() throws Exception {
protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
underTest = new SendIssueNotificationsStep(protoIssueCache, treeRootHolder, notificationService, analysisMetadataHolder,
notificationFactory, db.getDbClient());
when(notificationFactory.newNewIssuesNotification(any(assigneeCacheType))).thenReturn(newIssuesNotificationMock);
when(notificationFactory.newMyNewIssuesNotification(any(assigneeCacheType))).thenReturn(myNewIssuesNotificationMock);
}
@Test
public void do_not_send_notifications_if_no_subscribers() {
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(false);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService, never()).deliver(any(Notification.class));
verify(notificationService, never()).deliverEmails(anyCollection());
verifyStatistics(context, 0, 0, 0);
}
@Test
public void send_global_new_issues_notification() {
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION)
.setCreationDate(new Date(ANALYSE_DATE)))
.close();
when(notificationService.hasProjectSubscribersForTypes(eq(PROJECT.getUuid()), any())).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService).deliver(newIssuesNotificationMock);
verify(newIssuesNotificationMock).setProject(PROJECT.getKey(), PROJECT.getName(), null, null);
verify(newIssuesNotificationMock).setAnalysisDate(new Date(ANALYSE_DATE));
verify(newIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), any());
verify(newIssuesNotificationMock).setDebt(ISSUE_DURATION);
verifyStatistics(context, 1, 0, 0);
}
@Test
public void send_global_new_issues_notification_only_for_non_backdated_issues() {
Random random = new Random();
Integer[] efforts = IntStream.range(0, 1 + random.nextInt(10)).mapToObj(i -> 10_000 * i).toArray(Integer[]::new);
Integer[] backDatedEfforts = IntStream.range(0, 1 + random.nextInt(10)).mapToObj(i -> 10 + random.nextInt(100)).toArray(Integer[]::new);
Duration expectedEffort = Duration.create(stream(efforts).mapToInt(i -> i).sum());
List<DefaultIssue> issues = concat(stream(efforts)
.map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort))
.setCreationDate(new Date(ANALYSE_DATE))),
stream(backDatedEfforts)
.map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort))
.setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))))
.collect(toList());
shuffle(issues);
DiskCache.CacheAppender issueCache = this.protoIssueCache.newAppender();
issues.forEach(issueCache::append);
issueCache.close();
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService).deliver(newIssuesNotificationMock);
ArgumentCaptor<NewIssuesStatistics.Stats> statsCaptor = forClass(NewIssuesStatistics.Stats.class);
verify(newIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), statsCaptor.capture());
verify(newIssuesNotificationMock).setDebt(expectedEffort);
NewIssuesStatistics.Stats stats = statsCaptor.getValue();
assertThat(stats.hasIssues()).isTrue();
// just checking all issues have been added to the stats
DistributedMetricStatsInt severity = stats.getDistributedMetricStats(NewIssuesStatistics.Metric.RULE_TYPE);
assertThat(severity.getOnCurrentAnalysis()).isEqualTo(efforts.length);
assertThat(severity.getTotal()).isEqualTo(backDatedEfforts.length + efforts.length);
verifyStatistics(context, 1, 0, 0);
}
@Test
public void do_not_send_global_new_issues_notification_if_issue_has_been_backdated() {
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION)
.setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS)))
.close();
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService, never()).deliver(any(Notification.class));
verify(notificationService, never()).deliverEmails(anyCollection());
verifyStatistics(context, 0, 0, 0);
}
@Test
public void send_global_new_issues_notification_on_branch() {
ComponentDto project = newPrivateProjectDto();
ComponentDto branch = setUpBranch(project, BRANCH);
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setCreationDate(new Date(ANALYSE_DATE))).close();
when(notificationService.hasProjectSubscribersForTypes(branch.uuid(), NOTIF_TYPES)).thenReturn(true);
analysisMetadataHolder.setProject(Project.from(project));
analysisMetadataHolder.setBranch(newBranch(BranchType.BRANCH));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService).deliver(newIssuesNotificationMock);
verify(newIssuesNotificationMock).setProject(branch.getKey(), branch.longName(), BRANCH_NAME, null);
verify(newIssuesNotificationMock).setAnalysisDate(new Date(ANALYSE_DATE));
verify(newIssuesNotificationMock).setStatistics(eq(branch.longName()), any(NewIssuesStatistics.Stats.class));
verify(newIssuesNotificationMock).setDebt(ISSUE_DURATION);
verifyStatistics(context, 1, 0, 0);
}
@Test
public void do_not_send_global_new_issues_notification_on_pull_request() {
ComponentDto project = newPrivateProjectDto();
ComponentDto branch = setUpBranch(project, PULL_REQUEST);
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setCreationDate(new Date(ANALYSE_DATE))).close();
when(notificationService.hasProjectSubscribersForTypes(project.uuid(), NOTIF_TYPES)).thenReturn(true);
analysisMetadataHolder.setProject(Project.from(project));
analysisMetadataHolder.setBranch(newPullRequest());
analysisMetadataHolder.setPullRequestKey(PULL_REQUEST_ID);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verifyNoInteractions(notificationService, newIssuesNotificationMock);
}
private DefaultIssue createIssue() {
return new DefaultIssue().setKey("k").setProjectKey("p").setStatus("OPEN").setProjectUuid("uuid").setComponentKey("c").setRuleKey(RuleKey.of("r", "r"));
}
@Test
public void do_not_send_global_new_issues_notification_on_branch_if_issue_has_been_backdated() {
ComponentDto project = newPrivateProjectDto();
ComponentDto branch = setUpBranch(project, BRANCH);
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))).close();
when(notificationService.hasProjectSubscribersForTypes(branch.uuid(), NOTIF_TYPES)).thenReturn(true);
analysisMetadataHolder.setProject(Project.from(project));
analysisMetadataHolder.setBranch(newBranch(BranchType.BRANCH));
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService, never()).deliver(any(Notification.class));
verify(notificationService, never()).deliverEmails(anyCollection());
verifyStatistics(context, 0, 0, 0);
}
@Test
public void send_new_issues_notification_to_user() {
UserDto user = db.users().insertUser();
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setAssigneeUuid(user.getUuid()).setCreationDate(new Date(ANALYSE_DATE)))
.close();
when(notificationService.hasProjectSubscribersForTypes(eq(PROJECT.getUuid()), any())).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService).deliverEmails(ImmutableSet.of(newIssuesNotificationMock));
verify(notificationService).deliverEmails(ImmutableSet.of(myNewIssuesNotificationMock));
// old API compatibility call
verify(notificationService).deliver(newIssuesNotificationMock);
verify(notificationService).deliver(myNewIssuesNotificationMock);
verify(myNewIssuesNotificationMock).setAssignee(any(UserDto.class));
verify(myNewIssuesNotificationMock).setProject(PROJECT.getKey(), PROJECT.getName(), null, null);
verify(myNewIssuesNotificationMock).setAnalysisDate(new Date(ANALYSE_DATE));
verify(myNewIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), any(NewIssuesStatistics.Stats.class));
verify(myNewIssuesNotificationMock).setDebt(ISSUE_DURATION);
verifyStatistics(context, 1, 1, 0);
}
@Test
public void send_new_issues_notification_to_user_only_for_those_assigned_to_her() throws IOException {
UserDto perceval = db.users().insertUser(u -> u.setLogin("perceval"));
Integer[] assigned = IntStream.range(0, 5).mapToObj(i -> 10_000 * i).toArray(Integer[]::new);
Duration expectedEffort = Duration.create(stream(assigned).mapToInt(i -> i).sum());
UserDto arthur = db.users().insertUser(u -> u.setLogin("arthur"));
Integer[] assignedToOther = IntStream.range(0, 3).mapToObj(i -> 10).toArray(Integer[]::new);
List<DefaultIssue> issues = concat(stream(assigned)
.map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort))
.setAssigneeUuid(perceval.getUuid())
.setNew(true)
.setCreationDate(new Date(ANALYSE_DATE))),
stream(assignedToOther)
.map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort))
.setAssigneeUuid(arthur.getUuid())
.setNew(true)
.setCreationDate(new Date(ANALYSE_DATE))))
.collect(toList());
shuffle(issues);
ProtoIssueCache protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
DiskCache.CacheAppender newIssueCache = protoIssueCache.newAppender();
issues.forEach(newIssueCache::append);
newIssueCache.close();
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
NotificationFactory notificationFactory = mock(NotificationFactory.class);
NewIssuesNotification newIssuesNotificationMock = createNewIssuesNotificationMock();
when(notificationFactory.newNewIssuesNotification(assigneeCacheCaptor.capture()))
.thenReturn(newIssuesNotificationMock);
MyNewIssuesNotification myNewIssuesNotificationMock1 = createMyNewIssuesNotificationMock();
MyNewIssuesNotification myNewIssuesNotificationMock2 = createMyNewIssuesNotificationMock();
doReturn(myNewIssuesNotificationMock1).doReturn(myNewIssuesNotificationMock2).when(notificationFactory).newMyNewIssuesNotification(any(assigneeCacheType));
TestComputationStepContext context = new TestComputationStepContext();
new SendIssueNotificationsStep(protoIssueCache, treeRootHolder, notificationService, analysisMetadataHolder, notificationFactory, db.getDbClient())
.execute(context);
verify(notificationService).deliverEmails(ImmutableSet.of(myNewIssuesNotificationMock1, myNewIssuesNotificationMock2));
// old API compatibility
verify(notificationService).deliver(myNewIssuesNotificationMock1);
verify(notificationService).deliver(myNewIssuesNotificationMock2);
verify(notificationFactory).newNewIssuesNotification(assigneeCacheCaptor.capture());
verify(notificationFactory, times(2)).newMyNewIssuesNotification(assigneeCacheCaptor.capture());
verifyNoMoreInteractions(notificationFactory);
verifyAssigneeCache(assigneeCacheCaptor, perceval, arthur);
Map<String, MyNewIssuesNotification> myNewIssuesNotificationMocksByUsersName = new HashMap<>();
ArgumentCaptor<UserDto> userCaptor1 = forClass(UserDto.class);
verify(myNewIssuesNotificationMock1).setAssignee(userCaptor1.capture());
myNewIssuesNotificationMocksByUsersName.put(userCaptor1.getValue().getLogin(), myNewIssuesNotificationMock1);
ArgumentCaptor<UserDto> userCaptor2 = forClass(UserDto.class);
verify(myNewIssuesNotificationMock2).setAssignee(userCaptor2.capture());
myNewIssuesNotificationMocksByUsersName.put(userCaptor2.getValue().getLogin(), myNewIssuesNotificationMock2);
MyNewIssuesNotification myNewIssuesNotificationMock = myNewIssuesNotificationMocksByUsersName.get("perceval");
ArgumentCaptor<NewIssuesStatistics.Stats> statsCaptor = forClass(NewIssuesStatistics.Stats.class);
verify(myNewIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), statsCaptor.capture());
verify(myNewIssuesNotificationMock).setDebt(expectedEffort);
NewIssuesStatistics.Stats stats = statsCaptor.getValue();
assertThat(stats.hasIssues()).isTrue();
// just checking all issues have been added to the stats
DistributedMetricStatsInt severity = stats.getDistributedMetricStats(NewIssuesStatistics.Metric.RULE_TYPE);
assertThat(severity.getOnCurrentAnalysis()).isEqualTo(assigned.length);
assertThat(severity.getTotal()).isEqualTo(assigned.length);
verifyStatistics(context, 1, 2, 0);
}
@Test
public void send_new_issues_notification_to_user_only_for_non_backdated_issues() {
UserDto user = db.users().insertUser();
Random random = new Random();
Integer[] efforts = IntStream.range(0, 1 + random.nextInt(10)).mapToObj(i -> 10_000 * i).toArray(Integer[]::new);
Integer[] backDatedEfforts = IntStream.range(0, 1 + random.nextInt(10)).mapToObj(i -> 10 + random.nextInt(100)).toArray(Integer[]::new);
Duration expectedEffort = Duration.create(stream(efforts).mapToInt(i -> i).sum());
List<DefaultIssue> issues = concat(stream(efforts)
.map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort))
.setAssigneeUuid(user.getUuid())
.setCreationDate(new Date(ANALYSE_DATE))),
stream(backDatedEfforts)
.map(effort -> createIssue().setType(randomRuleType).setEffort(Duration.create(effort))
.setAssigneeUuid(user.getUuid())
.setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS))))
.collect(toList());
shuffle(issues);
DiskCache.CacheAppender issueCache = this.protoIssueCache.newAppender();
issues.forEach(issueCache::append);
issueCache.close();
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService).deliver(newIssuesNotificationMock);
verify(notificationService).deliverEmails(ImmutableSet.of(myNewIssuesNotificationMock));
// old API compatibility
verify(notificationService).deliver(myNewIssuesNotificationMock);
verify(notificationFactory).newNewIssuesNotification(assigneeCacheCaptor.capture());
verify(notificationFactory).newMyNewIssuesNotification(assigneeCacheCaptor.capture());
verifyNoMoreInteractions(notificationFactory);
verifyAssigneeCache(assigneeCacheCaptor, user);
verify(myNewIssuesNotificationMock).setAssignee(any(UserDto.class));
ArgumentCaptor<NewIssuesStatistics.Stats> statsCaptor = forClass(NewIssuesStatistics.Stats.class);
verify(myNewIssuesNotificationMock).setStatistics(eq(PROJECT.getName()), statsCaptor.capture());
verify(myNewIssuesNotificationMock).setDebt(expectedEffort);
NewIssuesStatistics.Stats stats = statsCaptor.getValue();
assertThat(stats.hasIssues()).isTrue();
// just checking all issues have been added to the stats
DistributedMetricStatsInt severity = stats.getDistributedMetricStats(NewIssuesStatistics.Metric.RULE_TYPE);
assertThat(severity.getOnCurrentAnalysis()).isEqualTo(efforts.length);
assertThat(severity.getTotal()).isEqualTo(backDatedEfforts.length + efforts.length);
verifyStatistics(context, 1, 1, 0);
}
private static void verifyAssigneeCache(ArgumentCaptor<Map<String, UserDto>> assigneeCacheCaptor, UserDto... users) {
Map<String, UserDto> cache = assigneeCacheCaptor.getAllValues().iterator().next();
assertThat(assigneeCacheCaptor.getAllValues())
.filteredOn(t -> t != cache)
.isEmpty();
Tuple[] expected = stream(users).map(user -> tuple(user.getUuid(), user.getUuid(), user.getUuid(), user.getLogin())).toArray(Tuple[]::new);
assertThat(cache.entrySet())
.extracting(Map.Entry::getKey, t -> t.getValue().getUuid(), t -> t.getValue().getUuid(), t -> t.getValue().getLogin())
.containsOnly(expected);
}
@Test
public void do_not_send_new_issues_notification_to_user_if_issue_is_backdated() {
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
UserDto user = db.users().insertUser();
protoIssueCache.newAppender().append(
createIssue().setType(randomRuleType).setEffort(ISSUE_DURATION).setAssigneeUuid(user.getUuid())
.setCreationDate(new Date(ANALYSE_DATE - FIVE_MINUTES_IN_MS)))
.close();
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService, never()).deliver(any(Notification.class));
verify(notificationService, never()).deliverEmails(anyCollection());
verifyStatistics(context, 0, 0, 0);
}
@Test
public void send_issues_change_notification() {
sendIssueChangeNotification(ANALYSE_DATE);
}
@Test
public void do_not_send_new_issues_notifications_for_hotspot() {
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto().setKey(PROJECT.getKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setKey(FILE.getKey()).setLongName(FILE.getName());
RuleDto ruleDefinitionDto = newRule();
prepareIssue(ANALYSE_DATE, user, project, file, ruleDefinitionDto, RuleType.SECURITY_HOTSPOT);
analysisMetadataHolder.setProject(new Project(PROJECT.getUuid(), PROJECT.getKey(), PROJECT.getName(), null, emptyList()));
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
TestComputationStepContext context = new TestComputationStepContext();
underTest.execute(context);
verify(notificationService, never()).deliver(any(Notification.class));
verify(notificationService, never()).deliverEmails(anyCollection());
verifyStatistics(context, 0, 0, 0);
}
@Test
public void send_issues_change_notification_even_if_issue_is_backdated() {
sendIssueChangeNotification(ANALYSE_DATE - FIVE_MINUTES_IN_MS);
}
private void sendIssueChangeNotification(long issueCreatedAt) {
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto().setKey(PROJECT.getKey()).setLongName(PROJECT.getName());
analysisMetadataHolder.setProject(Project.from(project));
ComponentDto file = newFileDto(project).setKey(FILE.getKey()).setLongName(FILE.getName());
treeRootHolder.setRoot(builder(Type.PROJECT, 2).setKey(project.getKey()).setName(project.longName()).setUuid(project.uuid())
.addChildren(
builder(Type.FILE, 11).setKey(file.getKey()).setName(file.longName()).build())
.build());
RuleDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
DefaultIssue issue = prepareIssue(issueCreatedAt, user, project, file, ruleDefinitionDto, randomTypeExceptHotspot);
IssuesChangesNotification issuesChangesNotification = mock(IssuesChangesNotification.class);
when(notificationService.hasProjectSubscribersForTypes(project.uuid(), NOTIF_TYPES)).thenReturn(true);
when(notificationFactory.newIssuesChangesNotification(anySet(), anyMap())).thenReturn(issuesChangesNotification);
underTest.execute(new TestComputationStepContext());
verify(notificationFactory).newIssuesChangesNotification(issuesSetCaptor.capture(), assigneeByUuidCaptor.capture());
assertThat(issuesSetCaptor.getValue()).hasSize(1);
assertThat(issuesSetCaptor.getValue().iterator().next()).isEqualTo(issue);
assertThat(assigneeByUuidCaptor.getValue()).hasSize(1);
assertThat(assigneeByUuidCaptor.getValue().get(user.getUuid())).isNotNull();
verify(notificationService).hasProjectSubscribersForTypes(project.uuid(), NOTIF_TYPES);
verify(notificationService).deliverEmails(singleton(issuesChangesNotification));
verify(notificationService).deliver(issuesChangesNotification);
verifyNoMoreInteractions(notificationService);
}
private DefaultIssue prepareIssue(long issueCreatedAt, UserDto user, ComponentDto project, ComponentDto file, RuleDto ruleDefinitionDto, RuleType type) {
DefaultIssue issue = newIssue(ruleDefinitionDto, project, file).setType(type).toDefaultIssue()
.setNew(false).setChanged(true).setSendNotifications(true).setCreationDate(new Date(issueCreatedAt)).setAssigneeUuid(user.getUuid());
protoIssueCache.newAppender().append(issue).close();
when(notificationService.hasProjectSubscribersForTypes(project.branchUuid(), NOTIF_TYPES)).thenReturn(true);
return issue;
}
@Test
public void send_issues_change_notification_on_branch() {
sendIssueChangeNotificationOnBranch(ANALYSE_DATE);
}
@Test
public void send_issues_change_notification_on_branch_even_if_issue_is_backdated() {
sendIssueChangeNotificationOnBranch(ANALYSE_DATE - FIVE_MINUTES_IN_MS);
}
private void sendIssueChangeNotificationOnBranch(long issueCreatedAt) {
ComponentDto project = newPrivateProjectDto();
ComponentDto branch = newBranchComponent(project, newBranchDto(project).setKey(BRANCH_NAME));
ComponentDto file = newFileDto(branch, project.uuid());
treeRootHolder.setRoot(builder(Type.PROJECT, 2).setKey(branch.getKey()).setName(branch.longName()).setUuid(branch.uuid()).addChildren(
builder(Type.FILE, 11).setKey(file.getKey()).setName(file.longName()).build()).build());
analysisMetadataHolder.setProject(Project.from(project));
RuleDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
DefaultIssue issue = newIssue(ruleDefinitionDto, branch, file).setType(randomTypeExceptHotspot).toDefaultIssue()
.setNew(false)
.setChanged(true)
.setSendNotifications(true)
.setCreationDate(new Date(issueCreatedAt));
protoIssueCache.newAppender().append(issue).close();
when(notificationService.hasProjectSubscribersForTypes(project.uuid(), NOTIF_TYPES)).thenReturn(true);
IssuesChangesNotification issuesChangesNotification = mock(IssuesChangesNotification.class);
when(notificationFactory.newIssuesChangesNotification(anySet(), anyMap())).thenReturn(issuesChangesNotification);
analysisMetadataHolder.setBranch(newBranch(BranchType.BRANCH));
underTest.execute(new TestComputationStepContext());
verify(notificationFactory).newIssuesChangesNotification(issuesSetCaptor.capture(), assigneeByUuidCaptor.capture());
assertThat(issuesSetCaptor.getValue()).hasSize(1);
assertThat(issuesSetCaptor.getValue().iterator().next()).isEqualTo(issue);
assertThat(assigneeByUuidCaptor.getValue()).isEmpty();
verify(notificationService).hasProjectSubscribersForTypes(project.uuid(), NOTIF_TYPES);
verify(notificationService).deliverEmails(singleton(issuesChangesNotification));
verify(notificationService).deliver(issuesChangesNotification);
verifyNoMoreInteractions(notificationService);
}
@Test
public void sends_one_issue_change_notification_every_1000_issues() {
UserDto user = db.users().insertUser();
ComponentDto project = newPrivateProjectDto().setKey(PROJECT.getKey()).setLongName(PROJECT.getName());
ComponentDto file = newFileDto(project).setKey(FILE.getKey()).setLongName(FILE.getName());
RuleDto ruleDefinitionDto = newRule();
RuleType randomTypeExceptHotspot = RuleType.values()[nextInt(RuleType.values().length - 1)];
List<DefaultIssue> issues = IntStream.range(0, 2001 + new Random().nextInt(10))
.mapToObj(i -> newIssue(ruleDefinitionDto, project, file).setKee("uuid_" + i).setType(randomTypeExceptHotspot).toDefaultIssue()
.setNew(false).setChanged(true).setSendNotifications(true).setAssigneeUuid(user.getUuid()))
.toList();
DiskCache.CacheAppender cacheAppender = protoIssueCache.newAppender();
issues.forEach(cacheAppender::append);
cacheAppender.close();
analysisMetadataHolder.setProject(Project.from(project));
NewIssuesFactoryCaptor newIssuesFactoryCaptor = new NewIssuesFactoryCaptor(() -> mock(IssuesChangesNotification.class));
when(notificationFactory.newIssuesChangesNotification(anySet(), anyMap())).thenAnswer(newIssuesFactoryCaptor);
when(notificationService.hasProjectSubscribersForTypes(PROJECT.getUuid(), NOTIF_TYPES)).thenReturn(true);
when(notificationService.hasProjectSubscribersForTypes(project.uuid(), NOTIF_TYPES)).thenReturn(true);
underTest.execute(new TestComputationStepContext());
verify(notificationFactory, times(3)).newIssuesChangesNotification(anySet(), anyMap());
assertThat(newIssuesFactoryCaptor.issuesSetCaptor).hasSize(3);
assertThat(newIssuesFactoryCaptor.issuesSetCaptor.get(0)).hasSize(1000);
assertThat(newIssuesFactoryCaptor.issuesSetCaptor.get(1)).hasSize(1000);
assertThat(newIssuesFactoryCaptor.issuesSetCaptor.get(2)).hasSize(issues.size() - 2000);
assertThat(newIssuesFactoryCaptor.assigneeCacheCaptor)
.hasSize(3)
.containsOnly(newIssuesFactoryCaptor.assigneeCacheCaptor.iterator().next());
ArgumentCaptor<Collection> collectionCaptor = forClass(Collection.class);
verify(notificationService, times(3)).deliverEmails(collectionCaptor.capture());
assertThat(collectionCaptor.getAllValues()).hasSize(3);
assertThat(collectionCaptor.getAllValues().get(0)).hasSize(1);
assertThat(collectionCaptor.getAllValues().get(1)).hasSize(1);
assertThat(collectionCaptor.getAllValues().get(2)).hasSize(1);
verify(notificationService, times(3)).deliver(any(IssuesChangesNotification.class));
}
/**
* Since the very same Set object is passed to {@link NotificationFactory#newIssuesChangesNotification(Set, Map)} and
* reset between each call. We must make a copy of each argument to capture what's been passed to the factory.
* This is of course not supported by Mockito's {@link ArgumentCaptor} and we implement this ourselves with a
* {@link Answer}.
*/
private static class NewIssuesFactoryCaptor implements Answer<Object> {
private final Supplier<IssuesChangesNotification> delegate;
private final List<Set<DefaultIssue>> issuesSetCaptor = new ArrayList<>();
private final List<Map<String, UserDto>> assigneeCacheCaptor = new ArrayList<>();
private NewIssuesFactoryCaptor(Supplier<IssuesChangesNotification> delegate) {
this.delegate = delegate;
}
@Override
public Object answer(InvocationOnMock t) {
Set<DefaultIssue> issuesSet = t.getArgument(0);
Map<String, UserDto> assigneeCatch = t.getArgument(1);
issuesSetCaptor.add(ImmutableSet.copyOf(issuesSet));
assigneeCacheCaptor.add(ImmutableMap.copyOf(assigneeCatch));
return delegate.get();
}
}
private NewIssuesNotification createNewIssuesNotificationMock() {
NewIssuesNotification notification = mock(NewIssuesNotification.class);
when(notification.setProject(any(), any(), any(), any())).thenReturn(notification);
when(notification.setProjectVersion(any())).thenReturn(notification);
when(notification.setAnalysisDate(any())).thenReturn(notification);
when(notification.setStatistics(any(), any())).thenReturn(notification);
when(notification.setDebt(any())).thenReturn(notification);
return notification;
}
private MyNewIssuesNotification createMyNewIssuesNotificationMock() {
MyNewIssuesNotification notification = mock(MyNewIssuesNotification.class);
when(notification.setAssignee(any(UserDto.class))).thenReturn(notification);
when(notification.setProject(any(), any(), any(), any())).thenReturn(notification);
when(notification.setProjectVersion(any())).thenReturn(notification);
when(notification.setAnalysisDate(any())).thenReturn(notification);
when(notification.setStatistics(any(), any())).thenReturn(notification);
when(notification.setDebt(any())).thenReturn(notification);
return notification;
}
private static Branch newBranch(BranchType type) {
Branch branch = mock(Branch.class);
when(branch.isMain()).thenReturn(false);
when(branch.getName()).thenReturn(BRANCH_NAME);
when(branch.getType()).thenReturn(type);
return branch;
}
private static Branch newPullRequest() {
Branch branch = mock(Branch.class);
when(branch.isMain()).thenReturn(false);
when(branch.getType()).thenReturn(PULL_REQUEST);
when(branch.getName()).thenReturn(BRANCH_NAME);
when(branch.getPullRequestKey()).thenReturn(PULL_REQUEST_ID);
return branch;
}
private ComponentDto setUpBranch(ComponentDto project, BranchType branchType) {
ComponentDto branch = null;
if(branchType == PULL_REQUEST) {
branch = newBranchComponent(project, newBranchDto(project, PULL_REQUEST, project.uuid()));
} else {
branch = newBranchComponent(project, newMainBranchDto(project, project.uuid()).setKey(BRANCH_NAME));
}
ComponentDto file = newFileDto(branch, project.uuid());
treeRootHolder.setRoot(builder(Type.PROJECT, 2).setKey(branch.getKey()).setName(branch.longName()).setUuid(branch.uuid()).addChildren(
builder(Type.FILE, 11).setKey(file.getKey()).setName(file.longName()).build()).build());
return branch;
}
private static void verifyStatistics(TestComputationStepContext context, int expectedNewIssuesNotifications, int expectedMyNewIssuesNotifications,
int expectedIssueChangesNotifications) {
context.getStatistics().assertValue("newIssuesNotifs", expectedNewIssuesNotifications);
context.getStatistics().assertValue("myNewIssuesNotifs", expectedMyNewIssuesNotifications);
context.getStatistics().assertValue("changesNotifs", expectedIssueChangesNotifications);
}
@Override
protected ComputationStep step() {
return underTest;
}
}
| 39,614 | 53.416209 | 159 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/UpdateNeedIssueSyncStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ComponentDto;
import static org.assertj.core.api.Assertions.assertThat;
public class UpdateNeedIssueSyncStepIT {
private static final Component PROJECT = ReportComponent.DUMB_PROJECT;
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT);
private DbClient dbClient = db.getDbClient();
UpdateNeedIssueSyncStep underTest = new UpdateNeedIssueSyncStep(dbClient, treeRootHolder);
@Test
public void analysis_step_updates_need_issue_sync_flag() {
ComponentDto project = db.components()
.insertPrivateProject(c -> c.setUuid(PROJECT.getUuid()).setKey(PROJECT.getKey())).getMainBranchComponent();
dbClient.branchDao().updateNeedIssueSync(db.getSession(), PROJECT.getUuid(), true);
db.getSession().commit();
assertThat(dbClient.branchDao().selectByUuid(db.getSession(), project.uuid()))
.isNotEmpty()
.map(BranchDto::isNeedIssueSync)
.hasValue(true);
underTest.execute(new TestComputationStepContext());
assertThat(dbClient.branchDao().selectByUuid(db.getSession(), project.uuid()))
.isNotEmpty()
.map(BranchDto::isNeedIssueSync)
.hasValue(false);
}
}
| 2,602 | 36.185714 | 113 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/UpdateQualityProfilesLastUsedDateStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Arrays;
import java.util.Date;
import javax.annotation.CheckForNull;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepositoryRule;
import org.sonar.ce.task.projectanalysis.metric.MetricRepositoryRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.RowNotFoundException;
import org.sonar.db.qualityprofile.QProfileDto;
import org.sonar.db.qualityprofile.QualityProfileDbTester;
import org.sonar.server.qualityprofile.QPMeasureData;
import org.sonar.server.qualityprofile.QualityProfile;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES;
import static org.sonar.api.measures.CoreMetrics.QUALITY_PROFILES_KEY;
import static org.sonar.db.qualityprofile.QualityProfileTesting.newQualityProfileDto;
public class UpdateQualityProfilesLastUsedDateStepIT {
private static final long ANALYSIS_DATE = 1_123_456_789L;
private static final Component PROJECT = ReportComponent.DUMB_PROJECT;
private QProfileDto sonarWayJava = newProfile("sonar-way-java");
private QProfileDto sonarWayPhp = newProfile("sonar-way-php");
private QProfileDto myQualityProfile = newProfile("my-qp");
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule().setAnalysisDate(ANALYSIS_DATE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule().setRoot(PROJECT);
@Rule
public MetricRepositoryRule metricRepository = new MetricRepositoryRule().add(QUALITY_PROFILES);
@Rule
public MeasureRepositoryRule measureRepository = MeasureRepositoryRule.create(treeRootHolder, metricRepository);
private DbClient dbClient = db.getDbClient();
private DbSession dbSession = db.getSession();
private QualityProfileDbTester qualityProfileDb = new QualityProfileDbTester(db);
UpdateQualityProfilesLastUsedDateStep underTest = new UpdateQualityProfilesLastUsedDateStep(dbClient, analysisMetadataHolder, treeRootHolder, metricRepository,
measureRepository);
@Test
public void doest_not_update_profiles_when_no_measure() {
qualityProfileDb.insert(sonarWayJava, sonarWayPhp, myQualityProfile);
underTest.execute(new TestComputationStepContext());
assertQualityProfileIsTheSame(sonarWayJava);
assertQualityProfileIsTheSame(sonarWayPhp);
assertQualityProfileIsTheSame(myQualityProfile);
}
@Test
public void update_profiles_defined_in_quality_profiles_measure() {
qualityProfileDb.insert(sonarWayJava, sonarWayPhp, myQualityProfile);
measureRepository.addRawMeasure(1, QUALITY_PROFILES_KEY, Measure.newMeasureBuilder().create(
toJson(sonarWayJava.getKee(), myQualityProfile.getKee())));
underTest.execute(new TestComputationStepContext());
assertQualityProfileIsTheSame(sonarWayPhp);
assertQualityProfileIsUpdated(sonarWayJava);
assertQualityProfileIsUpdated(myQualityProfile);
}
@Test
public void ancestor_profiles_are_updated() {
// Parent profiles should be updated
QProfileDto rootProfile = newProfile("root");
QProfileDto parentProfile = newProfile("parent").setParentKee(rootProfile.getKee());
// Current profile => should be updated
QProfileDto currentProfile = newProfile("current").setParentKee(parentProfile.getKee());
// Child of current profile => should not be updated
QProfileDto childProfile = newProfile("child").setParentKee(currentProfile.getKee());
qualityProfileDb.insert(rootProfile, parentProfile, currentProfile, childProfile);
measureRepository.addRawMeasure(1, QUALITY_PROFILES_KEY, Measure.newMeasureBuilder().create(toJson(currentProfile.getKee())));
underTest.execute(new TestComputationStepContext());
assertQualityProfileIsUpdated(rootProfile);
assertQualityProfileIsUpdated(parentProfile);
assertQualityProfileIsUpdated(currentProfile);
assertQualityProfileIsTheSame(childProfile);
}
@Test
public void fail_when_profile_is_linked_to_unknown_parent() {
QProfileDto currentProfile = newProfile("current").setParentKee("unknown");
qualityProfileDb.insert(currentProfile);
measureRepository.addRawMeasure(1, QUALITY_PROFILES_KEY, Measure.newMeasureBuilder().create(toJson(currentProfile.getKee())));
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(RowNotFoundException.class);
}
@Test
public void test_description() {
assertThat(underTest.getDescription()).isEqualTo("Update last usage date of quality profiles");
}
private static QProfileDto newProfile(String key) {
return newQualityProfileDto().setKee(key)
// profile has been used before the analysis
.setLastUsed(ANALYSIS_DATE - 10_000);
}
private void assertQualityProfileIsUpdated(QProfileDto qp) {
assertThat(selectLastUser(qp.getKee())).withFailMessage("Quality profile '%s' hasn't been updated. Value: %d", qp.getKee(), qp.getLastUsed()).isEqualTo(ANALYSIS_DATE);
}
private void assertQualityProfileIsTheSame(QProfileDto qp) {
assertThat(selectLastUser(qp.getKee())).isEqualTo(qp.getLastUsed());
}
@CheckForNull
private Long selectLastUser(String qualityProfileKey) {
return dbClient.qualityProfileDao().selectByUuid(dbSession, qualityProfileKey).getLastUsed();
}
private static String toJson(String... keys) {
return QPMeasureData.toJson(new QPMeasureData(
Arrays.stream(keys)
.map(key -> new QualityProfile(key, key, key, new Date()))
.toList()));
}
}
| 7,059 | 40.775148 | 171 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ValidateProjectStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.Date;
import javax.annotation.Nullable;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl;
import org.sonar.ce.task.projectanalysis.component.ReportComponent;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotTesting;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
public class ValidateProjectStepIT {
static long PAST_ANALYSIS_TIME = 1_420_088_400_000L; // 2015-01-01
static long DEFAULT_ANALYSIS_TIME = 1_433_131_200_000L; // 2015-06-01
static final String PROJECT_KEY = "PROJECT_KEY";
static final Branch DEFAULT_BRANCH = new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME);
@Rule
public DbTester db = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule()
.setAnalysisDate(new Date(DEFAULT_ANALYSIS_TIME))
.setBranch(DEFAULT_BRANCH);
private final DbClient dbClient = db.getDbClient();
private final ValidateProjectStep underTest = new ValidateProjectStep(dbClient, treeRootHolder, analysisMetadataHolder);
@Test
public void not_fail_if_analysis_date_is_after_last_analysis() {
ComponentDto project = db.components().insertPrivateProject("ABCD", c -> c.setKey(PROJECT_KEY)).getMainBranchComponent();
dbClient.snapshotDao().insert(db.getSession(), SnapshotTesting.newAnalysis(project).setCreatedAt(PAST_ANALYSIS_TIME));
db.getSession().commit();
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).build());
underTest.execute(new TestComputationStepContext());
}
@Test
public void fail_if_analysis_date_is_before_last_analysis() {
analysisMetadataHolder.setAnalysisDate(DateUtils.parseDate("2015-01-01"));
ComponentDto project = db.components().insertPrivateProject("ABCD", c -> c.setKey(PROJECT_KEY)).getMainBranchComponent();
dbClient.snapshotDao().insert(db.getSession(), SnapshotTesting.newAnalysis(project).setCreatedAt(1433131200000L)); // 2015-06-01
db.getSession().commit();
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1).setUuid("ABCD").setKey(PROJECT_KEY).build());
var stepContext = new TestComputationStepContext();
assertThatThrownBy(() -> underTest.execute(stepContext))
.isInstanceOf(MessageException.class)
.hasMessageContainingAll("Validation of project failed:",
"Date of analysis cannot be older than the date of the last known analysis on this project. Value: ",
"Latest analysis: ");
}
@Test
public void fail_when_project_key_is_invalid() {
ComponentDto project = db.components().insertPrivateProject(p -> p.setKey("inv$lid!")).getMainBranchComponent();
db.components().insertSnapshot(project, a -> a.setCreatedAt(PAST_ANALYSIS_TIME));
treeRootHolder.setRoot(ReportComponent.builder(Component.Type.PROJECT, 1)
.setUuid(project.uuid())
.setKey(project.getKey())
.build());
var stepContext = new TestComputationStepContext();
assertThatThrownBy(() -> underTest.execute(stepContext))
.isInstanceOf(MessageException.class)
.hasMessageContainingAll("Validation of project failed:",
"The project key ‘inv$lid!’ contains invalid characters.",
"Allowed characters are alphanumeric, '-', '_', '.' and ':', with at least one non-digit.",
"You should update the project key with the expected format.");
}
private void setBranch(BranchType type, @Nullable String mergeBranchUuid) {
Branch branch = mock(Branch.class);
when(branch.getType()).thenReturn(type);
when(branch.getReferenceBranchUuid()).thenReturn(mergeBranchUuid);
analysisMetadataHolder.setBranch(branch);
}
}
| 5,480 | 44.297521 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ViewsPersistAnalysisStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.util.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.DateUtils;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.component.ViewsComponent;
import org.sonar.ce.task.projectanalysis.period.Period;
import org.sonar.ce.task.projectanalysis.period.PeriodHolderRule;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.component.SnapshotQuery;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.Component.Type.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.db.component.ComponentTesting.newPrivateProjectDto;
public class ViewsPersistAnalysisStepIT extends BaseStepTest {
private static final String ANALYSIS_UUID = "U1";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
@Rule
public PeriodHolderRule periodsHolder = new PeriodHolderRule();
private System2 system2 = mock(System2.class);
private DbClient dbClient = dbTester.getDbClient();
private long analysisDate;
private long now;
private PersistAnalysisStep underTest;
@Before
public void setup() {
analysisDate = DateUtils.parseDateQuietly("2015-06-01").getTime();
analysisMetadataHolder.setUuid(ANALYSIS_UUID);
analysisMetadataHolder.setAnalysisDate(analysisDate);
now = DateUtils.parseDateQuietly("2015-06-02").getTime();
when(system2.now()).thenReturn(now);
underTest = new PersistAnalysisStep(system2, dbClient, treeRootHolder, analysisMetadataHolder, periodsHolder);
// initialize PeriodHolder to empty by default
periodsHolder.setPeriod(null);
}
@Override
protected ComputationStep step() {
return underTest;
}
@Test
public void persist_analysis() {
ComponentDto viewDto = save(ComponentTesting.newPortfolio("UUID_VIEW").setKey("KEY_VIEW"));
save(ComponentTesting.newSubPortfolio(viewDto, "UUID_SUBVIEW", "KEY_SUBVIEW"));
save(newPrivateProjectDto("proj"));
dbTester.getSession().commit();
Component projectView = ViewsComponent.builder(PROJECT_VIEW, "KEY_PROJECT_COPY").setUuid("UUID_PROJECT_COPY").build();
Component subView = ViewsComponent.builder(SUBVIEW, "KEY_SUBVIEW").setUuid("UUID_SUBVIEW").addChildren(projectView).build();
Component view = ViewsComponent.builder(VIEW, "KEY_VIEW").setUuid("UUID_VIEW").addChildren(subView).build();
treeRootHolder.setRoot(view);
underTest.execute(new TestComputationStepContext());
assertThat(dbTester.countRowsOfTable("snapshots")).isOne();
SnapshotDto viewSnapshot = getUnprocessedSnapshot(viewDto.uuid());
assertThat(viewSnapshot.getUuid()).isEqualTo(ANALYSIS_UUID);
assertThat(viewSnapshot.getRootComponentUuid()).isEqualTo(view.getUuid());
assertThat(viewSnapshot.getProjectVersion()).isNull();
assertThat(viewSnapshot.getLast()).isFalse();
assertThat(viewSnapshot.getStatus()).isEqualTo("U");
assertThat(viewSnapshot.getCreatedAt()).isEqualTo(analysisDate);
assertThat(viewSnapshot.getBuildDate()).isEqualTo(now);
}
@Test
public void persist_snapshots_with_new_code_period() {
ComponentDto viewDto = save(ComponentTesting.newPortfolio("UUID_VIEW").setKey("KEY_VIEW"));
ComponentDto subViewDto = save(ComponentTesting.newSubPortfolio(viewDto, "UUID_SUBVIEW", "KEY_SUBVIEW"));
dbTester.getSession().commit();
Component subView = ViewsComponent.builder(SUBVIEW, "KEY_SUBVIEW").setUuid("UUID_SUBVIEW").build();
Component view = ViewsComponent.builder(VIEW, "KEY_VIEW").setUuid("UUID_VIEW").addChildren(subView).build();
treeRootHolder.setRoot(view);
periodsHolder.setPeriod(new Period("NUMBER_OF_DAYS", "30", analysisDate));
underTest.execute(new TestComputationStepContext());
SnapshotDto viewSnapshot = getUnprocessedSnapshot(viewDto.uuid());
assertThat(viewSnapshot.getPeriodMode()).isEqualTo("NUMBER_OF_DAYS");
assertThat(viewSnapshot.getPeriodDate()).isEqualTo(analysisDate);
assertThat(viewSnapshot.getPeriodModeParameter()).isNotNull();
}
private ComponentDto save(ComponentDto componentDto) {
return dbTester.components().insertComponent(componentDto);
}
private SnapshotDto getUnprocessedSnapshot(String componentUuid) {
List<SnapshotDto> projectSnapshots = dbClient.snapshotDao().selectAnalysesByQuery(dbTester.getSession(),
new SnapshotQuery().setRootComponentUuid(componentUuid).setIsLast(false).setStatus(SnapshotDto.STATUS_UNPROCESSED));
assertThat(projectSnapshots).hasSize(1);
return projectSnapshots.get(0);
}
}
| 6,350 | 41.624161 | 128 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/step/ViewsPersistComponentsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.step;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.stream.Stream;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
import org.sonar.ce.task.projectanalysis.component.BranchPersister;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl;
import org.sonar.ce.task.projectanalysis.component.MutableDisabledComponentsHolder;
import org.sonar.ce.task.projectanalysis.component.ProjectPersister;
import org.sonar.ce.task.projectanalysis.component.ProjectViewAttributes;
import org.sonar.ce.task.projectanalysis.component.SubViewAttributes;
import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
import org.sonar.ce.task.projectanalysis.component.ViewAttributes;
import org.sonar.ce.task.projectanalysis.component.ViewsComponent;
import org.sonar.ce.task.projectanalysis.component.VisitException;
import org.sonar.ce.task.step.ComputationStep;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ComponentTesting;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.ce.task.projectanalysis.component.ViewAttributes.Type.APPLICATION;
import static org.sonar.ce.task.projectanalysis.component.ViewAttributes.Type.PORTFOLIO;
import static org.sonar.ce.task.projectanalysis.component.ViewsComponent.builder;
import static org.sonar.db.component.BranchDto.DEFAULT_MAIN_BRANCH_NAME;
import static org.sonar.db.component.ComponentTesting.newPrivateProjectDto;
import static org.sonar.db.component.ComponentTesting.newProjectCopy;
import static org.sonar.db.component.ComponentTesting.newSubPortfolio;
public class ViewsPersistComponentsStepIT extends BaseStepTest {
private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
private static final String VIEW_KEY = "VIEW_KEY";
private static final String VIEW_NAME = "VIEW_NAME";
private static final String VIEW_DESCRIPTION = "view description";
private static final String VIEW_UUID = "VIEW_UUID";
private static final String SUBVIEW_1_KEY = "SUBVIEW_1_KEY";
private static final String SUBVIEW_1_NAME = "SUBVIEW_1_NAME";
private static final String SUBVIEW_1_DESCRIPTION = "subview 1 description";
private static final String SUBVIEW_1_UUID = "SUBVIEW_1_UUID";
private static final String PROJECT_VIEW_1_KEY = "PV1_KEY";
private static final String PROJECT_VIEW_1_NAME = "PV1_NAME";
private static final String PROJECT_VIEW_1_UUID = "PV1_UUID";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
@Rule
public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
private final System2 system2 = mock(System2.class);
private final DbClient dbClient = dbTester.getDbClient();
private Date now;
private final MutableDisabledComponentsHolder disabledComponentsHolder = mock(MutableDisabledComponentsHolder.class, RETURNS_DEEP_STUBS);
private PersistComponentsStep underTest;
@Before
public void setup() throws Exception {
now = DATE_FORMAT.parse("2015-06-02");
when(system2.now()).thenReturn(now.getTime());
analysisMetadataHolder.setBranch(new DefaultBranchImpl(DEFAULT_MAIN_BRANCH_NAME));
BranchPersister branchPersister = mock(BranchPersister.class);
ProjectPersister projectPersister = mock(ProjectPersister.class);
underTest = new PersistComponentsStep(dbClient, treeRootHolder, system2, disabledComponentsHolder, analysisMetadataHolder, branchPersister, projectPersister);
}
@Override
protected ComputationStep step() {
return underTest;
}
@Test
public void persist_empty_view() {
treeRootHolder.setRoot(createViewBuilder(PORTFOLIO).build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(1);
ComponentDto projectDto = getComponentFromDb(VIEW_KEY);
assertDtoIsView(projectDto);
}
@Test
public void persist_existing_empty_view() {
// most of the time view already exists since its supposed to be created when config is uploaded
persistComponents(newViewDto());
treeRootHolder.setRoot(createViewBuilder(PORTFOLIO).build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(1);
assertDtoNotUpdated(VIEW_KEY);
}
@Test
public void persist_view_with_projectView() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
persistComponents(project);
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(createProjectView1Builder(project, null).build())
.build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(3);
ComponentDto viewDto = getComponentFromDb(VIEW_KEY);
assertDtoIsView(viewDto);
ComponentDto pv1Dto = getComponentFromDb(PROJECT_VIEW_1_KEY);
assertDtoIsProjectView1(pv1Dto, viewDto, viewDto, project);
}
/**
* Assumption under test here is that application should always exists in the projects table.
* We should never have a state where application exists in Components table but not in Projects table
*/
@Test
public void execute_whenApplicationDoesNotExistsAndTryingToInsertItInComponentsTable_throwException() {
ComponentDto project = dbTester.components().insertPrivateProject().getMainBranchComponent();
treeRootHolder.setRoot(
createViewBuilder(APPLICATION)
.addChildren(createProjectView1Builder(project, null).build())
.build());
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(VisitException.class);
}
@Test
public void persist_empty_subview() {
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null).build())
.build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(2);
ComponentDto viewDto = getComponentFromDb(VIEW_KEY);
assertDtoIsView(viewDto);
ComponentDto sv1Dto = getComponentFromDb(SUBVIEW_1_KEY);
assertDtoIsSubView1(viewDto, sv1Dto);
}
@Test
public void persist_empty_subview_having_original_view_uuid() {
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder("ORIGINAL_UUID").build())
.build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(2);
ComponentDto subView = getComponentFromDb(SUBVIEW_1_KEY);
assertThat(subView.getCopyComponentUuid()).isEqualTo("ORIGINAL_UUID");
}
@Test
public void persist_existing_empty_subview_under_existing_view() {
ComponentDto viewDto = newViewDto();
persistComponents(viewDto);
persistComponents(ComponentTesting.newSubPortfolio(viewDto, SUBVIEW_1_UUID, SUBVIEW_1_KEY).setName(SUBVIEW_1_NAME));
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null).build())
.build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(2);
assertDtoNotUpdated(VIEW_KEY);
assertDtoNotUpdated(SUBVIEW_1_KEY);
}
@Test
public void persist_empty_subview_under_existing_view() {
persistComponents(newViewDto());
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null).build())
.build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(2);
assertDtoNotUpdated(VIEW_KEY);
assertDtoIsSubView1(getComponentFromDb(VIEW_KEY), getComponentFromDb(SUBVIEW_1_KEY));
}
@Test
public void persist_project_view_under_subview() {
ComponentDto project = ComponentTesting.newPrivateProjectDto();
persistComponents(project);
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null)
.addChildren(
createProjectView1Builder(project, null).build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
assertRowsCountInTableComponents(4);
ComponentDto viewDto = getComponentFromDb(VIEW_KEY);
assertDtoIsView(viewDto);
ComponentDto subView1Dto = getComponentFromDb(SUBVIEW_1_KEY);
assertDtoIsSubView1(viewDto, subView1Dto);
ComponentDto pv1Dto = getComponentFromDb(PROJECT_VIEW_1_KEY);
assertDtoIsProjectView1(pv1Dto, viewDto, subView1Dto, project);
}
@Test
public void update_view_name_and_longName() {
ComponentDto viewDto = newViewDto().setLongName("another long name").setCreatedAt(now);
persistComponents(viewDto);
treeRootHolder.setRoot(createViewBuilder(PORTFOLIO).build());
underTest.execute(new TestComputationStepContext());
// commit functional transaction -> copies B-fields to A-fields
dbClient.componentDao().applyBChangesForBranchUuid(dbTester.getSession(), viewDto.uuid());
dbTester.commit();
assertRowsCountInTableComponents(1);
ComponentDto newViewDto = getComponentFromDb(VIEW_KEY);
assertDtoIsView(newViewDto);
}
@Test
public void update_project_view() {
ComponentDto view = newViewDto();
ComponentDto project = ComponentTesting.newPrivateProjectDto();
persistComponents(view, project);
ComponentDto projectView = ComponentTesting.newProjectCopy(PROJECT_VIEW_1_UUID, project, view)
.setKey(PROJECT_VIEW_1_KEY)
.setName("Old name")
.setCreatedAt(now);
persistComponents(projectView);
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(createProjectView1Builder(project, null).build())
.build());
underTest.execute(new TestComputationStepContext());
// commit functional transaction -> copies B-fields to A-fields
dbClient.componentDao().applyBChangesForBranchUuid(dbTester.getSession(), view.uuid());
dbTester.commit();
assertRowsCountInTableComponents(3);
ComponentDto pv1Dto = getComponentFromDb(PROJECT_VIEW_1_KEY);
assertDtoIsProjectView1(pv1Dto, view, view, project);
}
@Test
public void update_copy_component_uuid_of_project_view() {
ComponentDto view = newViewDto();
ComponentDto project1 = newPrivateProjectDto("P1");
ComponentDto project2 = newPrivateProjectDto("P2");
persistComponents(view, project1, project2);
// Project view in DB is associated to project1
ComponentDto projectView = ComponentTesting.newProjectCopy(PROJECT_VIEW_1_UUID, project1, view)
.setKey(PROJECT_VIEW_1_KEY)
.setCreatedAt(now);
persistComponents(projectView);
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
// Project view in the View is linked to the first project2
.addChildren(createProjectView1Builder(project2, null).build())
.build());
underTest.execute(new TestComputationStepContext());
// commit functional transaction -> copies B-fields to A-fields
dbClient.componentDao().applyBChangesForBranchUuid(dbTester.getSession(), view.uuid());
dbTester.commit();
ComponentDto pv1Dto = getComponentFromDb(PROJECT_VIEW_1_KEY);
// Project view should now be linked to project2
assertDtoIsProjectView1(pv1Dto, view, view, project2);
}
@Test
public void update_copy_component_uuid_of_sub_view() {
ComponentDto view = newViewDto();
ComponentDto subView = newSubViewDto(view).setCopyComponentUuid("OLD_COPY");
persistComponents(view, subView);
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder("NEW_COPY").build())
.build());
underTest.execute(new TestComputationStepContext());
// commit functional transaction -> copies B-fields to A-fields
dbClient.componentDao().applyBChangesForBranchUuid(dbTester.getSession(), view.uuid());
dbTester.commit();
ComponentDto subViewReloaded = getComponentFromDb(SUBVIEW_1_KEY);
assertThat(subViewReloaded.getCopyComponentUuid()).isEqualTo("NEW_COPY");
}
@Test
public void persists_new_components_as_public_if_root_does_not_exist_yet_out_of_functional_transaction() {
ComponentDto project = dbTester.components().insertComponent(ComponentTesting.newPrivateProjectDto());
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null)
.addChildren(
createProjectView1Builder(project, null).build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
Stream.of(VIEW_UUID, SUBVIEW_1_UUID, PROJECT_VIEW_1_UUID)
.forEach(uuid -> assertThat(dbClient.componentDao().selectByUuid(dbTester.getSession(), uuid).get().isPrivate()).isFalse());
}
@Test
public void persists_new_components_with_visibility_of_root_in_db_out_of_functional_transaction() {
boolean isRootPrivate = new Random().nextBoolean();
ComponentDto project = dbTester.components().insertComponent(ComponentTesting.newPrivateProjectDto());
ComponentDto view = newViewDto().setUuid(VIEW_UUID).setKey(VIEW_KEY).setName("View").setPrivate(isRootPrivate);
dbTester.components().insertComponent(view);
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null)
.addChildren(
createProjectView1Builder(project, null).build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
Stream.of(VIEW_UUID, SUBVIEW_1_UUID, PROJECT_VIEW_1_UUID)
.forEach(uuid -> assertThat(dbClient.componentDao().selectByUuid(dbTester.getSession(), uuid).get().isPrivate())
.describedAs("for uuid " + uuid)
.isEqualTo(isRootPrivate));
}
@Test
public void persists_existing_components_with_visibility_of_root_in_db_out_of_functional_transaction() {
boolean isRootPrivate = new Random().nextBoolean();
ComponentDto project = dbTester.components().insertComponent(ComponentTesting.newPrivateProjectDto());
ComponentDto view = newViewDto().setUuid(VIEW_UUID).setKey(VIEW_KEY).setName("View").setPrivate(isRootPrivate);
dbTester.components().insertComponent(view);
ComponentDto subView = newSubPortfolio(view).setUuid("BCDE").setKey("MODULE").setPrivate(!isRootPrivate);
dbTester.components().insertComponent(subView);
dbTester.components().insertComponent(newProjectCopy("DEFG", project, view).setKey("DIR").setPrivate(isRootPrivate));
treeRootHolder.setRoot(
createViewBuilder(PORTFOLIO)
.addChildren(
createSubView1Builder(null)
.addChildren(
createProjectView1Builder(project, null).build())
.build())
.build());
underTest.execute(new TestComputationStepContext());
Stream.of(VIEW_UUID, SUBVIEW_1_UUID, PROJECT_VIEW_1_UUID, subView.uuid(), "DEFG")
.forEach(uuid -> assertThat(dbClient.componentDao().selectByUuid(dbTester.getSession(), uuid).get().isPrivate())
.describedAs("for uuid " + uuid)
.isEqualTo(isRootPrivate));
}
private static ViewsComponent.Builder createViewBuilder(ViewAttributes.Type viewType) {
return builder(Component.Type.VIEW, VIEW_KEY)
.setUuid(VIEW_UUID)
.setName(VIEW_NAME)
.setDescription(VIEW_DESCRIPTION)
.setViewAttributes(new ViewAttributes(viewType));
}
private ViewsComponent.Builder createSubView1Builder(@Nullable String originalViewUuid) {
return builder(Component.Type.SUBVIEW, SUBVIEW_1_KEY)
.setUuid(SUBVIEW_1_UUID)
.setName(SUBVIEW_1_NAME)
.setDescription(SUBVIEW_1_DESCRIPTION)
.setSubViewAttributes(new SubViewAttributes(originalViewUuid));
}
private static ViewsComponent.Builder createProjectView1Builder(ComponentDto project, Long analysisDate) {
return builder(Component.Type.PROJECT_VIEW, PROJECT_VIEW_1_KEY)
.setUuid(PROJECT_VIEW_1_UUID)
.setName(PROJECT_VIEW_1_NAME)
.setDescription("project view description is not persisted")
.setProjectViewAttributes(new ProjectViewAttributes(project.uuid(), project.getKey(), analysisDate, null));
}
private void persistComponents(ComponentDto... componentDtos) {
dbTester.components().insertComponents(componentDtos);
}
private ComponentDto getComponentFromDb(String componentKey) {
return dbClient.componentDao().selectByKey(dbTester.getSession(), componentKey).get();
}
private void assertRowsCountInTableComponents(int rowCount) {
assertThat(dbTester.countRowsOfTable("components")).isEqualTo(rowCount);
}
private void assertDtoNotUpdated(String componentKey) {
assertThat(getComponentFromDb(componentKey).getCreatedAt()).isNotEqualTo(now);
}
private ComponentDto newViewDto() {
return ComponentTesting.newPortfolio(VIEW_UUID)
.setKey(VIEW_KEY)
.setName(VIEW_NAME);
}
private ComponentDto newSubViewDto(ComponentDto rootView) {
return ComponentTesting.newSubPortfolio(rootView, SUBVIEW_1_UUID, SUBVIEW_1_KEY)
.setName(SUBVIEW_1_NAME);
}
/**
* Assertions to verify the DTO created from {@link #createViewBuilder(ViewAttributes.Type)} ()}
*/
private void assertDtoIsView(ComponentDto dto) {
assertThat(dto.name()).isEqualTo(VIEW_NAME);
assertThat(dto.longName()).isEqualTo(VIEW_NAME);
assertThat(dto.description()).isEqualTo(VIEW_DESCRIPTION);
assertThat(dto.path()).isNull();
assertThat(dto.uuid()).isEqualTo(VIEW_UUID);
assertThat(dto.branchUuid()).isEqualTo(VIEW_UUID);
assertThat(dto.qualifier()).isEqualTo(Qualifiers.VIEW);
assertThat(dto.scope()).isEqualTo(Scopes.PROJECT);
assertThat(dto.getCopyComponentUuid()).isNull();
assertThat(dto.getCreatedAt()).isEqualTo(now);
}
/**
* Assertions to verify the DTO created from {@link #createViewBuilder(ViewAttributes.Type)} ()}
*/
private void assertDtoIsApplication(ComponentDto dto) {
assertThat(dto.name()).isEqualTo(VIEW_NAME);
assertThat(dto.longName()).isEqualTo(VIEW_NAME);
assertThat(dto.description()).isEqualTo(VIEW_DESCRIPTION);
assertThat(dto.path()).isNull();
assertThat(dto.uuid()).isEqualTo(VIEW_UUID);
assertThat(dto.branchUuid()).isEqualTo(VIEW_UUID);
assertThat(dto.qualifier()).isEqualTo(Qualifiers.APP);
assertThat(dto.scope()).isEqualTo(Scopes.PROJECT);
assertThat(dto.getCopyComponentUuid()).isNull();
assertThat(dto.getCreatedAt()).isEqualTo(now);
}
/**
* Assertions to verify the DTO created from {@link #createProjectView1Builder(ComponentDto, Long)}
*/
private void assertDtoIsSubView1(ComponentDto viewDto, ComponentDto sv1Dto) {
assertThat(sv1Dto.name()).isEqualTo(SUBVIEW_1_NAME);
assertThat(sv1Dto.longName()).isEqualTo(SUBVIEW_1_NAME);
assertThat(sv1Dto.description()).isEqualTo(SUBVIEW_1_DESCRIPTION);
assertThat(sv1Dto.path()).isNull();
assertThat(sv1Dto.uuid()).isEqualTo(SUBVIEW_1_UUID);
assertThat(sv1Dto.branchUuid()).isEqualTo(viewDto.uuid());
assertThat(sv1Dto.qualifier()).isEqualTo(Qualifiers.SUBVIEW);
assertThat(sv1Dto.scope()).isEqualTo(Scopes.PROJECT);
assertThat(sv1Dto.getCopyComponentUuid()).isNull();
assertThat(sv1Dto.getCreatedAt()).isEqualTo(now);
}
private void assertDtoIsProjectView1(ComponentDto pv1Dto, ComponentDto viewDto, ComponentDto parentViewDto, ComponentDto project) {
assertThat(pv1Dto.name()).isEqualTo(PROJECT_VIEW_1_NAME);
assertThat(pv1Dto.longName()).isEqualTo(PROJECT_VIEW_1_NAME);
assertThat(pv1Dto.description()).isNull();
assertThat(pv1Dto.path()).isNull();
assertThat(pv1Dto.uuid()).isEqualTo(PROJECT_VIEW_1_UUID);
assertThat(pv1Dto.branchUuid()).isEqualTo(viewDto.uuid());
assertThat(pv1Dto.qualifier()).isEqualTo(Qualifiers.PROJECT);
assertThat(pv1Dto.scope()).isEqualTo(Scopes.FILE);
assertThat(pv1Dto.getCopyComponentUuid()).isEqualTo(project.uuid());
assertThat(pv1Dto.getCreatedAt()).isEqualTo(now);
}
}
| 21,666 | 38.538321 | 162 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditHousekeepingFrequencyHelperIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.sonar.api.impl.utils.TestSystem2;
import org.sonar.api.utils.System2;
import org.sonar.core.config.Frequency;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
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.core.config.PurgeConstants.AUDIT_HOUSEKEEPING_FREQUENCY;
import static org.sonar.core.config.PurgeProperties.DEFAULT_FREQUENCY;
@RunWith(DataProviderRunner.class)
public class AuditHousekeepingFrequencyHelperIT {
private static final long NOW = 10_000_000_000L;
private final DbClient dbClient = mock(DbClient.class);
private final DbSession dbSession = mock(DbSession.class);
private final PropertiesDao propertiesDao = mock(PropertiesDao.class);
private final System2 system2 = new TestSystem2().setNow(NOW);
private final AuditHousekeepingFrequencyHelper underTest = new AuditHousekeepingFrequencyHelper(system2);
@Test
@UseDataProvider("frequencyOptions")
public void getThresholdDate(Frequency frequency) {
long result = underTest.getThresholdDate(frequency.getDescription());
long expected = Instant.ofEpochMilli(system2.now())
.minus(frequency.getDays(), ChronoUnit.DAYS)
.toEpochMilli();
assertThat(result).isEqualTo(expected);
}
@Test
public void getThresholdDateForUnknownFrequencyFails() {
assertThatThrownBy(() -> underTest.getThresholdDate("Lalala"))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("Unsupported frequency: Lalala");
}
@Test
public void getHouseKeepingFrequency() {
String value = "Weekly";
PropertyDto propertyDto = new PropertyDto().setKey(AUDIT_HOUSEKEEPING_FREQUENCY).setValue(value);
when(dbClient.propertiesDao()).thenReturn(propertiesDao);
when(propertiesDao
.selectGlobalProperty(dbSession, AUDIT_HOUSEKEEPING_FREQUENCY))
.thenReturn(propertyDto);
assertThat(underTest.getHouseKeepingFrequency(dbClient, dbSession).getValue()).isEqualTo(value);
}
@Test
public void getDefaultHouseKeepingFrequencyWhenNotSet() {
when(dbClient.propertiesDao()).thenReturn(propertiesDao);
when(propertiesDao
.selectGlobalProperty(dbSession, AUDIT_HOUSEKEEPING_FREQUENCY))
.thenReturn(null);
assertThat(underTest.getHouseKeepingFrequency(dbClient, dbSession).getValue())
.isEqualTo(DEFAULT_FREQUENCY);
}
@DataProvider
public static Object[][] frequencyOptions() {
return new Object[][] {
{Frequency.WEEKLY},
{Frequency.MONTHLY},
{Frequency.TRIMESTRIAL},
{Frequency.YEARLY}
};
}
}
| 3,992 | 37.028571 | 107 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/taskprocessor/AuditPurgeStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.audit.AuditDto;
import org.sonar.db.audit.AuditTesting;
import org.sonar.db.property.PropertyDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.core.config.Frequency.MONTHLY;
import static org.sonar.core.config.PurgeConstants.AUDIT_HOUSEKEEPING_FREQUENCY;
public class AuditPurgeStepIT {
private final static long NOW = 1_400_000_000_000L;
private final static long BEFORE = 1_300_000_000_000L;
private final static long LATER = 1_500_000_000_000L;
private final static ZonedDateTime thresholdDate = Instant.ofEpochMilli(NOW)
.atZone(ZoneId.systemDefault());
private final static PropertyDto FREQUENCY_PROPERTY = new PropertyDto()
.setKey(AUDIT_HOUSEKEEPING_FREQUENCY)
.setValue(MONTHLY.name());
@Rule
public final DbTester dbTester = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = dbTester.getDbClient();
private final System2 system2 = new System2();
@Rule
public final DbTester db = DbTester.create(system2);
private final AuditHousekeepingFrequencyHelper auditHousekeepingFrequencyHelper = mock(AuditHousekeepingFrequencyHelper.class);
private final AuditPurgeStep underTest = new AuditPurgeStep(auditHousekeepingFrequencyHelper, dbClient);
@Before
public void setUp() {
when(auditHousekeepingFrequencyHelper.getHouseKeepingFrequency(any(), any())).thenReturn(FREQUENCY_PROPERTY);
when(auditHousekeepingFrequencyHelper.getThresholdDate(anyString())).thenReturn(NOW);
}
@Test
public void executeDeletesOlderAudits() {
prepareRowsWithDeterministicCreatedAt();
assertThat(dbClient.auditDao().selectOlderThan(db.getSession(), LATER + 1)).hasSize(3);
underTest.execute(() -> null);
assertThat(dbClient.auditDao().selectOlderThan(db.getSession(), LATER + 1)).hasSize(2);
}
@Test
public void getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Purge Audit Logs");
}
private void prepareRowsWithDeterministicCreatedAt() {
insertAudit(BEFORE);
insertAudit(NOW);
insertAudit(LATER);
db.getSession().commit();
}
private void insertAudit(long timestamp) {
AuditDto auditDto = AuditTesting.newAuditDto(timestamp);
dbClient.auditDao().insert(db.getSession(), auditDto);
}
}
| 3,623 | 35.24 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/taskprocessor/IgnoreOrphanBranchStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.BranchType.BRANCH;
public class IgnoreOrphanBranchStepIT {
private final String ENTITY_UUID = "entity_uuid";
private final String BRANCH_UUID = "branch_uuid";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final CeTask.Component entity = new CeTask.Component(ENTITY_UUID, "component key", "component name");
private final CeTask.Component component = new CeTask.Component(BRANCH_UUID, "component key", "component name");
private final CeTask ceTask = new CeTask.Builder()
.setType("type")
.setUuid("uuid")
.setComponent(component)
.setEntity(entity)
.build();
private final DbClient dbClient = dbTester.getDbClient();
private final IgnoreOrphanBranchStep underTest = new IgnoreOrphanBranchStep(ceTask, dbClient);
@Test
public void execute() {
BranchDto branchDto = new BranchDto()
.setBranchType(BRANCH)
.setKey("branchName")
.setIsMain(false)
.setUuid(BRANCH_UUID)
.setProjectUuid("project_uuid")
.setNeedIssueSync(true);
dbClient.branchDao().insert(dbTester.getSession(), branchDto);
dbTester.commit();
underTest.execute(() -> null);
Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbTester.getSession(), BRANCH_UUID);
assertThat(branch.get().isNeedIssueSync()).isFalse();
assertThat(branch.get().isExcludeFromPurge()).isFalse();
}
@Test
public void execute_on_already_indexed_branch() {
BranchDto branchDto = new BranchDto()
.setBranchType(BRANCH)
.setKey("branchName")
.setUuid(BRANCH_UUID)
.setProjectUuid("project_uuid")
.setIsMain(false)
.setNeedIssueSync(false);
dbClient.branchDao().insert(dbTester.getSession(), branchDto);
dbTester.commit();
underTest.execute(() -> null);
Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbTester.getSession(), BRANCH_UUID);
assertThat(branch.get().isNeedIssueSync()).isFalse();
assertThat(branch.get().isExcludeFromPurge()).isFalse();
}
@Test
public void fail_if_missing_main_component_in_task() {
CeTask ceTask = new CeTask.Builder()
.setType("type")
.setUuid("uuid")
.setComponent(null)
.setEntity(null)
.build();
IgnoreOrphanBranchStep underTest = new IgnoreOrphanBranchStep(ceTask, dbClient);
assertThatThrownBy(() -> underTest.execute(() -> null))
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("entity not found in task");
}
@Test
public void verify_step_description() {
assertThat(underTest.getDescription()).isEqualTo("Ignore orphan component");
}
}
| 3,946 | 33.929204 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectanalysis/taskprocessor/IndexIssuesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.Optional;
import org.junit.Rule;
import org.junit.Test;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.CeTask;
import org.sonar.db.DbClient;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.server.es.EsTester;
import org.sonar.server.issue.index.IssueIndexer;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.sonar.db.component.BranchType.BRANCH;
public class IndexIssuesStepIT {
private final String ENTITY_UUID = "entity_uuid";
private final String BRANCH_UUID = "branch_uuid";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final DbClient dbClient = dbTester.getDbClient();
private final CeTask.Component entity = new CeTask.Component(ENTITY_UUID, "component key", "component name");
private final CeTask.Component component = new CeTask.Component(BRANCH_UUID, "component key", "component name");
private final CeTask ceTask = new CeTask.Builder()
.setType("type")
.setUuid("uuid")
.setComponent(component)
.setEntity(entity)
.build();
@Rule
public EsTester es = EsTester.create();
private final IssueIndexer issueIndexer = mock(IssueIndexer.class);
private final IndexIssuesStep underTest = new IndexIssuesStep(ceTask, dbClient, issueIndexer);
@Test
public void execute() {
BranchDto branchDto = new BranchDto()
.setBranchType(BRANCH)
.setKey("branchName")
.setUuid(BRANCH_UUID)
.setProjectUuid("project_uuid")
.setIsMain(false)
.setNeedIssueSync(true);
dbClient.branchDao().insert(dbTester.getSession(), branchDto);
dbTester.commit();
underTest.execute(() -> null);
verify(issueIndexer, times(1)).indexOnAnalysis(BRANCH_UUID);
Optional<BranchDto> branch = dbClient.branchDao().selectByUuid(dbTester.getSession(), BRANCH_UUID);
assertThat(branch.get().isNeedIssueSync()).isFalse();
}
@Test
public void execute_on_already_indexed_branch() {
BranchDto branchDto = new BranchDto()
.setBranchType(BRANCH)
.setKey("branchName")
.setUuid(BRANCH_UUID)
.setProjectUuid("project_uuid")
.setIsMain(false)
.setNeedIssueSync(false);
dbClient.branchDao().insert(dbTester.getSession(), branchDto);
dbTester.commit();
underTest.execute(() -> null);
verify(issueIndexer, times(0)).indexOnAnalysis(BRANCH_UUID);
}
@Test
public void fail_if_missing_component_in_task() {
CeTask ceTask = new CeTask.Builder()
.setType("type")
.setUuid("uuid")
.setComponent(null)
.setEntity(null)
.build();
IndexIssuesStep underTest = new IndexIssuesStep(ceTask, dbClient, issueIndexer);
assertThatThrownBy(() -> underTest.execute(() -> null))
.isInstanceOf(UnsupportedOperationException.class)
.hasMessage("component not found in task");
}
}
| 3,978 | 33.6 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/analysis/ExportAnalysesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.analysis;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.util.List;
import java.util.Set;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic;
import static org.apache.commons.lang.StringUtils.defaultString;
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.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR;
@RunWith(DataProviderRunner.class)
public class ExportAnalysesStepIT {
private static final String PROJECT_UUID = "PROJECT_UUID";
private static final ComponentDto PROJECT = new ComponentDto()
// no id yet
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.PROJECT)
.setKey("the_project")
.setName("The Project")
.setDescription("The project description")
.setEnabled(true)
.setUuid(PROJECT_UUID)
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid(PROJECT_UUID);
private static final String DIR_UUID = "DIR_UUID";
private static final String UUID_PATH = UUID_PATH_OF_ROOT + UUID_PATH_SEPARATOR + DIR_UUID;
private static final ComponentDto DIR = new ComponentDto()
// no id yet
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.DIRECTORY)
.setKey("the_dir")
.setName("The Dir")
.setDescription("description of dir")
.setEnabled(true)
.setUuid(DIR_UUID)
.setUuidPath(UUID_PATH)
.setBranchUuid(PROJECT_UUID);
private static final String FILE_UUID = "FILE_UUID";
private static final ComponentDto FILE = new ComponentDto()
// no id yet
.setScope(Scopes.FILE)
.setQualifier(Qualifiers.FILE)
.setKey("the_file")
.setName("The File")
.setUuid(FILE_UUID)
.setUuidPath(UUID_PATH + UUID_PATH_SEPARATOR + FILE_UUID)
.setEnabled(true)
.setBranchUuid(PROJECT_UUID);
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private final ComponentRepositoryImpl componentRepository = new ComponentRepositoryImpl();
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final ExportAnalysesStep underTest = new ExportAnalysesStep(dbTester.getDbClient(), projectHolder, componentRepository, dumpWriter);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
ComponentDto projectDto = dbTester.components().insertPublicProject(PROJECT).getMainBranchComponent();
componentRepository.register(1, projectDto.uuid(), false);
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), Set.of(DIR, FILE), true);
dbTester.commit();
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(projectDto));
}
@Test
public void getDescription_is_defined() {
assertThat(underTest.getDescription()).isEqualTo("Export analyses");
}
@Test
@UseDataProvider("versionAndBuildStringCombinations")
public void export_analyses(@Nullable String version, @Nullable String buildString) {
SnapshotDto firstAnalysis = newAnalysis("U_1", 1_450_000_000_000L, PROJECT.uuid(), "1.0", false, "1.0.2.3", 1_450_000_000_000L);
SnapshotDto secondAnalysis = newAnalysis("U_4", 1_460_000_000_000L, PROJECT.uuid(), "1.1", true, "1.1.3.4", 1_460_000_000_000L);
SnapshotDto thirdAnalysis = newAnalysis("U_7", 1_460_000_000_000L, PROJECT.uuid(), version, true, buildString, 1_470_000_000_000L);
dbTester.getDbClient().snapshotDao().insert(dbTester.getSession(), firstAnalysis, secondAnalysis, thirdAnalysis);
dbTester.commit();
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("3 analyses exported");
List<ProjectDump.Analysis> analyses = dumpWriter.getWrittenMessagesOf(DumpElement.ANALYSES);
assertThat(analyses).hasSize(3);
assertAnalysis(analyses.get(0), PROJECT, firstAnalysis);
assertAnalysis(analyses.get(1), PROJECT, secondAnalysis);
assertAnalysis(analyses.get(2), PROJECT, thirdAnalysis);
}
@DataProvider
public static Object[][] versionAndBuildStringCombinations() {
String version = randomAlphabetic(7);
String buildString = randomAlphabetic(12);
return new Object[][] {
{null, null},
{version, null},
{null, buildString},
{version, buildString},
{"", ""},
{version, ""},
{"", buildString},
};
}
@Test
public void export_analyses_by_ordering_by_technical_creation_date() {
SnapshotDto firstAnalysis = newAnalysis("U_1", 1_450_000_000_000L, PROJECT.uuid(), "1.0", false, "1.0.2.3", 3_000_000_000_000L);
SnapshotDto secondAnalysis = newAnalysis("U_4", 1_460_000_000_000L, PROJECT.uuid(), "1.1", true, "1.1.3.4", 1_000_000_000_000L);
SnapshotDto thirdAnalysis = newAnalysis("U_7", 1_460_500_000_000L, PROJECT.uuid(), null, true, null, 2_000_000_000_000L);
dbTester.getDbClient().snapshotDao().insert(dbTester.getSession(), firstAnalysis, secondAnalysis, thirdAnalysis);
dbTester.commit();
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Analysis> analyses = dumpWriter.getWrittenMessagesOf(DumpElement.ANALYSES);
assertAnalysis(analyses.get(0), PROJECT, secondAnalysis);
assertAnalysis(analyses.get(1), PROJECT, thirdAnalysis);
assertAnalysis(analyses.get(2), PROJECT, firstAnalysis);
}
@Test
public void export_provisioned_projects_without_any_analyses() {
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Analysis> analyses = dumpWriter.getWrittenMessagesOf(DumpElement.ANALYSES);
assertThat(analyses).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 analyses exported");
}
@Test
public void throws_ISE_if_error() {
SnapshotDto firstAnalysis = newAnalysis("U_1", 1_450_000_000_000L, PROJECT.uuid(), "1.0", false, "1.0.2.3", 1);
SnapshotDto secondAnalysis = newAnalysis("U_4", 1_460_000_000_000L, PROJECT.uuid(), "1.1", true, "1.1.3.4", 2);
dbTester.getDbClient().snapshotDao().insert(dbTester.getSession(), firstAnalysis, secondAnalysis);
dbTester.commit();
dumpWriter.failIfMoreThan(1, DumpElement.ANALYSES);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Analysis Export failed after processing 1 analyses successfully");
}
private static SnapshotDto newAnalysis(String uuid, long date, String componentUuid, @Nullable String version, boolean isLast, @Nullable String buildString, long buildDate) {
return new SnapshotDto()
.setUuid(uuid)
.setCreatedAt(date)
.setRootComponentUuid(componentUuid)
.setProjectVersion(version)
.setBuildString(buildString)
.setLast(isLast)
.setStatus(SnapshotDto.STATUS_PROCESSED)
.setBuildDate(buildDate);
}
private static void assertAnalysis(ProjectDump.Analysis analysis, ComponentDto component, SnapshotDto dto) {
assertThat(analysis.getUuid()).isEqualTo(dto.getUuid());
assertThat(analysis.getComponentRef()).isOne();
assertThat(analysis.getDate()).isEqualTo(dto.getCreatedAt());
assertThat(analysis.getProjectVersion()).isEqualTo(defaultString(dto.getProjectVersion()));
assertThat(analysis.getBuildString()).isEqualTo(defaultString(dto.getBuildString()));
}
}
| 9,402 | 42.734884 | 176 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/branches/ExportBranchesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.branches;
import com.google.common.collect.ImmutableList;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.apache.commons.lang.time.DateUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ProjectData;
import org.sonar.db.project.ProjectExportMapper;
import static java.util.stream.Collectors.toMap;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ExportBranchesStepIT {
private static final String PROJECT_UUID = "PROJECT_UUID";
@Rule
public DbTester dbTester = DbTester.createWithExtensionMappers(System2.INSTANCE, ProjectExportMapper.class);
@Rule
public LogTester logTester = new LogTester();
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ExportBranchesStep underTest = new ExportBranchesStep(dumpWriter, dbTester.getDbClient(), projectHolder);
private final List<BranchDto> branches = ImmutableList.of(
new BranchDto()
.setBranchType(BranchType.BRANCH)
.setProjectUuid(PROJECT_UUID)
.setKey("branch-1")
.setUuid("branch-1-uuid")
.setMergeBranchUuid("master")
.setIsMain(false)
.setExcludeFromPurge(true),
new BranchDto()
.setBranchType(BranchType.PULL_REQUEST)
.setProjectUuid(PROJECT_UUID)
.setKey("branch-3")
.setUuid("branch-3-uuid")
.setIsMain(false)
.setMergeBranchUuid("master"),
new BranchDto()
.setBranchType(BranchType.BRANCH)
.setProjectUuid(PROJECT_UUID)
.setKey("branch-4")
.setUuid("branch-4-uuid")
.setIsMain(false)
.setMergeBranchUuid("branch-1-uuid"),
new BranchDto()
.setBranchType(BranchType.BRANCH)
.setProjectUuid(PROJECT_UUID)
.setKey("branch-5")
.setUuid("branch-5-uuid")
.setIsMain(false)
.setMergeBranchUuid("master")
.setExcludeFromPurge(true));
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
Date createdAt = new Date();
ProjectData projectData = dbTester.components().insertPublicProject(PROJECT_UUID);
for (BranchDto branch : branches) {
createdAt = DateUtils.addMinutes(createdAt, 10);
dbTester.components().insertProjectBranch(projectData.getProjectDto(), branch).setCreatedAt(createdAt);
}
dbTester.commit();
when(projectHolder.projectDto()).thenReturn(projectData.getProjectDto());
}
@Test
public void export_branches() {
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("3 branches exported");
Map<String, ProjectDump.Branch> branches = dumpWriter.getWrittenMessagesOf(DumpElement.BRANCHES)
.stream()
.collect(toMap(ProjectDump.Branch::getUuid, Function.identity()));
assertThat(branches).hasSize(3);
ProjectDump.Branch mainBranch = branches.values().stream().filter(ProjectDump.Branch::getIsMain).findFirst().get();
assertThat(mainBranch).isNotNull();
assertThat(mainBranch.getKee()).isEqualTo(BranchDto.DEFAULT_MAIN_BRANCH_NAME);
assertThat(mainBranch.getProjectUuid()).isEqualTo(PROJECT_UUID);
assertThat(mainBranch.getMergeBranchUuid()).isEmpty();
assertThat(mainBranch.getBranchType()).isEqualTo("BRANCH");
ProjectDump.Branch branch1 = branches.get("branch-1-uuid");
assertThat(branch1.getKee()).isEqualTo("branch-1");
assertThat(branch1.getProjectUuid()).isEqualTo(PROJECT_UUID);
assertThat(branch1.getMergeBranchUuid()).isEqualTo("master");
assertThat(branch1.getBranchType()).isEqualTo("BRANCH");
ProjectDump.Branch branch5 = branches.get("branch-5-uuid");
assertThat(branch5.getKee()).isEqualTo("branch-5");
assertThat(branch5.getProjectUuid()).isEqualTo(PROJECT_UUID);
assertThat(branch5.getMergeBranchUuid()).isEqualTo("master");
assertThat(branch5.getBranchType()).isEqualTo("BRANCH");
}
@Test
public void throws_ISE_if_error() {
dumpWriter.failIfMoreThan(1, DumpElement.BRANCHES);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Branch export failed after processing 1 branch(es) successfully");
}
@Test
public void getDescription_is_defined() {
assertThat(underTest.getDescription()).isEqualTo("Export branches");
}
}
| 6,015 | 39.648649 | 121 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/component/ExportComponentsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 com.google.common.collect.ImmutableSet;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.Date;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
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.when;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR;
public class ExportComponentsStepIT {
private static final String PROJECT_UUID = "PROJECT_UUID";
private static final ComponentDto PROJECT = new ComponentDto()
// no id yet
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.PROJECT)
.setKey("the_project")
.setName("The Project")
.setDescription("The project description")
.setEnabled(true)
.setUuid(PROJECT_UUID)
.setUuidPath(UUID_PATH_OF_ROOT)
.setCreatedAt(new Date(1596749115856L))
.setBranchUuid(PROJECT_UUID);
private static final String FILE_UUID = "FILE_UUID";
private static final String FILE_UUID_PATH = PROJECT_UUID + FILE_UUID + UUID_PATH_SEPARATOR;
private static final ComponentDto FILE = new ComponentDto()
// no id yet
.setScope(Scopes.FILE)
.setQualifier(Qualifiers.FILE)
.setKey("the_file")
.setName("The File")
.setUuid(FILE_UUID)
.setUuidPath(FILE_UUID_PATH)
.setEnabled(true)
.setCreatedAt(new Date(1596749148406L))
.setBranchUuid(PROJECT_UUID);
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final MutableComponentRepository componentRepository = new ComponentRepositoryImpl();
private final ExportComponentsStep underTest = new ExportComponentsStep(dbTester.getDbClient(), projectHolder, componentRepository, dumpWriter);
@Before
public void before() {
logTester.setLevel(Level.DEBUG);
}
@After
public void tearDown() {
dbTester.getSession().close();
}
@Test
public void export_components_including_project() {
dbTester.components().insertPublicProject(PROJECT).getMainBranchComponent();
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), FILE, true);
dbTester.commit();
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(PROJECT));
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("2 components exported");
List<ProjectDump.Component> components = dumpWriter.getWrittenMessagesOf(DumpElement.COMPONENTS);
assertThat(components).extracting(ProjectDump.Component::getQualifier, ProjectDump.Component::getUuid, ProjectDump.Component::getUuidPath)
.containsExactlyInAnyOrder(
tuple(Qualifiers.FILE, FILE_UUID, FILE_UUID_PATH),
tuple(Qualifiers.PROJECT, PROJECT_UUID, UUID_PATH_OF_ROOT));
}
@Test
public void execute_register_all_components_uuids_as_their_id_in_ComponentRepository() {
dbTester.components().insertPublicProject(PROJECT).getMainBranchComponent();
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), FILE, true);
dbTester.commit();
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(PROJECT));
underTest.execute(new TestComputationStepContext());
assertThat(ImmutableSet.of(
componentRepository.getRef(PROJECT.uuid()),
componentRepository.getRef(FILE.uuid()))).containsExactlyInAnyOrder(1L, 2L);
}
@Test
public void throws_ISE_if_error() {
dbTester.components().insertPublicProject(PROJECT).getMainBranchComponent();
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), FILE, true);
dbTester.commit();
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(PROJECT));
dumpWriter.failIfMoreThan(1, DumpElement.COMPONENTS);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Component Export failed after processing 1 components successfully");
}
@Test
public void getDescription_is_defined() {
assertThat(underTest.getDescription()).isEqualTo("Export components");
}
}
| 6,029 | 39.2 | 146 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/file/ExportLineHashesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.file;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.List;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.component.MutableComponentRepository;
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 org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.MyBatis;
import org.sonar.db.source.FileSourceDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
public class ExportLineHashesStepIT {
private static final String PROJECT_MASTER_UUID = "project uuid";
private static final String PROJECT_BRANCH_UUID = "branch-uuid";
private static final String FILE_UUID = "file uuid";
private static final String FILE_UUID_2 = "file-2-uuid";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbClient.openSession(false);
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final MutableComponentRepository componentRepository = new ComponentRepositoryImpl();
private final ExportLineHashesStep underTest = new ExportLineHashesStep(dbClient, dumpWriter, componentRepository);
@Before
public void before() {
logTester.setLevel(Level.DEBUG);
}
@After
public void tearDown() {
dbSession.close();
}
@Test
public void getDescription_is_set() {
assertThat(underTest.getDescription()).isEqualTo("Export line hashes");
}
@Test
public void execute_does_not_create_a_session_when_there_is_no_file_in_ComponentRepository() {
DbClient spy = spy(dbClient);
new ExportLineHashesStep(spy, dumpWriter, componentRepository)
.execute(new TestComputationStepContext());
verifyNoInteractions(spy);
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINES_HASHES)).isEmpty();
}
@Test
public void execute_relies_only_on_file_uuid_and_does_not_check_project_uuid() {
componentRepository.register(1, FILE_UUID, true);
insertFileSource(createDto(FILE_UUID, "blabla", "A"));
insertFileSource(createDto(FILE_UUID_2, "blabla", "B"));
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINES_HASHES)).hasSize(1);
}
@Test
public void execute_maps_ref_of_component_and_hashes_from_fileSources() {
int fileRef = 984615;
componentRepository.register(fileRef, FILE_UUID, true);
FileSourceDto dto = createDto(FILE_UUID, PROJECT_MASTER_UUID, "B");
insertFileSource(dto);
underTest.execute(new TestComputationStepContext());
List<ProjectDump.LineHashes> messages = dumpWriter.getWrittenMessagesOf(DumpElement.LINES_HASHES);
assertThat(messages).hasSize(1);
ProjectDump.LineHashes lineHashes = messages.iterator().next();
assertThat(lineHashes.getHashes()).isEqualTo(dto.getRawLineHashes());
assertThat(lineHashes.getComponentRef()).isEqualTo(fileRef);
}
@Test
public void execute_does_one_SQL_request_by_1000_items_per_IN_clause() {
for (int i = 0; i < 2500; i++) {
componentRepository.register(i, "uuid_" + i, true);
}
DbClient spyDbClient = spy(dbClient);
MyBatis spyMyBatis = spy(dbClient.getMyBatis());
when(spyDbClient.getMyBatis()).thenReturn(spyMyBatis);
ArgumentCaptor<String> stringCaptor = ArgumentCaptor.forClass(String.class);
doCallRealMethod().when(spyMyBatis).newScrollingSelectStatement(any(DbSession.class), stringCaptor.capture());
new ExportLineHashesStep(spyDbClient, dumpWriter, componentRepository)
.execute(new TestComputationStepContext());
List<String> statements = stringCaptor.getAllValues();
assertThat(statements).hasSize(3);
assertThat(statements.get(0).split("\\?")).hasSize(1001);
assertThat(statements.get(1).split("\\?")).hasSize(1001);
assertThat(statements.get(2).split("\\?")).hasSize(501);
}
@Test
public void execute_exports_lines_hashes_of_file_sources() {
componentRepository.register(1, FILE_UUID, true);
insertFileSource(FILE_UUID, "A");
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINES_HASHES))
.extracting(ProjectDump.LineHashes::getHashes)
.containsOnly("A");
}
@Test
public void execute_logs_number_of_filesource_exported_and_export_by_order_of_id() {
componentRepository.register(1, FILE_UUID, true);
componentRepository.register(2, "file-2", true);
componentRepository.register(3, "file-3", true);
componentRepository.register(4, "file-4", true);
insertFileSource(createDto(FILE_UUID, PROJECT_MASTER_UUID, "A"));
insertFileSource(createDto("file-2", PROJECT_MASTER_UUID, "C"));
insertFileSource(createDto("file-3", PROJECT_MASTER_UUID, "D"));
insertFileSource(createDto("file-4", PROJECT_BRANCH_UUID, "E"));
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINES_HASHES))
.extracting(ProjectDump.LineHashes::getHashes)
.containsExactly("A", "C", "D", "E");
assertThat(logTester.logs(Level.DEBUG)).contains("Lines hashes of 4 files exported");
}
private FileSourceDto insertFileSource(String fileUuid, String hashes) {
FileSourceDto dto = createDto(fileUuid, PROJECT_MASTER_UUID, hashes);
return insertFileSource(dto);
}
private FileSourceDto insertFileSource(FileSourceDto dto) {
dbClient.fileSourceDao().insert(dbSession, dto);
dbSession.commit();
return dto;
}
private FileSourceDto createDto(String fileUuid, String componentUuid, String hashes) {
FileSourceDto fileSourceDto = new FileSourceDto()
.setUuid(Uuids.createFast())
.setFileUuid(fileUuid)
.setProjectUuid(componentUuid);
fileSourceDto.setRawLineHashes(hashes);
return fileSourceDto;
}
}
| 7,528 | 37.025253 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/issue/ExportIssuesChangelogStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.issue;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.core.util.Uuids;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.issue.IssueChangeDto;
import org.sonar.db.issue.IssueDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.issue.Issue.STATUS_CLOSED;
import static org.sonar.api.issue.Issue.STATUS_CONFIRMED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
import static org.sonar.api.issue.Issue.STATUS_RESOLVED;
public class ExportIssuesChangelogStepIT {
private static final String PROJECT_UUID = "project uuid";
private static final String ISSUE_OPEN_UUID = "issue 1 uuid";
private static final String ISSUE_CONFIRMED_UUID = "issue 2 uuid";
private static final String ISSUE_REOPENED_UUID = "issue 3 uuid";
private static final String ISSUE_RESOLVED_UUID = "issue 4 uuid";
private static final String ISSUE_CLOSED_UUID = "issue closed uuid";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbClient.openSession(false);
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ExportIssuesChangelogStep underTest = new ExportIssuesChangelogStep(dbClient, projectHolder, dumpWriter);
private BranchDto mainBranch;
private int issueChangeUuidGenerator = 0;
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
ProjectData projectData = dbTester.components().insertPublicProject(PROJECT_UUID);
mainBranch = projectData.getMainBranchDto();
when(projectHolder.projectDto()).thenReturn(projectData.getProjectDto());
when(projectHolder.branches()).thenReturn(List.of(mainBranch));
insertIssue(mainBranch.getUuid(), ISSUE_OPEN_UUID, STATUS_OPEN);
insertIssue(mainBranch.getUuid(), ISSUE_CONFIRMED_UUID, STATUS_CONFIRMED);
insertIssue(mainBranch.getUuid(), ISSUE_REOPENED_UUID, STATUS_REOPENED);
insertIssue(mainBranch.getUuid(), ISSUE_RESOLVED_UUID, STATUS_RESOLVED);
insertIssue(mainBranch.getUuid(), ISSUE_CLOSED_UUID, STATUS_CLOSED);
}
@After
public void tearDown() {
dbSession.close();
}
@Test
public void getDescription_is_set() {
assertThat(underTest.getDescription()).isEqualTo("Export issues changelog");
}
@Test
public void execute_writes_now_RuleChange_is_db_is_empty() {
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES_CHANGELOG)).isEmpty();
}
@Test
public void execute_writes_entries_of_issues_of_any_type_but_CLOSED() {
long createdAt = 1_999_993L;
String[] expectedKeys = new String[] {
insertIssueChange(ISSUE_OPEN_UUID, createdAt).getKey(),
insertIssueChange(ISSUE_CONFIRMED_UUID, createdAt + 1).getKey(),
insertIssueChange(ISSUE_REOPENED_UUID, createdAt + 2).getKey(),
insertIssueChange(ISSUE_RESOLVED_UUID, createdAt + 3).getKey()
};
insertIssueChange(ISSUE_CLOSED_UUID, createdAt + 4);
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES_CHANGELOG))
.extracting(ProjectDump.IssueChange::getKey).containsExactly(expectedKeys);
}
@Test
public void execute_writes_only_entries_of_current_project() {
String issueUuid = "issue uuid";
insertIssue("other project uuid", issueUuid, STATUS_OPEN);
insertIssueChange(issueUuid);
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES_CHANGELOG)).isEmpty();
}
@Test
public void execute_maps_all_fields_to_protobuf() {
IssueChangeDto issueChangeDto = new IssueChangeDto()
.setUuid("uuid")
.setKey("key")
.setIssueKey(ISSUE_OPEN_UUID)
.setChangeData("change data")
.setChangeType("change type")
.setUserUuid("user_uuid")
.setIssueChangeCreationDate(454135L)
.setProjectUuid(mainBranch.getUuid());
insertIssueChange(issueChangeDto);
underTest.execute(new TestComputationStepContext());
ProjectDump.IssueChange issueChange = getSingleMessage();
assertThat(issueChange.getKey()).isEqualTo(issueChangeDto.getKey());
assertThat(issueChange.getIssueUuid()).isEqualTo(issueChangeDto.getIssueKey());
assertThat(issueChange.getChangeData()).isEqualTo(issueChangeDto.getChangeData());
assertThat(issueChange.getChangeType()).isEqualTo(issueChangeDto.getChangeType());
assertThat(issueChange.getUserUuid()).isEqualTo(issueChangeDto.getUserUuid());
assertThat(issueChange.getCreatedAt()).isEqualTo(issueChangeDto.getIssueChangeCreationDate());
assertThat(issueChange.getProjectUuid()).isEqualTo(issueChangeDto.getProjectUuid());
}
@Test
public void execute_exports_issues_by_oldest_create_date_first() {
long createdAt = 1_999_993L;
long now = createdAt + 1_000_000_000L;
String key1 = insertIssueChange(ISSUE_OPEN_UUID, createdAt, now).getKey();
String key2 = insertIssueChange(ISSUE_OPEN_UUID, createdAt - 500, now + 100).getKey();
String key3 = insertIssueChange(ISSUE_OPEN_UUID, createdAt - 1000, now + 200).getKey();
String key4 = insertIssueChange(ISSUE_OPEN_UUID, createdAt + 200, now + 300).getKey();
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES_CHANGELOG))
.extracting(ProjectDump.IssueChange::getKey)
.containsExactly(key3, key2, key1, key4);
}
@Test
public void execute_sets_missing_fields_to_default_values() {
long createdAt = 1_999_888L;
insertIssueChange(new IssueChangeDto().setUuid(Uuids.createFast()).setIssueKey(ISSUE_REOPENED_UUID).setCreatedAt(createdAt).setProjectUuid("project_uuid"));
underTest.execute(new TestComputationStepContext());
ProjectDump.IssueChange issueChange = getSingleMessage();
assertThat(issueChange.getKey()).isEmpty();
assertThat(issueChange.getChangeType()).isEmpty();
assertThat(issueChange.getChangeData()).isEmpty();
assertThat(issueChange.getUserUuid()).isEmpty();
assertThat(issueChange.getCreatedAt()).isEqualTo(createdAt);
}
@Test
public void execute_sets_createAt_to_zero_if_both_createdAt_and_issueChangeDate_are_null() {
insertIssueChange(new IssueChangeDto().setUuid(Uuids.createFast()).setIssueKey(ISSUE_REOPENED_UUID).setProjectUuid(mainBranch.getUuid()));
underTest.execute(new TestComputationStepContext());
ProjectDump.IssueChange issueChange = getSingleMessage();
assertThat(issueChange.getCreatedAt()).isZero();
}
@Test
public void execute_writes_entries_of_closed_issue() {
insertIssueChange(ISSUE_CLOSED_UUID);
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES_CHANGELOG)).isEmpty();
}
@Test
public void execute_logs_number_total_exported_issue_changes_count_when_successful() {
logTester.setLevel(Level.DEBUG);
insertIssueChange(ISSUE_OPEN_UUID);
insertIssueChange(ISSUE_CONFIRMED_UUID);
insertIssueChange(ISSUE_REOPENED_UUID);
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("3 issue changes exported");
}
@Test
public void execute_throws_ISE_when_exception_occurs_and_message_contains_number_of_successfully_processed_files_in_() {
insertIssueChange(ISSUE_OPEN_UUID);
insertIssueChange(ISSUE_CONFIRMED_UUID);
insertIssueChange(ISSUE_REOPENED_UUID);
dumpWriter.failIfMoreThan(2, DumpElement.ISSUES_CHANGELOG);
TestComputationStepContext context = new TestComputationStepContext();
assertThatThrownBy(() -> underTest.execute(context))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Issues changelog export failed after processing 2 issue changes successfully");
}
private void insertIssueChange(String issueUuid) {
insertIssueChange(issueUuid, System2.INSTANCE.now(), null);
}
private IssueChangeDto insertIssueChange(String issueUuid, long creationDate) {
return insertIssueChange(issueUuid, creationDate, null);
}
private IssueChangeDto insertIssueChange(String issueUuid, long creationDate, @Nullable Long issueChangeDate) {
IssueChangeDto dto = new IssueChangeDto()
.setKey("uuid_" + issueChangeUuidGenerator++)
.setUuid(Uuids.createFast())
.setCreatedAt(creationDate)
.setIssueKey(issueUuid)
.setProjectUuid("project_uuid");
if (issueChangeDate != null) {
dto.setIssueChangeCreationDate(issueChangeDate);
}
return insertIssueChange(dto);
}
private IssueChangeDto insertIssueChange(IssueChangeDto dto) {
dbClient.issueChangeDao().insert(dbSession, dto);
dbSession.commit();
return dto;
}
private void insertIssue(String branchUuid, String uuid, String status) {
IssueDto dto = new IssueDto()
.setKee(uuid)
.setProjectUuid(branchUuid)
.setStatus(status);
dbClient.issueDao().insert(dbSession, dto);
dbSession.commit();
}
private ProjectDump.IssueChange getSingleMessage() {
List<ProjectDump.IssueChange> messages = dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES_CHANGELOG);
assertThat(messages).hasSize(1);
return messages.get(0);
}
}
| 11,207 | 39.172043 | 160 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/issue/ExportIssuesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.issue;
import com.google.protobuf.InvalidProtocolBufferException;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import com.tngtech.java.junit.dataprovider.DataProvider;
import com.tngtech.java.junit.dataprovider.DataProviderRunner;
import com.tngtech.java.junit.dataprovider.UseDataProvider;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Random;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.event.Level;
import org.sonar.api.issue.Issue;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rules.RuleType;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.projectexport.component.MutableComponentRepository;
import org.sonar.ce.task.projectexport.rule.RuleRepository;
import org.sonar.ce.task.projectexport.rule.RuleRepositoryImpl;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.protobuf.DbIssues;
import org.sonar.db.protobuf.DbIssues.Locations;
import org.sonar.db.protobuf.DbIssues.MessageFormattingType;
import org.sonar.db.rule.RuleDto;
import org.sonar.db.rule.RuleDto.Scope;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.issue.Issue.STATUS_CONFIRMED;
import static org.sonar.api.issue.Issue.STATUS_OPEN;
import static org.sonar.api.issue.Issue.STATUS_REOPENED;
import static org.sonar.api.issue.Issue.STATUS_RESOLVED;
@RunWith(DataProviderRunner.class)
public class ExportIssuesStepIT {
private static final String SOME_PROJECT_UUID = "project uuid";
private static final String PROJECT_KEY = "projectkey";
private static final String SOME_REPO = "rule repo";
private static final String READY_RULE_KEY = "rule key 1";
public static final DbIssues.MessageFormatting MESSAGE_FORMATTING = DbIssues.MessageFormatting.newBuilder().setStart(0).setEnd(4).setType(MessageFormattingType.CODE).build();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private final DbClient dbClient = dbTester.getDbClient();
private final DbSession dbSession = dbClient.openSession(false);
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final RuleRepository ruleRepository = new RuleRepositoryImpl();
private final MutableComponentRepository componentRepository = new ComponentRepositoryImpl();
private final ExportIssuesStep underTest = new ExportIssuesStep(dbClient, projectHolder, dumpWriter, ruleRepository, componentRepository);
private RuleDto readyRuleDto;
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
ProjectDto project = createProject();
when(projectHolder.projectDto()).thenReturn(project);
when(projectHolder.branches()).thenReturn(newArrayList(
new BranchDto().setBranchType(BranchType.BRANCH).setKey("master").setProjectUuid(SOME_PROJECT_UUID).setUuid(SOME_PROJECT_UUID)));
// adds a random number of Rules to db and repository so that READY_RULE_KEY does always get id=ref=1
for (int i = 0; i < new Random().nextInt(150); i++) {
RuleKey ruleKey = RuleKey.of("repo_" + i, "key_" + i);
RuleDto ruleDto = insertRule(ruleKey.toString());
ruleRepository.register(ruleDto.getUuid(), ruleKey);
}
this.readyRuleDto = insertRule(READY_RULE_KEY);
componentRepository.register(12, SOME_PROJECT_UUID, false);
}
@After
public void tearDown() {
dbSession.close();
}
@Test
public void getDescription_is_set() {
assertThat(underTest.getDescription()).isEqualTo("Export issues");
}
@Test
public void execute_written_writes_no_issues_when_project_has_no_issues() {
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES)).isEmpty();
}
@Test
public void execute_written_writes_no_issues_when_project_has_only_CLOSED_issues() {
insertIssue(readyRuleDto, SOME_PROJECT_UUID, Issue.STATUS_CLOSED);
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES)).isEmpty();
}
@Test
public void execute_fails_with_ISE_if_componentUuid_is_not_set() {
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setComponentUuid(null));
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Issue export failed after processing 0 issues successfully")
.hasRootCauseInstanceOf(NullPointerException.class)
.hasRootCauseMessage("uuid can not be null");
}
@DataProvider
public static Object[][] allStatusesButCLOSED() {
return new Object[][] {
{STATUS_OPEN},
{STATUS_CONFIRMED},
{STATUS_REOPENED},
{STATUS_RESOLVED}
};
}
@Test
@UseDataProvider("allStatusesButCLOSED")
public void execute_writes_issues_with_any_status_but_CLOSED(String status) {
String uuid = insertIssue(readyRuleDto, SOME_PROJECT_UUID, status).getKey();
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES))
.extracting(ProjectDump.Issue::getUuid)
.containsOnly(uuid);
}
@Test
public void execute_writes_issues_from_any_component_in_project_are_written() {
componentRepository.register(13, "module uuid", false);
componentRepository.register(14, "dir uuid", false);
componentRepository.register(15, "file uuid", false);
String projectIssueUuid = insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID)).getKey();
String moduleIssueUuid = insertIssue(createBaseIssueDto(readyRuleDto, "module uuid")).getKey();
String dirIssueUuid = insertIssue(createBaseIssueDto(readyRuleDto, "dir uuid")).getKey();
String fileIssueUuid = insertIssue(createBaseIssueDto(readyRuleDto, "file uuid")).getKey();
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES))
.extracting(ProjectDump.Issue::getUuid)
.containsOnly(projectIssueUuid, moduleIssueUuid, dirIssueUuid, fileIssueUuid);
}
@Test
public void execute_ignores_issues_of_other_projects() {
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setProjectUuid("other project"));
String projectIssueUuid = insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID)).getKey();
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES))
.extracting(ProjectDump.Issue::getUuid)
.containsOnly(projectIssueUuid);
}
@Test
public void verify_field_by_field_mapping() throws InvalidProtocolBufferException {
String componentUuid = "component uuid";
long componentRef = 5454;
componentRepository.register(componentRef, componentUuid, false);
DbIssues.MessageFormattings messageFormattings = DbIssues.MessageFormattings.newBuilder().addMessageFormatting(MESSAGE_FORMATTING).build();
IssueDto issueDto = new IssueDto()
.setKee("issue uuid")
.setComponentUuid(componentUuid)
.setType(988)
.setMessage("msg")
.setMessageFormattings(messageFormattings)
.setLine(10)
.setChecksum("checksum")
.setResolution("resolution")
.setSeverity("severity")
.setManualSeverity(true)
.setGap(13.13d)
.setEffort(99L)
.setAssigneeUuid("assignee-uuid")
.setAuthorLogin("author")
.setTagsString("tags")
.setRuleDescriptionContextKey("test_rule_description_context_key")
.setIssueCreationTime(963L)
.setIssueUpdateTime(852L)
.setIssueCloseTime(741L)
.setCodeVariants(List.of("v1", "v2"));
// fields tested separately and/or required to match SQL request
issueDto
.setType(RuleType.CODE_SMELL)
.setLocations(Locations.newBuilder().addFlow(DbIssues.Flow.newBuilder()).build())
.setRuleUuid(readyRuleDto.getUuid())
.setStatus(STATUS_OPEN).setProjectUuid(SOME_PROJECT_UUID);
insertIssue(issueDto);
underTest.execute(new TestComputationStepContext());
ProjectDump.Issue issue = getWrittenIssue();
assertThat(issue.getUuid()).isEqualTo(issueDto.getKey());
assertThat(issue.getComponentRef()).isEqualTo(componentRef);
assertThat(issue.getType()).isEqualTo(issueDto.getType());
assertThat(issue.getMessage()).isEqualTo(issueDto.getMessage());
assertThat(issue.getLine()).isEqualTo(issueDto.getLine());
assertThat(issue.getChecksum()).isEqualTo(issueDto.getChecksum());
assertThat(issue.getStatus()).isEqualTo(issueDto.getStatus());
assertThat(issue.getResolution()).isEqualTo(issueDto.getResolution());
assertThat(issue.getSeverity()).isEqualTo(issueDto.getSeverity());
assertThat(issue.getManualSeverity()).isEqualTo(issueDto.isManualSeverity());
assertThat(issue.getGap()).isEqualTo(issueDto.getGap());
assertThat(issue.getEffort()).isEqualTo(issueDto.getEffort());
assertThat(issue.getAssignee()).isEqualTo(issueDto.getAssigneeUuid());
assertThat(issue.getAuthor()).isEqualTo(issueDto.getAuthorLogin());
assertThat(issue.getTags()).isEqualTo(issueDto.getTagsString());
assertThat(issue.getRuleDescriptionContextKey()).isEqualTo(issue.getRuleDescriptionContextKey());
assertThat(issue.getIssueCreatedAt()).isEqualTo(issueDto.getIssueCreationTime());
assertThat(issue.getIssueUpdatedAt()).isEqualTo(issueDto.getIssueUpdateTime());
assertThat(issue.getIssueClosedAt()).isEqualTo(issueDto.getIssueCloseTime());
assertThat(issue.getLocations()).isNotEmpty();
assertThat(issue.getMessageFormattingsList())
.isEqualTo(ExportIssuesStep.dbToDumpMessageFormatting(messageFormattings.getMessageFormattingList()));
assertThat(issue.getCodeVariants()).isEqualTo(issueDto.getCodeVariantsString());
}
@Test
public void verify_mapping_of_nullable_numerical_fields_to_defaultValue() {
insertIssue(readyRuleDto, SOME_PROJECT_UUID, STATUS_OPEN);
underTest.execute(new TestComputationStepContext());
ProjectDump.Issue issue = getWrittenIssue();
assertThat(issue.getLine()).isEqualTo(DumpElement.ISSUES.NO_LINE);
assertThat(issue.getGap()).isEqualTo(DumpElement.ISSUES.NO_GAP);
assertThat(issue.getEffort()).isEqualTo(DumpElement.ISSUES.NO_EFFORT);
assertThat(issue.getIssueCreatedAt()).isEqualTo(DumpElement.NO_DATETIME);
assertThat(issue.getIssueUpdatedAt()).isEqualTo(DumpElement.NO_DATETIME);
assertThat(issue.getIssueClosedAt()).isEqualTo(DumpElement.NO_DATETIME);
assertThat(issue.hasRuleDescriptionContextKey()).isFalse();
}
@Test
public void ruleRef_is_ref_provided_by_RuleRepository() {
IssueDto issueDto = insertIssue(readyRuleDto, SOME_PROJECT_UUID, STATUS_OPEN);
underTest.execute(new TestComputationStepContext());
ProjectDump.Issue issue = getWrittenIssue();
assertThat(issue.getRuleRef())
.isEqualTo(ruleRepository.register(issueDto.getRuleUuid(), readyRuleDto.getKey()).ref());
}
@Test
public void locations_is_not_set_in_protobuf_if_null_in_DB() {
insertIssue(readyRuleDto, SOME_PROJECT_UUID, STATUS_OPEN);
underTest.execute(new TestComputationStepContext());
assertThat(getWrittenIssue().getLocations()).isEmpty();
}
@Test
public void message_formattings_is_empty_in_protobuf_if_null_in_DB() {
insertIssue(readyRuleDto, SOME_PROJECT_UUID, STATUS_OPEN);
underTest.execute(new TestComputationStepContext());
assertThat(getWrittenIssue().getMessageFormattingsList()).isEmpty();
}
@Test
public void execute_fails_with_ISE_if_locations_cannot_be_parsed_to_protobuf() throws URISyntaxException, IOException {
byte[] rubbishBytes = getRubbishBytes();
String uuid = insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setLocations(rubbishBytes)).getKey();
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Issue export failed after processing 0 issues successfully");
}
@Test
public void execute_logs_number_total_exported_issue_count_when_successful() {
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID));
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID));
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID));
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("3 issues exported");
}
@Test
public void execute_throws_ISE_with_number_of_successful_exports_before_failure() throws URISyntaxException, IOException {
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID));
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID));
insertIssue(createBaseIssueDto(readyRuleDto, SOME_PROJECT_UUID).setLocations(getRubbishBytes())).getKey();
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Issue export failed after processing 2 issues successfully");
}
private byte[] getRubbishBytes() throws IOException, URISyntaxException {
return FileUtils.readFileToByteArray(new File(getClass().getResource("rubbish_data.txt").toURI()));
}
private ProjectDump.Issue getWrittenIssue() {
return dumpWriter.getWrittenMessagesOf(DumpElement.ISSUES).get(0);
}
// private void expectExportFailure() {
// expectExportFailure(0);
// }
// private void expectExportFailure(int i) {
// expectedException.expect(IllegalStateException.class);
// expectedException.expectMessage("Issue export failed after processing " + i + " issues successfully");
// }
private int issueUuidGenerator = 1;
private IssueDto insertIssue(RuleDto ruleDto, String componentUuid, String status) {
IssueDto dto = createBaseIssueDto(ruleDto, componentUuid, status);
return insertIssue(dto);
}
private IssueDto insertIssue(IssueDto dto) {
dbClient.issueDao().insert(dbSession, dto);
dbSession.commit();
return dto;
}
private ProjectDto createProject() {
ComponentDto projectDto = dbTester.components().insertPrivateProject(c -> c.setKey(PROJECT_KEY).setUuid(SOME_PROJECT_UUID)).getMainBranchComponent();
dbTester.commit();
return dbTester.components().getProjectDtoByMainBranch(projectDto);
}
private IssueDto createBaseIssueDto(RuleDto ruleDto, String componentUuid) {
return createBaseIssueDto(ruleDto, componentUuid, STATUS_OPEN);
}
private IssueDto createBaseIssueDto(RuleDto ruleDto, String componentUuid, String status) {
return new IssueDto()
.setKee("issue_uuid_" + issueUuidGenerator++)
.setComponentUuid(componentUuid)
.setProjectUuid(SOME_PROJECT_UUID)
.setRuleUuid(ruleDto.getUuid())
.setCreatedAt(System2.INSTANCE.now())
.setStatus(status);
}
private RuleDto insertRule(String ruleKey1) {
RuleDto dto = new RuleDto().setRepositoryKey(SOME_REPO).setScope(Scope.MAIN).setRuleKey(ruleKey1).setStatus(RuleStatus.READY);
dbTester.rules().insert(dto);
dbSession.commit();
return dto;
}
}
| 17,142 | 40.914425 | 176 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/rule/ExportAdHocRulesStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.google.common.collect.ImmutableList;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.RandomStringUtils;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.rule.RuleKey;
import org.sonar.api.rule.RuleStatus;
import org.sonar.api.rule.Severity;
import org.sonar.api.rules.RuleType;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.steps.DumpElement;
import org.sonar.ce.task.projectexport.steps.FakeDumpWriter;
import org.sonar.ce.task.projectexport.steps.ProjectHolder;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.ProjectData;
import org.sonar.db.issue.IssueDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.rule.RuleDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ExportAdHocRulesStepIT {
private static final String PROJECT_UUID = "some-uuid";
private static final List<BranchDto> BRANCHES = ImmutableList.of(
new BranchDto().setBranchType(BranchType.PULL_REQUEST).setProjectUuid(PROJECT_UUID).setKey("pr-1").setUuid("pr-1-uuid").setMergeBranchUuid("master").setIsMain(false),
new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(PROJECT_UUID).setKey("branch-2").setUuid("branch-2-uuid").setMergeBranchUuid("master")
.setExcludeFromPurge(true).setIsMain(false),
new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(PROJECT_UUID).setKey("branch-3").setUuid("branch-3-uuid").setMergeBranchUuid("master")
.setExcludeFromPurge(false).setIsMain(false));
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private int issueUuidGenerator = 1;
private ComponentDto mainBranch;
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final ExportAdHocRulesStep underTest = new ExportAdHocRulesStep(dbTester.getDbClient(), projectHolder, dumpWriter);
@Before
public void setup() {
logTester.setLevel(Level.DEBUG);
ProjectDto project = createProject();
when(projectHolder.projectDto()).thenReturn(project);
}
@Test
public void export_zero_ad_hoc_rules() {
underTest.execute(new TestComputationStepContext());
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 ad-hoc rules exported");
}
@Test
public void execute_only_exports_ad_hoc_rules_that_reference_project_issue() {
String differentProject = "diff-proj-uuid";
RuleDto rule1 = insertAddHocRule( "rule-1");
RuleDto rule2 = insertAddHocRule( "rule-2");
insertAddHocRule( "rule-3");
insertIssue(rule1, differentProject, differentProject);
insertIssue(rule2, mainBranch.uuid(), mainBranch.uuid());
underTest.execute(new TestComputationStepContext());
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).hasSize(1);
assertProtobufAdHocRuleIsCorrectlyBuilt(exportedRules.iterator().next(), rule2);
assertThat(logTester.logs(Level.DEBUG)).contains("1 ad-hoc rules exported");
}
@Test
public void execute_only_exports_rules_that_are_ad_hoc() {
RuleDto rule1 = insertStandardRule("rule-1");
RuleDto rule2 = insertExternalRule("rule-2");
RuleDto rule3 = insertAddHocRule("rule-3");
insertIssue(rule1, mainBranch.uuid(), mainBranch.uuid());
insertIssue(rule2, mainBranch.uuid(), mainBranch.uuid());
insertIssue(rule3, mainBranch.uuid(), mainBranch.uuid());
underTest.execute(new TestComputationStepContext());
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).hasSize(1);
assertProtobufAdHocRuleIsCorrectlyBuilt(exportedRules.iterator().next(), rule3);
assertThat(logTester.logs(Level.DEBUG)).contains("1 ad-hoc rules exported");
}
@Test
public void execute_exports_ad_hoc_rules_that_are_referenced_by_issues_on_branches_excluded_from_purge() {
when(projectHolder.branches()).thenReturn(BRANCHES);
RuleDto rule1 = insertAddHocRule("rule-1");
RuleDto rule2 = insertAddHocRule("rule-2");
RuleDto rule3 = insertAddHocRule("rule-3");
insertIssue(rule1, "branch-1-uuid", "branch-1-uuid");
insertIssue(rule2, "branch-2-uuid", "branch-2-uuid");
insertIssue(rule3, "branch-3-uuid", "branch-3-uuid");
underTest.execute(new TestComputationStepContext());
List<ProjectDump.AdHocRule> exportedRules = dumpWriter.getWrittenMessagesOf(DumpElement.AD_HOC_RULES);
assertThat(exportedRules).hasSize(1);
assertProtobufAdHocRuleIsCorrectlyBuilt(exportedRules.iterator().next(), rule2);
assertThat(logTester.logs(Level.DEBUG)).contains("1 ad-hoc rules exported");
}
@Test
public void execute_throws_ISE_with_number_of_successful_exports_before_failure() {
RuleDto rule1 = insertAddHocRule("rule-1");
RuleDto rule2 = insertAddHocRule("rule-2");
RuleDto rule3 = insertAddHocRule("rule-3");
insertIssue(rule1, mainBranch.uuid(), mainBranch.uuid());
insertIssue(rule2, mainBranch.uuid(), mainBranch.uuid());
insertIssue(rule3, mainBranch.uuid(), mainBranch.uuid());
dumpWriter.failIfMoreThan(2, DumpElement.AD_HOC_RULES);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Ad-hoc rules export failed after processing 2 rules successfully");
}
@Test
public void getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Export ad-hoc rules");
}
private ProjectDto createProject() {
Date createdAt = new Date();
ProjectData projectData = dbTester.components().insertPublicProject(PROJECT_UUID);
mainBranch = projectData.getMainBranchComponent();
BRANCHES.forEach(branch -> dbTester.components().insertProjectBranch(projectData.getProjectDto(), branch).setCreatedAt(createdAt));
dbTester.commit();
return projectData.getProjectDto();
}
private void insertIssue(RuleDto ruleDto, String branchUuid, String componentUuid) {
IssueDto dto = createBaseIssueDto(ruleDto, branchUuid, componentUuid);
insertIssue(dto);
}
private void insertIssue(IssueDto dto) {
dbTester.getDbClient().issueDao().insert(dbTester.getSession(), dto);
dbTester.commit();
}
private IssueDto createBaseIssueDto(RuleDto ruleDto, String branchUuid, String componentUuid) {
return new IssueDto()
.setKee("issue_uuid_" + issueUuidGenerator++)
.setComponentUuid(componentUuid)
.setProjectUuid(branchUuid)
.setRuleUuid(ruleDto.getUuid())
.setStatus("OPEN");
}
private RuleDto insertExternalRule(String ruleName) {
RuleDto ruleDto = new RuleDto()
.setIsExternal(true)
.setIsAdHoc(false);
return insertRule(ruleName, ruleDto);
}
private RuleDto insertAddHocRule(String ruleName) {
RuleDto ruleDto = new RuleDto()
.setIsExternal(false)
.setIsAdHoc(true)
.setAdHocName("ad_hoc_rule" + RandomStringUtils.randomAlphabetic(10))
.setAdHocType(RuleType.VULNERABILITY)
.setAdHocSeverity(Severity.CRITICAL)
.setAdHocDescription("ad hoc description: " + RandomStringUtils.randomAlphanumeric(100));
return insertRule(ruleName, ruleDto);
}
private RuleDto insertStandardRule(String ruleName) {
RuleDto ruleDto = new RuleDto()
.setIsExternal(false)
.setIsAdHoc(false);
return insertRule(ruleName, ruleDto);
}
private RuleDto insertRule(String ruleName, RuleDto partiallyInitRuleDto) {
RuleKey ruleKey = RuleKey.of("plugin1", ruleName);
partiallyInitRuleDto
.setName("ruleName" + RandomStringUtils.randomAlphanumeric(10))
.setRuleKey(ruleKey)
.setPluginKey("pluginKey" + RandomStringUtils.randomAlphanumeric(10))
.setStatus(RuleStatus.READY)
.setScope(RuleDto.Scope.ALL);
dbTester.rules().insert(partiallyInitRuleDto);
dbTester.commit();
return dbTester.getDbClient().ruleDao().selectByKey(dbTester.getSession(), ruleKey)
.orElseThrow(() -> new RuntimeException("insertAdHocRule failed"));
}
private static void assertProtobufAdHocRuleIsCorrectlyBuilt(ProjectDump.AdHocRule protobufAdHocRule, RuleDto source) {
assertThat(protobufAdHocRule.getName()).isEqualTo(source.getName());
assertThat(protobufAdHocRule.getRef()).isEqualTo(source.getUuid());
assertThat(protobufAdHocRule.getPluginKey()).isEqualTo(source.getPluginKey());
assertThat(protobufAdHocRule.getPluginRuleKey()).isEqualTo(source.getRuleKey());
assertThat(protobufAdHocRule.getPluginName()).isEqualTo(source.getRepositoryKey());
assertThat(protobufAdHocRule.getName()).isEqualTo(source.getName());
assertThat(protobufAdHocRule.getStatus()).isEqualTo(source.getStatus().name());
assertThat(protobufAdHocRule.getType()).isEqualTo(source.getType());
assertThat(protobufAdHocRule.getScope()).isEqualTo(source.getScope().name());
assertProtobufAdHocRuleIsCorrectlyBuilt(protobufAdHocRule.getMetadata(), source);
}
private static void assertProtobufAdHocRuleIsCorrectlyBuilt(ProjectDump.AdHocRule.RuleMetadata metadata, RuleDto expected) {
assertThat(metadata.getAdHocName()).isEqualTo(expected.getAdHocName());
assertThat(metadata.getAdHocDescription()).isEqualTo(expected.getAdHocDescription());
assertThat(metadata.getAdHocSeverity()).isEqualTo(expected.getAdHocSeverity());
assertThat(metadata.getAdHocType()).isEqualTo(expected.getAdHocType());
}
}
| 11,109 | 43.087302 | 170 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportEventsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.resources.Scopes;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.event.EventDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
public class ExportEventsStepIT {
private static final long NOW = 1_450_000_000_000L;
private static final long IN_THE_PAST = 1_440_000_000_000L;
private static final String PROJECT_UUID = "project_uuid";
private static final ComponentDto PROJECT = new ComponentDto()
.setUuid(PROJECT_UUID)
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid(PROJECT_UUID)
.setScope(Scopes.PROJECT)
.setQualifier(Qualifiers.PROJECT)
.setKey("the_project")
.setEnabled(true);
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
@Rule
public LogTester logTester = new LogTester();
private FakeDumpWriter dumpWriter = new FakeDumpWriter();
private MutableProjectHolder projectHolder = new MutableProjectHolderImpl();
private ComponentRepositoryImpl componentRepository = new ComponentRepositoryImpl();
private ExportEventsStep underTest = new ExportEventsStep(dbTester.getDbClient(), projectHolder, componentRepository, dumpWriter);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
ComponentDto projectDto = dbTester.components().insertPublicProject(PROJECT).getMainBranchComponent();
componentRepository.register(1, projectDto.uuid(), false);
projectHolder.setProjectDto(dbTester.components().getProjectDtoByMainBranch(projectDto));
}
@Test
public void export_zero_events() {
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("0 events exported");
List<ProjectDump.Event> events = dumpWriter.getWrittenMessagesOf(DumpElement.EVENTS);
assertThat(events).isEmpty();
}
@Test
public void export_events() {
SnapshotDto snapshot = insertSnapshot();
insertEvent(snapshot, "E1", "one");
insertEvent(snapshot, "E2", "two");
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("2 events exported");
List<ProjectDump.Event> events = dumpWriter.getWrittenMessagesOf(DumpElement.EVENTS);
assertThat(events).hasSize(2);
assertThat(events).extracting(ProjectDump.Event::getUuid).containsOnly("E1", "E2");
}
@Test
public void throws_ISE_if_error() {
SnapshotDto snapshot = insertSnapshot();
insertEvent(snapshot, "E1", "one");
insertEvent(snapshot, "E2", "two");
dumpWriter.failIfMoreThan(1, DumpElement.EVENTS);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Event Export failed after processing 1 events successfully");
}
@Test
public void export_all_fields() {
SnapshotDto snapshot = insertSnapshot();
dbTester.getDbClient().eventDao().insert(dbTester.getSession(), new EventDto()
.setUuid("E1")
.setAnalysisUuid(snapshot.getUuid())
.setComponentUuid(snapshot.getRootComponentUuid())
.setDate(IN_THE_PAST)
.setCreatedAt(NOW)
.setData("data")
.setName("name")
.setCategory("categ")
.setDescription("desc"));
dbTester.commit();
underTest.execute(new TestComputationStepContext());
ProjectDump.Event event = dumpWriter.getWrittenMessagesOf(DumpElement.EVENTS).get(0);
assertThat(event.getUuid()).isEqualTo("E1");
assertThat(event.getName()).isEqualTo("name");
assertThat(event.getData()).isEqualTo("data");
assertThat(event.getCategory()).isEqualTo("categ");
assertThat(event.getDescription()).isEqualTo("desc");
assertThat(event.getDate()).isEqualTo(IN_THE_PAST);
assertThat(event.getAnalysisUuid()).isEqualTo(snapshot.getUuid());
assertThat(event.getComponentRef()).isOne();
}
@Test
public void getDescription_is_defined() {
assertThat(underTest.getDescription()).isEqualTo("Export events");
}
private void insertEvent(SnapshotDto snapshot, String uuid, String name) {
dbTester.getDbClient().eventDao().insert(dbTester.getSession(), new EventDto()
.setUuid(uuid)
.setAnalysisUuid(snapshot.getUuid())
.setComponentUuid(snapshot.getRootComponentUuid())
.setDate(IN_THE_PAST)
.setCreatedAt(NOW)
.setName(name));
dbTester.commit();
}
private SnapshotDto insertSnapshot() {
SnapshotDto snapshot = new SnapshotDto()
.setUuid("U1")
.setRootComponentUuid(PROJECT.uuid())
.setStatus(STATUS_PROCESSED)
.setLast(false);
dbTester.getDbClient().snapshotDao().insert(dbTester.getSession(), snapshot);
dbTester.commit();
return snapshot;
}
}
| 6,312 | 36.35503 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportLinksStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.Link;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ProjectData;
import org.sonar.db.component.ProjectLinkDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.project.ProjectExportMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.groups.Tuple.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ExportLinksStepIT {
private static final String PROJECT_UUID = "project_uuid";
private ProjectDto projectDto;
@Rule
public DbTester db = DbTester.createWithExtensionMappers(System2.INSTANCE, ProjectExportMapper.class);
@Rule
public LogTester logTester = new LogTester();
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final ExportLinksStep underTest = new ExportLinksStep(db.getDbClient(), projectHolder, dumpWriter);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
ProjectData project = db.components().insertPublicProject(PROJECT_UUID);
this.projectDto = project.getProjectDto();
when(projectHolder.projectDto()).thenReturn(projectDto);
}
@Test
public void export_zero_links() {
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("0 links exported");
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINKS)).isEmpty();
}
@Test
public void export_links() {
ProjectLinkDto link1 = db.projectLinks().insertCustomLink(projectDto);
ProjectLinkDto link2 = db.projectLinks().insertProvidedLink(projectDto);
db.projectLinks().insertCustomLink(db.components().insertPrivateProject().getProjectDto());
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("2 links exported");
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LINKS))
.extracting(Link::getUuid, Link::getName, Link::getType, Link::getHref)
.containsExactlyInAnyOrder(
tuple(link1.getUuid(), link1.getName(), link1.getType(), link1.getHref()),
tuple(link2.getUuid(), "", link2.getType(), link2.getHref()));
}
@Test
public void throws_ISE_if_error() {
db.projectLinks().insertCustomLink(projectDto);
db.projectLinks().insertProvidedLink(projectDto);
db.projectLinks().insertProvidedLink(projectDto);
db.projectLinks().insertCustomLink(db.components().insertPrivateProject().getProjectDto());
dumpWriter.failIfMoreThan(2, DumpElement.LINKS);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Link export failed after processing 2 link(s) successfully");
}
@Test
public void test_all_fields() {
ProjectLinkDto link = db.projectLinks().insertCustomLink(projectDto, l -> l.setName("name").setHref("href").setType("type"));
underTest.execute(new TestComputationStepContext());
Link reloaded = dumpWriter.getWrittenMessagesOf(DumpElement.LINKS).get(0);
assertThat(reloaded.getUuid()).isEqualTo(link.getUuid());
assertThat(reloaded.getName()).isEqualTo(link.getName());
assertThat(reloaded.getHref()).isEqualTo(link.getHref());
assertThat(reloaded.getType()).isEqualTo(link.getType());
}
@Test
public void getDescription_is_defined() {
assertThat(underTest.getDescription()).isEqualTo("Export links");
}
}
| 4,768 | 37.772358 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportLiveMeasuresStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.metric.MetricDto;
import org.sonar.db.project.ProjectDto;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.tuple;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.api.measures.Metric.ValueType.INT;
public class ExportLiveMeasuresStepIT {
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final ComponentRepositoryImpl componentRepository = new ComponentRepositoryImpl();
private final MutableMetricRepository metricRepository = new MutableMetricRepositoryImpl();
private final ProjectHolder projectHolder = mock(ProjectHolder.class);
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ExportLiveMeasuresStep underTest = new ExportLiveMeasuresStep(dbTester.getDbClient(), projectHolder, componentRepository, metricRepository, dumpWriter);
@Before
public void before() {
logTester.setLevel(Level.DEBUG);
}
@Test
public void export_zero_measures() {
when(projectHolder.branches()).thenReturn(newArrayList());
when(projectHolder.projectDto()).thenReturn(new ProjectDto().setUuid("does not exist"));
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES)).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 live measures exported");
assertThat(metricRepository.getRefByUuid()).isEmpty();
}
@Test
public void export_measures() {
ComponentDto project = createProject(true);
componentRepository.register(1, project.uuid(), false);
MetricDto metric = dbTester.measures().insertMetric(m -> m.setKey("metric1").setValueType(INT.name()));
dbTester.measures().insertLiveMeasure(project, metric, m -> m.setValue(4711.0d));
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(project));
when(projectHolder.branches()).thenReturn(newArrayList(new BranchDto()
.setProjectUuid(project.uuid())
.setUuid(project.uuid())
.setKey("master")
.setBranchType(BranchType.BRANCH)));
underTest.execute(new TestComputationStepContext());
List<ProjectDump.LiveMeasure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES);
assertThat(exportedMeasures).hasSize(1);
assertThat(exportedMeasures)
.extracting(ProjectDump.LiveMeasure::getMetricRef, m -> m.getDoubleValue().getValue(), ProjectDump.LiveMeasure::hasVariation)
.containsOnly(tuple(0, 4711.0d, false));
assertThat(logTester.logs(Level.DEBUG)).contains("1 live measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(metric.getUuid());
}
@Test
public void do_not_export_measures_on_disabled_projects() {
ComponentDto project = createProject(false);
componentRepository.register(1, project.uuid(), false);
MetricDto metric = dbTester.measures().insertMetric(m -> m.setValueType(INT.name()));
dbTester.measures().insertLiveMeasure(project, metric, m -> m.setValue(4711.0d));
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(project));
when(projectHolder.branches()).thenReturn(newArrayList(new BranchDto()
.setProjectUuid(project.uuid())
.setUuid(project.uuid())
.setKey("master")
.setBranchType(BranchType.BRANCH)));
underTest.execute(new TestComputationStepContext());
List<ProjectDump.LiveMeasure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES);
assertThat(exportedMeasures).isEmpty();
}
@Test
public void do_not_export_measures_on_disabled_metrics() {
ComponentDto project = createProject(true);
componentRepository.register(1, project.uuid(), false);
MetricDto metric = dbTester.measures().insertMetric(m -> m.setValueType(INT.name()).setEnabled(false));
dbTester.measures().insertLiveMeasure(project, metric, m -> m.setValue(4711.0d));
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(project));
when(projectHolder.branches()).thenReturn(newArrayList(new BranchDto()
.setProjectUuid(project.uuid())
.setUuid(project.uuid())
.setKey("master")
.setBranchType(BranchType.BRANCH)));
underTest.execute(new TestComputationStepContext());
List<ProjectDump.LiveMeasure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES);
assertThat(exportedMeasures).isEmpty();
}
@Test
public void test_exported_fields() {
ComponentDto project = createProject(true);
componentRepository.register(1, project.uuid(), false);
MetricDto metric = dbTester.measures().insertMetric(m -> m.setKey("new_metric").setValueType(INT.name()));
dbTester.measures().insertLiveMeasure(project, metric, m -> m.setProjectUuid(project.uuid()).setValue(7.0d).setData("test"));
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(project));
when(projectHolder.branches()).thenReturn(newArrayList(new BranchDto()
.setProjectUuid(project.uuid())
.setUuid(project.uuid())
.setKey("master")
.setBranchType(BranchType.BRANCH)));
underTest.execute(new TestComputationStepContext());
List<ProjectDump.LiveMeasure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES);
assertThat(exportedMeasures).hasSize(1);
assertThat(exportedMeasures)
.extracting(
ProjectDump.LiveMeasure::getComponentRef,
ProjectDump.LiveMeasure::getMetricRef,
m -> m.getDoubleValue().getValue(),
ProjectDump.LiveMeasure::getTextValue,
m -> m.getVariation().getValue())
.containsOnly(tuple(
1L,
0,
0.0d,
"test",
7.0d));
assertThat(logTester.logs(Level.DEBUG)).contains("1 live measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(metric.getUuid());
}
@Test
public void test_null_exported_fields() {
ComponentDto project = createProject(true);
componentRepository.register(1, project.uuid(), false);
MetricDto metric = dbTester.measures().insertMetric(m -> m.setValueType(INT.name()));
dbTester.measures().insertLiveMeasure(project, metric, m -> m.setProjectUuid(project.uuid()).setValue(null).setData((String) null));
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(project));
when(projectHolder.branches()).thenReturn(newArrayList(new BranchDto()
.setProjectUuid(project.uuid())
.setUuid(project.uuid())
.setKey("master")
.setBranchType(BranchType.BRANCH)));
underTest.execute(new TestComputationStepContext());
List<ProjectDump.LiveMeasure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.LIVE_MEASURES);
assertThat(exportedMeasures).hasSize(1);
assertThat(exportedMeasures)
.extracting(
ProjectDump.LiveMeasure::hasDoubleValue,
ProjectDump.LiveMeasure::getTextValue,
ProjectDump.LiveMeasure::hasVariation)
.containsOnly(tuple(
false,
"",
false));
assertThat(logTester.logs(Level.DEBUG)).contains("1 live measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(metric.getUuid());
}
@Test
public void test_getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Export live measures");
}
private ComponentDto createProject(boolean enabled) {
return dbTester.components().insertPrivateProject(p -> p.setEnabled(enabled)).getMainBranchComponent();
}
}
| 9,286 | 43.435407 | 168 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportMeasuresStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.component.ComponentRepositoryImpl;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.component.SnapshotDto;
import org.sonar.db.measure.MeasureDto;
import org.sonar.db.metric.MetricDto;
import static com.google.common.collect.Lists.newArrayList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.component.ComponentDto.UUID_PATH_SEPARATOR;
import static org.sonar.db.component.SnapshotDto.STATUS_PROCESSED;
import static org.sonar.db.component.SnapshotDto.STATUS_UNPROCESSED;
public class ExportMeasuresStepIT {
private static final ComponentDto PROJECT = new ComponentDto()
.setKey("project_key")
.setUuid("project_uuid")
.setBranchUuid("project_uuid")
.setUuidPath(UUID_PATH_OF_ROOT)
.setEnabled(true);
private static final ComponentDto FILE = new ComponentDto()
.setKey("file_key")
.setUuid("file_uuid")
.setBranchUuid("project_uuid")
.setUuidPath(UUID_PATH_OF_ROOT + PROJECT.uuid() + UUID_PATH_SEPARATOR)
.setEnabled(true);
private static final ComponentDto ANOTHER_PROJECT = new ComponentDto()
.setKey("another_project_key")
.setUuid("another_project_uuid")
.setBranchUuid("another_project_uuid")
.setUuidPath(UUID_PATH_OF_ROOT)
.setEnabled(true);
private static final MetricDto NCLOC = new MetricDto()
.setUuid("3")
.setKey("ncloc")
.setShortName("Lines of code")
.setEnabled(true);
private static final MetricDto DISABLED_METRIC = new MetricDto()
.setUuid("4")
.setKey("coverage")
.setShortName("Coverage")
.setEnabled(false);
private static final MetricDto NEW_NCLOC = new MetricDto()
.setUuid("5")
.setKey("new_ncloc")
.setShortName("New Lines of code")
.setEnabled(true);
private static final List<BranchDto> BRANCHES = newArrayList(
new BranchDto()
.setBranchType(BranchType.BRANCH)
.setKey("master")
.setUuid(PROJECT.uuid())
.setProjectUuid(PROJECT.uuid()));
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private ComponentRepositoryImpl componentRepository = new ComponentRepositoryImpl();
private MutableMetricRepository metricRepository = new MutableMetricRepositoryImpl();
private ProjectHolder projectHolder = mock(ProjectHolder.class);
private FakeDumpWriter dumpWriter = new FakeDumpWriter();
private ExportMeasuresStep underTest = new ExportMeasuresStep(dbTester.getDbClient(), projectHolder, componentRepository, metricRepository, dumpWriter);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
String projectUuid = dbTester.components().insertPublicProject(PROJECT).getMainBranchComponent().uuid();
componentRepository.register(1, projectUuid, false);
dbTester.getDbClient().componentDao().insert(dbTester.getSession(), List.of(FILE, ANOTHER_PROJECT), true);
dbTester.getDbClient().metricDao().insert(dbTester.getSession(), NCLOC, DISABLED_METRIC, NEW_NCLOC);
dbTester.commit();
when(projectHolder.projectDto()).thenReturn(dbTester.components().getProjectDtoByMainBranch(PROJECT));
when(projectHolder.branches()).thenReturn(BRANCHES);
}
@Test
public void export_zero_measures() {
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES)).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 measures exported");
assertThat(metricRepository.getRefByUuid()).isEmpty();
}
@Test
public void export_measures() {
SnapshotDto firstAnalysis = insertSnapshot("U_1", PROJECT, STATUS_PROCESSED);
insertMeasure(firstAnalysis, PROJECT, new MeasureDto().setValue(100.0).setMetricUuid(NCLOC.getUuid()));
SnapshotDto secondAnalysis = insertSnapshot("U_2", PROJECT, STATUS_PROCESSED);
insertMeasure(secondAnalysis, PROJECT, new MeasureDto().setValue(110.0).setMetricUuid(NCLOC.getUuid()));
SnapshotDto anotherProjectAnalysis = insertSnapshot("U_3", ANOTHER_PROJECT, STATUS_PROCESSED);
insertMeasure(anotherProjectAnalysis, ANOTHER_PROJECT, new MeasureDto().setValue(500.0).setMetricUuid(NCLOC.getUuid()));
dbTester.commit();
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Measure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES);
assertThat(exportedMeasures).hasSize(2);
assertThat(exportedMeasures).extracting(ProjectDump.Measure::getAnalysisUuid).containsOnly(firstAnalysis.getUuid(), secondAnalysis.getUuid());
assertThat(exportedMeasures).extracting(ProjectDump.Measure::getMetricRef).containsOnly(0);
assertThat(logTester.logs(Level.DEBUG)).contains("2 measures exported");
assertThat(metricRepository.getRefByUuid()).containsOnlyKeys(NCLOC.getUuid());
}
@Test
public void do_not_export_measures_on_unprocessed_snapshots() {
SnapshotDto firstAnalysis = insertSnapshot("U_1", PROJECT, STATUS_UNPROCESSED);
insertMeasure(firstAnalysis, PROJECT, new MeasureDto().setValue(100.0).setMetricUuid(NCLOC.getUuid()));
dbTester.commit();
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Measure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES);
assertThat(exportedMeasures).isEmpty();
}
@Test
public void do_not_export_measures_on_disabled_metrics() {
SnapshotDto firstAnalysis = insertSnapshot("U_1", PROJECT, STATUS_PROCESSED);
insertMeasure(firstAnalysis, PROJECT, new MeasureDto().setValue(100.0).setMetricUuid(DISABLED_METRIC.getUuid()));
dbTester.commit();
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Measure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES);
assertThat(exportedMeasures).isEmpty();
}
@Test
public void test_exported_fields() {
SnapshotDto analysis = insertSnapshot("U_1", PROJECT, STATUS_PROCESSED);
MeasureDto dto = new MeasureDto()
.setMetricUuid(NCLOC.getUuid())
.setValue(100.0)
.setData("data")
.setAlertStatus("OK")
.setAlertText("alert text");
insertMeasure(analysis, PROJECT, dto);
dbTester.commit();
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Measure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES);
ProjectDump.Measure measure = exportedMeasures.get(0);
assertThat(measure.getAlertStatus()).isEqualTo(dto.getAlertStatus());
assertThat(measure.getAlertText()).isEqualTo(dto.getAlertText());
assertThat(measure.getDoubleValue().getValue()).isEqualTo(dto.getValue());
assertThat(measure.getTextValue()).isEqualTo(dto.getData());
assertThat(measure.getMetricRef()).isZero();
assertThat(measure.getAnalysisUuid()).isEqualTo(analysis.getUuid());
assertThat(measure.getVariation1().getValue()).isZero();
}
@Test
public void test_exported_fields_new_metric() {
SnapshotDto analysis = insertSnapshot("U_1", PROJECT, STATUS_PROCESSED);
MeasureDto dto = new MeasureDto()
.setMetricUuid(NEW_NCLOC.getUuid())
.setValue(100.0)
.setData("data")
.setAlertStatus("OK")
.setAlertText("alert text");
insertMeasure(analysis, PROJECT, dto);
dbTester.commit();
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Measure> exportedMeasures = dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES);
ProjectDump.Measure measure = exportedMeasures.get(0);
assertThat(measure.getAlertStatus()).isEqualTo(dto.getAlertStatus());
assertThat(measure.getAlertText()).isEqualTo(dto.getAlertText());
assertThat(measure.getDoubleValue().getValue()).isZero();
assertThat(measure.getTextValue()).isEqualTo(dto.getData());
assertThat(measure.getMetricRef()).isZero();
assertThat(measure.getAnalysisUuid()).isEqualTo(analysis.getUuid());
assertThat(measure.getVariation1().getValue()).isEqualTo(dto.getValue());
}
@Test
public void test_null_exported_fields() {
SnapshotDto analysis = insertSnapshot("U_1", PROJECT, STATUS_PROCESSED);
insertMeasure(analysis, PROJECT, new MeasureDto().setMetricUuid(NCLOC.getUuid()));
dbTester.commit();
underTest.execute(new TestComputationStepContext());
ProjectDump.Measure measure = dumpWriter.getWrittenMessagesOf(DumpElement.MEASURES).get(0);
assertThat(measure.getAlertStatus()).isEmpty();
assertThat(measure.getAlertText()).isEmpty();
assertThat(measure.hasDoubleValue()).isFalse();
assertThat(measure.getTextValue()).isEmpty();
assertThat(measure.hasVariation1()).isFalse();
}
@Test
public void test_getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Export measures");
}
private SnapshotDto insertSnapshot(String snapshotUuid, ComponentDto project, String status) {
SnapshotDto snapshot = new SnapshotDto()
.setUuid(snapshotUuid)
.setRootComponentUuid(project.uuid())
.setStatus(status)
.setLast(true);
dbTester.getDbClient().snapshotDao().insert(dbTester.getSession(), snapshot);
return snapshot;
}
private void insertMeasure(SnapshotDto analysisDto, ComponentDto componentDto, MeasureDto measureDto) {
measureDto
.setAnalysisUuid(analysisDto.getUuid())
.setComponentUuid(componentDto.uuid());
dbTester.getDbClient().measureDao().insert(dbTester.getSession(), measureDto);
}
}
| 10,969 | 41.030651 | 154 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportMetricsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.List;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.metric.MetricDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class ExportMetricsStepIT {
private static final MetricDto NCLOC = new MetricDto()
.setUuid("1")
.setKey("ncloc")
.setShortName("Lines of code")
.setEnabled(true);
private static final MetricDto COVERAGE = new MetricDto()
.setUuid("2")
.setKey("coverage")
.setShortName("Coverage")
.setEnabled(true);
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
MutableMetricRepository metricsHolder = new MutableMetricRepositoryImpl();
FakeDumpWriter dumpWriter = new FakeDumpWriter();
ExportMetricsStep underTest = new ExportMetricsStep(dbTester.getDbClient(), metricsHolder, dumpWriter);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
dbTester.getDbClient().metricDao().insert(dbTester.getSession(), NCLOC, COVERAGE);
dbTester.commit();
}
@Test
public void export_zero_metrics() {
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("0 metrics exported");
}
@Test
public void export_metrics() {
metricsHolder.add(NCLOC.getUuid());
metricsHolder.add(COVERAGE.getUuid());
underTest.execute(new TestComputationStepContext());
assertThat(logTester.logs(Level.DEBUG)).contains("2 metrics exported");
List<ProjectDump.Metric> exportedMetrics = dumpWriter.getWrittenMessagesOf(DumpElement.METRICS);
ProjectDump.Metric ncloc = exportedMetrics.stream().filter(input -> input.getRef() == 0).findAny().orElseThrow();
assertThat(ncloc.getRef()).isZero();
assertThat(ncloc.getKey()).isEqualTo("ncloc");
assertThat(ncloc.getName()).isEqualTo("Lines of code");
ProjectDump.Metric coverage = exportedMetrics.stream().filter(input -> input.getRef() == 1).findAny().orElseThrow();
assertThat(coverage.getRef()).isOne();
assertThat(coverage.getKey()).isEqualTo("coverage");
assertThat(coverage.getName()).isEqualTo("Coverage");
}
@Test
public void throw_ISE_if_error() {
metricsHolder.add(NCLOC.getUuid());
dumpWriter.failIfMoreThan(0, DumpElement.METRICS);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Metric Export failed after processing 0 metrics successfully");
}
@Test
public void test_getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Export metrics");
}
}
| 3,904 | 34.18018 | 120 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportNewCodePeriodsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.ImmutableList;
import com.sonarsource.governance.projectdump.protobuf.ProjectDump;
import java.util.Date;
import java.util.List;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.newcodeperiod.NewCodePeriodDto;
import org.sonar.db.newcodeperiod.NewCodePeriodType;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.project.ProjectExportMapper;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.PREVIOUS_VERSION;
import static org.sonar.db.newcodeperiod.NewCodePeriodType.SPECIFIC_ANALYSIS;
public class ExportNewCodePeriodsStepIT {
private static final String PROJECT_UUID = "project_uuid";
private static final String ANOTHER_PROJECT_UUID = "another_project_uuid";
private static final ComponentDto ANOTHER_PROJECT = new ComponentDto()
.setUuid(ANOTHER_PROJECT_UUID)
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid(ANOTHER_PROJECT_UUID)
.setQualifier(Qualifiers.PROJECT)
.setName("another_project")
.setKey("another_project");
private static final List<BranchDto> PROJECT_BRANCHES = ImmutableList.of(
new BranchDto().setBranchType(BranchType.PULL_REQUEST).setProjectUuid(PROJECT_UUID).setKey("pr-1").setUuid("pr-uuid-1").setMergeBranchUuid("master").setIsMain(false),
new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(PROJECT_UUID).setKey("branch-1").setUuid("branch-uuid-1").setMergeBranchUuid("master")
.setExcludeFromPurge(true).setIsMain(false),
new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(PROJECT_UUID).setKey("branch-2").setUuid("branch-uuid-2").setMergeBranchUuid("master")
.setExcludeFromPurge(false).setIsMain(false));
private static final List<BranchDto> ANOTHER_PROJECT_BRANCHES = ImmutableList.of(
new BranchDto().setBranchType(BranchType.BRANCH).setProjectUuid(ANOTHER_PROJECT_UUID).setKey("branch-3").setUuid("branch-uuid-3").setMergeBranchUuid("master")
.setExcludeFromPurge(true).setIsMain(false));
private ProjectDto project;
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.createWithExtensionMappers(System2.INSTANCE, ProjectExportMapper.class);
private MutableProjectHolder projectHolder = new MutableProjectHolderImpl();
private FakeDumpWriter dumpWriter = new FakeDumpWriter();
private ExportNewCodePeriodsStep underTest = new ExportNewCodePeriodsStep(dbTester.getDbClient(), projectHolder, dumpWriter);
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
Date createdAt = new Date();
project = dbTester.components().insertPrivateProject(PROJECT_UUID).getProjectDto();
PROJECT_BRANCHES.forEach(branch -> dbTester.components().insertProjectBranch(project, branch).setCreatedAt(createdAt));
ComponentDto anotherProjectDto = dbTester.components().insertPublicProject(ANOTHER_PROJECT).getMainBranchComponent();
ANOTHER_PROJECT_BRANCHES.forEach(branch -> dbTester.components().insertProjectBranch(anotherProjectDto, branch).setCreatedAt(createdAt));
dbTester.commit();
projectHolder.setProjectDto(project);
}
@Test
public void export_zero_new_code_periods() {
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.NEW_CODE_PERIODS)).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 new code periods exported");
}
@Test
public void export_only_project_new_code_periods_on_branches_excluded_from_purge() {
NewCodePeriodDto newCodePeriod1 = newDto("uuid1", project.getUuid(), null, SPECIFIC_ANALYSIS, "analysis-uuid");
NewCodePeriodDto newCodePeriod2 = newDto("uuid2", project.getUuid(), "branch-uuid-1", SPECIFIC_ANALYSIS, "analysis-uuid");
// the following new code periods are not exported
NewCodePeriodDto newCodePeriod3 = newDto("uuid3", project.getUuid(), "branch-uuid-2", SPECIFIC_ANALYSIS, "analysis-uuid");
NewCodePeriodDto anotherProjectNewCodePeriods = newDto("uuid4", ANOTHER_PROJECT.uuid(), "branch-uuid-3", SPECIFIC_ANALYSIS, "analysis-uuid");
NewCodePeriodDto globalNewCodePeriod = newDto("uuid5", null, null, PREVIOUS_VERSION, null);
insertNewCodePeriods(newCodePeriod1, newCodePeriod2, newCodePeriod3, anotherProjectNewCodePeriods, globalNewCodePeriod);
underTest.execute(new TestComputationStepContext());
List<ProjectDump.NewCodePeriod> exportedProps = dumpWriter.getWrittenMessagesOf(DumpElement.NEW_CODE_PERIODS);
assertThat(exportedProps).hasSize(2);
assertThat(exportedProps).extracting(ProjectDump.NewCodePeriod::getUuid).containsOnly("uuid1", "uuid2");
assertThat(logTester.logs(Level.DEBUG)).contains("2 new code periods exported");
}
@Test
public void test_exported_fields() {
NewCodePeriodDto dto = newDto("uuid1", project.getUuid(), "branch-uuid-1", SPECIFIC_ANALYSIS, "analysis-uuid");
insertNewCodePeriods(dto);
underTest.execute(new TestComputationStepContext());
ProjectDump.NewCodePeriod exportedNewCodePeriod = dumpWriter.getWrittenMessagesOf(DumpElement.NEW_CODE_PERIODS).get(0);
assertThat(exportedNewCodePeriod.getUuid()).isEqualTo(dto.getUuid());
assertThat(exportedNewCodePeriod.getProjectUuid()).isEqualTo(dto.getProjectUuid());
assertThat(exportedNewCodePeriod.getBranchUuid()).isEqualTo(dto.getBranchUuid());
assertThat(exportedNewCodePeriod.getType()).isEqualTo(dto.getType().name());
assertThat(exportedNewCodePeriod.getValue()).isEqualTo(dto.getValue());
}
@Test
public void throws_ISE_if_error() {
dumpWriter.failIfMoreThan(1, DumpElement.NEW_CODE_PERIODS);
insertNewCodePeriods(
newDto("uuid1", project.getUuid(), null, SPECIFIC_ANALYSIS, "analysis-uuid"),
newDto("uuid2", project.getUuid(), "branch-uuid-1", SPECIFIC_ANALYSIS, "analysis-uuid"));
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("New Code Periods Export failed after processing 1 new code periods successfully");
}
@Test
public void test_getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Export new code periods");
}
private static NewCodePeriodDto newDto(String uuid, @Nullable String projectUuid, @Nullable String branchUuid, NewCodePeriodType type, @Nullable String value) {
return new NewCodePeriodDto()
.setUuid(uuid)
.setProjectUuid(projectUuid)
.setBranchUuid(branchUuid)
.setType(type)
.setValue(value);
}
private void insertNewCodePeriods(NewCodePeriodDto... dtos) {
for (NewCodePeriodDto dto : dtos) {
dbTester.getDbClient().newCodePeriodDao().insert(dbTester.getSession(), dto);
}
dbTester.commit();
}
}
| 8,260 | 47.02907 | 170 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/ExportSettingsStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.List;
import javax.annotation.Nullable;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.slf4j.event.Level;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.testfixtures.log.LogTester;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.entity.EntityDto;
import org.sonar.db.project.ProjectDto;
import org.sonar.db.project.ProjectExportMapper;
import org.sonar.db.property.PropertyDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.sonar.db.component.ComponentDto.UUID_PATH_OF_ROOT;
public class ExportSettingsStepIT {
private static final ComponentDto PROJECT = new ComponentDto()
.setUuid("project_uuid")
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid("project_uuid")
.setKey("the_project");
private static final ComponentDto ANOTHER_PROJECT = new ComponentDto()
.setUuid("another_project_uuid")
.setUuidPath(UUID_PATH_OF_ROOT)
.setBranchUuid("another_project_uuid")
.setKey("another_project");
@Rule
public LogTester logTester = new LogTester();
@Rule
public DbTester dbTester = DbTester.createWithExtensionMappers(System2.INSTANCE, ProjectExportMapper.class);
private final MutableProjectHolder projectHolder = new MutableProjectHolderImpl();
private final FakeDumpWriter dumpWriter = new FakeDumpWriter();
private final ExportSettingsStep underTest = new ExportSettingsStep(dbTester.getDbClient(), projectHolder, dumpWriter);
private ProjectDto project;
private ProjectDto anotherProject;
@Before
public void setUp() {
logTester.setLevel(Level.DEBUG);
project = dbTester.components().insertPublicProject(PROJECT).getProjectDto();
anotherProject = dbTester.components().insertPublicProject(ANOTHER_PROJECT).getProjectDto();
dbTester.commit();
projectHolder.setProjectDto(project);
}
@Test
public void export_zero_settings() {
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS)).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 settings exported");
}
@Test
public void export_only_project_settings() {
PropertyDto projectProperty1 = newDto("p1", "v1", project);
PropertyDto projectProperty2 = newDto("p2", "v2", project);
// the following properties are not exported
PropertyDto propOnOtherProject = newDto("p3", "v3", anotherProject);
PropertyDto globalProperty = newDto("p4", "v4", null);
insertProperties(project.getKey(), project.getName(), projectProperty1, projectProperty2);
insertProperties(anotherProject.getKey(), anotherProject.getName(), propOnOtherProject);
insertProperties(null, null, globalProperty);
underTest.execute(new TestComputationStepContext());
List<ProjectDump.Setting> exportedProps = dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS);
assertThat(exportedProps).hasSize(2);
assertThat(exportedProps).extracting(ProjectDump.Setting::getKey).containsOnly("p1", "p2");
assertThat(logTester.logs(Level.DEBUG)).contains("2 settings exported");
}
@Test
public void exclude_properties_specific_to_environment() {
insertProperties(project.getKey(), project.getName(), newDto("sonar.issues.defaultAssigneeLogin", null, project));
underTest.execute(new TestComputationStepContext());
assertThat(dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS)).isEmpty();
assertThat(logTester.logs(Level.DEBUG)).contains("0 settings exported");
}
@Test
public void test_exported_fields() {
PropertyDto dto = newDto("p1", "v1", project);
insertProperties(project.getKey(), project.getName(), dto);
underTest.execute(new TestComputationStepContext());
ProjectDump.Setting exportedProp = dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS).get(0);
assertThat(exportedProp.getKey()).isEqualTo(dto.getKey());
assertThat(exportedProp.getValue()).isEqualTo(dto.getValue());
}
@Test
public void property_can_have_empty_value() {
insertProperties(project.getKey(), project.getName(), newDto("p1", null, project));
underTest.execute(new TestComputationStepContext());
ProjectDump.Setting exportedProp = dumpWriter.getWrittenMessagesOf(DumpElement.SETTINGS).get(0);
assertThat(exportedProp.getKey()).isEqualTo("p1");
assertThat(exportedProp.getValue()).isEmpty();
}
@Test
public void throws_ISE_if_error() {
dumpWriter.failIfMoreThan(1, DumpElement.SETTINGS);
insertProperties(project.getKey(), project.getName(), newDto("p1", null, project),
newDto("p2", null, project));
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(IllegalStateException.class)
.hasMessage("Settings Export failed after processing 1 settings successfully");
}
@Test
public void test_getDescription() {
assertThat(underTest.getDescription()).isEqualTo("Export settings");
}
private static PropertyDto newDto(String key, @Nullable String value, @Nullable EntityDto project) {
PropertyDto dto = new PropertyDto().setKey(key).setValue(value);
if (project != null) {
dto.setEntityUuid(project.getUuid());
}
return dto;
}
private void insertProperties(@Nullable String entityKey, @Nullable String entityName, PropertyDto... dtos) {
for (PropertyDto dto : dtos) {
dbTester.getDbClient().propertiesDao().saveProperty(dbTester.getSession(), dto, null, entityKey, entityName, Qualifiers.VIEW);
}
dbTester.commit();
}
}
| 6,718 | 39.233533 | 132 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/java/org/sonar/ce/task/projectexport/steps/LoadProjectStepIT.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.Rule;
import org.junit.Test;
import org.sonar.api.resources.Qualifiers;
import org.sonar.api.utils.MessageException;
import org.sonar.api.utils.System2;
import org.sonar.ce.task.projectexport.taskprocessor.ProjectDescriptor;
import org.sonar.ce.task.step.TestComputationStepContext;
import org.sonar.db.DbTester;
import org.sonar.db.component.ComponentDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
public class LoadProjectStepIT {
private static final String PROJECT_KEY = "project_key";
@Rule
public DbTester dbTester = DbTester.create(System2.INSTANCE);
private final ProjectDescriptor descriptor = new ProjectDescriptor("project_uuid", PROJECT_KEY, "Project Name");
private final MutableProjectHolder definitionHolder = new MutableProjectHolderImpl();
private final LoadProjectStep underTest = new LoadProjectStep(descriptor, definitionHolder, dbTester.getDbClient());
@Test
public void fails_if_project_does_not_exist() {
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(MessageException.class)
.hasMessage("Project with key [project_key] does not exist");
}
@Test
public void fails_if_component_is_not_a_project() {
// insert a module, but not a project
dbTester.executeInsert("projects",
"kee", PROJECT_KEY,
"qualifier", Qualifiers.APP,
"uuid", "not_used",
"private", false,
"created_at", 1L,
"updated_at", 1L);
assertThatThrownBy(() -> underTest.execute(new TestComputationStepContext()))
.isInstanceOf(MessageException.class)
.hasMessage("Project with key [project_key] does not exist");
}
@Test
public void registers_project_if_valid() {
ComponentDto project = dbTester.components().insertPublicProject(c -> c.setKey(PROJECT_KEY)).getMainBranchComponent();
underTest.execute(new TestComputationStepContext());
assertThat(definitionHolder.projectDto().getKey()).isEqualTo(project.getKey());
}
@Test
public void getDescription_is_defined() {
assertThat(underTest.getDescription()).isNotEmpty();
}
}
| 3,078 | 37.012346 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v1/AddAnalysisUuidColumnToDuplicationsIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepTest.v1;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.db.version.AddColumnsBuilder;
import static org.sonar.db.version.VarcharColumnDef.UUID_VARCHAR_SIZE;
import static org.sonar.db.version.VarcharColumnDef.newVarcharColumnDefBuilder;
public class AddAnalysisUuidColumnToDuplicationsIndex extends DdlChange {
private static final String TABLE_DUPLICATIONS_INDEX = "duplications_index";
public AddAnalysisUuidColumnToDuplicationsIndex(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
context.execute(new AddColumnsBuilder(getDatabase().getDialect(), TABLE_DUPLICATIONS_INDEX)
.addColumn(newVarcharColumnDefBuilder().setColumnName("analysis_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(true).build())
.build());
}
}
| 1,752 | 37.955556 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v1/AddComponentUuidColumnToDuplicationsIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepTest.v1;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.db.version.AddColumnsBuilder;
import static org.sonar.db.version.VarcharColumnDef.UUID_VARCHAR_SIZE;
import static org.sonar.db.version.VarcharColumnDef.newVarcharColumnDefBuilder;
public class AddComponentUuidAndAnalysisUuidColumnToDuplicationsIndex extends DdlChange {
private static final String TABLE_PUBLICATIONS_INDEX = "duplications_index";
public AddComponentUuidAndAnalysisUuidColumnToDuplicationsIndex(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
context.execute(new AddColumnsBuilder(getDatabase().getDialect(), TABLE_PUBLICATIONS_INDEX)
.addColumn(newVarcharColumnDefBuilder().setColumnName("component_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(true).build())
.addColumn(newVarcharColumnDefBuilder().setColumnName("analysis_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(true).build())
.build());
}
}
| 1,919 | 40.73913 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v1/DeleteOrphanDuplicationsIndexRowsWithoutComponent.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepTest.v1;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.server.platform.db.migration.step.MassUpdate;
public class DeleteOrphanDuplicationsIndexRowsWithoutComponent extends BaseDataChange {
public DeleteOrphanDuplicationsIndexRowsWithoutComponent(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
MassUpdate massUpdate = context.prepareMassUpdate();
massUpdate.select("SELECT id from duplications_index where component_uuid is null");
massUpdate.update("DELETE from duplications_index WHERE id=?");
massUpdate.rowPluralName("resources_index entries");
massUpdate.execute((row, update) -> {
update.setLong(1, row.getLong(1));
return true;
});
}
}
| 1,693 | 36.644444 | 88 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v1/MakeComponentUuidNotNullOnDuplicationsIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepTest.v1;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.db.version.AlterColumnsBuilder;
import static org.sonar.db.version.VarcharColumnDef.UUID_VARCHAR_SIZE;
import static org.sonar.db.version.VarcharColumnDef.newVarcharColumnDefBuilder;
public class MakeComponentUuidNotNullOnDuplicationsIndex extends DdlChange {
private static final String TABLE_DUPLICATIONS_INDEX = "duplications_index";
public MakeComponentUuidNotNullOnDuplicationsIndex(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
context.execute(new AlterColumnsBuilder(getDatabase().getDialect(), TABLE_DUPLICATIONS_INDEX)
.updateColumn(newVarcharColumnDefBuilder().setColumnName("component_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(false).build())
.build());
}
}
| 1,767 | 38.288889 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v2/AddComponentUuidAndAnalysisUuidColumnToDuplicationsIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepTest.v2;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.db.version.AddColumnsBuilder;
import static org.sonar.db.version.VarcharColumnDef.UUID_VARCHAR_SIZE;
import static org.sonar.db.version.VarcharColumnDef.newVarcharColumnDefBuilder;
public class AddComponentUuidColumnToDuplicationsIndex extends DdlChange {
private static final String TABLE_PUBLICATIONS_INDEX = "duplications_index";
public AddComponentUuidColumnToDuplicationsIndex(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
context.execute(new AddColumnsBuilder(getDatabase().getDialect(), TABLE_PUBLICATIONS_INDEX)
.addColumn(newVarcharColumnDefBuilder().setColumnName("component_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(true).build())
.build());
}
}
| 1,755 | 38.022222 | 134 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/it/resources/org/sonar/ce/task/projectanalysis/filemove/FileMoveDetectionStepIT/v2/MakeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.filemove.FileMoveDetectionStepTest.v2;
import java.sql.SQLException;
import org.sonar.db.Database;
import org.sonar.db.version.AlterColumnsBuilder;
import static org.sonar.db.version.VarcharColumnDef.UUID_VARCHAR_SIZE;
import static org.sonar.db.version.VarcharColumnDef.newVarcharColumnDefBuilder;
public class MakeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex extends DdlChange {
private static final String TABLE_DUPLICATIONS_INDEX = "duplications_index";
public MakeComponentUuidAndAnalysisUuidNotNullOnDuplicationsIndex(Database db) {
super(db);
}
@Override
public void execute(Context context) throws SQLException {
context.execute(new AlterColumnsBuilder(getDatabase().getDialect(), TABLE_DUPLICATIONS_INDEX)
.updateColumn(newVarcharColumnDefBuilder().setColumnName("component_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(false).build())
.updateColumn(newVarcharColumnDefBuilder().setColumnName("analysis_uuid").setLimit(UUID_VARCHAR_SIZE).setIsNullable(false).build())
.build());
}
}
| 1,935 | 41.086957 | 138 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/ProjectAnalysisTaskModule.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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;
import org.sonar.ce.task.projectanalysis.container.ContainerFactoryImpl;
import org.sonar.ce.task.projectanalysis.taskprocessor.ReportTaskProcessor;
import org.sonar.ce.task.projectexport.taskprocessor.ProjectExportTaskProcessor;
import org.sonar.ce.task.step.ComputationStepExecutor;
import org.sonar.core.platform.Module;
public class ProjectAnalysisTaskModule extends Module {
@Override
protected void configureModule() {
add(
// task
ContainerFactoryImpl.class,
ComputationStepExecutor.class,
ReportTaskProcessor.class,
ProjectExportTaskProcessor.class);
}
}
| 1,491 | 37.25641 | 80 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/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.projectanalysis;
import javax.annotation.ParametersAreNonnullByDefault;
| 973 | 39.583333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/Analysis.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.Objects;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static com.google.common.base.Preconditions.checkNotNull;
@Immutable
public class Analysis {
private String uuid;
private long createdAt;
private Analysis(Builder builder) {
this.uuid = builder.uuid;
this.createdAt = builder.createdAt;
}
public String getUuid() {
return uuid;
}
public long getCreatedAt() {
return createdAt;
}
public static final class Builder {
@CheckForNull
private String uuid;
@CheckForNull
private Long createdAt;
public Builder setUuid(String uuid) {
this.uuid = uuid;
return this;
}
public Builder setCreatedAt(long createdAt) {
this.createdAt = createdAt;
return this;
}
public Analysis build() {
checkNotNull(uuid, "uuid cannot be null");
checkNotNull(createdAt, "createdAt cannot be null");
return new Analysis(this);
}
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Analysis analysis = (Analysis) o;
return Objects.equals(uuid, analysis.uuid);
}
@Override
public int hashCode() {
return Objects.hash(uuid);
}
@Override
public String toString() {
return "Analysis{" +
"uuid='" + uuid + '\'' +
", createdAt=" + createdAt +
'}';
}
}
| 2,422 | 23.979381 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisFromSonarQube94Visitor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 org.sonar.api.measures.CoreMetrics;
import org.sonar.ce.task.projectanalysis.component.Component;
import org.sonar.ce.task.projectanalysis.component.CrawlerDepthLimit;
import org.sonar.ce.task.projectanalysis.component.PathAwareVisitorAdapter;
import org.sonar.ce.task.projectanalysis.measure.Measure;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
public class AnalysisFromSonarQube94Visitor extends PathAwareVisitorAdapter<AnalysisFromSonarQube94Visitor.AnalysisFromSonarQube94> {
private final MeasureRepository measureRepository;
private final Metric analysisFromSonarQube94Metric;
public AnalysisFromSonarQube94Visitor(MetricRepository metricRepository, MeasureRepository measureRepository) {
super(CrawlerDepthLimit.PROJECT, Order.PRE_ORDER, new AnalysisFromSonarQube94StackFactory());
this.measureRepository = measureRepository;
this.analysisFromSonarQube94Metric = metricRepository.getByKey(CoreMetrics.ANALYSIS_FROM_SONARQUBE_9_4_KEY);
}
@Override
public void visitProject(Component project, Path<AnalysisFromSonarQube94Visitor.AnalysisFromSonarQube94> path) {
measureRepository.add(project, analysisFromSonarQube94Metric, Measure.newMeasureBuilder().create(path.current().sonarQube94OrGreater));
}
public static final class AnalysisFromSonarQube94StackFactory extends SimpleStackElementFactory<AnalysisFromSonarQube94> {
@Override
public AnalysisFromSonarQube94 createForAny(Component component) {
return new AnalysisFromSonarQube94();
}
/** Stack item is not used at ProjectView level, saves on instantiating useless objects */
@Override
public AnalysisFromSonarQube94 createForProjectView(Component projectView) {
return null;
}
}
public static final class AnalysisFromSonarQube94 {
final boolean sonarQube94OrGreater = true;
}
}
| 2,879 | 42.636364 | 139 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 org.sonar.server.project.Project;
import org.sonar.server.qualityprofile.QualityProfile;
public interface AnalysisMetadataHolder {
/**
* Returns the UUID generated for this analysis.
* @throws IllegalStateException if uuid has not been set
*/
String getUuid();
/**
* @throws IllegalStateException if no analysis date has been set
*/
long getAnalysisDate();
/**
* Tell whether the analysisDate has been set.
*/
boolean hasAnalysisDateBeenSet();
/**
* Convenience method equivalent to calling {@link #getBaseAnalysis() == null}
*
* @throws IllegalStateException if baseProjectSnapshot has not been set
*/
boolean isFirstAnalysis();
/**
* Return the last analysis of the project.
* If it's the first analysis, it will return null.
*
* @throws IllegalStateException if baseAnalysis has not been set
*/
@CheckForNull
Analysis getBaseAnalysis();
/**
* Convenience method equivalent to do the check using {@link #getBranch()}
*
* @throws IllegalStateException if branch has not been set
*/
boolean isBranch();
/**
* Convenience method equivalent to do the check using {@link #getBranch()}
*
* @throws IllegalStateException if branch has not been set
*/
boolean isPullRequest();
/**
* @throws IllegalStateException if cross project duplication flag has not been set
*/
boolean isCrossProjectDuplicationEnabled();
/**
* Branch being analyzed.
*
* @throws IllegalStateException if branch has not been set
*/
Branch getBranch();
/**
* In a pull request analysis, return the ID of the pull request
*
* @throws IllegalStateException if pull request key has not been set
*/
String getPullRequestKey();
/**
* The project being analyzed. It can be a project, application or portfolio.
* It is used to load settings like Quality gates, webhooks and configuration.
*
* @throws IllegalStateException if project has not been set
*/
Project getProject();
/**
* @throws IllegalStateException if root component ref has not been set
*/
int getRootComponentRef();
Map<String, QualityProfile> getQProfilesByLanguage();
/**
* Plugins used during the analysis on scanner side
*/
Map<String, ScannerPlugin> getScannerPluginsByKey();
/**
* Scm Revision of the analysed code
*/
Optional<String> getScmRevision();
/**
* Reference branch for the new code period, set by scanner parameter sonar.newCode.referenceBranch
*/
Optional<String> getNewCodeReferenceBranch();
}
| 3,548 | 27.392 | 101 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/AnalysisMetadataHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 com.google.common.collect.ImmutableMap;
import java.util.Map;
import java.util.Optional;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.ce.task.util.InitializedProperty;
import org.sonar.core.platform.EditionProvider;
import org.sonar.core.platform.PlatformEditionProvider;
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.checkState;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.defaultIfBlank;
public class AnalysisMetadataHolderImpl implements MutableAnalysisMetadataHolder {
private static final String BRANCH_NOT_SET = "Branch has not been set";
private final InitializedProperty<String> uuid = new InitializedProperty<>();
private final InitializedProperty<Long> analysisDate = new InitializedProperty<>();
private final InitializedProperty<Analysis> baseProjectSnapshot = new InitializedProperty<>();
private final InitializedProperty<Boolean> crossProjectDuplicationEnabled = new InitializedProperty<>();
private final InitializedProperty<Branch> branch = new InitializedProperty<>();
private final InitializedProperty<String> pullRequestKey = 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<>();
private final PlatformEditionProvider editionProvider;
public AnalysisMetadataHolderImpl(PlatformEditionProvider editionProvider) {
this.editionProvider = editionProvider;
}
@Override
public MutableAnalysisMetadataHolder setUuid(String s) {
checkState(!uuid.isInitialized(), "Analysis uuid has already been set");
requireNonNull(s, "Analysis uuid can't 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();
}
@Override
public MutableAnalysisMetadataHolder setAnalysisDate(long date) {
checkState(!analysisDate.isInitialized(), "Analysis date has already been set");
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 MutableAnalysisMetadataHolder setBaseAnalysis(@Nullable Analysis baseAnalysis) {
checkState(!this.baseProjectSnapshot.isInitialized(), "Base project snapshot has already been set");
this.baseProjectSnapshot.setProperty(baseAnalysis);
return this;
}
@Override
@CheckForNull
public Analysis getBaseAnalysis() {
checkState(baseProjectSnapshot.isInitialized(), "Base project snapshot has not been set");
return baseProjectSnapshot.getProperty();
}
@Override
public MutableAnalysisMetadataHolder setCrossProjectDuplicationEnabled(boolean isCrossProjectDuplicationEnabled) {
checkState(!this.crossProjectDuplicationEnabled.isInitialized(), "Cross project duplication flag has already been set");
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 MutableAnalysisMetadataHolder setBranch(Branch branch) {
checkState(!this.branch.isInitialized(), "Branch has already been set");
boolean isCommunityEdition = editionProvider.get().filter(t -> t == EditionProvider.Edition.COMMUNITY).isPresent();
checkState(
!isCommunityEdition || branch.isMain(),
"Branches and Pull Requests are not supported in Community Edition");
this.branch.setProperty(branch);
return this;
}
@Override
public Branch getBranch() {
checkState(branch.isInitialized(), BRANCH_NOT_SET);
return branch.getProperty();
}
@Override
public MutableAnalysisMetadataHolder setPullRequestKey(String pullRequestKey) {
checkState(!this.pullRequestKey.isInitialized(), "Pull request key has already been set");
this.pullRequestKey.setProperty(pullRequestKey);
return this;
}
@Override
public String getPullRequestKey() {
checkState(pullRequestKey.isInitialized(), "Pull request key has not been set");
return pullRequestKey.getProperty();
}
@Override
public MutableAnalysisMetadataHolder setProject(Project project) {
checkState(!this.project.isInitialized(), "Project has already been set");
this.project.setProperty(project);
return this;
}
@Override
public Project getProject() {
checkState(project.isInitialized(), "Project has not been set");
return project.getProperty();
}
@Override
public MutableAnalysisMetadataHolder setRootComponentRef(int rootComponentRef) {
checkState(!this.rootComponentRef.isInitialized(), "Root component ref has already been set");
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 MutableAnalysisMetadataHolder setQProfilesByLanguage(Map<String, QualityProfile> qprofilesByLanguage) {
checkState(!this.qProfilesPerLanguage.isInitialized(), "QProfiles by language has already been set");
this.qProfilesPerLanguage.setProperty(ImmutableMap.copyOf(qprofilesByLanguage));
return this;
}
@Override
public Map<String, QualityProfile> getQProfilesByLanguage() {
checkState(qProfilesPerLanguage.isInitialized(), "QProfiles by language has not been set");
return qProfilesPerLanguage.getProperty();
}
@Override
public MutableAnalysisMetadataHolder setScannerPluginsByKey(Map<String, ScannerPlugin> pluginsByKey) {
checkState(!this.pluginsByKey.isInitialized(), "Plugins by key has already been set");
this.pluginsByKey.setProperty(ImmutableMap.copyOf(pluginsByKey));
return this;
}
@Override
public Map<String, ScannerPlugin> getScannerPluginsByKey() {
checkState(pluginsByKey.isInitialized(), "Plugins by key has not been set");
return pluginsByKey.getProperty();
}
@Override
public MutableAnalysisMetadataHolder setScmRevision(@Nullable String s) {
checkState(!this.scmRevision.isInitialized(), "ScmRevision has already been set");
this.scmRevision.setProperty(defaultIfBlank(s, null));
return this;
}
@Override
public MutableAnalysisMetadataHolder setNewCodeReferenceBranch(String newCodeReferenceBranch) {
checkState(!this.newCodeReferenceBranch.isInitialized(), "newCodeReferenceBranch has already been set");
requireNonNull(newCodeReferenceBranch, "newCodeReferenceBranch can't be null");
this.newCodeReferenceBranch.setProperty(newCodeReferenceBranch);
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.of(newCodeReferenceBranch.getProperty());
}
@Override
public boolean isBranch() {
checkState(this.branch.isInitialized(), BRANCH_NOT_SET);
Branch prop = branch.getProperty();
return prop != null && prop.getType() == BranchType.BRANCH;
}
@Override
public boolean isPullRequest() {
checkState(this.branch.isInitialized(), BRANCH_NOT_SET);
Branch prop = branch.getProperty();
return prop != null && prop.getType() == BranchType.PULL_REQUEST;
}
}
| 9,572 | 36.988095 | 124 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/Branch.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 javax.annotation.concurrent.Immutable;
import org.sonar.ce.task.projectanalysis.component.ComponentKeyGenerator;
import org.sonar.db.component.BranchType;
import static org.apache.logging.log4j.util.Strings.trimToNull;
import static org.sonar.core.component.ComponentKeys.createEffectiveKey;
@Immutable
public interface Branch extends ComponentKeyGenerator {
BranchType getType();
boolean isMain();
/**
* Name of the branch
*/
String getName();
/**
* Indicates the UUID of the branch used as reference
*
* @throws IllegalStateException for main branches or legacy branches.
*/
String getReferenceBranchUuid();
/**
* Whether the cross-project duplication tracker can be enabled
* or not.
*/
boolean supportsCrossProjectCpd();
/**
* @throws IllegalStateException if this branch configuration is not a pull request.
*/
String getPullRequestKey();
/**
* The target/base branch name of a PR.
* Correspond to <pre>sonar.pullrequest.base</pre> or <pre>sonar.branch.target</pre>
* It's not guaranteed to exist.
*
* @throws IllegalStateException if this branch configuration is not a pull request.
*/
String getTargetBranchName();
@Override
default String generateKey(String projectKey, @Nullable String fileOrDirPath) {
if (fileOrDirPath == null) {
return projectKey;
} else {
return createEffectiveKey(projectKey, trimToNull(fileOrDirPath));
}
}
}
| 2,393 | 29.692308 | 86 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/MutableAnalysisMetadataHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 javax.annotation.Nullable;
import org.sonar.server.project.Project;
import org.sonar.server.qualityprofile.QualityProfile;
public interface MutableAnalysisMetadataHolder extends AnalysisMetadataHolder {
/**
* @throws IllegalStateException if the analysis uuid has already been set
*/
MutableAnalysisMetadataHolder setUuid(String uuid);
/**
* @throws IllegalStateException if the analysis date has already been set
*/
MutableAnalysisMetadataHolder setAnalysisDate(long date);
/**
* @throws IllegalStateException if baseAnalysis has already been set
*/
MutableAnalysisMetadataHolder setBaseAnalysis(@Nullable Analysis baseAnalysis);
/**
* @throws IllegalStateException if cross project duplication flag has already been set
*/
MutableAnalysisMetadataHolder setCrossProjectDuplicationEnabled(boolean isCrossProjectDuplicationEnabled);
/**
* @throws IllegalStateException if branch has already been set
*/
MutableAnalysisMetadataHolder setBranch(Branch branch);
/**
* @throws IllegalStateException if pull request key has already been set
*/
MutableAnalysisMetadataHolder setPullRequestKey(String pullRequestKey);
/**
* @throws IllegalStateException if project has already been set
*/
MutableAnalysisMetadataHolder setProject(Project project);
/**
* @throws IllegalStateException if root component ref has already been set
*/
MutableAnalysisMetadataHolder setRootComponentRef(int rootComponentRef);
/**
* @throws IllegalStateException if QProfile by language has already been set
*/
MutableAnalysisMetadataHolder setQProfilesByLanguage(Map<String, QualityProfile> qprofilesByLanguage);
/**
* @throws IllegalStateException if Plugins by key has already been set
*/
MutableAnalysisMetadataHolder setScannerPluginsByKey(Map<String, ScannerPlugin> pluginsByKey);
/**
* @throws IllegalStateException if scm revision id has already been set
*/
MutableAnalysisMetadataHolder setScmRevision(String scmRevisionId);
MutableAnalysisMetadataHolder setNewCodeReferenceBranch(String newCodeReferenceBranch);
}
| 3,042 | 34.383721 | 108 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/ProjectConfigurationFactory.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 org.sonar.api.ce.ComputeEngineSide;
import org.sonar.api.config.Configuration;
import org.sonar.api.config.internal.ConfigurationBridge;
import org.sonar.api.config.internal.Settings;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.server.setting.ChildSettings;
@ComputeEngineSide
public class ProjectConfigurationFactory {
private final Settings globalSettings;
private final DbClient dbClient;
public ProjectConfigurationFactory(Settings globalSettings, DbClient dbClient) {
this.globalSettings = globalSettings;
this.dbClient = dbClient;
}
public Configuration newProjectConfiguration(String projectUuid) {
Settings projectSettings = new ChildSettings(globalSettings);
addSettings(projectSettings, projectUuid);
return new ConfigurationBridge(projectSettings);
}
private void addSettings(Settings settings, String componentUuid) {
try (DbSession session = dbClient.openSession(false)) {
dbClient.propertiesDao()
.selectEntityProperties(session, componentUuid)
.forEach(property -> settings.setProperty(property.getKey(), property.getValue()));
}
}
}
| 2,057 | 36.418182 | 91 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/ScannerPlugin.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import static java.util.Objects.requireNonNull;
@Immutable
public class ScannerPlugin {
private final String key;
private final String basePluginKey;
private final long updatedAt;
public ScannerPlugin(String key, @Nullable String basePluginKey, long updatedAt) {
this.key = requireNonNull(key, "key can't be null");
this.basePluginKey = basePluginKey;
this.updatedAt = updatedAt;
}
public String getKey() {
return key;
}
@CheckForNull
public String getBasePluginKey() {
return basePluginKey;
}
public long getUpdatedAt() {
return updatedAt;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ScannerPlugin that = (ScannerPlugin) o;
return key.equals(that.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return "ScannerPlugin{" +
"key='" + key + '\'' +
", basePluginKey='" + basePluginKey + '\'' +
", updatedAt='" + updatedAt + '\'' +
'}';
}
}
| 2,147 | 25.85 | 84 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/analysis/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.projectanalysis.analysis;
import javax.annotation.ParametersAreNonnullByDefault;
| 982 | 39.958333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/ComponentImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.measurecomputer;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.measure.Component;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
@Immutable
public class ComponentImpl implements Component {
private final String key;
private final Type type;
@CheckForNull
private final FileAttributes fileAttributes;
public ComponentImpl(String key, Type type, @Nullable FileAttributes fileAttributes) {
this.key = requireNonNull(key, "Key cannot be null");
this.type = requireNonNull(type, "Type cannot be null");
this.fileAttributes = checkFileAttributes(fileAttributes);
}
@CheckForNull
private FileAttributes checkFileAttributes(@Nullable FileAttributes fileAttributes) {
if (fileAttributes == null && type == Type.FILE) {
throw new IllegalArgumentException("Component of type FILE must have a FileAttributes object");
} else if (fileAttributes != null && type != Type.FILE) {
throw new IllegalArgumentException("Only component of type FILE have a FileAttributes object");
}
return fileAttributes;
}
@Override
public Type getType() {
return type;
}
@Override
public String getKey() {
return key;
}
@Override
public FileAttributes getFileAttributes() {
checkState(this.type == Component.Type.FILE, "Only component of type FILE have a FileAttributes object");
return fileAttributes;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ComponentImpl component = (ComponentImpl) o;
return key.equals(component.key);
}
@Override
public int hashCode() {
return key.hashCode();
}
@Override
public String toString() {
return "ComponentImpl{" +
"key=" + key +
", type='" + type + '\'' +
", fileAttributes=" + fileAttributes +
'}';
}
@Immutable
public static class FileAttributesImpl implements FileAttributes {
private final boolean unitTest;
private final String languageKey;
public FileAttributesImpl(@Nullable String languageKey, boolean unitTest) {
this.languageKey = languageKey;
this.unitTest = unitTest;
}
@Override
public boolean isUnitTest() {
return unitTest;
}
@Override
@CheckForNull
public String getLanguageKey() {
return languageKey;
}
@Override
public String toString() {
return "FileAttributesImpl{" +
"languageKey='" + languageKey + '\'' +
", unitTest=" + unitTest +
'}';
}
}
}
| 3,628 | 26.70229 | 109 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerContextImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.measurecomputer;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import javax.annotation.CheckForNull;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.sonar.api.ce.measure.Component;
import org.sonar.api.ce.measure.Issue;
import org.sonar.api.ce.measure.Measure;
import org.sonar.api.ce.measure.MeasureComputer.MeasureComputerContext;
import org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition;
import org.sonar.api.ce.measure.Settings;
import org.sonar.ce.task.projectanalysis.component.ConfigurationRepository;
import org.sonar.ce.task.projectanalysis.issue.ComponentIssuesRepository;
import org.sonar.ce.task.projectanalysis.measure.MeasureRepository;
import org.sonar.ce.task.projectanalysis.metric.Metric;
import org.sonar.ce.task.projectanalysis.metric.MetricRepository;
import org.sonar.core.issue.DefaultIssue;
import static com.google.common.base.Preconditions.checkArgument;
import static org.sonar.ce.task.projectanalysis.measure.Measure.newMeasureBuilder;
public class MeasureComputerContextImpl implements MeasureComputerContext {
private final ConfigurationRepository config;
private final MeasureRepository measureRepository;
private final MetricRepository metricRepository;
private final org.sonar.ce.task.projectanalysis.component.Component internalComponent;
private final Component component;
private final List<DefaultIssue> componentIssues;
private MeasureComputerDefinition definition;
private Set<String> allowedMetrics;
public MeasureComputerContextImpl(org.sonar.ce.task.projectanalysis.component.Component component, ConfigurationRepository config,
MeasureRepository measureRepository, MetricRepository metricRepository, ComponentIssuesRepository componentIssuesRepository) {
this.config = config;
this.internalComponent = component;
this.measureRepository = measureRepository;
this.metricRepository = metricRepository;
this.component = newComponent(component);
this.componentIssues = componentIssuesRepository.getIssues(component);
}
/**
* Definition needs to be reset each time a new computer is processed.
* Defining it by a setter allows to reduce the number of this class to be created (one per component instead of one per component and per computer).
*/
public MeasureComputerContextImpl setDefinition(MeasureComputerDefinition definition) {
this.definition = definition;
this.allowedMetrics = allowedMetric(definition);
return this;
}
private static Set<String> allowedMetric(MeasureComputerDefinition definition) {
Set<String> allowedMetrics = new HashSet<>();
allowedMetrics.addAll(definition.getInputMetrics());
allowedMetrics.addAll(definition.getOutputMetrics());
return allowedMetrics;
}
@Override
public Component getComponent() {
return component;
}
@Override
public Settings getSettings() {
return new Settings() {
@Override
@CheckForNull
public String getString(String key) {
return config.getConfiguration().get(key).orElse(null);
}
@Override
public String[] getStringArray(String key) {
return config.getConfiguration().getStringArray(key);
}
};
}
@Override
@CheckForNull
public Measure getMeasure(String metric) {
validateInputMetric(metric);
Optional<org.sonar.ce.task.projectanalysis.measure.Measure> measure = measureRepository.getRawMeasure(internalComponent, metricRepository.getByKey(metric));
if (measure.isPresent()) {
return new MeasureImpl(measure.get());
}
return null;
}
@Override
public Iterable<Measure> getChildrenMeasures(String metric) {
validateInputMetric(metric);
return () -> internalComponent.getChildren().stream()
.map(new ComponentToMeasure(metricRepository.getByKey(metric)))
.map(ToMeasureAPI.INSTANCE)
.filter(Objects::nonNull)
.iterator();
}
@Override
public void addMeasure(String metricKey, int value) {
Metric metric = metricRepository.getByKey(metricKey);
validateAddMeasure(metric);
measureRepository.add(internalComponent, metric, newMeasureBuilder().create(value));
}
@Override
public void addMeasure(String metricKey, double value) {
Metric metric = metricRepository.getByKey(metricKey);
validateAddMeasure(metric);
measureRepository.add(internalComponent, metric, newMeasureBuilder().create(value, metric.getDecimalScale()));
}
@Override
public void addMeasure(String metricKey, long value) {
Metric metric = metricRepository.getByKey(metricKey);
validateAddMeasure(metric);
measureRepository.add(internalComponent, metric, newMeasureBuilder().create(value));
}
@Override
public void addMeasure(String metricKey, String value) {
Metric metric = metricRepository.getByKey(metricKey);
validateAddMeasure(metric);
measureRepository.add(internalComponent, metric, newMeasureBuilder().create(value));
}
@Override
public void addMeasure(String metricKey, boolean value) {
Metric metric = metricRepository.getByKey(metricKey);
validateAddMeasure(metric);
measureRepository.add(internalComponent, metric, newMeasureBuilder().create(value));
}
private void validateInputMetric(String metric) {
checkArgument(allowedMetrics.contains(metric), "Only metrics in %s can be used to load measures", definition.getInputMetrics());
}
private void validateAddMeasure(Metric metric) {
checkArgument(definition.getOutputMetrics().contains(metric.getKey()), "Only metrics in %s can be used to add measures. Metric '%s' is not allowed.",
definition.getOutputMetrics(), metric.getKey());
if (measureRepository.getRawMeasure(internalComponent, metric).isPresent()) {
throw new UnsupportedOperationException(String.format("A measure on metric '%s' already exists on component '%s'", metric.getKey(), internalComponent.getKey()));
}
}
@Override
public List<? extends Issue> getIssues() {
return componentIssues;
}
private static Component newComponent(org.sonar.ce.task.projectanalysis.component.Component component) {
return new ComponentImpl(
component.getKey(),
Component.Type.valueOf(component.getType().name()),
component.getType() == org.sonar.ce.task.projectanalysis.component.Component.Type.FILE
? new ComponentImpl.FileAttributesImpl(component.getFileAttributes().getLanguageKey(), component.getFileAttributes().isUnitTest())
: null);
}
private class ComponentToMeasure
implements Function<org.sonar.ce.task.projectanalysis.component.Component, Optional<org.sonar.ce.task.projectanalysis.measure.Measure>> {
private final Metric metric;
public ComponentToMeasure(Metric metric) {
this.metric = metric;
}
@Override
public Optional<org.sonar.ce.task.projectanalysis.measure.Measure> apply(@Nonnull org.sonar.ce.task.projectanalysis.component.Component input) {
return measureRepository.getRawMeasure(input, metric);
}
}
private enum ToMeasureAPI implements Function<Optional<org.sonar.ce.task.projectanalysis.measure.Measure>, Measure> {
INSTANCE;
@Nullable
@Override
public Measure apply(@Nonnull Optional<org.sonar.ce.task.projectanalysis.measure.Measure> input) {
return input.isPresent() ? new MeasureImpl(input.get()) : null;
}
}
}
| 8,379 | 37.796296 | 167 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerDefinitionImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.measurecomputer;
import com.google.common.collect.ImmutableSet;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.sonar.api.ce.measure.MeasureComputer;
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
public class MeasureComputerDefinitionImpl implements MeasureComputer.MeasureComputerDefinition {
private final Set<String> inputMetricKeys;
private final Set<String> outputMetrics;
private MeasureComputerDefinitionImpl(BuilderImpl builder) {
this.inputMetricKeys = ImmutableSet.copyOf(builder.inputMetricKeys);
this.outputMetrics = ImmutableSet.copyOf(builder.outputMetrics);
}
@Override
public Set<String> getInputMetrics() {
return inputMetricKeys;
}
@Override
public Set<String> getOutputMetrics() {
return outputMetrics;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
MeasureComputerDefinitionImpl that = (MeasureComputerDefinitionImpl) o;
if (!inputMetricKeys.equals(that.inputMetricKeys)) {
return false;
}
return outputMetrics.equals(that.outputMetrics);
}
@Override
public int hashCode() {
int result = inputMetricKeys.hashCode();
result = 31 * result + outputMetrics.hashCode();
return result;
}
@Override
public String toString() {
return "MeasureComputerDefinitionImpl{" +
"inputMetricKeys=" + inputMetricKeys +
", outputMetrics=" + outputMetrics +
'}';
}
public static class BuilderImpl implements Builder {
private String[] inputMetricKeys = new String[] {};
@CheckForNull
private String[] outputMetrics = null;
@Override
public Builder setInputMetrics(String... inputMetrics) {
this.inputMetricKeys = validateInputMetricKeys(inputMetrics);
return this;
}
@Override
public Builder setOutputMetrics(String... outputMetrics) {
this.outputMetrics = validateOutputMetricKeys(outputMetrics);
return this;
}
@Override
public MeasureComputer.MeasureComputerDefinition build() {
validateInputMetricKeys(this.inputMetricKeys);
validateOutputMetricKeys(this.outputMetrics);
return new MeasureComputerDefinitionImpl(this);
}
private static String[] validateInputMetricKeys(@Nullable String[] inputMetrics) {
requireNonNull(inputMetrics, "Input metrics cannot be null");
checkNotNull(inputMetrics);
return inputMetrics;
}
private static String[] validateOutputMetricKeys(@Nullable String[] outputMetrics) {
requireNonNull(outputMetrics, "Output metrics cannot be null");
checkArgument(outputMetrics.length > 0, "At least one output metric must be defined");
checkNotNull(outputMetrics);
return outputMetrics;
}
private static void checkNotNull(String[] metrics) {
for (String metric : metrics) {
requireNonNull(metric, "Null metric is not allowed");
}
}
}
}
| 4,002 | 30.273438 | 97 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureComputerWrapper.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.measurecomputer;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.measure.MeasureComputer;
import org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition;
import static java.util.Objects.requireNonNull;
@Immutable
public class MeasureComputerWrapper {
private final MeasureComputer computer;
private final MeasureComputerDefinition definition;
public MeasureComputerWrapper(MeasureComputer computer, MeasureComputerDefinition definition) {
this.computer = requireNonNull(computer);
this.definition = requireNonNull(definition);
}
public MeasureComputer getComputer() {
return computer;
}
public MeasureComputerDefinition getDefinition() {
return definition;
}
@Override
public String toString() {
return computer.toString();
}
}
| 1,700 | 31.711538 | 97 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/MeasureImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.measurecomputer;
import java.util.EnumSet;
import java.util.Locale;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.measure.Measure;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.sonar.ce.task.projectanalysis.measure.Measure.ValueType.BOOLEAN;
import static org.sonar.ce.task.projectanalysis.measure.Measure.ValueType.DOUBLE;
import static org.sonar.ce.task.projectanalysis.measure.Measure.ValueType.INT;
import static org.sonar.ce.task.projectanalysis.measure.Measure.ValueType.LONG;
import static org.sonar.ce.task.projectanalysis.measure.Measure.ValueType.STRING;
@Immutable
public class MeasureImpl implements Measure {
private static final EnumSet<org.sonar.ce.task.projectanalysis.measure.Measure.ValueType> ALLOWED_VALUE_TYPES = EnumSet.of(INT, LONG, DOUBLE, STRING, BOOLEAN);
private final org.sonar.ce.task.projectanalysis.measure.Measure measure;
public MeasureImpl(org.sonar.ce.task.projectanalysis.measure.Measure measure) {
this.measure = requireNonNull(measure, "Measure couldn't be null");
checkState(ALLOWED_VALUE_TYPES.contains(measure.getValueType()), "Only following types are allowed %s", ALLOWED_VALUE_TYPES);
}
@Override
public int getIntValue() {
checkValueType(INT);
return measure.getIntValue();
}
@Override
public long getLongValue() {
checkValueType(LONG);
return measure.getLongValue();
}
@Override
public double getDoubleValue() {
checkValueType(DOUBLE);
return measure.getDoubleValue();
}
@Override
public String getStringValue() {
checkValueType(STRING);
return measure.getStringValue();
}
@Override
public boolean getBooleanValue() {
checkValueType(BOOLEAN);
return measure.getBooleanValue();
}
private void checkValueType(org.sonar.ce.task.projectanalysis.measure.Measure.ValueType expected) {
if (measure.getValueType() != expected) {
throw new IllegalStateException(format("Value can not be converted to %s because current value type is a %s",
expected.toString().toLowerCase(Locale.US),
measure.getValueType()));
}
}
@Override
public String toString() {
return "MeasureImpl{" +
"measure=" + measure +
'}';
}
}
| 3,234 | 33.784946 | 161 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/measurecomputer/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.projectanalysis.api.measurecomputer;
import javax.annotation.ParametersAreNonnullByDefault;
| 993 | 40.416667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/BranchImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.posttask.Branch;
@Immutable
public class BranchImpl implements Branch {
private final boolean isMain;
@Nullable
private final String name;
private final Type type;
public BranchImpl(boolean isMain, @Nullable String name, Type type) {
this.isMain = isMain;
this.name = name;
this.type = type;
}
@Override
public boolean isMain() {
return isMain;
}
@Override
public Optional<String> getName() {
return Optional.ofNullable(name);
}
@Override
public Type getType() {
return type;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("Branch{");
sb.append("isMain=").append(isMain);
sb.append(", name='").append(name).append('\'');
sb.append(", type=").append(type);
sb.append('}');
return sb.toString();
}
}
| 1,848 | 27.446154 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/CeTaskImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.posttask.CeTask;
import static java.util.Objects.requireNonNull;
@Immutable
class CeTaskImpl implements CeTask {
private final String id;
private final Status status;
CeTaskImpl(String id, Status status) {
this.id = requireNonNull(id, "uuid can not be null");
this.status = requireNonNull(status, "status can not be null");
}
@Override
public String getId() {
return id;
}
@Override
public Status getStatus() {
return status;
}
@Override
public String toString() {
return "CeTaskImpl{" +
"id='" + id + '\'' +
", status=" + status +
'}';
}
}
| 1,581 | 27.763636 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import javax.annotation.CheckForNull;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.posttask.QualityGate;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.sonar.api.ce.posttask.QualityGate.EvaluationStatus.NO_VALUE;
@Immutable
class ConditionImpl implements QualityGate.Condition {
private final QualityGate.EvaluationStatus status;
private final String metricKey;
private final QualityGate.Operator operator;
private final String errorThreshold;
private final boolean onLeakPeriod;
@CheckForNull
private final String value;
private ConditionImpl(Builder builder) {
requireNonNull(builder.status, "status can not be null");
requireNonNull(builder.metricKey, "metricKey can not be null");
requireNonNull(builder.operator, "operator can not be null");
requireNonNull(builder.errorThreshold, "errorThreshold can not be null");
verifyValue(builder);
this.status = builder.status;
this.metricKey = builder.metricKey;
this.operator = builder.operator;
this.errorThreshold = builder.errorThreshold;
this.onLeakPeriod = builder.metricKey.startsWith("new_");
this.value = builder.value;
}
private static void verifyValue(Builder builder) {
if (builder.status == NO_VALUE) {
checkArgument(builder.value == null, "value must be null when status is %s", NO_VALUE);
} else {
checkArgument(builder.value != null, "value can not be null when status is not %s", NO_VALUE);
}
}
public static Builder newBuilder() {
return new Builder();
}
public static class Builder {
private String metricKey;
private QualityGate.Operator operator;
private String errorThreshold;
@CheckForNull
private String value;
private QualityGate.EvaluationStatus status;
private Builder() {
// enforce use of static method
}
public Builder setMetricKey(String metricKey) {
this.metricKey = metricKey;
return this;
}
public Builder setOperator(QualityGate.Operator operator) {
this.operator = operator;
return this;
}
public Builder setErrorThreshold(String errorThreshold) {
this.errorThreshold = errorThreshold;
return this;
}
/**
* @deprecated in 7.6. This method has no longer any effect.
*/
@Deprecated
public Builder setWarningThreshold(String warningThreshold) {
return this;
}
/**
* @deprecated in 7.6. This method has no longer any effect.
*/
@Deprecated
public Builder setOnLeakPeriod(boolean onLeakPeriod) {
return this;
}
public Builder setValue(String value) {
this.value = value;
return this;
}
public Builder setStatus(QualityGate.EvaluationStatus status) {
this.status = status;
return this;
}
public ConditionImpl build() {
return new ConditionImpl(this);
}
}
@Override
public QualityGate.EvaluationStatus getStatus() {
return status;
}
@Override
public String getMetricKey() {
return metricKey;
}
@Override
public QualityGate.Operator getOperator() {
return operator;
}
@Override
public String getErrorThreshold() {
return errorThreshold;
}
@Deprecated
@Override
public String getWarningThreshold() {
return null;
}
/**
* @deprecated in 7.6. Conditions "on leak period" were removed. Use "New X" conditions instead.
*/
@Deprecated
@Override
public boolean isOnLeakPeriod() {
return onLeakPeriod;
}
@Override
public String getValue() {
checkState(status != NO_VALUE, "There is no value when status is %s", NO_VALUE);
return value;
}
@Override
public String toString() {
return "ConditionImpl{" +
"status=" + status +
", metricKey='" + metricKey + '\'' +
", operator=" + operator +
", errorThreshold='" + errorThreshold + '\'' +
", value='" + value + '\'' +
'}';
}
}
| 4,985 | 26.854749 | 100 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ConditionToCondition.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import java.util.Map;
import java.util.function.Function;
import org.sonar.api.ce.posttask.QualityGate;
import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus;
import static com.google.common.base.Preconditions.checkState;
import static java.lang.String.format;
/**
* Converts a {@link Condition} from the Compute Engine internal API to a {@link org.sonar.api.ce.posttask.QualityGate.Condition}
* of the public API.
*/
class ConditionToCondition implements Function<Condition, QualityGate.Condition> {
private final ConditionImpl.Builder builder = ConditionImpl.newBuilder();
private final Map<Condition, ConditionStatus> statusPerConditions;
public ConditionToCondition(Map<Condition, ConditionStatus> statusPerConditions) {
this.statusPerConditions = statusPerConditions;
}
@Override
public QualityGate.Condition apply(Condition input) {
String metricKey = input.getMetric().getKey();
ConditionStatus conditionStatus = statusPerConditions.get(input);
checkState(conditionStatus != null, "Missing ConditionStatus for condition on metric key %s", metricKey);
return builder
.setStatus(convert(conditionStatus.getStatus()))
.setMetricKey(metricKey)
.setOperator(convert(input.getOperator()))
.setErrorThreshold(input.getErrorThreshold())
.setValue(conditionStatus.getValue())
.build();
}
private static QualityGate.EvaluationStatus convert(ConditionStatus.EvaluationStatus status) {
switch (status) {
case NO_VALUE:
return QualityGate.EvaluationStatus.NO_VALUE;
case OK:
return QualityGate.EvaluationStatus.OK;
case ERROR:
return QualityGate.EvaluationStatus.ERROR;
default:
throw new IllegalArgumentException(format(
"Unsupported value '%s' of ConditionStatus.EvaluationStatus can not be converted to QualityGate.EvaluationStatus",
status));
}
}
private static QualityGate.Operator convert(Condition.Operator operator) {
switch (operator) {
case GREATER_THAN:
return QualityGate.Operator.GREATER_THAN;
case LESS_THAN:
return QualityGate.Operator.LESS_THAN;
default:
throw new IllegalArgumentException(format(
"Unsupported value '%s' of Condition.Operation can not be converted to QualityGate.Operator",
operator));
}
}
}
| 3,340 | 38.305882 | 129 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/PostProjectAnalysisTasksExecutor.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.sonar.api.ce.posttask.Analysis;
import org.sonar.api.ce.posttask.Branch;
import org.sonar.api.ce.posttask.CeTask;
import org.sonar.api.ce.posttask.Organization;
import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
import org.sonar.api.ce.posttask.Project;
import org.sonar.api.ce.posttask.QualityGate;
import org.sonar.api.ce.posttask.ScannerContext;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateHolder;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus;
import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatusHolder;
import org.sonar.ce.task.step.ComputationStepExecutor;
import org.sonar.core.util.logs.Profiler;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static java.util.Optional.empty;
import static java.util.Optional.of;
import static java.util.Optional.ofNullable;
import static org.sonar.api.ce.posttask.CeTask.Status.FAILED;
import static org.sonar.api.ce.posttask.CeTask.Status.SUCCESS;
import static org.sonar.db.component.BranchType.PULL_REQUEST;
/**
* Responsible for calling {@link PostProjectAnalysisTask} implementations (if any).
*/
public class PostProjectAnalysisTasksExecutor implements ComputationStepExecutor.Listener {
private static final PostProjectAnalysisTask[] NO_POST_PROJECT_ANALYSIS_TASKS = new PostProjectAnalysisTask[0];
private static final Logger LOG = LoggerFactory.getLogger(PostProjectAnalysisTasksExecutor.class);
private final org.sonar.ce.task.CeTask ceTask;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final QualityGateHolder qualityGateHolder;
private final QualityGateStatusHolder qualityGateStatusHolder;
private final PostProjectAnalysisTask[] postProjectAnalysisTasks;
private final BatchReportReader reportReader;
public PostProjectAnalysisTasksExecutor(org.sonar.ce.task.CeTask ceTask, AnalysisMetadataHolder analysisMetadataHolder, QualityGateHolder qualityGateHolder,
QualityGateStatusHolder qualityGateStatusHolder, BatchReportReader reportReader, @Nullable PostProjectAnalysisTask[] postProjectAnalysisTasks) {
this.analysisMetadataHolder = analysisMetadataHolder;
this.qualityGateHolder = qualityGateHolder;
this.qualityGateStatusHolder = qualityGateStatusHolder;
this.ceTask = ceTask;
this.reportReader = reportReader;
this.postProjectAnalysisTasks = postProjectAnalysisTasks == null ? NO_POST_PROJECT_ANALYSIS_TASKS : postProjectAnalysisTasks;
}
@Override
public void finished(boolean allStepsExecuted) {
if (postProjectAnalysisTasks.length == 0) {
return;
}
ProjectAnalysisImpl projectAnalysis = createProjectAnalysis(allStepsExecuted ? SUCCESS : FAILED);
for (PostProjectAnalysisTask postProjectAnalysisTask : postProjectAnalysisTasks) {
executeTask(projectAnalysis, postProjectAnalysisTask);
}
}
private static void executeTask(ProjectAnalysisImpl projectAnalysis, PostProjectAnalysisTask postProjectAnalysisTask) {
String status = "FAILED";
Profiler task = Profiler.create(LOG).logTimeLast(true);
try {
task.start();
postProjectAnalysisTask.finished(new ContextImpl(projectAnalysis, task));
status = "SUCCESS";
} catch (Exception e) {
LOG.error("Execution of task " + postProjectAnalysisTask.getClass() + " failed", e);
} finally {
task.addContext("status", status);
task.stopInfo("{}", postProjectAnalysisTask.getDescription());
}
}
private static class ContextImpl implements PostProjectAnalysisTask.Context {
private final ProjectAnalysisImpl projectAnalysis;
private final Profiler task;
private ContextImpl(ProjectAnalysisImpl projectAnalysis, Profiler task) {
this.projectAnalysis = projectAnalysis;
this.task = task;
}
@Override
public PostProjectAnalysisTask.ProjectAnalysis getProjectAnalysis() {
return projectAnalysis;
}
@Override
public PostProjectAnalysisTask.LogStatistics getLogStatistics() {
return new LogStatisticsImpl(task);
}
}
private static class LogStatisticsImpl implements PostProjectAnalysisTask.LogStatistics {
private final Profiler profiler;
private LogStatisticsImpl(Profiler profiler) {
this.profiler = profiler;
}
@Override
public PostProjectAnalysisTask.LogStatistics 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") && !key.equalsIgnoreCase("status"),
"Statistic with key [%s] is not accepted", key);
checkArgument(!profiler.hasContext(key), "Statistic with key [%s] is already present", key);
profiler.addContext(key, value);
return this;
}
}
private ProjectAnalysisImpl createProjectAnalysis(CeTask.Status status) {
return new ProjectAnalysisImpl(
new CeTaskImpl(this.ceTask.getUuid(), status),
createProject(this.ceTask),
getAnalysis().orElse(null),
ScannerContextImpl.from(reportReader.readContextProperties()),
status == SUCCESS ? createQualityGate() : null,
createBranch(),
reportReader.readMetadata().getScmRevisionId());
}
private Optional<Analysis> getAnalysis() {
if (analysisMetadataHolder.hasAnalysisDateBeenSet()) {
return of(new AnalysisImpl(analysisMetadataHolder.getUuid(), analysisMetadataHolder.getAnalysisDate(), analysisMetadataHolder.getScmRevision()));
}
return empty();
}
private static Project createProject(org.sonar.ce.task.CeTask ceTask) {
return ceTask.getEntity()
.map(c -> new ProjectImpl(
c.getUuid(),
c.getKey().orElseThrow(() -> new IllegalStateException("Missing project key")),
c.getName().orElseThrow(() -> new IllegalStateException("Missing project name"))))
.orElseThrow(() -> new IllegalStateException("Report processed for a task of a deleted component"));
}
@CheckForNull
private QualityGate createQualityGate() {
Optional<org.sonar.ce.task.projectanalysis.qualitygate.QualityGate> qualityGateOptional = this.qualityGateHolder.getQualityGate();
if (qualityGateOptional.isPresent()) {
org.sonar.ce.task.projectanalysis.qualitygate.QualityGate qualityGate = qualityGateOptional.get();
return new QualityGateImpl(
qualityGate.getUuid(),
qualityGate.getName(),
convert(qualityGateStatusHolder.getStatus()),
convert(qualityGate.getConditions(), qualityGateStatusHolder.getStatusPerConditions()));
}
return null;
}
@CheckForNull
private BranchImpl createBranch() {
org.sonar.ce.task.projectanalysis.analysis.Branch analysisBranch = analysisMetadataHolder.getBranch();
String branchKey = analysisBranch.getType() == PULL_REQUEST ? analysisBranch.getPullRequestKey() : analysisBranch.getName();
return new BranchImpl(analysisBranch.isMain(), branchKey, Branch.Type.valueOf(analysisBranch.getType().name()));
}
private static QualityGate.Status convert(QualityGateStatus status) {
switch (status) {
case OK:
return QualityGate.Status.OK;
case ERROR:
return QualityGate.Status.ERROR;
default:
throw new IllegalArgumentException(format(
"Unsupported value '%s' of QualityGateStatus can not be converted to QualityGate.Status",
status));
}
}
private static Collection<QualityGate.Condition> convert(Set<Condition> conditions, Map<Condition, ConditionStatus> statusPerConditions) {
return conditions.stream()
.map(new ConditionToCondition(statusPerConditions))
.toList();
}
private static class ProjectAnalysisImpl implements PostProjectAnalysisTask.ProjectAnalysis {
private final CeTask ceTask;
private final Project project;
private final ScannerContext scannerContext;
@Nullable
private final QualityGate qualityGate;
@Nullable
private final Branch branch;
@Nullable
private final Analysis analysis;
private final String scmRevisionId;
private ProjectAnalysisImpl(CeTask ceTask, Project project,
@Nullable Analysis analysis, ScannerContext scannerContext, @Nullable QualityGate qualityGate, @Nullable Branch branch, String scmRevisionId) {
this.ceTask = requireNonNull(ceTask, "ceTask can not be null");
this.project = requireNonNull(project, "project can not be null");
this.analysis = analysis;
this.scannerContext = requireNonNull(scannerContext, "scannerContext can not be null");
this.qualityGate = qualityGate;
this.branch = branch;
this.scmRevisionId = scmRevisionId;
}
/**
*
* @deprecated since 8.7. No longer used - it's always empty.
*/
@Override
@Deprecated
public Optional<Organization> getOrganization() {
return empty();
}
@Override
public CeTask getCeTask() {
return ceTask;
}
@Override
public Project getProject() {
return project;
}
@Override
public Optional<Branch> getBranch() {
return ofNullable(branch);
}
@Override
@CheckForNull
public QualityGate getQualityGate() {
return qualityGate;
}
@Override
public Optional<Analysis> getAnalysis() {
return ofNullable(analysis);
}
@Override
public ScannerContext getScannerContext() {
return scannerContext;
}
@Override
public String getScmRevisionId() {
return scmRevisionId;
}
@Override
public String toString() {
return "ProjectAnalysis{" +
"ceTask=" + ceTask +
", project=" + project +
", scannerContext=" + scannerContext +
", qualityGate=" + qualityGate +
", analysis=" + analysis +
'}';
}
}
private static class AnalysisImpl implements Analysis {
private final String analysisUuid;
private final long date;
private final Optional<String> revision;
private AnalysisImpl(String analysisUuid, long date, Optional<String> revision) {
this.analysisUuid = analysisUuid;
this.date = date;
this.revision = revision;
}
@Override
public String getAnalysisUuid() {
return analysisUuid;
}
@Override
public Date getDate() {
return new Date(date);
}
@Override
public Optional<String> getRevision() {
return revision;
}
}
}
| 11,968 | 35.602446 | 158 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ProjectImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.posttask.Project;
import static java.util.Objects.requireNonNull;
@Immutable
class ProjectImpl implements Project {
private final String uuid;
private final String key;
private final String name;
ProjectImpl(String uuid, String key, String name) {
this.uuid = requireNonNull(uuid, "uuid can not be null");
this.key = requireNonNull(key, "key can not be null");
this.name = requireNonNull(name, "name can not be null");
}
@Override
public String getUuid() {
return uuid;
}
@Override
public String getKey() {
return key;
}
@Override
public String getName() {
return name;
}
@Override
public String toString() {
return "ProjectImpl{" +
"uuid='" + uuid + '\'' +
", key='" + key + '\'' +
", name='" + name + '\'' +
'}';
}
}
| 1,782 | 27.301587 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/QGToEvaluatedQG.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.sonar.api.ce.posttask.QualityGate;
import org.sonar.api.ce.posttask.QualityGate.EvaluationStatus;
import org.sonar.api.measures.Metric;
import org.sonar.server.qualitygate.Condition;
import org.sonar.server.qualitygate.EvaluatedCondition;
import org.sonar.server.qualitygate.EvaluatedQualityGate;
public class QGToEvaluatedQG implements Function<QualityGate, EvaluatedQualityGate> {
public static final QGToEvaluatedQG INSTANCE = new QGToEvaluatedQG();
private QGToEvaluatedQG() {
// static only
}
@Override public EvaluatedQualityGate apply(QualityGate qg) {
EvaluatedQualityGate.Builder builder = EvaluatedQualityGate.newBuilder();
Set<Condition> conditions = qg.getConditions().stream()
.map(q -> {
Condition condition = new Condition(q.getMetricKey(), Condition.Operator.valueOf(q.getOperator().name()),
q.getErrorThreshold());
builder.addEvaluatedCondition(condition,
EvaluatedCondition.EvaluationStatus.valueOf(q.getStatus().name()),
q.getStatus() == EvaluationStatus.NO_VALUE ? null : q.getValue());
return condition;
})
.collect(Collectors.toSet());
return builder.setQualityGate(new org.sonar.server.qualitygate.QualityGate(qg.getId(), qg.getName(), conditions))
.setStatus(Metric.Level.valueOf(qg.getStatus().name()))
.build();
}
}
| 2,360 | 41.160714 | 117 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/QualityGateImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import com.google.common.collect.ImmutableList;
import java.util.Collection;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.posttask.QualityGate;
import static java.util.Objects.requireNonNull;
@Immutable
class QualityGateImpl implements QualityGate {
private final String id;
private final String name;
private final Status status;
private final Collection<Condition> conditions;
public QualityGateImpl(String id, String name, Status status, Collection<Condition> conditions) {
this.id = requireNonNull(id, "id can not be null");
this.name = requireNonNull(name, "name can not be null");
this.status = requireNonNull(status, "status can not be null");
this.conditions = ImmutableList.copyOf(requireNonNull(conditions, "conditions can not be null"));
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public Status getStatus() {
return status;
}
@Override
public Collection<Condition> getConditions() {
return conditions;
}
@Override
public String toString() {
return "QualityGateImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", status=" + status +
", conditions=" + conditions +
'}';
}
}
| 2,199 | 29.136986 | 101 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/ScannerContextImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.api.posttask;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
import javax.annotation.concurrent.Immutable;
import org.sonar.api.ce.posttask.ScannerContext;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
@Immutable
class ScannerContextImpl implements ScannerContext {
private final Map<String, String> props;
private ScannerContextImpl(Map<String, String> props) {
this.props = props;
}
@Override
public Map<String, String> getProperties() {
return props;
}
static ScannerContextImpl from(CloseableIterator<ScannerReport.ContextProperty> it) {
try {
ImmutableMap.Builder<String, String> mapBuilder = ImmutableMap.builder();
while (it.hasNext()) {
ScannerReport.ContextProperty prop = it.next();
mapBuilder.put(prop.getKey(), prop.getValue());
}
return new ScannerContextImpl(mapBuilder.build());
} finally {
it.close();
}
}
}
| 1,875 | 32.5 | 87 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/api/posttask/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.projectanalysis.api.posttask;
import javax.annotation.ParametersAreNonnullByDefault;
| 986 | 40.125 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.batch;
import java.io.File;
import org.sonar.ce.task.CeTask;
public interface BatchReportDirectoryHolder {
/**
* The File of the directory where the Batch report files for the current {@link CeTask} are stored.
*
* @throws IllegalStateException if the holder is empty (ie. there is no directory yet)
*/
File getDirectory();
}
| 1,230 | 35.205882 | 102 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/batch/BatchReportDirectoryHolderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.batch;
import java.io.File;
import java.util.Objects;
public class BatchReportDirectoryHolderImpl implements MutableBatchReportDirectoryHolder {
private File directory = null;
@Override
public void setDirectory(File newDirectory) {
this.directory = Objects.requireNonNull(newDirectory);
}
@Override
public File getDirectory() {
if (this.directory == null) {
throw new IllegalStateException("Directory has not been set yet");
}
return this.directory;
}
}
| 1,380 | 31.880952 | 90 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.batch;
import java.io.InputStream;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.sonar.core.util.CloseableIterator;
import org.sonar.scanner.protocol.output.ScannerReport;
public interface BatchReportReader {
ScannerReport.Metadata readMetadata();
@CheckForNull
InputStream getAnalysisCache();
CloseableIterator<String> readScannerLogs();
CloseableIterator<ScannerReport.ActiveRule> readActiveRules();
CloseableIterator<ScannerReport.AdHocRule> readAdHocRules();
CloseableIterator<ScannerReport.Measure> readComponentMeasures(int componentRef);
@CheckForNull
ScannerReport.Changesets readChangesets(int componentRef);
ScannerReport.Component readComponent(int componentRef);
CloseableIterator<ScannerReport.Issue> readComponentIssues(int componentRef);
CloseableIterator<ScannerReport.ExternalIssue> readComponentExternalIssues(int componentRef);
CloseableIterator<ScannerReport.Duplication> readComponentDuplications(int componentRef);
CloseableIterator<ScannerReport.CpdTextBlock> readCpdTextBlocks(int componentRef);
CloseableIterator<ScannerReport.Symbol> readComponentSymbols(int componentRef);
CloseableIterator<ScannerReport.SyntaxHighlightingRule> readComponentSyntaxHighlighting(int fileRef);
CloseableIterator<ScannerReport.LineCoverage> readComponentCoverage(int fileRef);
/**
* Reads a file's source code, line by line. Returns an absent optional if the file does not exist
*/
Optional<CloseableIterator<String>> readFileSource(int fileRef);
CloseableIterator<ScannerReport.ContextProperty> readContextProperties();
Optional<CloseableIterator<ScannerReport.LineSgnificantCode>> readComponentSignificantCode(int fileRef);
Optional<ScannerReport.ChangedLines> readComponentChangedLines(int fileRef);
CloseableIterator<ScannerReport.AnalysisWarning> readAnalysisWarnings();
}
| 2,773 | 36.486486 | 106 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/batch/BatchReportReaderImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.batch;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.NoSuchElementException;
import java.util.Optional;
import javax.annotation.CheckForNull;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.sonar.core.util.CloseableIterator;
import org.sonar.core.util.LineReaderIterator;
import org.sonar.scanner.protocol.output.FileStructure;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.LineSgnificantCode;
import org.sonar.scanner.protocol.output.ScannerReportReader;
import static java.nio.charset.StandardCharsets.UTF_8;
public class BatchReportReaderImpl implements BatchReportReader {
private final BatchReportDirectoryHolder batchReportDirectoryHolder;
private ScannerReportReader delegate;
// caching of metadata which are read often
private ScannerReport.Metadata metadata;
public BatchReportReaderImpl(BatchReportDirectoryHolder batchReportDirectoryHolder) {
this.batchReportDirectoryHolder = batchReportDirectoryHolder;
}
private void ensureInitialized() {
if (this.delegate == null) {
FileStructure fileStructure = new FileStructure(batchReportDirectoryHolder.getDirectory());
this.delegate = new ScannerReportReader(fileStructure);
}
}
@Override
public ScannerReport.Metadata readMetadata() {
ensureInitialized();
if (this.metadata == null) {
this.metadata = delegate.readMetadata();
}
return this.metadata;
}
@CheckForNull
@Override
public InputStream getAnalysisCache() {
ensureInitialized();
return delegate.getAnalysisCache();
}
@Override
public CloseableIterator<String> readScannerLogs() {
ensureInitialized();
File file = delegate.getFileStructure().analysisLog();
if (!file.exists()) {
return CloseableIterator.emptyCloseableIterator();
}
try {
InputStreamReader reader = new InputStreamReader(FileUtils.openInputStream(file), UTF_8);
return new LineReaderIterator(reader);
} catch (IOException e) {
throw new IllegalStateException("Fail to open file " + file, e);
}
}
@Override
public CloseableIterator<ScannerReport.ActiveRule> readActiveRules() {
ensureInitialized();
return delegate.readActiveRules();
}
@Override
public CloseableIterator<ScannerReport.AdHocRule> readAdHocRules() {
ensureInitialized();
return delegate.readAdHocRules();
}
@Override
public CloseableIterator<ScannerReport.Measure> readComponentMeasures(int componentRef) {
ensureInitialized();
return delegate.readComponentMeasures(componentRef);
}
@Override
@CheckForNull
public ScannerReport.Changesets readChangesets(int componentRef) {
ensureInitialized();
return delegate.readChangesets(componentRef);
}
@Override
public ScannerReport.Component readComponent(int componentRef) {
ensureInitialized();
return delegate.readComponent(componentRef);
}
@Override
public CloseableIterator<ScannerReport.Issue> readComponentIssues(int componentRef) {
ensureInitialized();
return delegate.readComponentIssues(componentRef);
}
@Override
public CloseableIterator<ScannerReport.ExternalIssue> readComponentExternalIssues(int componentRef) {
ensureInitialized();
return delegate.readComponentExternalIssues(componentRef);
}
@Override
public CloseableIterator<ScannerReport.Duplication> readComponentDuplications(int componentRef) {
ensureInitialized();
return delegate.readComponentDuplications(componentRef);
}
@Override
public CloseableIterator<ScannerReport.CpdTextBlock> readCpdTextBlocks(int componentRef) {
ensureInitialized();
return delegate.readCpdTextBlocks(componentRef);
}
@Override
public CloseableIterator<ScannerReport.Symbol> readComponentSymbols(int componentRef) {
ensureInitialized();
return delegate.readComponentSymbols(componentRef);
}
@Override
public CloseableIterator<ScannerReport.SyntaxHighlightingRule> readComponentSyntaxHighlighting(int fileRef) {
ensureInitialized();
return delegate.readComponentSyntaxHighlighting(fileRef);
}
@Override
public CloseableIterator<ScannerReport.LineCoverage> readComponentCoverage(int fileRef) {
ensureInitialized();
return delegate.readComponentCoverage(fileRef);
}
@Override
public Optional<CloseableIterator<String>> readFileSource(int fileRef) {
ensureInitialized();
File file = delegate.readFileSource(fileRef);
if (file == null) {
return Optional.empty();
}
try {
return Optional.of(new CloseableLineIterator(IOUtils.lineIterator(FileUtils.openInputStream(file), UTF_8)));
} catch (IOException e) {
throw new IllegalStateException("Fail to traverse file: " + file, e);
}
}
private static class CloseableLineIterator extends CloseableIterator<String> {
private final LineIterator lineIterator;
public CloseableLineIterator(LineIterator lineIterator) {
this.lineIterator = lineIterator;
}
@Override
public boolean hasNext() {
return lineIterator.hasNext();
}
@Override
public String next() {
return lineIterator.next();
}
@Override
protected String doNext() {
// never called anyway
throw new NoSuchElementException("Empty closeable Iterator has no element");
}
@Override
protected void doClose() throws IOException {
lineIterator.close();
}
}
@Override
public CloseableIterator<ScannerReport.ContextProperty> readContextProperties() {
ensureInitialized();
return delegate.readContextProperties();
}
@Override
public Optional<CloseableIterator<LineSgnificantCode>> readComponentSignificantCode(int fileRef) {
ensureInitialized();
return Optional.ofNullable(delegate.readComponentSignificantCode(fileRef));
}
@Override
public Optional<ScannerReport.ChangedLines> readComponentChangedLines(int fileRef) {
ensureInitialized();
return Optional.ofNullable(delegate.readComponentChangedLines(fileRef));
}
@Override
public CloseableIterator<ScannerReport.AnalysisWarning> readAnalysisWarnings() {
ensureInitialized();
return delegate.readAnalysisWarnings();
}
}
| 7,261 | 30.437229 | 114 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/batch/MutableBatchReportDirectoryHolder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.batch;
import java.io.File;
public interface MutableBatchReportDirectoryHolder extends BatchReportDirectoryHolder {
/**
* Sets the File of the directory in the BatchReportDirectoryHolder. Settings a File more than once is allowed but it
* can never be set to {@code null}.
*
* @param newDirectory a {@link File}, can not be {@code null}
*
* @throws NullPointerException if {@code newDirectory} is {@code null}
*/
void setDirectory(File newDirectory);
}
| 1,365 | 38.028571 | 119 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/batch/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.projectanalysis.batch;
import javax.annotation.ParametersAreNonnullByDefault;
| 979 | 39.833333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/BranchLoader.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 javax.annotation.Nullable;
import javax.inject.Inject;
import org.sonar.api.utils.MessageException;
import org.sonar.ce.task.projectanalysis.analysis.MutableAnalysisMetadataHolder;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.server.project.DefaultBranchNameResolver;
import static org.sonar.scanner.protocol.output.ScannerReport.Metadata.BranchType.UNSET;
public class BranchLoader {
private final MutableAnalysisMetadataHolder metadataHolder;
private final BranchLoaderDelegate delegate;
private final DefaultBranchNameResolver defaultBranchNameResolver;
public BranchLoader(MutableAnalysisMetadataHolder metadataHolder, DefaultBranchNameResolver defaultBranchNameResolver) {
this(metadataHolder, null, defaultBranchNameResolver);
}
@Inject
public BranchLoader(MutableAnalysisMetadataHolder metadataHolder, @Nullable BranchLoaderDelegate delegate,
DefaultBranchNameResolver defaultBranchNameResolver) {
this.metadataHolder = metadataHolder;
this.delegate = delegate;
this.defaultBranchNameResolver = defaultBranchNameResolver;
}
public void load(ScannerReport.Metadata metadata) {
if (delegate != null) {
delegate.load(metadata);
} else if (hasBranchProperties(metadata)) {
throw MessageException.of("Current edition does not support branch feature");
} else {
metadataHolder.setBranch(new DefaultBranchImpl(defaultBranchNameResolver.getEffectiveMainBranchName()));
}
}
private static boolean hasBranchProperties(ScannerReport.Metadata metadata) {
return !metadata.getBranchName().isEmpty()
|| !metadata.getPullRequestKey().isEmpty()
|| !metadata.getReferenceBranchName().isEmpty()
|| metadata.getBranchType() != UNSET;
}
}
| 2,665 | 39.393939 | 122 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/BranchLoaderDelegate.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import org.sonar.api.ce.ComputeEngineSide;
import org.sonar.scanner.protocol.output.ScannerReport;
@ComputeEngineSide
public interface BranchLoaderDelegate {
void load(ScannerReport.Metadata metadata);
}
| 1,106 | 34.709677 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/BranchPersister.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import org.sonar.db.DbSession;
public interface BranchPersister {
void persist(DbSession dbSession);
}
| 1,004 | 34.892857 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/BranchPersisterImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.component;
import java.util.Arrays;
import java.util.regex.Pattern;
import javax.annotation.Nullable;
import org.sonar.api.resources.Qualifiers;
import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.db.DbClient;
import org.sonar.db.DbSession;
import org.sonar.db.component.BranchDto;
import org.sonar.db.component.BranchType;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.protobuf.DbProjectBranches;
import org.sonar.server.project.Project;
import static org.sonar.core.config.PurgeConstants.BRANCHES_TO_KEEP_WHEN_INACTIVE;
/**
* Creates or updates the data in table {@code PROJECT_BRANCHES} for the current root.
*/
public class BranchPersisterImpl implements BranchPersister {
private final DbClient dbClient;
private final TreeRootHolder treeRootHolder;
private final AnalysisMetadataHolder analysisMetadataHolder;
private final ConfigurationRepository configurationRepository;
public BranchPersisterImpl(DbClient dbClient, TreeRootHolder treeRootHolder, AnalysisMetadataHolder analysisMetadataHolder, ConfigurationRepository configurationRepository) {
this.dbClient = dbClient;
this.treeRootHolder = treeRootHolder;
this.analysisMetadataHolder = analysisMetadataHolder;
this.configurationRepository = configurationRepository;
}
public void persist(DbSession dbSession) {
Branch branch = analysisMetadataHolder.getBranch();
Project project = analysisMetadataHolder.getProject();
String branchUuid = treeRootHolder.getRoot().getUuid();
ComponentDto branchComponentDto = dbClient.componentDao().selectByUuid(dbSession, branchUuid)
.orElseThrow(() -> new IllegalStateException("Component has been deleted by end-user during analysis"));
// insert or update in table project_branches
dbClient.branchDao().upsert(dbSession, toBranchDto(dbSession, branchComponentDto, branch, project, checkIfExcludedFromPurge()));
}
private boolean checkIfExcludedFromPurge() {
if (analysisMetadataHolder.getBranch().isMain()) {
return true;
}
if (BranchType.PULL_REQUEST.equals(analysisMetadataHolder.getBranch().getType())) {
return false;
}
String[] branchesToKeep = configurationRepository.getConfiguration().getStringArray(BRANCHES_TO_KEEP_WHEN_INACTIVE);
return Arrays.stream(branchesToKeep)
.map(Pattern::compile)
.anyMatch(excludePattern -> excludePattern.matcher(analysisMetadataHolder.getBranch().getName()).matches());
}
protected BranchDto toBranchDto(DbSession dbSession, ComponentDto componentDto, Branch branch, Project project, boolean excludeFromPurge) {
BranchDto dto = new BranchDto();
dto.setUuid(componentDto.uuid());
dto.setIsMain(branch.isMain());
dto.setProjectUuid(project.getUuid());
dto.setBranchType(branch.getType());
dto.setExcludeFromPurge(excludeFromPurge);
// merge branch is only present if it's not a main branch and not an application
if (!branch.isMain() && !Qualifiers.APP.equals(componentDto.qualifier())) {
dto.setMergeBranchUuid(branch.getReferenceBranchUuid());
}
if (branch.getType() == BranchType.PULL_REQUEST) {
String pullRequestKey = analysisMetadataHolder.getPullRequestKey();
dto.setKey(pullRequestKey);
DbProjectBranches.PullRequestData pullRequestData = getBuilder(dbSession, project.getUuid(), pullRequestKey)
.setBranch(branch.getName())
.setTitle(branch.getName())
.setTarget(branch.getTargetBranchName())
.build();
dto.setPullRequestData(pullRequestData);
} else {
dto.setKey(branch.getName());
}
return dto;
}
private DbProjectBranches.PullRequestData.Builder getBuilder(DbSession dbSession, String projectUuid, String pullRequestKey) {
return dbClient.branchDao().selectByPullRequestKey(dbSession, projectUuid, pullRequestKey)
.map(BranchDto::getPullRequestData)
.map(DbProjectBranches.PullRequestData::toBuilder)
.orElse(DbProjectBranches.PullRequestData.newBuilder());
}
private static <T> T firstNonNull(@Nullable T first, T second) {
return (first != null) ? first : second;
}
}
| 5,112 | 40.233871 | 176 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/Component.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.EnumSet;
import java.util.List;
import java.util.Set;
import javax.annotation.CheckForNull;
public interface Component {
enum Type {
PROJECT(0), DIRECTORY(2), FILE(3), VIEW(0), SUBVIEW(1), PROJECT_VIEW(2);
private static final Set<Type> REPORT_TYPES = EnumSet.of(PROJECT, DIRECTORY, FILE);
private static final Set<Type> VIEWS_TYPES = EnumSet.of(VIEW, SUBVIEW, PROJECT_VIEW);
private final int depth;
Type(int depth) {
this.depth = depth;
}
public int getDepth() {
return depth;
}
public boolean isDeeperThan(Type otherType) {
return this.getDepth() > otherType.getDepth();
}
public boolean isHigherThan(Type otherType) {
return this.getDepth() < otherType.getDepth();
}
public boolean isReportType() {
return REPORT_TYPES.contains(this);
}
public boolean isViewsType() {
return VIEWS_TYPES.contains(this);
}
}
/**
* On a branch, CHANGED and ADDED are relative to the previous analysis.
* On a pull request, these are relative to the base branch.
*/
enum Status {
UNAVAILABLE, SAME, CHANGED, ADDED
}
Type getType();
Status getStatus();
/**
* Returns the component uuid
*/
String getUuid();
/**
* Returns the key as it will be displayed in the ui.
* If legacy branch feature is used, the key will contain the branch name
* If new branch feature is used, the key will not contain the branch name
*/
String getKey();
/**
* The component long name. For files and directories this is the project relative path.
*/
String getName();
/**
* The component short name. For files and directories this is the parent relative path (ie filename for files). For projects and view this is the same as {@link #getName()}
*/
String getShortName();
/**
* The optional description of the component.
*/
@CheckForNull
String getDescription();
List<Component> getChildren();
/**
* Returns the attributes specific to components of type {@link Type#PROJECT}.
*
* @throws IllegalStateException when the component's type is not {@link Type#PROJECT}.
*/
ProjectAttributes getProjectAttributes();
/**
* Returns the attributes specific to components of type {@link Type#PROJECT}, {@link Type#MODULE},
* {@link Type#DIRECTORY} or {@link Type#FILE}.
*
* @throws IllegalStateException when the component's type is neither {@link Type#PROJECT}, {@link Type#MODULE},
* {@link Type#DIRECTORY} nor {@link Type#FILE}.
*/
ReportAttributes getReportAttributes();
/**
* The attributes of the Component if it's type is File.
*
* @throws IllegalStateException if the Component's type is not {@link Type#FILE}
*/
FileAttributes getFileAttributes();
/**
* The attributes of the Component if it's type is {@link Type#PROJECT_VIEW}.
*
* @throws IllegalStateException if the Component's type is not {@link Type#PROJECT_VIEW}
*/
ProjectViewAttributes getProjectViewAttributes();
/**
* The attributes of the Component if it's type is {@link Type#SUBVIEW}.
*
* @throws IllegalStateException if the Component's type is not {@link Type#SUBVIEW}
*/
SubViewAttributes getSubViewAttributes();
/**
* The attributes of the Component if it's type is {@link Type#VIEW}.
*
* @throws IllegalStateException if the Component's type is not {@link Type#VIEW}
*/
ViewAttributes getViewAttributes();
}
| 4,369 | 28.727891 | 175 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentCrawler.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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;
/**
* Allow to crawl a component tree from a given component
*/
public interface ComponentCrawler {
void visit(Component tree);
}
| 1,033 | 33.466667 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentFunctions.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.function.Function;
import javax.annotation.Nonnull;
public final class ComponentFunctions {
private ComponentFunctions() {
// prevents instantiation
}
public static Function<Component, String> toComponentUuid() {
return ToComponentUuid.INSTANCE;
}
private enum ToComponentUuid implements Function<Component, String> {
INSTANCE;
@Override
@Nonnull
public String apply(@Nonnull Component input) {
return input.getUuid();
}
}
}
| 1,390 | 29.911111 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentImpl.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.base.MoreObjects;
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.List;
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.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.abbreviate;
import static org.apache.commons.lang.StringUtils.trimToNull;
import static org.sonar.db.component.ComponentValidator.MAX_COMPONENT_DESCRIPTION_LENGTH;
import static org.sonar.db.component.ComponentValidator.MAX_COMPONENT_NAME_LENGTH;
@Immutable
public class ComponentImpl implements Component {
private final Type type;
private final Status status;
private final String name;
private final String shortName;
private final String key;
private final String uuid;
@CheckForNull
private final String description;
private final List<Component> children;
@CheckForNull
private final ProjectAttributes projectAttributes;
private final ReportAttributes reportAttributes;
@CheckForNull
private final FileAttributes fileAttributes;
private ComponentImpl(Builder builder) {
this.type = builder.type;
this.status = builder.status;
this.key = builder.key;
this.name = builder.name;
this.shortName = MoreObjects.firstNonNull(builder.shortName, builder.name).intern();
this.description = builder.description;
this.uuid = builder.uuid;
this.projectAttributes = builder.projectAttributes;
this.reportAttributes = builder.reportAttributes;
this.fileAttributes = builder.fileAttributes;
this.children = ImmutableList.copyOf(builder.children);
}
@Override
public Type getType() {
return type;
}
@Override
public Status getStatus() {
return status;
}
@Override
public String getUuid() {
return uuid;
}
@Override
public String getKey() {
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, "Only component of type PROJECT have a ProjectAttributes object");
return this.projectAttributes;
}
@Override
public ReportAttributes getReportAttributes() {
return this.reportAttributes;
}
@Override
public FileAttributes getFileAttributes() {
checkState(this.type == Type.FILE, "Only component of type FILE have a FileAttributes object");
return this.fileAttributes;
}
@Override
public ProjectViewAttributes getProjectViewAttributes() {
throw new IllegalStateException("Only component of type PROJECT_VIEW 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");
}
public static Builder builder(Type type) {
return new Builder(type);
}
public static final class Builder {
private static final String KEY_CANNOT_BE_NULL = "Key can't be null";
private static final String UUID_CANNOT_BE_NULL = "uuid can't be null";
private static final String REPORT_ATTRIBUTES_CANNOT_BE_NULL = "reportAttributes can't be null";
private static final String NAME_CANNOT_BE_NULL = "name can't be null";
private static final String STATUS_CANNOT_BE_NULL = "status can't be null";
private final Type type;
private Status status;
private ProjectAttributes projectAttributes;
private ReportAttributes reportAttributes;
private String uuid;
private String key;
private String name;
private String shortName;
private String description;
private FileAttributes fileAttributes;
private final List<Component> children = new ArrayList<>();
private Builder(Type type) {
this.type = requireNonNull(type, "type can't be null");
}
public Builder setUuid(String s) {
this.uuid = requireNonNull(s, UUID_CANNOT_BE_NULL);
return this;
}
@CheckForNull
public String getUuid() {
return uuid;
}
public Builder setStatus(Status status) {
this.status = requireNonNull(status, STATUS_CANNOT_BE_NULL);
return this;
}
public Builder setKey(String key) {
this.key = requireNonNull(key, KEY_CANNOT_BE_NULL);
return this;
}
public Builder setName(String name) {
this.name = abbreviate(requireNonNull(name, NAME_CANNOT_BE_NULL), MAX_COMPONENT_NAME_LENGTH);
return this;
}
public Builder setShortName(String shortName) {
this.shortName = abbreviate(requireNonNull(shortName, NAME_CANNOT_BE_NULL), MAX_COMPONENT_NAME_LENGTH);
return this;
}
public Builder setDescription(@Nullable String description) {
this.description = abbreviate(trimToNull(description), MAX_COMPONENT_DESCRIPTION_LENGTH);
return this;
}
public Builder setProjectAttributes(ProjectAttributes projectAttributes) {
checkProjectAttributes(projectAttributes);
this.projectAttributes = projectAttributes;
return this;
}
public Builder setReportAttributes(ReportAttributes reportAttributes) {
this.reportAttributes = requireNonNull(reportAttributes, REPORT_ATTRIBUTES_CANNOT_BE_NULL);
return this;
}
public Builder setFileAttributes(@Nullable FileAttributes fileAttributes) {
this.fileAttributes = fileAttributes;
return this;
}
public Builder addChildren(List<Component> components) {
for (Component component : components) {
checkArgument(component.getType().isReportType());
}
this.children.addAll(components);
return this;
}
public ComponentImpl build() {
requireNonNull(reportAttributes, REPORT_ATTRIBUTES_CANNOT_BE_NULL);
requireNonNull(uuid, UUID_CANNOT_BE_NULL);
requireNonNull(key, KEY_CANNOT_BE_NULL);
requireNonNull(name, NAME_CANNOT_BE_NULL);
requireNonNull(status, STATUS_CANNOT_BE_NULL);
checkProjectAttributes(this.projectAttributes);
return new ComponentImpl(this);
}
private void checkProjectAttributes(@Nullable ProjectAttributes projectAttributes) {
checkArgument(type != Type.PROJECT ^ projectAttributes != null, "ProjectAttributes must and can only be set for type PROJECT");
}
}
@Override
public String toString() {
return "ComponentImpl{" +
"type=" + type +
", status=" + status +
", name='" + name + '\'' +
", key='" + key + '\'' +
", uuid='" + uuid + '\'' +
", description='" + description + '\'' +
", children=" + children +
", projectAttributes=" + projectAttributes +
", reportAttributes=" + reportAttributes +
", fileAttributes=" + fileAttributes +
'}';
}
@Override
public boolean equals(@Nullable Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ComponentImpl component = (ComponentImpl) o;
return uuid.equals(component.uuid);
}
@Override
public int hashCode() {
return uuid.hashCode();
}
}
| 8,574 | 29.845324 | 133 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentKeyGenerator.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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 javax.annotation.Nullable;
@FunctionalInterface
public interface ComponentKeyGenerator {
String generateKey(String projectKey, @Nullable String fileOrDirPath);
}
| 1,071 | 34.733333 | 75 | java |
sonarqube | sonarqube-master/server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/component/ComponentTreeBuilder.java | /*
* SonarQube
* Copyright (C) 2009-2023 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; 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.ArrayList;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.sonar.ce.task.projectanalysis.analysis.Branch;
import org.sonar.scanner.protocol.output.ScannerReport;
import org.sonar.scanner.protocol.output.ScannerReport.Component.FileStatus;
import org.sonar.server.project.Project;
import static com.google.common.base.Preconditions.checkArgument;
import static java.lang.String.format;
import static java.util.Objects.requireNonNull;
import static org.apache.commons.lang.StringUtils.removeStart;
import static org.apache.commons.lang.StringUtils.trimToNull;
import static org.sonar.scanner.protocol.output.ScannerReport.Component.ComponentType.FILE;
public class ComponentTreeBuilder {
private final ComponentKeyGenerator keyGenerator;
/**
* Will supply the UUID for any component in the tree, given it's key.
* <p>
* The String argument of the {@link Function#apply(Object)} method is the component's key.
* </p>
*/
private final Function<String, String> uuidSupplier;
/**
* Will supply the {@link ScannerReport.Component} of all the components in the component tree as we crawl it from the
* root.
* <p>
* The Integer argument of the {@link Function#apply(Object)} method is the component's ref.
* </p>
*/
private final Function<Integer, ScannerReport.Component> scannerComponentSupplier;
private final Project project;
private final Branch branch;
private final ProjectAttributes projectAttributes;
private ScannerReport.Component rootComponent;
private String scmBasePath;
public ComponentTreeBuilder(
ComponentKeyGenerator keyGenerator,
UnaryOperator<String> uuidSupplier,
Function<Integer, ScannerReport.Component> scannerComponentSupplier,
Project project,
Branch branch,
ProjectAttributes projectAttributes) {
this.keyGenerator = keyGenerator;
this.uuidSupplier = uuidSupplier;
this.scannerComponentSupplier = scannerComponentSupplier;
this.project = project;
this.branch = branch;
this.projectAttributes = requireNonNull(projectAttributes, "projectAttributes can't be null");
}
public Component buildProject(ScannerReport.Component project, String scmBasePath) {
this.rootComponent = project;
this.scmBasePath = trimToNull(scmBasePath);
Node root = createProjectHierarchy(project);
return buildComponent(root, "", "");
}
private Node createProjectHierarchy(ScannerReport.Component rootComponent) {
checkArgument(rootComponent.getType() == ScannerReport.Component.ComponentType.PROJECT, "Expected root component of type 'PROJECT'");
LinkedList<ScannerReport.Component> queue = new LinkedList<>();
rootComponent.getChildRefList().stream()
.map(scannerComponentSupplier)
.forEach(queue::addLast);
Node root = new Node();
root.reportComponent = rootComponent;
while (!queue.isEmpty()) {
ScannerReport.Component component = queue.removeFirst();
checkArgument(component.getType() == FILE, "Unsupported component type '%s'", component.getType());
addFile(root, component);
}
return root;
}
private static void addFile(Node root, ScannerReport.Component file) {
checkArgument(!StringUtils.isEmpty(file.getProjectRelativePath()), "Files should have a project relative path: " + file);
String[] split = StringUtils.split(file.getProjectRelativePath(), '/');
Node currentNode = root;
for (int i = 0; i < split.length; i++) {
currentNode = currentNode.children().computeIfAbsent(split[i], k -> new Node());
}
currentNode.reportComponent = file;
}
private Component buildComponent(Node node, String currentPath, String parentPath) {
List<Component> childComponents = buildChildren(node, currentPath);
ScannerReport.Component component = node.reportComponent();
if (component != null) {
if (component.getType() == FILE) {
return buildFile(component);
} else if (component.getType() == ScannerReport.Component.ComponentType.PROJECT) {
return buildProject(childComponents);
}
}
return buildDirectory(parentPath, currentPath, childComponents);
}
private List<Component> buildChildren(Node node, String currentPath) {
List<Component> children = new ArrayList<>();
for (Map.Entry<String, Node> e : node.children().entrySet()) {
String path = buildPath(currentPath, e.getKey());
Node childNode = e.getValue();
// collapse folders that only contain one folder
while (childNode.children().size() == 1 && childNode.children().values().iterator().next().children().size() > 0) {
Map.Entry<String, Node> childEntry = childNode.children().entrySet().iterator().next();
path = buildPath(path, childEntry.getKey());
childNode = childEntry.getValue();
}
children.add(buildComponent(childNode, path, currentPath));
}
return children;
}
private static String buildPath(String currentPath, String file) {
if (currentPath.isEmpty()) {
return file;
}
return currentPath + "/" + file;
}
private Component buildProject(List<Component> children) {
String projectKey = keyGenerator.generateKey(rootComponent.getKey(), null);
String uuid = uuidSupplier.apply(projectKey);
ComponentImpl.Builder builder = ComponentImpl.builder(Component.Type.PROJECT)
.setUuid(uuid)
.setKey(projectKey)
.setStatus(convertStatus(rootComponent.getStatus()))
.setProjectAttributes(projectAttributes)
.setReportAttributes(createAttributesBuilder(rootComponent.getRef(), rootComponent.getProjectRelativePath(), scmBasePath).build())
.addChildren(children);
setNameAndDescription(rootComponent, builder);
return builder.build();
}
private ComponentImpl buildFile(ScannerReport.Component component) {
String key = keyGenerator.generateKey(rootComponent.getKey(), component.getProjectRelativePath());
return ComponentImpl.builder(Component.Type.FILE)
.setUuid(uuidSupplier.apply(key))
.setKey(key)
.setName(component.getProjectRelativePath())
.setShortName(FilenameUtils.getName(component.getProjectRelativePath()))
.setStatus(convertStatus(component.getStatus()))
.setDescription(trimToNull(component.getDescription()))
.setReportAttributes(createAttributesBuilder(component.getRef(), component.getProjectRelativePath(), scmBasePath).build())
.setFileAttributes(createFileAttributes(component))
.build();
}
private ComponentImpl buildDirectory(String parentPath, String path, List<Component> children) {
String key = keyGenerator.generateKey(rootComponent.getKey(), path);
return ComponentImpl.builder(Component.Type.DIRECTORY)
.setUuid(uuidSupplier.apply(key))
.setKey(key)
.setName(path)
.setShortName(removeStart(removeStart(path, parentPath), "/"))
.setStatus(convertStatus(FileStatus.UNAVAILABLE))
.setReportAttributes(createAttributesBuilder(null, path, scmBasePath).build())
.addChildren(children)
.build();
}
public Component buildChangedComponentTreeRoot(Component project) {
return buildChangedComponentTree(project);
}
@Nullable
private static Component buildChangedComponentTree(Component component) {
switch (component.getType()) {
case PROJECT:
return buildChangedProject(component);
case DIRECTORY:
return buildChangedDirectory(component);
case FILE:
return buildChangedFile(component);
default:
throw new IllegalArgumentException(format("Unsupported component type '%s'", component.getType()));
}
}
private static Component buildChangedProject(Component component) {
return changedComponentBuilder(component, "")
.setProjectAttributes(new ProjectAttributes(component.getProjectAttributes()))
.addChildren(buildChangedComponentChildren(component))
.build();
}
@Nullable
private static Component buildChangedDirectory(Component component) {
List<Component> children = buildChangedComponentChildren(component);
if (children.isEmpty()) {
return null;
}
if (children.size() == 1 && children.get(0).getType() == Component.Type.DIRECTORY) {
Component child = children.get(0);
String shortName = component.getShortName() + "/" + child.getShortName();
return changedComponentBuilder(child, shortName)
.addChildren(child.getChildren())
.build();
} else {
return changedComponentBuilder(component, component.getShortName())
.addChildren(children)
.build();
}
}
private static List<Component> buildChangedComponentChildren(Component component) {
return component.getChildren().stream()
.map(ComponentTreeBuilder::buildChangedComponentTree)
.filter(Objects::nonNull)
.toList();
}
private static ComponentImpl.Builder changedComponentBuilder(Component component, String newShortName) {
return ComponentImpl.builder(component.getType())
.setUuid(component.getUuid())
.setKey(component.getKey())
.setStatus(component.getStatus())
.setReportAttributes(component.getReportAttributes())
.setName(component.getName())
.setShortName(newShortName)
.setDescription(component.getDescription());
}
@Nullable
private static Component buildChangedFile(Component component) {
if (component.getStatus() == Component.Status.SAME) {
return null;
}
return component;
}
private void setNameAndDescription(ScannerReport.Component component, ComponentImpl.Builder builder) {
if (branch.isMain()) {
builder
.setName(nameOfProject(component))
.setDescription(component.getDescription());
} else {
builder
.setName(project.getName())
.setDescription(project.getDescription());
}
}
private static Component.Status convertStatus(FileStatus status) {
switch (status) {
case ADDED:
return Component.Status.ADDED;
case SAME:
return Component.Status.SAME;
case CHANGED:
return Component.Status.CHANGED;
case UNAVAILABLE:
return Component.Status.UNAVAILABLE;
case UNRECOGNIZED:
default:
throw new IllegalArgumentException("Unsupported ComponentType value " + status);
}
}
private String nameOfProject(ScannerReport.Component component) {
String name = trimToNull(component.getName());
if (name != null) {
return name;
}
return project.getName();
}
private static ReportAttributes.Builder createAttributesBuilder(@Nullable Integer ref, String path, @Nullable String scmBasePath) {
return ReportAttributes.newBuilder(ref)
.setScmPath(computeScmPath(scmBasePath, path));
}
@CheckForNull
private static String computeScmPath(@Nullable String scmBasePath, String scmRelativePath) {
if (scmRelativePath.isEmpty()) {
return scmBasePath;
}
if (scmBasePath == null) {
return scmRelativePath;
}
return scmBasePath + '/' + scmRelativePath;
}
private static FileAttributes createFileAttributes(ScannerReport.Component component) {
checkArgument(component.getType() == FILE);
checkArgument(component.getLines() > 0, "File '%s' has no line", component.getProjectRelativePath());
String lang = trimToNull(component.getLanguage());
return new FileAttributes(
component.getIsTest(),
lang != null ? lang.intern() : null,
component.getLines(),
component.getMarkedAsUnchanged(),
component.getOldRelativeFilePath()
);
}
private static class Node {
private final Map<String, Node> children = new LinkedHashMap<>();
private ScannerReport.Component reportComponent = null;
private Map<String, Node> children() {
return children;
}
@CheckForNull
private ScannerReport.Component reportComponent() {
return reportComponent;
}
}
}
| 13,197 | 36.073034 | 137 | java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.