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.SourceLinesRepository;
53 import org.sonar.ce.task.projectanalysis.source.SourceLinesRepositoryRule;
54 import org.sonar.core.issue.DefaultIssue;
55 import org.sonar.core.issue.FieldDiffs;
56 import org.sonar.core.issue.IssueChangeContext;
57 import org.sonar.core.issue.tracking.Tracker;
58 import org.sonar.db.DbClient;
59 import org.sonar.db.DbTester;
60 import org.sonar.db.component.BranchType;
61 import org.sonar.db.component.ComponentDto;
62 import org.sonar.db.component.ComponentTesting;
63 import org.sonar.db.issue.IssueDto;
64 import org.sonar.db.issue.IssueTesting;
65 import org.sonar.db.rule.RuleDto;
66 import org.sonar.db.rule.RuleTesting;
67 import org.sonar.scanner.protocol.Constants;
68 import org.sonar.scanner.protocol.output.ScannerReport;
69 import org.sonar.server.issue.IssueFieldsSetter;
70 import org.sonar.server.issue.workflow.IssueWorkflow;
72 import static com.google.common.collect.Lists.newArrayList;
73 import static java.util.Collections.singletonList;
74 import static org.assertj.core.api.Assertions.assertThat;
75 import static org.assertj.core.api.Assertions.entry;
76 import static org.mockito.ArgumentMatchers.any;
77 import static org.mockito.ArgumentMatchers.eq;
78 import static org.mockito.Mockito.mock;
79 import static org.mockito.Mockito.verify;
80 import static org.mockito.Mockito.when;
82 public class IntegrateIssuesVisitorTest {
84 private static final String FILE_UUID = "FILE_UUID";
85 private static final String FILE_UUID_ON_BRANCH = "FILE_UUID_BRANCH";
86 private static final String FILE_KEY = "FILE_KEY";
87 private static final int FILE_REF = 2;
89 private static final Component FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF)
94 private static final String PROJECT_KEY = "PROJECT_KEY";
95 private static final String PROJECT_UUID = "PROJECT_UUID";
96 private static final String PROJECT_UUID_ON_BRANCH = "PROJECT_UUID_BRANCH";
97 private static final int PROJECT_REF = 1;
98 private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, PROJECT_REF)
100 .setUuid(PROJECT_UUID)
105 public TemporaryFolder temp = new TemporaryFolder();
107 public DbTester dbTester = DbTester.create(System2.INSTANCE);
109 public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
111 public BatchReportReaderRule reportReader = new BatchReportReaderRule();
113 public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
115 public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
117 public SourceLinesRepositoryRule fileSourceRepository = new SourceLinesRepositoryRule();
119 private final AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
120 private final IssueFilter issueFilter = mock(IssueFilter.class);
121 private final MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class);
122 private final IssueChangeContext issueChangeContext = mock(IssueChangeContext.class);
123 private final IssueLifecycle issueLifecycle = new IssueLifecycle(analysisMetadataHolder, issueChangeContext, mock(IssueWorkflow.class), new IssueFieldsSetter(),
124 mock(DebtCalculator.class), ruleRepositoryRule);
125 private final IssueVisitor issueVisitor = mock(IssueVisitor.class);
126 private final ReferenceBranchComponentUuids mergeBranchComponentsUuids = mock(ReferenceBranchComponentUuids.class);
127 private final SiblingsIssueMerger issueStatusCopier = mock(SiblingsIssueMerger.class);
128 private final ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class);
129 private final SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class);
130 private final NewLinesRepository newLinesRepository = mock(NewLinesRepository.class);
131 private TargetBranchComponentUuids targetBranchComponentUuids = mock(TargetBranchComponentUuids.class);
132 private final SourceLinesRepository sourceLinesRepository = mock(SourceLinesRepository.class);
133 private ArgumentCaptor<DefaultIssue> defaultIssueCaptor;
135 private final ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(),
136 System2.INSTANCE, mock(IssueChangesToDeleteRepository.class));
137 private IssueTrackingDelegator trackingDelegator;
138 private TrackerExecution tracker;
139 private PullRequestTrackerExecution prBranchTracker;
140 private ReferenceBranchTrackerExecution mergeBranchTracker;
141 private final ActiveRulesHolder activeRulesHolder = new AlwaysActiveRulesHolderImpl();
142 private ProtoIssueCache protoIssueCache;
144 private TypeAwareVisitor underTest;
147 public void setUp() throws Exception {
148 IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
150 defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
151 when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty());
153 DbClient dbClient = dbTester.getDbClient();
154 TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash, sourceLinesRepository,
155 new CommonRuleEngineImpl(), issueFilter, ruleRepositoryRule, activeRulesHolder);
156 TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbClient, movedFilesRepository, mock(ReportModulesPath.class), analysisMetadataHolder,
157 new IssueFieldsSetter(), mock(ComponentsWithUnprocessedIssues.class));
158 TrackerTargetBranchInputFactory targetInputFactory = new TrackerTargetBranchInputFactory(issuesLoader, targetBranchComponentUuids, dbClient);
159 TrackerReferenceBranchInputFactory mergeInputFactory = new TrackerReferenceBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbClient);
160 ClosedIssuesInputFactory closedIssuesInputFactory = new ClosedIssuesInputFactory(issuesLoader, dbClient, movedFilesRepository);
161 tracker = new TrackerExecution(baseInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder);
162 mergeBranchTracker = new ReferenceBranchTrackerExecution(mergeInputFactory, new Tracker<>());
163 prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, targetInputFactory, new Tracker<>(), newLinesRepository);
164 trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder);
165 treeRootHolder.setRoot(PROJECT);
166 protoIssueCache = new ProtoIssueCache(temp.newFile(), System2.INSTANCE);
167 when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true);
168 when(issueChangeContext.date()).thenReturn(new Date());
169 underTest = new IntegrateIssuesVisitor(protoIssueCache, rawInputFactory, issueLifecycle, issueVisitors, trackingDelegator, issueStatusCopier, referenceBranchComponentUuids,
170 mock(PullRequestSourceBranchMerger.class));
174 public void process_new_issue() {
175 ruleRepositoryRule.add(RuleKey.of("xoo", "S001"));
176 when(analysisMetadataHolder.isBranch()).thenReturn(true);
177 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
178 .setMsg("the message")
179 .setRuleRepository("xoo")
181 .setSeverity(Constants.Severity.BLOCKER)
183 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
184 fileSourceRepository.addLine(FILE_REF, "line1");
186 underTest.visitAny(FILE);
188 assertThat(newArrayList(protoIssueCache.traverse())).hasSize(1);
192 public void process_existing_issue() {
194 RuleKey ruleKey = RuleTesting.XOO_X1;
195 // Issue from db has severity major
196 addBaseIssue(ruleKey);
198 // Issue from report has severity blocker
199 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
200 .setMsg("new message")
201 .setRuleRepository(ruleKey.repository())
202 .setRuleKey(ruleKey.rule())
203 .setSeverity(Constants.Severity.BLOCKER)
205 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
206 fileSourceRepository.addLine(FILE_REF, "line1");
208 underTest.visitAny(FILE);
210 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
211 assertThat(issues).hasSize(1);
212 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
217 public void dont_cache_existing_issue_if_unmodified() {
219 RuleKey ruleKey = RuleTesting.XOO_X1;
220 // Issue from db has severity major
221 addBaseIssue(ruleKey);
223 // Issue from report has severity blocker
224 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
225 .setMsg("the message")
226 .setRuleRepository(ruleKey.repository())
227 .setRuleKey(ruleKey.rule())
228 .setSeverity(Constants.Severity.BLOCKER)
230 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
231 fileSourceRepository.addLine(FILE_REF, "line1");
233 underTest.visitAny(FILE);
235 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
236 assertThat(issues).hasSize(1);
237 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
242 public void execute_issue_visitors() {
243 ruleRepositoryRule.add(RuleKey.of("xoo", "S001"));
244 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
245 .setMsg("the message")
246 .setRuleRepository("xoo")
248 .setSeverity(Constants.Severity.BLOCKER)
250 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
251 fileSourceRepository.addLine(FILE_REF, "line1");
253 underTest.visitAny(FILE);
255 verify(issueVisitor).beforeComponent(FILE);
256 verify(issueVisitor).afterComponent(FILE);
257 verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
258 assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
262 public void close_unmatched_base_issue() {
263 RuleKey ruleKey = RuleTesting.XOO_X1;
264 addBaseIssue(ruleKey);
266 // No issue in the report
267 underTest.visitAny(FILE);
269 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
270 assertThat(issues).isEmpty();
274 public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() {
275 String originalFileUuid = "original file uuid";
276 when(movedFilesRepository.getOriginalFile(FILE))
277 .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(originalFileUuid, "original file key")));
279 underTest.visitAny(FILE);
283 public void copy_issues_when_creating_new_non_main_branch() {
285 when(mergeBranchComponentsUuids.getComponentUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH);
286 when(referenceBranchComponentUuids.getReferenceBranchName()).thenReturn("master");
288 when(analysisMetadataHolder.isBranch()).thenReturn(true);
289 when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true);
290 Branch branch = mock(Branch.class);
291 when(branch.isMain()).thenReturn(false);
292 when(branch.getType()).thenReturn(BranchType.BRANCH);
293 when(analysisMetadataHolder.getBranch()).thenReturn(branch);
295 RuleKey ruleKey = RuleTesting.XOO_X1;
296 // Issue from main branch has severity major
297 addBaseIssueOnBranch(ruleKey);
299 // Issue from report has severity blocker
300 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
301 .setMsg("the message")
302 .setRuleRepository(ruleKey.repository())
303 .setRuleKey(ruleKey.rule())
304 .setSeverity(Constants.Severity.BLOCKER)
306 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
307 fileSourceRepository.addLine(FILE_REF, "line1");
309 underTest.visitAny(FILE);
311 List<DefaultIssue> issues = newArrayList(protoIssueCache.traverse());
312 assertThat(issues).hasSize(1);
313 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
314 assertThat(issues.get(0).isNew()).isFalse();
315 assertThat(issues.get(0).isCopied()).isTrue();
316 assertThat(issues.get(0).changes()).hasSize(1);
317 assertThat(issues.get(0).changes().get(0).diffs()).contains(entry(IssueFieldsSetter.FROM_BRANCH, new FieldDiffs.Diff<>("master", null)));
320 private void addBaseIssue(RuleKey ruleKey) {
321 ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID).setDbKey(PROJECT_KEY);
322 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setDbKey(FILE_KEY);
323 dbTester.components().insertComponents(project, file);
325 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
326 dbTester.rules().insertRule(ruleDto);
327 ruleRepositoryRule.add(ruleKey);
329 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
331 .setStatus(Issue.STATUS_OPEN)
332 .setSeverity(Severity.MAJOR);
333 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
334 dbTester.getSession().commit();
337 private void addBaseIssueOnBranch(RuleKey ruleKey) {
338 ComponentDto project = ComponentTesting.newPrivateProjectDto(PROJECT_UUID_ON_BRANCH).setDbKey(PROJECT_KEY);
339 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID_ON_BRANCH).setDbKey(FILE_KEY);
340 dbTester.components().insertComponents(project, file);
342 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
343 dbTester.rules().insertRule(ruleDto);
344 ruleRepositoryRule.add(ruleKey);
346 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
348 .setStatus(Issue.STATUS_OPEN)
349 .setSeverity(Severity.MAJOR);
350 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
351 dbTester.getSession().commit();