]> source.dussan.org Git - sonarqube.git/blob
0f695c19d65f4dedd017b7e417f48a2f3bcfc2dd
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2017 SonarSource SA
4  * mailto:info AT sonarsource DOT com
5  *
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.
10  *
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.
15  *
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.
19  */
20 package org.sonar.server.computation.task.projectanalysis.issue;
21
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;
60
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;
70
71 public class IntegrateIssuesVisitorTest {
72
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;
77
78   static final Component FILE = builder(Component.Type.FILE, FILE_REF)
79     .setKey(FILE_KEY)
80     .setUuid(FILE_UUID)
81     .build();
82
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)
88     .setKey(PROJECT_KEY)
89     .setUuid(PROJECT_UUID)
90     .addChildren(FILE)
91     .build();
92
93   @Rule
94   public TemporaryFolder temp = new TemporaryFolder();
95   @Rule
96   public DbTester dbTester = DbTester.create(System2.INSTANCE);
97   @Rule
98   public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
99   @Rule
100   public BatchReportReaderRule reportReader = new BatchReportReaderRule();
101   @Rule
102   public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
103   @Rule
104   public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
105   @Rule
106   public SourceLinesRepositoryRule fileSourceRepository = new SourceLinesRepositoryRule();
107
108   @Mock
109   private AnalysisMetadataHolder analysisMetadataHolder;
110   @Mock
111   private IssueFilter issueFilter;
112   @Mock
113   private MovedFilesRepository movedFilesRepository;
114   @Mock
115   private IssueLifecycle issueLifecycle;
116   @Mock
117   private IssueVisitor issueVisitor;
118   @Mock
119   private MergeBranchComponentUuids mergeBranchComponentsUuids;
120   @Mock
121   private ShortBranchIssueMerger issueStatusCopier;
122   @Mock
123   private MergeBranchComponentUuids mergeBranchComponentUuids;
124
125   ArgumentCaptor<DefaultIssue> defaultIssueCaptor;
126
127   ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule);
128   IssueTrackingDelegator trackingDelegator;
129   TrackerExecution tracker;
130   ShortBranchTrackerExecution shortBranchTracker;
131   MergeBranchTrackerExecution mergeBranchTracker;
132   IssueCache issueCache;
133
134   TypeAwareVisitor underTest;
135
136   @Before
137   public void setUp() throws Exception {
138     MockitoAnnotations.initMocks(this);
139     IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
140
141     defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
142     when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.<MovedFilesRepository.OriginalFile>absent());
143
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<>());
150
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);
156   }
157
158   @Test
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")
164       .setRuleKey("S001")
165       .setSeverity(Constants.Severity.BLOCKER)
166       .build();
167     reportReader.putIssues(FILE_REF, asList(reportIssue));
168     fileSourceRepository.addLine(FILE_REF, "line1");
169
170     underTest.visitAny(FILE);
171
172     verify(issueLifecycle).initNewOpenIssue(defaultIssueCaptor.capture());
173     DefaultIssue capturedIssue = defaultIssueCaptor.getValue();
174     assertThat(capturedIssue.ruleKey().rule()).isEqualTo("S001");
175
176     verify(issueStatusCopier).tryMerge(FILE, Collections.singletonList(capturedIssue));
177
178     verify(issueLifecycle).doAutomaticTransition(capturedIssue);
179
180     assertThat(newArrayList(issueCache.traverse())).hasSize(1);
181   }
182
183   @Test
184   public void process_existing_issue() throws Exception {
185
186     RuleKey ruleKey = RuleTesting.XOO_X1;
187     // Issue from db has severity major
188     addBaseIssue(ruleKey);
189
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)
196       .build();
197     reportReader.putIssues(FILE_REF, asList(reportIssue));
198     fileSourceRepository.addLine(FILE_REF, "line1");
199
200     underTest.visitAny(FILE);
201
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);
207
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);
213
214   }
215
216   @Test
217   public void execute_issue_visitors() throws Exception {
218     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
219       .setMsg("the message")
220       .setRuleRepository("xoo")
221       .setRuleKey("S001")
222       .setSeverity(Constants.Severity.BLOCKER)
223       .build();
224     reportReader.putIssues(FILE_REF, asList(reportIssue));
225     fileSourceRepository.addLine(FILE_REF, "line1");
226
227     underTest.visitAny(FILE);
228
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");
233   }
234
235   @Test
236   public void close_unmatched_base_issue() throws Exception {
237     RuleKey ruleKey = RuleTesting.XOO_X1;
238     addBaseIssue(ruleKey);
239
240     // No issue in the report
241
242     underTest.visitAny(FILE);
243
244     verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
245     assertThat(defaultIssueCaptor.getValue().isBeingClosed()).isTrue();
246     List<DefaultIssue> issues = newArrayList(issueCache.traverse());
247     assertThat(issues).hasSize(1);
248   }
249
250   @Test
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")));
255
256     underTest.visitAny(FILE);
257   }
258
259   @Test
260   public void copy_issues_when_creating_new_long_living_branch() throws Exception {
261
262     when(mergeBranchComponentsUuids.getUuid(FILE_KEY)).thenReturn(FILE_UUID_ON_BRANCH);
263     when(mergeBranchComponentUuids.getMergeBranchName()).thenReturn("master");
264
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));
271
272     RuleKey ruleKey = RuleTesting.XOO_X1;
273     // Issue from main branch has severity major
274     addBaseIssueOnBranch(ruleKey);
275
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)
282       .build();
283     reportReader.putIssues(FILE_REF, asList(reportIssue));
284     fileSourceRepository.addLine(FILE_REF, "line1");
285
286     underTest.visitAny(FILE);
287
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);
293
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);
299   }
300
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);
305
306     RuleDto ruleDto = RuleTesting.newDto(ruleKey);
307     dbTester.rules().insertRule(ruleDto);
308     ruleRepositoryRule.add(ruleKey);
309
310     IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
311       .setKee("ISSUE")
312       .setStatus(Issue.STATUS_OPEN)
313       .setSeverity(Severity.MAJOR);
314     dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
315     dbTester.getSession().commit();
316   }
317
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);
322
323     RuleDto ruleDto = RuleTesting.newDto(ruleKey);
324     dbTester.rules().insertRule(ruleDto);
325     ruleRepositoryRule.add(ruleKey);
326
327     IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
328       .setKee("ISSUE")
329       .setStatus(Issue.STATUS_OPEN)
330       .setSeverity(Severity.MAJOR);
331     dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
332     dbTester.getSession().commit();
333   }
334 }