]> source.dussan.org Git - sonarqube.git/blob
31039ddee50b46e59e940014c6d308e5d1cab16a
[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 static com.google.common.collect.Lists.newArrayList;
23 import static java.util.Arrays.asList;
24 import static org.assertj.core.api.Assertions.assertThat;
25 import static org.mockito.Matchers.any;
26 import static org.mockito.Matchers.eq;
27 import static org.mockito.Mockito.verify;
28 import static org.mockito.Mockito.when;
29 import static org.sonar.server.computation.task.projectanalysis.component.ReportComponent.builder;
30
31 import java.util.List;
32
33 import org.junit.Before;
34 import org.junit.Rule;
35 import org.junit.Test;
36 import org.junit.rules.TemporaryFolder;
37 import org.mockito.ArgumentCaptor;
38 import org.mockito.Mock;
39 import org.mockito.MockitoAnnotations;
40 import org.sonar.api.issue.Issue;
41 import org.sonar.api.rule.RuleKey;
42 import org.sonar.api.rule.Severity;
43 import org.sonar.api.utils.System2;
44 import org.sonar.core.issue.DefaultIssue;
45 import org.sonar.core.issue.tracking.Tracker;
46 import org.sonar.db.DbTester;
47 import org.sonar.db.component.ComponentDto;
48 import org.sonar.db.component.ComponentTesting;
49 import org.sonar.db.issue.IssueDto;
50 import org.sonar.db.issue.IssueTesting;
51 import org.sonar.db.rule.RuleDto;
52 import org.sonar.db.rule.RuleTesting;
53 import org.sonar.scanner.protocol.Constants;
54 import org.sonar.scanner.protocol.output.ScannerReport;
55 import org.sonar.server.computation.task.projectanalysis.analysis.AnalysisMetadataHolder;
56 import org.sonar.server.computation.task.projectanalysis.batch.BatchReportReaderRule;
57 import org.sonar.server.computation.task.projectanalysis.component.Component;
58 import org.sonar.server.computation.task.projectanalysis.component.Component.Status;
59 import org.sonar.server.computation.task.projectanalysis.component.DefaultBranchImpl;
60 import org.sonar.server.computation.task.projectanalysis.component.MergeBranchComponentUuids;
61 import org.sonar.server.computation.task.projectanalysis.component.TreeRootHolderRule;
62 import org.sonar.server.computation.task.projectanalysis.component.TypeAwareVisitor;
63 import org.sonar.server.computation.task.projectanalysis.filemove.MovedFilesRepository;
64 import org.sonar.server.computation.task.projectanalysis.issue.commonrule.CommonRuleEngineImpl;
65 import org.sonar.server.computation.task.projectanalysis.issue.filter.IssueFilter;
66 import org.sonar.server.computation.task.projectanalysis.qualityprofile.ActiveRulesHolderRule;
67 import org.sonar.server.computation.task.projectanalysis.source.SourceLinesRepositoryRule;
68
69 import com.google.common.base.Optional;
70
71 public class IntegrateIssuesVisitorTest {
72
73   static final String FILE_UUID = "FILE_UUID";
74   static final String FILE_KEY = "FILE_KEY";
75   static final int FILE_REF = 2;
76
77   static final Component FILE = builder(Component.Type.FILE, FILE_REF)
78     .setKey(FILE_KEY)
79     .setUuid(FILE_UUID)
80     .build();
81
82   static final String PROJECT_KEY = "PROJECT_KEY";
83   static final String PROJECT_UUID = "PROJECT_UUID";
84   static final int PROJECT_REF = 1;
85   static final Component PROJECT = builder(Component.Type.PROJECT, PROJECT_REF)
86     .setKey(PROJECT_KEY)
87     .setUuid(PROJECT_UUID)
88     .addChildren(FILE)
89     .build();
90
91   @Rule
92   public TemporaryFolder temp = new TemporaryFolder();
93   @Rule
94   public DbTester dbTester = DbTester.create(System2.INSTANCE);
95   @Rule
96   public TreeRootHolderRule treeRootHolder = new TreeRootHolderRule();
97   @Rule
98   public BatchReportReaderRule reportReader = new BatchReportReaderRule();
99   @Rule
100   public ActiveRulesHolderRule activeRulesHolderRule = new ActiveRulesHolderRule();
101   @Rule
102   public RuleRepositoryRule ruleRepositoryRule = new RuleRepositoryRule();
103   @Rule
104   public SourceLinesRepositoryRule fileSourceRepository = new SourceLinesRepositoryRule();
105
106   @Mock
107   private AnalysisMetadataHolder analysisMetadataHolder;
108   @Mock
109   private IssueFilter issueFilter;
110   @Mock
111   private MovedFilesRepository movedFilesRepository;
112   @Mock
113   private IssueLifecycle issueLifecycle;
114   @Mock
115   private IssueVisitor issueVisitor;
116   @Mock
117   private MergeBranchComponentUuids mergeBranchComponentsUuids;
118
119   ArgumentCaptor<DefaultIssue> defaultIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
120
121   ComponentIssuesLoader issuesLoader = new ComponentIssuesLoader(dbTester.getDbClient(), ruleRepositoryRule, activeRulesHolderRule);
122   IssueTrackingDelegator trackingDelegator;
123   TrackerExecution tracker;
124   ShortBranchTrackerExecution shortBranchTracker;
125   MergeBranchTrackerExecution mergeBranchTracker;
126   IssueCache issueCache;
127
128   TypeAwareVisitor underTest;
129
130   @Before
131   public void setUp() throws Exception {
132     MockitoAnnotations.initMocks(this);
133     IssueVisitors issueVisitors = new IssueVisitors(new IssueVisitor[] {issueVisitor});
134
135     when(movedFilesRepository.getOriginalFile(any(Component.class))).thenReturn(Optional.<MovedFilesRepository.OriginalFile>absent());
136
137     TrackerRawInputFactory rawInputFactory = new TrackerRawInputFactory(treeRootHolder, reportReader, fileSourceRepository, new CommonRuleEngineImpl(), issueFilter);
138     TrackerBaseInputFactory baseInputFactory = new TrackerBaseInputFactory(issuesLoader, dbTester.getDbClient(), movedFilesRepository);
139     TrackerMergeBranchInputFactory mergeInputFactory = new TrackerMergeBranchInputFactory(issuesLoader, mergeBranchComponentsUuids, dbTester.getDbClient());
140     tracker = new TrackerExecution(baseInputFactory, rawInputFactory, new Tracker<>());
141     shortBranchTracker = new ShortBranchTrackerExecution(baseInputFactory, rawInputFactory, mergeInputFactory, new Tracker<>());
142     mergeBranchTracker = new MergeBranchTrackerExecution(rawInputFactory, mergeInputFactory, new Tracker<>());
143
144     trackingDelegator = new IssueTrackingDelegator(shortBranchTracker, mergeBranchTracker, tracker, analysisMetadataHolder);
145     treeRootHolder.setRoot(PROJECT);
146     issueCache = new IssueCache(temp.newFile(), System2.INSTANCE);
147     when(analysisMetadataHolder.isIncrementalAnalysis()).thenReturn(false);
148     when(analysisMetadataHolder.getBranch()).thenReturn(java.util.Optional.of(new DefaultBranchImpl()));
149     when(issueFilter.accept(any(DefaultIssue.class), eq(FILE))).thenReturn(true);
150     underTest = new IntegrateIssuesVisitor(issueCache, issueLifecycle, issueVisitors, issuesLoader, analysisMetadataHolder, trackingDelegator);
151   }
152
153   @Test
154   public void process_issues_on_incremental_mode() {
155     when(analysisMetadataHolder.isIncrementalAnalysis()).thenReturn(true);
156
157     Component file = builder(Component.Type.FILE, FILE_REF)
158       .setKey(FILE_KEY)
159       .setUuid(FILE_UUID)
160       .setStatus(Status.SAME)
161       .build();
162
163     addBaseIssue(RuleTesting.XOO_X1);
164
165     underTest.visitAny(file);
166
167     verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
168     assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("x1");
169
170     assertThat(newArrayList(issueCache.traverse())).hasSize(1);
171   }
172
173   @Test
174   public void process_new_issue() throws Exception {
175     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
176       .setMsg("the message")
177       .setRuleRepository("xoo")
178       .setRuleKey("S001")
179       .setSeverity(Constants.Severity.BLOCKER)
180       .build();
181     reportReader.putIssues(FILE_REF, asList(reportIssue));
182     fileSourceRepository.addLine(FILE_REF, "line1");
183
184     underTest.visitAny(FILE);
185
186     verify(issueLifecycle).initNewOpenIssue(defaultIssueCaptor.capture());
187     assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
188
189     verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
190     assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
191
192     assertThat(newArrayList(issueCache.traverse())).hasSize(1);
193   }
194
195   @Test
196   public void process_existing_issue() throws Exception {
197
198     RuleKey ruleKey = RuleTesting.XOO_X1;
199     // Issue from db has severity major
200     addBaseIssue(ruleKey);
201
202     // Issue from report has severity blocker
203     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
204       .setMsg("the message")
205       .setRuleRepository(ruleKey.repository())
206       .setRuleKey(ruleKey.rule())
207       .setSeverity(Constants.Severity.BLOCKER)
208       .build();
209     reportReader.putIssues(FILE_REF, asList(reportIssue));
210     fileSourceRepository.addLine(FILE_REF, "line1");
211
212     underTest.visitAny(FILE);
213
214     ArgumentCaptor<DefaultIssue> rawIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
215     ArgumentCaptor<DefaultIssue> baseIssueCaptor = ArgumentCaptor.forClass(DefaultIssue.class);
216     verify(issueLifecycle).mergeExistingOpenIssue(rawIssueCaptor.capture(), baseIssueCaptor.capture());
217     assertThat(rawIssueCaptor.getValue().severity()).isEqualTo(Severity.BLOCKER);
218     assertThat(baseIssueCaptor.getValue().severity()).isEqualTo(Severity.MAJOR);
219
220     verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
221     assertThat(defaultIssueCaptor.getValue().ruleKey()).isEqualTo(ruleKey);
222     List<DefaultIssue> issues = newArrayList(issueCache.traverse());
223     assertThat(issues).hasSize(1);
224     assertThat(issues.get(0).severity()).isEqualTo(Severity.BLOCKER);
225
226   }
227
228   @Test
229   public void execute_issue_visitors() throws Exception {
230     ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder()
231       .setMsg("the message")
232       .setRuleRepository("xoo")
233       .setRuleKey("S001")
234       .setSeverity(Constants.Severity.BLOCKER)
235       .build();
236     reportReader.putIssues(FILE_REF, asList(reportIssue));
237     fileSourceRepository.addLine(FILE_REF, "line1");
238
239     underTest.visitAny(FILE);
240
241     verify(issueVisitor).beforeComponent(FILE);
242     verify(issueVisitor).afterComponent(FILE);
243     verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture());
244     assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001");
245   }
246
247   @Test
248   public void close_unmatched_base_issue() throws Exception {
249     RuleKey ruleKey = RuleTesting.XOO_X1;
250     addBaseIssue(ruleKey);
251
252     // No issue in the report
253
254     underTest.visitAny(FILE);
255
256     verify(issueLifecycle).doAutomaticTransition(defaultIssueCaptor.capture());
257     assertThat(defaultIssueCaptor.getValue().isBeingClosed()).isTrue();
258     List<DefaultIssue> issues = newArrayList(issueCache.traverse());
259     assertThat(issues).hasSize(1);
260   }
261
262   @Test
263   public void remove_uuid_of_original_file_from_componentsWithUnprocessedIssues_if_component_has_one() {
264     String originalFileUuid = "original file uuid";
265     when(movedFilesRepository.getOriginalFile(FILE))
266       .thenReturn(Optional.of(new MovedFilesRepository.OriginalFile(4851, originalFileUuid, "original file key")));
267
268     underTest.visitAny(FILE);
269   }
270
271   private void addBaseIssue(RuleKey ruleKey) {
272     ComponentDto project = ComponentTesting.newPrivateProjectDto(dbTester.organizations().insert(), PROJECT_UUID).setDbKey(PROJECT_KEY);
273     ComponentDto file = ComponentTesting.newFileDto(project, null, FILE_UUID).setDbKey(FILE_KEY);
274     dbTester.getDbClient().componentDao().insert(dbTester.getSession(), project, file);
275
276     RuleDto ruleDto = RuleTesting.newDto(ruleKey);
277     dbTester.rules().insertRule(ruleDto);
278     ruleRepositoryRule.add(ruleKey);
279
280     IssueDto issue = IssueTesting.newDto(ruleDto, file, project)
281       .setKee("ISSUE")
282       .setStatus(Issue.STATUS_OPEN)
283       .setSeverity(Severity.MAJOR);
284     dbTester.getDbClient().issueDao().insert(dbTester.getSession(), issue);
285     dbTester.getSession().commit();
286   }
287 }