]> source.dussan.org Git - sonarqube.git/blob
9faf3d250465e9b856a638000b0570a95e20cd67
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2022 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.ce.task.projectanalysis.scm;
21
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;
50
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;
60
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;
69
70   @Rule
71   public LogTester logTester = new LogTester();
72   @Rule
73   public BatchReportReaderRule reportReader = new BatchReportReaderRule();
74   @Rule
75   public AnalysisMetadataHolderRule analysisMetadata = new AnalysisMetadataHolderRule();
76
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();
81
82   private ScmInfoRepositoryImpl underTest = new ScmInfoRepositoryImpl(reportReader, analysisMetadata, dbLoader, diff, sourceHashRepository);
83
84   @Before
85   public void setUp() {
86     analysisMetadata.setAnalysisDate(analysisDate);
87   }
88
89   @Test
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();
94   }
95
96   @Test
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);
101
102     assertThat(logTester.logs(TRACE)).hasSize(1);
103     logTester.clear();
104
105     underTest.getScmInfo(FILE);
106     assertThat(logTester.logs(TRACE)).isEmpty();
107
108     verifyZeroInteractions(dbLoader);
109     verifyZeroInteractions(sourceHashRepository);
110     verifyZeroInteractions(diff);
111   }
112
113   @Test
114   public void read_from_report() {
115     addChangesetInReport("john", DATE_1, "rev-1");
116
117     ScmInfo scmInfo = underTest.getScmInfo(FILE).get();
118     assertThat(scmInfo.getAllChangesets()).hasSize(1);
119
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");
124
125     assertThat(logTester.logs(TRACE)).containsOnly("Reading SCM info from report for file 'FILE_KEY'");
126
127     verifyZeroInteractions(dbLoader);
128     verifyZeroInteractions(sourceHashRepository);
129     verifyZeroInteractions(diff);
130   }
131
132   @Test
133   public void read_from_DB_if_no_report_and_file_unchanged() {
134     createDbScmInfoWithOneLine("hash");
135     when(sourceHashRepository.getRawSourceHash(FILE_SAME)).thenReturn("hash");
136
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);
141
142     verify(sourceHashRepository).getRawSourceHash(FILE_SAME);
143     verify(dbLoader).getScmInfo(FILE_SAME);
144
145     verifyNoMoreInteractions(dbLoader);
146     verifyNoMoreInteractions(sourceHashRepository);
147     verifyZeroInteractions(diff);
148   }
149
150   @Test
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();
156
157     ScmInfo scmInfo = underTest.getScmInfo(FILE_SAME).get();
158     assertThat(scmInfo.getAllChangesets()).hasSize(1);
159     assertChangeset(scmInfo.getChangesetForLine(1), "rev1", "author1", 10L);
160
161     verify(sourceHashRepository).getRawSourceHash(FILE_SAME);
162     verify(dbLoader).getScmInfo(FILE_SAME);
163
164     verifyNoMoreInteractions(dbLoader);
165     verifyNoMoreInteractions(sourceHashRepository);
166     verifyZeroInteractions(diff);
167   }
168
169   @Test
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);
174
175     for (int i = 1; i <= 3; i++) {
176       assertChangeset(scmInfo.getChangesetForLine(i), null, null, analysisDate.getTime());
177     }
178
179     verify(dbLoader).getScmInfo(FILE);
180     verifyNoMoreInteractions(dbLoader);
181     verifyZeroInteractions(sourceHashRepository);
182     verifyZeroInteractions(diff);
183   }
184
185   @Test
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);
191
192     for (int i = 1; i <= 3; i++) {
193       assertChangeset(scmInfo.getChangesetForLine(i), null, null, analysisDate.getTime());
194     }
195
196     verify(dbLoader).getScmInfo(FILE);
197     verifyNoMoreInteractions(dbLoader);
198     verifyZeroInteractions(sourceHashRepository);
199     verifyZeroInteractions(diff);
200   }
201
202   @Test
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);
209
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());
213
214     verify(dbLoader).getScmInfo(FILE);
215     verify(diff).computeMatchingLines(FILE);
216     verifyNoMoreInteractions(dbLoader);
217     verifyZeroInteractions(sourceHashRepository);
218     verifyNoMoreInteractions(diff);
219   }
220
221   @Test
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");
226   }
227
228   @Test
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);
233
234     assertThat(underTest.getScmInfo(component)).isEmpty();
235
236     verifyZeroInteractions(batchReportReader, dbLoader);
237   }
238
239   @DataProvider
240   public static Object[][] allTypeComponentButFile() {
241     Object[][] res = new Object[Component.Type.values().length - 1][1];
242     int i = 0;
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();
246       } else {
247         res[i][0] = ViewsComponent.builder(type, i).build();
248       }
249       i++;
250     }
251     return res;
252   }
253
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);
258   }
259
260   private void addChangesetInReport(String author, Long date, String revision) {
261     addChangesetInReport(author, date, revision, false);
262   }
263
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()
269         .setAuthor(author)
270         .setDate(date)
271         .setRevision(revision)
272         .build())
273       .addChangesetIndexByLine(0)
274       .build());
275   }
276
277   private void addCopyFromPrevious() {
278     reportReader.putChangesets(Changesets.newBuilder().setComponentRef(FILE_REF).setCopyFromPrevious(true).build());
279   }
280
281   private DbScmInfo createDbScmInfoWithOneLine(String hash) {
282     Line line1 = Line.newBuilder().setLine(1)
283       .setScmRevision("rev1")
284       .setScmAuthor("author1")
285       .setScmDate(10L)
286       .build();
287     DbScmInfo scmInfo = DbScmInfo.create(Collections.singletonList(line1), 1, hash).get();
288     when(dbLoader.getScmInfo(FILE)).thenReturn(Optional.of(scmInfo));
289     return scmInfo;
290   }
291
292   private void addFileSourceInReport(int lineCount) {
293     reportReader.putFileSourceLines(FILE_REF, generateLines(lineCount));
294     reportReader.putComponent(ScannerReport.Component.newBuilder()
295       .setRef(FILE_REF)
296       .setLines(lineCount)
297       .build());
298   }
299
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);
304     }
305     return builder.build();
306   }
307
308 }