3 * Copyright (C) 2009-2017 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.server.computation.task.projectanalysis.issue;
22 import com.google.common.base.Optional;
23 import java.util.Collections;
24 import java.util.List;
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.mockito.Mock;
31 import org.mockito.MockitoAnnotations;
32 import org.sonar.api.issue.Issue;
33 import org.sonar.api.rule.RuleKey;
34 import org.sonar.api.rule.Severity;
35 import org.sonar.api.utils.System2;
36 import org.sonar.core.issue.DefaultIssue;
37 import org.sonar.core.issue.tracking.Tracker;
38 import org.sonar.db.DbTester;
39 import org.sonar.db.component.BranchType;
40 import org.sonar.db.component.ComponentDto;
41 import org.sonar.db.component.ComponentTesting;
42 import org.sonar.db.issue.IssueDto;
43 import org.sonar.db.issue.IssueTesting;
44 import org.sonar.db.rule.RuleDto;
45 import org.sonar.db.rule.RuleTesting;
46 import org.sonar.scanner.protocol.Constants;
47 import org.sonar.scanner.protocol.output.ScannerReport;
48 import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolder;
49 import org.sonar.server.computation.task.projectanalysis.analysis.Branch;
50 import org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderRule;
51 import org.sonar.server.computation.task.projectanalysis.component.Component;
52 import org.sonar.server.computation.task.projectanalysis.component.MergeBranchComponentUuids;
53 import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
54 import org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitor;
55 import org.sonar.server.computation.task.projectanalysis.filemove.MovedFilesRepository;
56 import org.sonar.server.computation.task.projectanalysis.issue.commonrule.CommonRuleEngineImpl;
57 import org.sonar.server.computation.task.projectanalysis.issue.filter.IssueFilter;
58 import org.sonar.server.computation.task.projectanalysis.qualityprofile.ActiveRulesHolderRule;
59 import org.sonar.server.computation.task.projectanalysis.source.SourceLinesRepositoryRule;
61 import static com.google.common.collect.Lists.newArrayList;
62 import static java.util.Arrays.asList;
63 import static org.assertj.core.api.Assertions.assertThat;
64 import static org.mockito.Matchers.any;
65 import static org.mockito.Matchers.eq;
66 import static org.mockito.Mockito.mock;
67 import static org.mockito.Mockito.verify;
68 import static org.mockito.Mockito.when;
69 import static org.sonar.server.computation.task.projectanalysis.component.ReportComponent.builder;
71 public class IntegrateIssuesVisitorTest {
73 static final String FILE_UUID = "FILE_UUID";
74 static final String FILE_UUID_ON_BRANCH = "FILE_UUID_BRANCH";
75 static final String FILE_KEY = "FILE_KEY";
76 static final int FILE_REF = 2;
78 static final Component FILE = builder(Component.Type.FILE, FILE_REF)
83 static final String PROJECT_KEY = "PROJECT_KEY";
84 static final String PROJECT_UUID = "PROJECT_UUID";
85 static final String PROJECT_UUID_ON_BRANCH = "PROJECT_UUID_BRANCH";
86 static final int PROJECT_REF = 1;
87 static final Component PROJECT = builder(Component.Type.PROJECT, PROJECT_REF)
89 .setUuid(PROJECT_UUID)
94 public TemporaryFolder temp = new TemporaryFolder();
96 public DbTester dbTester = DbTester.create(System2.INSTANCE);
98 public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
100 public BatchReportReaderRule reportReader = new BatchReportReaderRule();
102 public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
104 public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
106 public SourceLinesRepositoryRule fileSourceRepository = new SourceLinesRepositoryRule();
109 private AnalysisMetadataHolder analysisMetadataHolder;
111 private IssueFilter issueFilter;
113 private MovedFilesRepository movedFilesRepository;
115 private IssueLifecycle issueLifecycle;
117 private IssueVisitor issueVisitor;
119 private MergeBranchComponentUuids mergeBranchComponentsUuids;
121 private ShortBranchIssueMerger issueStatusCopier;
123 private MergeBranchComponentUuids mergeBranchComponentUuids;
125 ArgumentCaptor<DefaultIssue> defaultIssueCaptor;
127 ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule);
128 IssueTrackingDelegator trackingDelegator;
129 TrackerExecution tracker;
130 ShortBranchTrackerExecution shortBranchTracker;
131 MergeBranchTrackerExecution mergeBranchTracker;
132 IssueCache issueCache;
134 TypeAwareVisitor underTest;
137 public void setUp() throws Exception {
138 MockitoAnnotations.initMocks(this);
139 IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
141 defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
142 when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.<MovedFilesRepository.OriginalFile>absent());
144 TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, fileSourceRepository, new CommonRuleEngineImpl(), issueFilter);
145 TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbTester.getDbClient(), movedFilesRepository);
146 TrackerMergeBranchInputFactory mergeInputFactory = new TrackerMergeBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbTester.getDbClient());
147 tracker = new TrackerExecution(baseInputFactory, rawInputFactory, new Tracker<>());
148 shortBranchTracker = new ShortBranchTrackerExecution(baseInputFactory, rawInputFactory, mergeInputFactory, new Tracker<>());
149 mergeBranchTracker = new MergeBranchTrackerExecution(rawInputFactory, mergeInputFactory, new Tracker<>());
151 trackingDelegator = new IssueTrackingDelegator(shortBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder);
152 treeRootHolder.setRoot(PROJECT);
153 issueCache = new IssueCache(temp.newFile(), System2.INSTANCE);
154 when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true);
155 underTest = new IntegrateIssuesVisitor(issueCache, issueLifecycle, issueVisitors, analysisMetadataHolder, trackingDelegator, issueStatusCopier, mergeBranchComponentUuids);
159 public void process_new_issue() throws Exception {
160 when(analysisMetadataHolder.isLongLivingBranch()).thenReturn(true);
161 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
162 .setMsg("the message")
163 .setRuleRepository("xoo")
165 .setSeverity(Constants.Severity.BLOCKER)
167 reportReader.putIssues(FILE_REF, asList(reportIssue));
168 fileSourceRepository.addLine(FILE_REF, "line1");
170 underTest.visitAny(FILE);
172 verify(issueLifecycle).initNewOpenIssue(defaultIssueCaptor.capture());
173 DefaultIssue capturedIssue = defaultIssueCaptor.getValue();
174 assertThat(capturedIssue.ruleKey().rule()).isEqualTo("S001");
176 verify(issueStatusCopier).tryMerge(FILE, Collections.singletonList(capturedIssue));
178 verify(issueLifecycle).doAutomaticTransition(capturedIssue);
180 assertThat(newArrayList(issueCache.traverse())).hasSize(1);
184 public void process_existing_issue() throws Exception {
186 RuleKey ruleKey = RuleTesting.XOO_X1;
187 // Issue from db has severity major
188 addBaseIssue(ruleKey);
190 // Issue from report has severity blocker
191 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
192 .setMsg("the message")
193 .setRuleRepository(ruleKey.repository())
194 .setRuleKey(ruleKey.rule())
195 .setSeverity(Constants.Severity.BLOCKER)
197 reportReader.putIssues(FILE_REF, asList(reportIssue));
198 fileSourceRepository.addLine(FILE_REF, "line1");
200 underTest.visitAny(FILE);
202 ArgumentCaptor<DefaultIssue> rawIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
203 ArgumentCaptor<DefaultIssue> baseIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
204 verify(issueLifecycle).mergeExistingOpenIssue(rawIssueCaptor.capture(), baseIssueCaptor.capture());
205 assertThat(rawIssueCaptor.getValue().severity()).isEqualTo(Severity.BLOCKER);
206 assertThat(baseIssueCaptor.getValue().severity()).isEqualTo(Severity.MAJOR);
208 verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
209 assertThat(defaultIssueCaptor.getValue().ruleKey()).isEqualTo(ruleKey);
210 List<DefaultIssue> issues = newArrayList(issueCache.traverse());
211 assertThat(issues).hasSize(1);
212 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
217 public void execute_issue_visitors() throws Exception {
218 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
219 .setMsg("the message")
220 .setRuleRepository("xoo")
222 .setSeverity(Constants.Severity.BLOCKER)
224 reportReader.putIssues(FILE_REF, asList(reportIssue));
225 fileSourceRepository.addLine(FILE_REF, "line1");
227 underTest.visitAny(FILE);
229 verify(issueVisitor).beforeComponent(FILE);
230 verify(issueVisitor).afterComponent(FILE);
231 verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
232 assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
236 public void close_unmatched_base_issue() throws Exception {
237 RuleKey ruleKey = RuleTesting.XOO_X1;
238 addBaseIssue(ruleKey);
240 // No issue in the report
242 underTest.visitAny(FILE);
244 verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
245 assertThat(defaultIssueCaptor.getValue().isBeingClosed()).isTrue();
246 List<DefaultIssue> issues = newArrayList(issueCache.traverse());
247 assertThat(issues).hasSize(1);
251 public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() {
252 String originalFileUuid = "original file uuid";
253 when(movedFilesRepository.getOriginalFile(FILE))
254 .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(4851, originalFileUuid, "original file key")));
256 underTest.visitAny(FILE);
260 public void copy_issues_when_creating_new_long_living_branch() throws Exception {
262 when(mergeBranchComponentsUuids.getUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH);
263 when(mergeBranchComponentUuids.getMergeBranchName()).thenReturn("master");
265 when(analysisMetadataHolder.isLongLivingBranch()).thenReturn(true);
266 when(analysisMetadataHolder.isFirstAnalysis()).thenReturn(true);
267 Branch branch = mock(Branch.class);
268 when(branch.isMain()).thenReturn(false);
269 when(branch.getType()).thenReturn(BranchType.LONG);
270 when(analysisMetadataHolder.getBranch()).thenReturn(java.util.Optional.of(branch));
272 RuleKey ruleKey = RuleTesting.XOO_X1;
273 // Issue from main branch has severity major
274 addBaseIssueOnBranch(ruleKey);
276 // Issue from report has severity blocker
277 ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
278 .setMsg("the message")
279 .setRuleRepository(ruleKey.repository())
280 .setRuleKey(ruleKey.rule())
281 .setSeverity(Constants.Severity.BLOCKER)
283 reportReader.putIssues(FILE_REF, asList(reportIssue));
284 fileSourceRepository.addLine(FILE_REF, "line1");
286 underTest.visitAny(FILE);
288 ArgumentCaptor<DefaultIssue> rawIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
289 ArgumentCaptor<DefaultIssue> baseIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
290 verify(issueLifecycle).copyExistingOpenIssueFromLongLivingBranch(rawIssueCaptor.capture(), baseIssueCaptor.capture(), eq("master"));
291 assertThat(rawIssueCaptor.getValue().severity()).isEqualTo(Severity.BLOCKER);
292 assertThat(baseIssueCaptor.getValue().severity()).isEqualTo(Severity.MAJOR);
294 verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
295 assertThat(defaultIssueCaptor.getValue().ruleKey()).isEqualTo(ruleKey);
296 List<DefaultIssue> issues = newArrayList(issueCache.traverse());
297 assertThat(issues).hasSize(1);
298 assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
301 private void addBaseIssue(RuleKey ruleKey) {
302 ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), PROJECT_UUID).setDbKey(PROJECT_KEY);
303 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setDbKey(FILE_KEY);
304 dbTester.getDbClient().componentDao().insert(dbTester.getSession(), project, file);
306 RuleDto ruleDto = RuleTesting.newDto(ruleKey);
307 dbTester.rules().insertRule(ruleDto);
308 ruleRepositoryRule.add(ruleKey);
310 IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
312 .setStatus(Issue.STATUS_OPEN)
313 .setSeverity(Severity.MAJOR);
314 dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
315 dbTester.getSession().commit();
318 private void addBaseIssueOnBranch(RuleKey ruleKey) {
319 ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), PROJECT_UUID_ON_BRANCH).setDbKey(PROJECT_KEY);
320 ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID_ON_BRANCH).setDbKey(FILE_KEY);
321 dbTester.getDbClient().componentDao().insert(dbTester.getSession(), 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();