3 * Copyright (C) 2009-2020 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.List;
23 import java.util.Optional;
24 import org.junit.Before;
25 import org.junit.Rule;
26 import org.junit.Test;
27 import org.junit.rules.TemporaryFolder;
28 import org.mockito.ArgumentCaptor;
29 import org.sonar.api.config.internal.MapSettings;
30 import org.sonar.api.issue.Issue;
31 import org.sonar.api.rule.RuleKey;
32 import org.sonar.api.rule.Severity;
33 import org.sonar.api.utils.System2;
34 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolder;
35 import org.sonar.ce.task.projectanalysis.analysis.Branch;
36 import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
37 import org.sonar.ce.task.projectanalysis.component.Component;
38 import org.sonar.ce.task.projectanalysis.component.ReferenceBranchComponentUuids;
39 import org.sonar.ce.task.projectanalysis.component.ReportComponent;
40 import org.sonar.ce.task.projectanalysis.component.ReportModulesPath;
41 import org.sonar.ce.task.projectanalysis.component.TreeRootHolderRule;
42 import org.sonar.ce.task.projectanalysis.component.TypeAwareVisitor;
43 import org.sonar.ce.task.projectanalysis.filemove.MovedFilesRepository;
44 import org.sonar.ce.task.projectanalysis.issue.commonrule.CommonRuleEngineImpl;
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.SourceLinesRepositoryRule;
52 import org.sonar.core.issue.DefaultIssue;
53 import org.sonar.core.issue.tracking.Tracker;
54 import org.sonar.db.DbClient;
55 import org.sonar.db.DbTester;
56 import org.sonar.db.component.BranchType;
57 import org.sonar.db.component.ComponentDto;
58 import org.sonar.db.component.ComponentTesting;
59 import org.sonar.db.issue.IssueDto;
60 import org.sonar.db.issue.IssueTesting;
61 import org.sonar.db.rule.RuleDto;
62 import org.sonar.db.rule.RuleTesting;
63 import org.sonar.scanner.protocol.Constants;
64 import org.sonar.scanner.protocol.output.ScannerReport;
65 import org.sonar.server.issue.IssueFieldsSetter;
67 import static com.google.common.collect.Lists.newArrayList;
68 import static java.util.Arrays.asList;
69 import static java.util.Collections.singletonList;
70 import static org.assertj.core.api.Assertions.assertThat;
71 import static org.mockito.ArgumentMatchers.any;
72 import static org.mockito.ArgumentMatchers.eq;
73 import static org.mockito.Mockito.mock;
74 import static org.mockito.Mockito.verify;
75 import static org.mockito.Mockito.when;
77 public class IntegrateIssuesVisitorTest {
79 private static final String FILE_UUID = "FILE_UUID";
80 private static final String FILE_UUID_ON_BRANCH = "FILE_UUID_BRANCH";
81 private static final String FILE_KEY = "FILE_KEY";
82 private static final int FILE_REF = 2;
84 private static final Component FILE = ReportComponent.builder(Component.Type.FILE, FILE_REF)
89 private static final String PROJECT_KEY = "PROJECT_KEY";
90 private static final String PROJECT_UUID = "PROJECT_UUID";
91 private static final String PROJECT_UUID_ON_BRANCH = "PROJECT_UUID_BRANCH";
92 private static final int PROJECT_REF = 1;
93 private static final Component PROJECT = ReportComponent.builder(Component.Type.PROJECT, PROJECT_REF)
95 .setUuid(PROJECT_UUID)
100 public TemporaryFolder temp = new TemporaryFolder();
102 public DbTester dbTester = DbTester.create(System2.INSTANCE);
104 public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
106 public BatchReportReaderRule reportReader = new BatchReportReaderRule();
108 public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
110 public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
112 public SourceLinesRepositoryRule fileSourceRepository = new SourceLinesRepositoryRule();
114 private AnalysisMetadataHolder analysisMetadataHolder = mock(AnalysisMetadataHolder.class);
115 private IssueFilter issueFilter = mock(IssueFilter.class);
116 private MovedFilesRepository movedFilesRepository = mock(MovedFilesRepository.class);
117 private IssueLifecycle issueLifecycle = mock(IssueLifecycle.class);
118 private IssueVisitor issueVisitor = mock(IssueVisitor.class);
119 private ReferenceBranchComponentUuids mergeBranchComponentsUuids = mock(ReferenceBranchComponentUuids.class);
120 private SiblingsIssueMerger issueStatusCopier = mock(SiblingsIssueMerger.class);
121 private ReferenceBranchComponentUuids referenceBranchComponentUuids = mock(ReferenceBranchComponentUuids.class);
122 private SourceLinesHashRepository sourceLinesHash = mock(SourceLinesHashRepository.class);
123 private NewLinesRepository newLinesRepository = mock(NewLinesRepository.class);
125 private ArgumentCaptor<DefaultIssue> defaultIssueCaptor;
127 private ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule, new MapSettings().asConfig(),
129 private IssueTrackingDelegator trackingDelegator;
130 private TrackerExecution tracker;
131 private PullRequestTrackerExecution prBranchTracker;
132 private ReferenceBranchTrackerExecution mergeBranchTracker;
133 private ActiveRulesHolder activeRulesHolder = new AlwaysActiveRulesHolderImpl();
134 private IssueCache issueCache;
136 private TypeAwareVisitor underTest;
139 public void setUp() throws Exception {
140 IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
142 defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
143 when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.empty());
145 DbClient dbClient = dbTester.getDbClient();
146 TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, sourceLinesHash, new CommonRuleEngineImpl(),
147 issueFilter, ruleRepositoryRule, activeRulesHolder);
148 TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbClient, movedFilesRepository, mock(ReportModulesPath.class), analysisMetadataHolder,
149 new IssueFieldsSetter(), mock(ComponentsWithUnprocessedIssues.class));
150 TrackerReferenceBranchInputFactory mergeInputFactory = new TrackerReferenceBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbClient);
151 ClosedIssuesInputFactory closedIssuesInputFactory = new ClosedIssuesInputFactory(issuesLoader, dbClient, movedFilesRepository);
152 tracker = new TrackerExecution(baseInputFactory, rawInputFactory, closedIssuesInputFactory, new Tracker<>(), issuesLoader, analysisMetadataHolder);
153 prBranchTracker = new PullRequestTrackerExecution(baseInputFactory, rawInputFactory, new Tracker<>(), newLinesRepository);
154 mergeBranchTracker = new ReferenceBranchTrackerExecution(rawInputFactory, mergeInputFactory, new Tracker<>());
155 trackingDelegator = new IssueTrackingDelegator(prBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder);
156 treeRootHolder.setRoot(PROJECT);
157 issueCache = new IssueCache(temp.newFile(), System2.INSTANCE);
158 when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true);
159 underTest = new IntegrateIssuesVisitor(issueCache, issueLifecycle, issueVisitors, trackingDelegator, issueStatusCopier, referenceBranchComponentUuids);
163 public void process_new_issue() {
164 when(analysisMetadataHolder.isBranch()).thenReturn(true);
165 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
166 .setMsg("the message")
167 .setRuleRepository("xoo")
169 .setSeverity(Constants.Severity.BLOCKER)
171 reportReader.putIssues(FILE_REF, asList(reportIssue));
172 fileSourceRepository.addLine(FILE_REF, "line1");
174 underTest.visitAny(FILE);
176 verify(issueLifecycle).initNewOpenIssue(defaultIssueCaptor.capture());
177 DefaultIssue capturedIssue = defaultIssueCaptor.getValue();
178 assertThat(capturedIssue.ruleKey().rule()).isEqualTo("S001");
180 verify(issueStatusCopier).tryMerge(FILE, singletonList(capturedIssue));
182 verify(issueLifecycle).doAutomaticTransition(capturedIssue);
184 assertThat(newArrayList(issueCache.traverse())).hasSize(1);
188 public void process_existing_issue() {
190 RuleKey ruleKey = RuleTesting.XOO_X1;
191 // Issue from db has severity major
192 addBaseIssue(ruleKey);
194 // Issue from report has severity blocker
195 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
196 .setMsg("the message")
197 .setRuleRepository(ruleKey.repository())
198 .setRuleKey(ruleKey.rule())
199 .setSeverity(Constants.Severity.BLOCKER)
201 reportReader.putIssues(FILE_REF, asList(reportIssue));
202 fileSourceRepository.addLine(FILE_REF, "line1");
204 underTest.visitAny(FILE);
206 ArgumentCaptor<DefaultIssue> rawIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
207 ArgumentCaptor<DefaultIssue> baseIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
208 verify(issueLifecycle).mergeExistingOpenIssue(rawIssueCaptor.capture(), baseIssueCaptor.capture());
209 assertThat(rawIssueCaptor.getValue().severity()).isEqualTo(Severity.BLOCKER);
210 assertThat(baseIssueCaptor.getValue().severity()).isEqualTo(Severity.MAJOR);
212 verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
213 assertThat(defaultIssueCaptor.getValue().ruleKey()).isEqualTo(ruleKey);
214 List<DefaultIssue> issues = newArrayList(issueCache.traverse());
215 assertThat(issues).hasSize(1);
216 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
221 public void execute_issue_visitors() {
222 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
223 .setMsg("the message")
224 .setRuleRepository("xoo")
226 .setSeverity(Constants.Severity.BLOCKER)
228 reportReader.putIssues(FILE_REF, asList(reportIssue));
229 fileSourceRepository.addLine(FILE_REF, "line1");
231 underTest.visitAny(FILE);
233 verify(issueVisitor).beforeComponent(FILE);
234 verify(issueVisitor).afterComponent(FILE);
235 verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
236 assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
240 public void close_unmatched_base_issue() {
241 RuleKey ruleKey = RuleTesting.XOO_X1;
242 addBaseIssue(ruleKey);
244 // No issue in the report
246 underTest.visitAny(FILE);
248 verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
249 assertThat(defaultIssueCaptor.getValue().isBeingClosed()).isTrue();
250 List<DefaultIssue> issues = newArrayList(issueCache.traverse());
251 assertThat(issues).hasSize(1);
255 public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() {
256 String originalFileUuid = "original file uuid";
257 when(movedFilesRepository.getOriginalFile(FILE))
258 .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(4851, originalFileUuid, "original file key")));
260 underTest.visitAny(FILE);
264 public void copy_issues_when_creating_new_non_main_branch() {
266 when(mergeBranchComponentsUuids.getComponentUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH);
267 when(referenceBranchComponentUuids.getReferenceBranchName()).thenReturn("master");
269 when(analysisMetadataHolder.isBranch()).thenReturn(true);
270 when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true);
271 Branch branch = mock(Branch.class);
272 when(branch.isMain()).thenReturn(false);
273 when(branch.getType()).thenReturn(BranchType.BRANCH);
274 when(analysisMetadataHolder.getBranch()).thenReturn(branch);
276 RuleKey ruleKey = RuleTesting.XOO_X1;
277 // Issue from main branch has severity major
278 addBaseIssueOnBranch(ruleKey);
280 // Issue from report has severity blocker
281 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
282 .setMsg("the message")
283 .setRuleRepository(ruleKey.repository())
284 .setRuleKey(ruleKey.rule())
285 .setSeverity(Constants.Severity.BLOCKER)
287 reportReader.putIssues(FILE_REF, singletonList(reportIssue));
288 fileSourceRepository.addLine(FILE_REF, "line1");
290 underTest.visitAny(FILE);
292 ArgumentCaptor<DefaultIssue> rawIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
293 ArgumentCaptor<DefaultIssue> baseIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
294 verify(issueLifecycle).copyExistingOpenIssueFromBranch(rawIssueCaptor.capture(), baseIssueCaptor.capture(), eq("master"));
295 assertThat(rawIssueCaptor.getValue().severity()).isEqualTo(Severity.BLOCKER);
296 assertThat(baseIssueCaptor.getValue().severity()).isEqualTo(Severity.MAJOR);
298 verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
299 assertThat(defaultIssueCaptor.getValue().ruleKey()).isEqualTo(ruleKey);
300 List<DefaultIssue> issues = newArrayList(issueCache.traverse());
301 assertThat(issues).hasSize(1);
302 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
305 private void addBaseIssue(RuleKey ruleKey) {
306 ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), PROJECT_UUID).setDbKey(PROJECT_KEY);
307 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setDbKey(FILE_KEY);
308 dbTester.getDbClient().componentDao().insert(dbTester.getSession(), project, file);
310 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
311 dbTester.rules().insertRule(ruleDto);
312 ruleRepositoryRule.add(ruleKey);
314 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
316 .setStatus(Issue.STATUS_OPEN)
317 .setSeverity(Severity.MAJOR);
318 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
319 dbTester.getSession().commit();
322 private void addBaseIssueOnBranch(RuleKey ruleKey) {
323 ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), PROJECT_UUID_ON_BRANCH).setDbKey(PROJECT_KEY);
324 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID_ON_BRANCH).setDbKey(FILE_KEY);
325 dbTester.getDbClient().componentDao().insert(dbTester.getSession(), project, file);
327 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
328 dbTester.rules().insertRule(ruleDto);
329 ruleRepositoryRule.add(ruleKey);
331 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
333 .setStatus(Issue.STATUS_OPEN)
334 .setSeverity(Severity.MAJOR);
335 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
336 dbTester.getSession().commit();