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