3 * Copyright (C) 2009-2022 SonarSource SA
4 * mailto:info AT sonarsource DOT com
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 3 of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 package org.sonar.ce.task.projectanalysis.scm;
22 import com.google.common.collect.ImmutableList;
23 import com.tngtech.java.junit.dataprovider.DataProvider;
24 import com.tngtech.java.junit.dataprovider.DataProviderRunner;
25 import com.tngtech.java.junit.dataprovider.UseDataProvider;
26 import java.util.Collections;
27 import java.util.Date;
28 import java.util.EnumSet;
29 import java.util.List;
30 import java.util.Optional;
31 import org.junit.Before;
32 import org.junit.Rule;
33 import org.junit.Test;
34 import org.junit.runner.RunWith;
35 import org.sonar.api.utils.log.LogTester;
36 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
37 import org.sonar.ce.task.projectanalysis.batch.BatchReportReader;
38 import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
39 import org.sonar.ce.task.projectanalysis.component.Component;
40 import org.sonar.ce.task.projectanalysis.component.Component.Status;
41 import org.sonar.ce.task.projectanalysis.component.Component.Type;
42 import org.sonar.ce.task.projectanalysis.component.FileAttributes;
43 import org.sonar.ce.task.projectanalysis.component.ReportComponent;
44 import org.sonar.ce.task.projectanalysis.component.ViewsComponent;
45 import org.sonar.ce.task.projectanalysis.source.SourceHashRepository;
46 import org.sonar.ce.task.projectanalysis.source.SourceLinesDiff;
47 import org.sonar.db.protobuf.DbFileSources.Line;
48 import org.sonar.scanner.protocol.output.ScannerReport;
49 import org.sonar.scanner.protocol.output.ScannerReport.Changesets;
51 import static org.assertj.core.api.Assertions.assertThat;
52 import static org.assertj.core.api.Assertions.assertThatThrownBy;
53 import static org.mockito.Mockito.mock;
54 import static org.mockito.Mockito.verify;
55 import static org.mockito.Mockito.verifyNoMoreInteractions;
56 import static org.mockito.Mockito.verifyZeroInteractions;
57 import static org.mockito.Mockito.when;
58 import static org.sonar.api.utils.log.LoggerLevel.TRACE;
59 import static org.sonar.ce.task.projectanalysis.component.ReportComponent.builder;
61 @RunWith(DataProviderRunner.class)
62 public class ScmInfoRepositoryImplTest {
63 static final int FILE_REF = 1;
64 static final FileAttributes attributes = new FileAttributes(false, "java", 3);
65 static final Component FILE = builder(Component.Type.FILE, FILE_REF).setKey("FILE_KEY").setUuid("FILE_UUID").setFileAttributes(attributes).build();
66 static final Component FILE_SAME = builder(Component.Type.FILE, FILE_REF).setStatus(Status.SAME).setKey("FILE_KEY").setUuid("FILE_UUID").setFileAttributes(attributes).build();
67 static final long DATE_1 = 123456789L;
68 static final long DATE_2 = 1234567810L;
71 public LogTester logTester = new LogTester();
73 public BatchReportReaderRule reportReader = new BatchReportReaderRule();
75 public AnalysisMetadataHolderRule analysisMetadata = new AnalysisMetadataHolderRule();
77 private SourceHashRepository sourceHashRepository = mock(SourceHashRepository.class);
78 private SourceLinesDiff diff = mock(SourceLinesDiff.class);
79 private ScmInfoDbLoader dbLoader = mock(ScmInfoDbLoader.class);
80 private Date analysisDate = new Date();
82 private ScmInfoRepositoryImpl underTest = new ScmInfoRepositoryImpl(reportReader, analysisMetadata, dbLoader, diff, sourceHashRepository);
86 analysisMetadata.setAnalysisDate(analysisDate);
90 public void return_empty_if_component_is_not_file() {
91 Component c = mock(Component.class);
92 when(c.getType()).thenReturn(Type.DIRECTORY);
93 assertThat(underTest.getScmInfo(c)).isEmpty();
97 public void load_scm_info_from_cache_when_already_loaded() {
98 addChangesetInReport("john", DATE_1, "rev-1");
99 ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
100 assertThat(scmInfo.getAllChangesets()).hasSize(1);
102 assertThat(logTester.logs(TRACE)).hasSize(1);
105 underTest.getScmInfo(FILE);
106 assertThat(logTester.logs(TRACE)).isEmpty();
108 verifyZeroInteractions(dbLoader);
109 verifyZeroInteractions(sourceHashRepository);
110 verifyZeroInteractions(diff);
114 public void read_from_report() {
115 addChangesetInReport("john", DATE_1, "rev-1");
117 ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
118 assertThat(scmInfo.getAllChangesets()).hasSize(1);
120 Changeset changeset = scmInfo.getChangesetForLine(1);
121 assertThat(changeset.getAuthor()).isEqualTo("john");
122 assertThat(changeset.getDate()).isEqualTo(DATE_1);
123 assertThat(changeset.getRevision()).isEqualTo("rev-1");
125 assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from report for file 'FILE_KEY'");
127 verifyZeroInteractions(dbLoader);
128 verifyZeroInteractions(sourceHashRepository);
129 verifyZeroInteractions(diff);
133 public void read_from_DB_if_no_report_and_file_unchanged() {
134 createDbScmInfoWithOneLine("hash");
135 when(sourceHashRepository.getRawSourceHash(FILE_SAME)).thenReturn("hash");
137 // should clear revision and author
138 ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get();
139 assertThat(scmInfo.getAllChangesets()).hasSize(1);
140 assertChangeset(scmInfo.getChangesetForLine(1), null, null, 10L);
142 verify(sourceHashRepository).getRawSourceHash(FILE_SAME);
143 verify(dbLoader).getScmInfo(FILE_SAME);
145 verifyNoMoreInteractions(dbLoader);
146 verifyNoMoreInteractions(sourceHashRepository);
147 verifyZeroInteractions(diff);
151 public void read_from_DB_if_no_report_and_file_unchanged_and_copyFromPrevious_is_true() {
152 createDbScmInfoWithOneLine("hash");
153 when(sourceHashRepository.getRawSourceHash(FILE_SAME)).thenReturn("hash");
154 addFileSourceInReport(1);
155 addCopyFromPrevious();
157 ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get();
158 assertThat(scmInfo.getAllChangesets()).hasSize(1);
159 assertChangeset(scmInfo.getChangesetForLine(1), "rev1", "author1", 10L);
161 verify(sourceHashRepository).getRawSourceHash(FILE_SAME);
162 verify(dbLoader).getScmInfo(FILE_SAME);
164 verifyNoMoreInteractions(dbLoader);
165 verifyNoMoreInteractions(sourceHashRepository);
166 verifyZeroInteractions(diff);
170 public void generate_scm_info_when_nothing_in_report_nor_db() {
171 when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.empty());
172 ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
173 assertThat(scmInfo.getAllChangesets()).hasSize(3);
175 for (int i = 1; i <= 3; i++) {
176 assertChangeset(scmInfo.getChangesetForLine(i), null, null, analysisDate.getTime());
179 verify(dbLoader).getScmInfo(FILE);
180 verifyNoMoreInteractions(dbLoader);
181 verifyZeroInteractions(sourceHashRepository);
182 verifyZeroInteractions(diff);
186 public void generate_scm_info_when_nothing_in_db_and_report_is_has_no_changesets() {
187 when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.empty());
188 addFileSourceInReport(3);
189 ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
190 assertThat(scmInfo.getAllChangesets()).hasSize(3);
192 for (int i = 1; i <= 3; i++) {
193 assertChangeset(scmInfo.getChangesetForLine(i), null, null, analysisDate.getTime());
196 verify(dbLoader).getScmInfo(FILE);
197 verifyNoMoreInteractions(dbLoader);
198 verifyZeroInteractions(sourceHashRepository);
199 verifyZeroInteractions(diff);
203 public void generate_scm_info_for_new_and_changed_lines_when_report_is_empty() {
204 createDbScmInfoWithOneLine("hash");
205 when(diff.computeMatchingLines(FILE)).thenReturn(new int[] {1, 0, 0});
206 addFileSourceInReport(3);
207 ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
208 assertThat(scmInfo.getAllChangesets()).hasSize(3);
210 assertChangeset(scmInfo.getChangesetForLine(1), null, null, 10L);
211 assertChangeset(scmInfo.getChangesetForLine(2), null, null, analysisDate.getTime());
212 assertChangeset(scmInfo.getChangesetForLine(3), null, null, analysisDate.getTime());
214 verify(dbLoader).getScmInfo(FILE);
215 verify(diff).computeMatchingLines(FILE);
216 verifyNoMoreInteractions(dbLoader);
217 verifyZeroInteractions(sourceHashRepository);
218 verifyNoMoreInteractions(diff);
222 public void fail_with_NPE_when_component_is_null() {
223 assertThatThrownBy(() -> underTest.getScmInfo(null))
224 .isInstanceOf(NullPointerException.class)
225 .hasMessage("Component cannot be null");
229 @UseDataProvider("allTypeComponentButFile")
230 public void do_not_query_db_nor_report_if_component_type_is_not_FILE(Component component) {
231 BatchReportReader batchReportReader = mock(BatchReportReader.class);
232 ScmInfoRepositoryImpl underTest = new ScmInfoRepositoryImpl(batchReportReader, analysisMetadata, dbLoader, diff, sourceHashRepository);
234 assertThat(underTest.getScmInfo(component)).isEmpty();
236 verifyZeroInteractions(batchReportReader, dbLoader);
240 public static Object[][] allTypeComponentButFile() {
241 Object[][] res = new Object[Component.Type.values().length - 1][1];
243 for (Component.Type type : EnumSet.complementOf(EnumSet.of(Component.Type.FILE))) {
244 if (type.isReportType()) {
245 res[i][0] = ReportComponent.builder(type, i).build();
247 res[i][0] = ViewsComponent.builder(type, i).build();
254 private void assertChangeset(Changeset changeset, String revision, String author, long date) {
255 assertThat(changeset.getAuthor()).isEqualTo(author);
256 assertThat(changeset.getRevision()).isEqualTo(revision);
257 assertThat(changeset.getDate()).isEqualTo(date);
260 private void addChangesetInReport(String author, Long date, String revision) {
261 addChangesetInReport(author, date, revision, false);
264 private void addChangesetInReport(String author, Long date, String revision, boolean copyFromPrevious) {
265 reportReader.putChangesets(ScannerReport.Changesets.newBuilder()
266 .setComponentRef(FILE_REF)
267 .setCopyFromPrevious(copyFromPrevious)
268 .addChangeset(ScannerReport.Changesets.Changeset.newBuilder()
271 .setRevision(revision)
273 .addChangesetIndexByLine(0)
277 private void addCopyFromPrevious() {
278 reportReader.putChangesets(Changesets.newBuilder().setComponentRef(FILE_REF).setCopyFromPrevious(true).build());
281 private DbScmInfo createDbScmInfoWithOneLine(String hash) {
282 Line line1 = Line.newBuilder().setLine(1)
283 .setScmRevision("rev1")
284 .setScmAuthor("author1")
287 DbScmInfo scmInfo = DbScmInfo.create(Collections.singletonList(line1), 1, hash).get();
288 when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.of(scmInfo));
292 private void addFileSourceInReport(int lineCount) {
293 reportReader.putFileSourceLines(FILE_REF, generateLines(lineCount));
294 reportReader.putComponent(ScannerReport.Component.newBuilder()
300 private static List<String> generateLines(int lineCount) {
301 ImmutableList.Builder<String> builder = ImmutableList.builder();
302 for (int i = 0; i < lineCount; i++) {
303 builder.add("line " + i);
305 return builder.build();