3 * Copyright (C) 2009-2023 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.issue;
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;
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;
80 public class IntegrateIssuesVisitorTest {
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;
87 private static final Component FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF)
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)
98 .setUuid(PROJECT_UUID)
103 public TemporaryFolder temp = new TemporaryFolder();
105 public DbTester dbTester = DbTester.create(System2.INSTANCE);
107 public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
109 public BatchReportReaderRule reportReader = new BatchReportReaderRule();
111 public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
113 public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
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;
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;
141 private TypeAwareVisitor underTest;
144 public void setUp() throws Exception {
145 IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
147 defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
148 when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty());
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);
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")
177 .setSeverity(Constants.Severity.BLOCKER)
179 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
181 underTest.visitAny(FILE);
183 assertThat(newArrayList(protoIssueCache.traverse())).hasSize(1);
187 public void process_existing_issue() {
188 RuleKey ruleKey = RuleTesting.XOO_X1;
189 // Issue from db has severity major
190 addBaseIssue(ruleKey);
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)
199 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
201 underTest.visitAny(FILE);
203 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
204 assertThat(issues).hasSize(1);
205 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
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);
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)
221 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
223 underTest.visitAny(FILE);
225 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
226 assertThat(issues).hasSize(1);
227 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
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")
237 .setSeverity(Constants.Severity.BLOCKER)
239 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
241 underTest.visitAny(FILE);
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");
250 public void close_unmatched_base_issue() {
251 RuleKey ruleKey = RuleTesting.XOO_X1;
252 addBaseIssue(ruleKey);
254 // No issue in the report
255 underTest.visitAny(FILE);
257 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
258 assertThat(issues).isEmpty();
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")));
267 underTest.visitAny(FILE);
271 public void reuse_issues_when_data_unchanged() {
272 RuleKey ruleKey = RuleTesting.XOO_X1;
273 // Issue from db has severity major
274 addBaseIssue(ruleKey);
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)
283 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
284 when(fileStatuses.isDataUnchanged(FILE)).thenReturn(true);
286 underTest.visitAny(FILE);
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());
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();
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");
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);
309 RuleKey ruleKey = RuleTesting.XOO_X1;
310 // Issue from main branch has severity major
311 addBaseIssueOnBranch(ruleKey);
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)
320 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
322 underTest.visitAny(FILE);
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)));
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);
338 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
339 dbTester.rules().insert(ruleDto);
340 ruleRepositoryRule.add(ruleKey);
342 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
344 .setStatus(Issue.STATUS_OPEN)
345 .setSeverity(Severity.MAJOR);
346 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
347 dbTester.getSession().commit();
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);
355 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
356 dbTester.rules().insert(ruleDto);
357 ruleRepositoryRule.add(ruleKey);
359 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
361 .setStatus(Issue.STATUS_OPEN)
362 .setSeverity(Severity.MAJOR);
363 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
364 dbTester.getSession().commit();