]> source.dussan.org Git - sonarqube.git/blob
1d1caf214c3abe32d0e920d7777196e1db1132d1
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2023 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.issue;
21
22 import java.util.Date;
23 import java.util.List;
24 import java.util.Optional;
25 import org.junit.Before;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.junit.rules.TemporaryFolder;
29 import org.mockito.ArgumentCaptor;
30 import org.sonar.api.config.internal.MapSettings;
31 import org.sonar.api.issue.Issue;
32 import org.sonar.api.rule.RuleKey;
33 import org.sonar.api.rule.Severity;
34 import org.sonar.api.utils.System2;
35 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
36 import org.sonar.ce.task.projectanalysis.analysis.Branch;
37 import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
38 import org.sonar.ce.task.projectanalysis.component.Component;
39 import org.sonar.ce.task.projectanalysis.component.FileStatuses;
40 import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
41 import org.sonar.ce.task.projectanalysis.component.ReportComponent;
42 import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
43 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitor;
44 import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
45 import org.sonar.ce.task.projectanalysis.issue.filter.IssueFilter;
46 import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder;
47 import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderRule;
48 import org.sonar.ce.task.projectanalysis.qualityprofile.AlwaysActiveRulesHolderImpl;
49 import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
50 import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository;
51 import org.sonar.ce.task.projectanalysis.source.SourceLinesRepository;
52 import org.sonar.core.issue.DefaultIssue;
53 import org.sonar.core.issue.FieldDiffs;
54 import org.sonar.core.issue.IssueChangeContext;
55 import org.sonar.core.issue.tracking.Tracker;
56 import org.sonar.db.DbClient;
57 import org.sonar.db.DbTester;
58 import org.sonar.db.component.BranchType;
59 import org.sonar.db.component.ComponentDto;
60 import org.sonar.db.component.ComponentTesting;
61 import org.sonar.db.issue.IssueDto;
62 import org.sonar.db.issue.IssueTesting;
63 import org.sonar.db.rule.RuleDto;
64 import org.sonar.db.rule.RuleTesting;
65 import org.sonar.scanner.protocol.Constants;
66 import org.sonar.scanner.protocol.output.ScannerReport;
67 import org.sonar.server.issue.IssueFieldsSetter;
68 import org.sonar.server.issue.workflow.IssueWorkflow;
69
70 import static com.google.common.collect.Lists.newArrayList;
71 import static java.util.Collections.singletonList;
72 import static org.assertj.core.api.Assertions.assertThat;
73 import static org.assertj.core.api.Assertions.entry;
74 import static org.mockito.ArgumentMatchers.any;
75 import static org.mockito.ArgumentMatchers.eq;
76 import static org.mockito.Mockito.mock;
77 import static org.mockito.Mockito.verify;
78 import static org.mockito.Mockito.when;
79
80 public class IntegrateIssuesVisitorTest {
81
82   private static final String FILE_UUID = "FILE_UUID";
83   private static final String FILE_UUID_ON_BRANCH = "FILE_UUID_BRANCH";
84   private static final String FILE_KEY = "FILE_KEY";
85   private static final int FILE_REF = 2;
86
87   private static final Component FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF)
88     .setKey(FILE_KEY)
89     .setUuid(FILE_UUID)
90     .build();
91
92   private static final String PROJECT_KEY = "PROJECT_KEY";
93   private static final String PROJECT_UUID = "PROJECT_UUID";
94   private static final String PROJECT_UUID_ON_BRANCH = "PROJECT_UUID_BRANCH";
95   private static final int PROJECT_REF = 1;
96   private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, PROJECT_REF)
97     .setKey(PROJECT_KEY)
98     .setUuid(PROJECT_UUID)
99     .addChildren(FILE)
100     .build();
101
102   @Rule
103   public TemporaryFolder temp = new TemporaryFolder();
104   @Rule
105   public DbTester dbTester = DbTester.create(System2.INSTANCE);
106   @Rule
107   public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
108   @Rule
109   public BatchReportReaderRule reportReader = new BatchReportReaderRule();
110   @Rule
111   public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
112   @Rule
113   public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
114
115   private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
116   private final IssueFilter issueFilter = mock(IssueFilter.class);
117   private final MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class);
118   private final IssueChangeContext issueChangeContext = mock(IssueChangeContext.class);
119   private final IssueLifecycle issueLifecycle = new IssueLifecycle(analysisMetadataHolder, issueChangeContext, mock(IssueWorkflow.class), new IssueFieldsSetter(),
120     mock(DebtCalculator.class), ruleRepositoryRule);
121   private final IssueVisitor issueVisitor = mock(IssueVisitor.class);
122   private final ReferenceBranchComponentUuids mergeBranchComponentsUuids = mock(ReferenceBranchComponentUuids.class);
123   private final SiblingsIssueMerger issueStatusCopier = mock(SiblingsIssueMerger.class);
124   private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class);
125   private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class);
126   private final NewLinesRepository newLinesRepository = mock(NewLinesRepository.class);
127   private final TargetBranchComponentUuids targetBranchComponentUuids = mock(TargetBranchComponentUuids.class);
128   private final SourceLinesRepository sourceLinesRepository = mock(SourceLinesRepository.class);
129   private final FileStatuses fileStatuses = mock(FileStatuses.class);
130   private ArgumentCaptor<DefaultIssue> defaultIssueCaptor;
131
132   private final ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(),
133     System2.INSTANCE, mock(IssueChangesToDeleteRepository.class));
134   private IssueTrackingDelegator trackingDelegator;
135   private TrackerExecution tracker;
136   private PullRequestTrackerExecution prBranchTracker;
137   private ReferenceBranchTrackerExecution mergeBranchTracker;
138   private final ActiveRulesHolder activeRulesHolder = new AlwaysActiveRulesHolderImpl();
139   private ProtoIssueCache protoIssueCache;
140
141   private TypeAwareVisitor underTest;
142
143   @Before
144   public void setUp() throws Exception {
145     IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
146
147     defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
148     when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty());
149
150     DbClient dbClient = dbTester.getDbClient();
151     TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash, issueFilter,
152       ruleRepositoryRule, activeRulesHolder);
153     TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbClient, movedFilesRepository);
154     TrackerTargetBranchInputFactory targetInputFactory = new TrackerTargetBranchInputFactory(issuesLoader, targetBranchComponentUuids, dbClient, movedFilesRepository);
155     TrackerReferenceBranchInputFactory mergeInputFactory = new TrackerReferenceBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbClient);
156     ClosedIssuesInputFactory closedIssuesInputFactory = new ClosedIssuesInputFactory(issuesLoader, dbClient, movedFilesRepository);
157     tracker = new TrackerExecution(baseInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder);
158     mergeBranchTracker = new ReferenceBranchTrackerExecution(mergeInputFactory, new Tracker<>());
159     prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, targetInputFactory, new Tracker<>(), newLinesRepository);
160     trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder);
161     treeRootHolder.setRoot(PROJECT);
162     protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
163     when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true);
164     when(issueChangeContext.date()).thenReturn(new Date());
165     underTest = new IntegrateIssuesVisitor(protoIssueCache, rawInputFactory, baseInputFactory, issueLifecycle, issueVisitors, trackingDelegator, issueStatusCopier,
166       referenceBranchComponentUuids, mock(PullRequestSourceBranchMerger.class), fileStatuses);
167   }
168
169   @Test
170   public void process_new_issue() {
171     ruleRepositoryRule.add(RuleKey.of("xoo", "S001"));
172     when(analysisMetadataHolder.isBranch()).thenReturn(true);
173     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
174       .setMsg("the message")
175       .setRuleRepository("xoo")
176       .setRuleKey("S001")
177       .setSeverity(Constants.Severity.BLOCKER)
178       .build();
179     reportReader.putIssues(FILE_REF, singletonList(reportIssue));
180
181     underTest.visitAny(FILE);
182
183     assertThat(newArrayList(protoIssueCache.traverse())).hasSize(1);
184   }
185
186   @Test
187   public void process_existing_issue() {
188     RuleKey ruleKey = RuleTesting.XOO_X1;
189     // Issue from db has severity major
190     addBaseIssue(ruleKey);
191
192     // Issue from report has severity blocker
193     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
194       .setMsg("new message")
195       .setRuleRepository(ruleKey.repository())
196       .setRuleKey(ruleKey.rule())
197       .setSeverity(Constants.Severity.BLOCKER)
198       .build();
199     reportReader.putIssues(FILE_REF, singletonList(reportIssue));
200
201     underTest.visitAny(FILE);
202
203     List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
204     assertThat(issues).hasSize(1);
205     assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
206   }
207
208   @Test
209   public void dont_cache_existing_issue_if_unmodified() {
210     RuleKey ruleKey = RuleTesting.XOO_X1;
211     // Issue from db has severity major
212     addBaseIssue(ruleKey);
213
214     // Issue from report has severity blocker
215     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
216       .setMsg("the message")
217       .setRuleRepository(ruleKey.repository())
218       .setRuleKey(ruleKey.rule())
219       .setSeverity(Constants.Severity.BLOCKER)
220       .build();
221     reportReader.putIssues(FILE_REF, singletonList(reportIssue));
222
223     underTest.visitAny(FILE);
224
225     List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
226     assertThat(issues).hasSize(1);
227     assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
228   }
229
230   @Test
231   public void execute_issue_visitors() {
232     ruleRepositoryRule.add(RuleKey.of("xoo", "S001"));
233     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
234       .setMsg("the message")
235       .setRuleRepository("xoo")
236       .setRuleKey("S001")
237       .setSeverity(Constants.Severity.BLOCKER)
238       .build();
239     reportReader.putIssues(FILE_REF, singletonList(reportIssue));
240
241     underTest.visitAny(FILE);
242
243     verify(issueVisitor).beforeComponent(FILE);
244     verify(issueVisitor).afterComponent(FILE);
245     verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
246     assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
247   }
248
249   @Test
250   public void close_unmatched_base_issue() {
251     RuleKey ruleKey = RuleTesting.XOO_X1;
252     addBaseIssue(ruleKey);
253
254     // No issue in the report
255     underTest.visitAny(FILE);
256
257     List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
258     assertThat(issues).isEmpty();
259   }
260
261   @Test
262   public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() {
263     String originalFileUuid = "original file uuid";
264     when(movedFilesRepository.getOriginalFile(FILE))
265       .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalFileUuid, "original file key")));
266
267     underTest.visitAny(FILE);
268   }
269
270   @Test
271   public void reuse_issues_when_data_unchanged() {
272     RuleKey ruleKey = RuleTesting.XOO_X1;
273     // Issue from db has severity major
274     addBaseIssue(ruleKey);
275
276     // Issue from report has severity blocker
277     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
278       .setMsg("new message")
279       .setRuleRepository(ruleKey.repository())
280       .setRuleKey(ruleKey.rule())
281       .setSeverity(Constants.Severity.BLOCKER)
282       .build();
283     reportReader.putIssues(FILE_REF, singletonList(reportIssue));
284     when(fileStatuses.isDataUnchanged(FILE)).thenReturn(true);
285
286     underTest.visitAny(FILE);
287
288     // visitors get called, so measures created from issues should be calculated taking these issues into account
289     verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
290     assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo(ruleKey.rule());
291
292     // most issues won't go to the cache since they aren't changed and don't need to be persisted
293     // In this test they are being closed but the workflows aren't working (we mock them) so nothing is changed on the issue is not cached.
294     assertThat(newArrayList(protoIssueCache.traverse())).isEmpty();
295   }
296
297   @Test
298   public void copy_issues_when_creating_new_non_main_branch() {
299     when(mergeBranchComponentsUuids.getComponentUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH);
300     when(referenceBranchComponentUuids.getReferenceBranchName()).thenReturn("master");
301
302     when(analysisMetadataHolder.isBranch()).thenReturn(true);
303     when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true);
304     Branch branch = mock(Branch.class);
305     when(branch.isMain()).thenReturn(false);
306     when(branch.getType()).thenReturn(BranchType.BRANCH);
307     when(analysisMetadataHolder.getBranch()).thenReturn(branch);
308
309     RuleKey ruleKey = RuleTesting.XOO_X1;
310     // Issue from main branch has severity major
311     addBaseIssueOnBranch(ruleKey);
312
313     // Issue from report has severity blocker
314     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
315       .setMsg("the message")
316       .setRuleRepository(ruleKey.repository())
317       .setRuleKey(ruleKey.rule())
318       .setSeverity(Constants.Severity.BLOCKER)
319       .build();
320     reportReader.putIssues(FILE_REF, singletonList(reportIssue));
321
322     underTest.visitAny(FILE);
323
324     List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
325     assertThat(issues).hasSize(1);
326     assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
327     assertThat(issues.get(0).isNew()).isFalse();
328     assertThat(issues.get(0).isCopied()).isTrue();
329     assertThat(issues.get(0).changes()).hasSize(1);
330     assertThat(issues.get(0).changes().get(0).diffs()).contains(entry(IssueFieldsSetter.FROM_BRANCH, new FieldDiffs.Diff<>("master", null)));
331   }
332
333   private void addBaseIssue(RuleKey ruleKey) {
334     ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID).setKey(PROJECT_KEY);
335     ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setKey(FILE_KEY);
336     dbTester.components().insertComponents(project, file);
337
338     RuleDto ruleDto = RuleTesting.newDto(ruleKey);
339     dbTester.rules().insert(ruleDto);
340     ruleRepositoryRule.add(ruleKey);
341
342     IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
343       .setKee("ISSUE")
344       .setStatus(Issue.STATUS_OPEN)
345       .setSeverity(Severity.MAJOR);
346     dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
347     dbTester.getSession().commit();
348   }
349
350   private void addBaseIssueOnBranch(RuleKey ruleKey) {
351     ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID_ON_BRANCH).setKey(PROJECT_KEY);
352     ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID_ON_BRANCH).setKey(FILE_KEY);
353     dbTester.components().insertComponents(project, file);
354
355     RuleDto ruleDto = RuleTesting.newDto(ruleKey);
356     dbTester.rules().insert(ruleDto);
357     ruleRepositoryRule.add(ruleKey);
358
359     IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
360       .setKee("ISSUE")
361       .setStatus(Issue.STATUS_OPEN)
362       .setSeverity(Severity.MAJOR);
363     dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
364     dbTester.getSession().commit();
365   }
366 }