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