]> source.dussan.org Git - sonarqube.git/blob
6a460d59425228b52f393ddc8975a5050a55c02b
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2019 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.ce.task.projectanalysis.api.posttask;
21
22 import com.google.common.collect.ImmutableMap;
23 import com.tngtech.java.junit.dataprovider.DataProvider;
24 import com.tngtech.java.junit.dataprovider.DataProviderRunner;
25 import com.tngtech.java.junit.dataprovider.UseDataProvider;
26 import java.util.Date;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.Random;
30 import javax.annotation.Nullable;
31 import org.apache.commons.lang.RandomStringUtils;
32 import org.junit.Before;
33 import org.junit.Rule;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.mockito.ArgumentCaptor;
37 import org.mockito.InOrder;
38 import org.sonar.api.ce.posttask.PostProjectAnalysisTask;
39 import org.sonar.api.ce.posttask.Project;
40 import org.sonar.api.utils.System2;
41 import org.sonar.ce.task.CeTask;
42 import org.sonar.ce.task.projectanalysis.analysis.AnalysisMetadataHolderRule;
43 import org.sonar.ce.task.projectanalysis.analysis.Branch;
44 import org.sonar.ce.task.projectanalysis.analysis.Organization;
45 import org.sonar.ce.task.projectanalysis.batch.BatchReportReaderRule;
46 import org.sonar.ce.task.projectanalysis.component.DefaultBranchImpl;
47 import org.sonar.ce.task.projectanalysis.metric.Metric;
48 import org.sonar.ce.task.projectanalysis.qualitygate.Condition;
49 import org.sonar.ce.task.projectanalysis.qualitygate.ConditionStatus;
50 import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateHolderRule;
51 import org.sonar.ce.task.projectanalysis.qualitygate.MutableQualityGateStatusHolderRule;
52 import org.sonar.ce.task.projectanalysis.qualitygate.QualityGate;
53 import org.sonar.ce.task.projectanalysis.qualitygate.QualityGateStatus;
54 import org.sonar.db.component.BranchType;
55 import org.sonar.db.organization.OrganizationDto;
56 import org.sonar.scanner.protocol.output.ScannerReport;
57
58 import static com.google.common.collect.ImmutableList.of;
59 import static java.util.Arrays.asList;
60 import static org.assertj.core.api.Assertions.assertThat;
61 import static org.assertj.core.data.MapEntry.entry;
62 import static org.mockito.ArgumentMatchers.any;
63 import static org.mockito.Mockito.doThrow;
64 import static org.mockito.Mockito.inOrder;
65 import static org.mockito.Mockito.mock;
66 import static org.mockito.Mockito.verify;
67 import static org.mockito.Mockito.when;
68
69 @RunWith(DataProviderRunner.class)
70 public class PostProjectAnalysisTasksExecutorTest {
71   private static final long QUALITY_GATE_ID = 98451;
72   private static final String QUALITY_GATE_NAME = "qualityGate name";
73   private static final Condition CONDITION_1 = createCondition("metric key 1");
74   private static final Condition CONDITION_2 = createCondition("metric key 2");
75
76   @Rule
77   public AnalysisMetadataHolderRule analysisMetadataHolder = new AnalysisMetadataHolderRule();
78   @Rule
79   public MutableQualityGateHolderRule qualityGateHolder = new MutableQualityGateHolderRule();
80   @Rule
81   public MutableQualityGateStatusHolderRule qualityGateStatusHolder = new MutableQualityGateStatusHolderRule();
82   @Rule
83   public BatchReportReaderRule reportReader = new BatchReportReaderRule();
84
85   private String organizationUuid = "org1";
86   private String organizationKey = organizationUuid + "_key";
87   private String organizationName = organizationUuid + "_name";
88   private System2 system2 = mock(System2.class);
89   private ArgumentCaptor<PostProjectAnalysisTask.ProjectAnalysis> projectAnalysisArgumentCaptor = ArgumentCaptor.forClass(PostProjectAnalysisTask.ProjectAnalysis.class);
90   private CeTask.Component component = new CeTask.Component("component uuid", "component key", "component name");
91   private CeTask ceTask = new CeTask.Builder()
92     .setOrganizationUuid(organizationUuid)
93     .setType("type")
94     .setUuid("uuid")
95     .setComponent(component)
96     .setMainComponent(component)
97     .build();
98   private PostProjectAnalysisTask postProjectAnalysisTask = mock(PostProjectAnalysisTask.class);
99   private PostProjectAnalysisTasksExecutor underTest = new PostProjectAnalysisTasksExecutor(
100     ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder,
101     reportReader, system2,
102     new PostProjectAnalysisTask[] {postProjectAnalysisTask});
103
104   @Before
105   public void setUp() throws Exception {
106     qualityGateHolder.setQualityGate(new QualityGate(QUALITY_GATE_ID, QUALITY_GATE_NAME, of(CONDITION_1, CONDITION_2)));
107     qualityGateStatusHolder.setStatus(QualityGateStatus.OK, ImmutableMap.of(
108       CONDITION_1, ConditionStatus.create(ConditionStatus.EvaluationStatus.OK, "value"),
109       CONDITION_2, ConditionStatus.NO_VALUE_STATUS));
110     Branch branch = mock(Branch.class);
111     when(branch.getType()).thenReturn(BranchType.LONG);
112     analysisMetadataHolder
113       .setBranch(branch)
114       .setOrganizationsEnabled(new Random().nextBoolean())
115       .setOrganization(Organization.from(
116         new OrganizationDto().setKey(organizationKey).setName(organizationName).setUuid(organizationUuid).setDefaultQualityGateUuid("foo")));
117
118     reportReader.setMetadata(ScannerReport.Metadata.newBuilder().build());
119   }
120
121   @Test
122   @UseDataProvider("booleanValues")
123   public void does_not_fail_when_there_is_no_PostProjectAnalysisTasksExecutor(boolean allStepsExecuted) {
124     new PostProjectAnalysisTasksExecutor(ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, system2)
125       .finished(allStepsExecuted);
126   }
127
128   @Test
129   @UseDataProvider("booleanValues")
130   public void finished_calls_all_PostProjectAnalysisTask_in_order_of_the_array_and_passes_the_same_object_to_all(boolean allStepsExecuted) {
131     PostProjectAnalysisTask postProjectAnalysisTask1 = mock(PostProjectAnalysisTask.class);
132     PostProjectAnalysisTask postProjectAnalysisTask2 = mock(PostProjectAnalysisTask.class);
133     InOrder inOrder = inOrder(postProjectAnalysisTask1, postProjectAnalysisTask2);
134
135     new PostProjectAnalysisTasksExecutor(
136       ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader,
137       system2, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2})
138         .finished(allStepsExecuted);
139
140     inOrder.verify(postProjectAnalysisTask1).finished(projectAnalysisArgumentCaptor.capture());
141     inOrder.verify(postProjectAnalysisTask2).finished(projectAnalysisArgumentCaptor.capture());
142     inOrder.verifyNoMoreInteractions();
143
144     List<PostProjectAnalysisTask.ProjectAnalysis> allValues = projectAnalysisArgumentCaptor.getAllValues();
145     assertThat(allValues).hasSize(2);
146     assertThat(allValues.get(0)).isSameAs(allValues.get(1));
147   }
148
149   @Test
150   @UseDataProvider("booleanValues")
151   public void organization_is_null_when_organization_are_disabled(boolean allStepsExecuted) {
152     analysisMetadataHolder
153       .setOrganizationsEnabled(false)
154       .setOrganization(Organization.from(
155         new OrganizationDto().setKey(organizationKey).setName(organizationName).setUuid(organizationUuid).setDefaultQualityGateUuid("foo")));
156     underTest.finished(allStepsExecuted);
157
158     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
159
160     assertThat(projectAnalysisArgumentCaptor.getValue().getOrganization()).isEmpty();
161   }
162
163   @Test
164   @UseDataProvider("booleanValues")
165   public void organization_is_not_null_when_organization_are_enabled(boolean allStepsExecuted) {
166     analysisMetadataHolder
167       .setOrganizationsEnabled(true)
168       .setOrganization(Organization.from(
169         new OrganizationDto().setKey(organizationKey).setName(organizationName).setUuid(organizationUuid).setDefaultQualityGateUuid("foo")));
170     underTest.finished(allStepsExecuted);
171
172     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
173
174     org.sonar.api.ce.posttask.Organization organization = projectAnalysisArgumentCaptor.getValue().getOrganization().get();
175     assertThat(organization.getKey()).isEqualTo(organizationKey);
176     assertThat(organization.getName()).isEqualTo(organizationName);
177   }
178
179   @Test
180   @UseDataProvider("booleanValues")
181   public void CeTask_status_depends_on_finished_method_argument_is_true_or_false(boolean allStepsExecuted) {
182     underTest.finished(allStepsExecuted);
183
184     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
185
186     assertThat(projectAnalysisArgumentCaptor.getValue().getCeTask().getStatus())
187       .isEqualTo(
188         allStepsExecuted ? org.sonar.api.ce.posttask.CeTask.Status.SUCCESS : org.sonar.api.ce.posttask.CeTask.Status.FAILED);
189   }
190
191   @Test
192   public void ceTask_uuid_is_UUID_of_CeTask() {
193     underTest.finished(true);
194
195     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
196
197     assertThat(projectAnalysisArgumentCaptor.getValue().getCeTask().getId())
198       .isEqualTo(ceTask.getUuid());
199   }
200
201   @Test
202   public void project_uuid_key_and_name_come_from_CeTask() {
203     underTest.finished(true);
204
205     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
206
207     Project project = projectAnalysisArgumentCaptor.getValue().getProject();
208     assertThat(project.getUuid()).isEqualTo(ceTask.getComponent().get().getUuid());
209     assertThat(project.getKey()).isEqualTo(ceTask.getComponent().get().getKey().get());
210     assertThat(project.getName()).isEqualTo(ceTask.getComponent().get().getName().get());
211   }
212
213   @Test
214   public void date_comes_from_AnalysisMetadataHolder() {
215     analysisMetadataHolder.setAnalysisDate(8_465_132_498L);
216     analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40));
217
218     underTest.finished(true);
219
220     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
221
222     assertThat(projectAnalysisArgumentCaptor.getValue().getDate())
223       .isEqualTo(new Date(analysisMetadataHolder.getAnalysisDate()));
224   }
225
226   @Test
227   public void date_comes_from_system2_if_not_set_in_AnalysisMetadataHolder() {
228     long now = 1_999_663L;
229     when(system2.now()).thenReturn(now);
230
231     underTest.finished(false);
232
233     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
234
235     assertThat(projectAnalysisArgumentCaptor.getValue().getDate()).isEqualTo(new Date(now));
236   }
237
238   @Test
239   public void analysisDate_and_analysisUuid_comes_from_AnalysisMetadataHolder_when_set() {
240     analysisMetadataHolder.setAnalysisDate(8465132498L);
241     analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40));
242
243     underTest.finished(true);
244
245     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
246
247     assertThat(projectAnalysisArgumentCaptor.getValue().getAnalysis().get().getDate())
248       .isEqualTo(new Date(analysisMetadataHolder.getAnalysisDate()));
249     assertThat(projectAnalysisArgumentCaptor.getValue().getAnalysis().get().getAnalysisUuid())
250       .isEqualTo(analysisMetadataHolder.getUuid());
251   }
252
253   @Test
254   public void analysis_is_empty_when_not_set_in_AnalysisMetadataHolder() {
255     underTest.finished(false);
256
257     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
258
259     assertThat(projectAnalysisArgumentCaptor.getValue().getAnalysis()).isEmpty();
260   }
261
262   @Test
263   public void branch_is_empty_when_legacy_branch_implementation_is_used() {
264     analysisMetadataHolder.setBranch(new DefaultBranchImpl("feature/foo"));
265
266     underTest.finished(true);
267
268     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
269
270     assertThat(projectAnalysisArgumentCaptor.getValue().getBranch()).isEmpty();
271   }
272
273   @Test
274   public void branch_comes_from_AnalysisMetadataHolder_when_set() {
275     analysisMetadataHolder.setBranch(new Branch() {
276       @Override
277       public BranchType getType() {
278         return BranchType.SHORT;
279       }
280
281       @Override
282       public boolean isMain() {
283         return false;
284       }
285
286       @Override
287       public boolean isLegacyFeature() {
288         return false;
289       }
290
291       @Override
292       public Optional<String> getMergeBranchUuid() {
293         return Optional.empty();
294       }
295
296       @Override
297       public String getName() {
298         return "feature/foo";
299       }
300
301       @Override
302       public boolean supportsCrossProjectCpd() {
303         throw new UnsupportedOperationException();
304       }
305
306       @Override
307       public String getPullRequestKey() {
308         throw new UnsupportedOperationException();
309       }
310
311       @Override
312       public String generateKey(ScannerReport.Component module, @Nullable ScannerReport.Component fileOrDir) {
313         throw new UnsupportedOperationException();
314       }
315     });
316
317     underTest.finished(true);
318
319     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
320
321     org.sonar.api.ce.posttask.Branch branch = projectAnalysisArgumentCaptor.getValue().getBranch().get();
322     assertThat(branch.isMain()).isFalse();
323     assertThat(branch.getName()).hasValue("feature/foo");
324     assertThat(branch.getType()).isEqualTo(BranchImpl.Type.SHORT);
325   }
326
327   @Test
328   public void qualityGate_is_null_when_finished_method_argument_is_false() {
329     underTest.finished(false);
330
331     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
332
333     assertThat(projectAnalysisArgumentCaptor.getValue().getQualityGate()).isNull();
334   }
335
336   @Test
337   public void qualityGate_is_populated_when_finished_method_argument_is_true() {
338     underTest.finished(true);
339
340     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
341
342     org.sonar.api.ce.posttask.QualityGate qualityGate = projectAnalysisArgumentCaptor.getValue().getQualityGate();
343     assertThat(qualityGate.getStatus()).isEqualTo(org.sonar.api.ce.posttask.QualityGate.Status.OK);
344     assertThat(qualityGate.getId()).isEqualTo(String.valueOf(QUALITY_GATE_ID));
345     assertThat(qualityGate.getName()).isEqualTo(QUALITY_GATE_NAME);
346     assertThat(qualityGate.getConditions()).hasSize(2);
347   }
348
349   @Test
350   public void scannerContext_loads_properties_from_scanner_report() {
351     reportReader.putContextProperties(asList(ScannerReport.ContextProperty.newBuilder().setKey("foo").setValue("bar").build()));
352     underTest.finished(true);
353
354     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
355
356     org.sonar.api.ce.posttask.ScannerContext scannerContext = projectAnalysisArgumentCaptor.getValue().getScannerContext();
357     assertThat(scannerContext.getProperties()).containsExactly(entry("foo", "bar"));
358   }
359
360   @Test
361   @UseDataProvider("booleanValues")
362   public void finished_does_not_fail_if_listener_throws_exception_and_execute_subsequent_listeners(boolean allStepsExecuted) {
363     PostProjectAnalysisTask postProjectAnalysisTask1 = mock(PostProjectAnalysisTask.class);
364     PostProjectAnalysisTask postProjectAnalysisTask2 = mock(PostProjectAnalysisTask.class);
365     PostProjectAnalysisTask postProjectAnalysisTask3 = mock(PostProjectAnalysisTask.class);
366     InOrder inOrder = inOrder(postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3);
367
368     doThrow(new RuntimeException("Faking a listener throws an exception"))
369       .when(postProjectAnalysisTask2)
370       .finished(any(PostProjectAnalysisTask.ProjectAnalysis.class));
371
372     new PostProjectAnalysisTasksExecutor(
373       ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader,
374       system2, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3})
375         .finished(allStepsExecuted);
376
377     inOrder.verify(postProjectAnalysisTask1).finished(projectAnalysisArgumentCaptor.capture());
378     inOrder.verify(postProjectAnalysisTask2).finished(projectAnalysisArgumentCaptor.capture());
379     inOrder.verify(postProjectAnalysisTask3).finished(projectAnalysisArgumentCaptor.capture());
380     inOrder.verifyNoMoreInteractions();
381   }
382
383   @DataProvider
384   public static Object[][] booleanValues() {
385     return new Object[][] {
386       {true},
387       {false}
388     };
389   }
390
391   private static Condition createCondition(String metricKey) {
392     Metric metric = mock(Metric.class);
393     when(metric.getKey()).thenReturn(metricKey);
394     return new Condition(metric, Condition.Operator.EQUALS.getDbValue(), "error threshold");
395   }
396
397 }