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.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.ReferenceBranchComponentUuids;
40 import org.sonar.ce.task.projectanalysis.component.ReportComponent;
41 import org.sonar.ce.task.projectanalysis.component.ReportModulesPath;
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.commonrule.CommonRuleEngineImpl;
46 import org.sonar.ce.task.projectanalysis.issue.filter.IssueFilter;
47 import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolder;
48 import org.sonar.ce.task.projectanalysis.qualityprofile.ActiveRulesHolderRule;
49 import org.sonar.ce.task.projectanalysis.qualityprofile.AlwaysActiveRulesHolderImpl;
50 import org.sonar.ce.task.projectanalysis.source.NewLinesRepository;
51 import org.sonar.ce.task.projectanalysis.source.SourceLinesHashRepository;
52 import org.sonar.ce.task.projectanalysis.source.SourceLinesRepositoryRule;
53 import org.sonar.core.issue.DefaultIssue;
54 import org.sonar.core.issue.FieldDiffs;
55 import org.sonar.core.issue.IssueChangeContext;
56 import org.sonar.core.issue.tracking.Tracker;
57 import org.sonar.db.DbClient;
58 import org.sonar.db.DbTester;
59 import org.sonar.db.component.BranchType;
60 import org.sonar.db.component.ComponentDto;
61 import org.sonar.db.component.ComponentTesting;
62 import org.sonar.db.issue.IssueDto;
63 import org.sonar.db.issue.IssueTesting;
64 import org.sonar.db.rule.RuleDto;
65 import org.sonar.db.rule.RuleTesting;
66 import org.sonar.scanner.protocol.Constants;
67 import org.sonar.scanner.protocol.output.ScannerReport;
68 import org.sonar.server.issue.IssueFieldsSetter;
69 import org.sonar.server.issue.workflow.IssueWorkflow;
71 import static com.google.common.collect.Lists.newArrayList;
72 import static java.util.Collections.singletonList;
73 import static org.assertj.core.api.Assertions.assertThat;
74 import static org.assertj.core.api.Assertions.entry;
75 import static org.mockito.ArgumentMatchers.any;
76 import static org.mockito.ArgumentMatchers.eq;
77 import static org.mockito.Mockito.mock;
78 import static org.mockito.Mockito.verify;
79 import static org.mockito.Mockito.when;
81 public class IntegrateIssuesVisitorTest {
83 private static final String FILE_UUID = "FILE_UUID";
84 private static final String FILE_UUID_ON_BRANCH = "FILE_UUID_BRANCH";
85 private static final String FILE_KEY = "FILE_KEY";
86 private static final int FILE_REF = 2;
88 private static final Component FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF)
93 private static final String PROJECT_KEY = "PROJECT_KEY";
94 private static final String PROJECT_UUID = "PROJECT_UUID";
95 private static final String PROJECT_UUID_ON_BRANCH = "PROJECT_UUID_BRANCH";
96 private static final int PROJECT_REF = 1;
97 private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, PROJECT_REF)
99 .setUuid(PROJECT_UUID)
104 public TemporaryFolder temp = new TemporaryFolder();
106 public DbTester dbTester = DbTester.create(System2.INSTANCE);
108 public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
110 public BatchReportReaderRule reportReader = new BatchReportReaderRule();
112 public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
114 public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
116 public SourceLinesRepositoryRule fileSourceRepository = new SourceLinesRepositoryRule();
118 private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
119 private final IssueFilter issueFilter = mock(IssueFilter.class);
120 private final MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class);
121 private final IssueChangeContext issueChangeContext = mock(IssueChangeContext.class);
122 private final IssueLifecycle issueLifecycle = new IssueLifecycle(analysisMetadataHolder, issueChangeContext, mock(IssueWorkflow.class), new IssueFieldsSetter(),
123 mock(DebtCalculator.class), ruleRepositoryRule);
124 private final IssueVisitor issueVisitor = mock(IssueVisitor.class);
125 private final ReferenceBranchComponentUuids mergeBranchComponentsUuids = mock(ReferenceBranchComponentUuids.class);
126 private final SiblingsIssueMerger issueStatusCopier = mock(SiblingsIssueMerger.class);
127 private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class);
128 private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class);
129 private final NewLinesRepository newLinesRepository = mock(NewLinesRepository.class);
130 private TargetBranchComponentUuids targetBranchComponentUuids = mock(TargetBranchComponentUuids.class);
131 private ArgumentCaptor<DefaultIssue> defaultIssueCaptor;
133 private final ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(),
134 System2.INSTANCE, mock(IssueChangesToDeleteRepository.class));
135 private IssueTrackingDelegator trackingDelegator;
136 private TrackerExecution tracker;
137 private PullRequestTrackerExecution prBranchTracker;
138 private ReferenceBranchTrackerExecution mergeBranchTracker;
139 private final ActiveRulesHolder activeRulesHolder = new AlwaysActiveRulesHolderImpl();
140 private ProtoIssueCache protoIssueCache;
142 private TypeAwareVisitor underTest;
145 public void setUp() throws Exception {
146 IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
148 defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
149 when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty());
151 DbClient dbClient = dbTester.getDbClient();
152 TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash, new CommonRuleEngineImpl(),
153 issueFilter, ruleRepositoryRule, activeRulesHolder);
154 TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbClient, movedFilesRepository, mock(ReportModulesPath.class), analysisMetadataHolder,
155 new IssueFieldsSetter(), mock(ComponentsWithUnprocessedIssues.class));
156 TrackerTargetBranchInputFactory targetInputFactory = new TrackerTargetBranchInputFactory(issuesLoader, targetBranchComponentUuids, dbClient);
157 TrackerReferenceBranchInputFactory mergeInputFactory = new TrackerReferenceBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbClient);
158 ClosedIssuesInputFactory closedIssuesInputFactory = new ClosedIssuesInputFactory(issuesLoader, dbClient, movedFilesRepository);
159 tracker = new TrackerExecution(baseInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder);
160 mergeBranchTracker = new ReferenceBranchTrackerExecution(mergeInputFactory, new Tracker<>());
161 prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, targetInputFactory, new Tracker<>(), newLinesRepository);
162 trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder);
163 treeRootHolder.setRoot(PROJECT);
164 protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
165 when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true);
166 when(issueChangeContext.date()).thenReturn(new Date());
167 underTest = new IntegrateIssuesVisitor(protoIssueCache, rawInputFactory, issueLifecycle, issueVisitors, trackingDelegator, issueStatusCopier, referenceBranchComponentUuids,
168 mock(PullRequestSourceBranchMerger.class));
172 public void process_new_issue() {
173 ruleRepositoryRule.add(RuleKey.of("xoo", "S001"));
174 when(analysisMetadataHolder.isBranch()).thenReturn(true);
175 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
176 .setMsg("the message")
177 .setRuleRepository("xoo")
179 .setSeverity(Constants.Severity.BLOCKER)
181 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
182 fileSourceRepository.addLine(FILE_REF, "line1");
184 underTest.visitAny(FILE);
186 assertThat(newArrayList(protoIssueCache.traverse())).hasSize(1);
190 public void process_existing_issue() {
192 RuleKey ruleKey = RuleTesting.XOO_X1;
193 // Issue from db has severity major
194 addBaseIssue(ruleKey);
196 // Issue from report has severity blocker
197 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
198 .setMsg("new message")
199 .setRuleRepository(ruleKey.repository())
200 .setRuleKey(ruleKey.rule())
201 .setSeverity(Constants.Severity.BLOCKER)
203 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
204 fileSourceRepository.addLine(FILE_REF, "line1");
206 underTest.visitAny(FILE);
208 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
209 assertThat(issues).hasSize(1);
210 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
215 public void dont_cache_existing_issue_if_unmodified() {
217 RuleKey ruleKey = RuleTesting.XOO_X1;
218 // Issue from db has severity major
219 addBaseIssue(ruleKey);
221 // Issue from report has severity blocker
222 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
223 .setMsg("the message")
224 .setRuleRepository(ruleKey.repository())
225 .setRuleKey(ruleKey.rule())
226 .setSeverity(Constants.Severity.BLOCKER)
228 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
229 fileSourceRepository.addLine(FILE_REF, "line1");
231 underTest.visitAny(FILE);
233 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
234 assertThat(issues).hasSize(1);
235 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
240 public void execute_issue_visitors() {
241 ruleRepositoryRule.add(RuleKey.of("xoo", "S001"));
242 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
243 .setMsg("the message")
244 .setRuleRepository("xoo")
246 .setSeverity(Constants.Severity.BLOCKER)
248 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
249 fileSourceRepository.addLine(FILE_REF, "line1");
251 underTest.visitAny(FILE);
253 verify(issueVisitor).beforeComponent(FILE);
254 verify(issueVisitor).afterComponent(FILE);
255 verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
256 assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
260 public void close_unmatched_base_issue() {
261 RuleKey ruleKey = RuleTesting.XOO_X1;
262 addBaseIssue(ruleKey);
264 // No issue in the report
265 underTest.visitAny(FILE);
267 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
268 assertThat(issues).isEmpty();
272 public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() {
273 String originalFileUuid = "original file uuid";
274 when(movedFilesRepository.getOriginalFile(FILE))
275 .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalFileUuid, "original file key")));
277 underTest.visitAny(FILE);
281 public void copy_issues_when_creating_new_non_main_branch() {
283 when(mergeBranchComponentsUuids.getComponentUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH);
284 when(referenceBranchComponentUuids.getReferenceBranchName()).thenReturn("master");
286 when(analysisMetadataHolder.isBranch()).thenReturn(true);
287 when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true);
288 Branch branch = mock(Branch.class);
289 when(branch.isMain()).thenReturn(false);
290 when(branch.getType()).thenReturn(BranchType.BRANCH);
291 when(analysisMetadataHolder.getBranch()).thenReturn(branch);
293 RuleKey ruleKey = RuleTesting.XOO_X1;
294 // Issue from main branch has severity major
295 addBaseIssueOnBranch(ruleKey);
297 // Issue from report has severity blocker
298 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
299 .setMsg("the message")
300 .setRuleRepository(ruleKey.repository())
301 .setRuleKey(ruleKey.rule())
302 .setSeverity(Constants.Severity.BLOCKER)
304 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
305 fileSourceRepository.addLine(FILE_REF, "line1");
307 underTest.visitAny(FILE);
309 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
310 assertThat(issues).hasSize(1);
311 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
312 assertThat(issues.get(0).isNew()).isFalse();
313 assertThat(issues.get(0).isCopied()).isTrue();
314 assertThat(issues.get(0).changes()).hasSize(1);
315 assertThat(issues.get(0).changes().get(0).diffs()).contains(entry(IssueFieldsSetter.FROM_BRANCH, new FieldDiffs.Diff<>("master", null)));
318 private void addBaseIssue(RuleKey ruleKey) {
319 ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID).setDbKey(PROJECT_KEY);
320 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setDbKey(FILE_KEY);
321 dbTester.components().insertComponents(project, file);
323 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
324 dbTester.rules().insertRule(ruleDto);
325 ruleRepositoryRule.add(ruleKey);
327 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
329 .setStatus(Issue.STATUS_OPEN)
330 .setSeverity(Severity.MAJOR);
331 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
332 dbTester.getSession().commit();
335 private void addBaseIssueOnBranch(RuleKey ruleKey) {
336 ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID_ON_BRANCH).setDbKey(PROJECT_KEY);
337 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID_ON_BRANCH).setDbKey(FILE_KEY);
338 dbTester.components().insertComponents(project, file);
340 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
341 dbTester.rules().insertRule(ruleDto);
342 ruleRepositoryRule.add(ruleKey);
344 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
346 .setStatus(Issue.STATUS_OPEN)
347 .setSeverity(Severity.MAJOR);
348 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
349 dbTester.getSession().commit();