]> source.dussan.org Git - sonarqube.git/blob
e03fc74189379e726c0e38c3eebdb45dd521e482
[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
119   @Test
120   @UseDataProvider("booleanValues")
121   public void does_not_fail_when_there_is_no_PostProjectAnalysisTasksExecutor(boolean allStepsExecuted) {
122     new PostProjectAnalysisTasksExecutor(ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader, system2)
123       .finished(allStepsExecuted);
124   }
125
126   @Test
127   @UseDataProvider("booleanValues")
128   public void finished_calls_all_PostProjectAnalysisTask_in_order_of_the_array_and_passes_the_same_object_to_all(boolean allStepsExecuted) {
129     PostProjectAnalysisTask postProjectAnalysisTask1 = mock(PostProjectAnalysisTask.class);
130     PostProjectAnalysisTask postProjectAnalysisTask2 = mock(PostProjectAnalysisTask.class);
131     InOrder inOrder = inOrder(postProjectAnalysisTask1, postProjectAnalysisTask2);
132
133     new PostProjectAnalysisTasksExecutor(
134       ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader,
135       system2, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2})
136         .finished(allStepsExecuted);
137
138     inOrder.verify(postProjectAnalysisTask1).finished(projectAnalysisArgumentCaptor.capture());
139     inOrder.verify(postProjectAnalysisTask2).finished(projectAnalysisArgumentCaptor.capture());
140     inOrder.verifyNoMoreInteractions();
141
142     List<PostProjectAnalysisTask.ProjectAnalysis> allValues = projectAnalysisArgumentCaptor.getAllValues();
143     assertThat(allValues).hasSize(2);
144     assertThat(allValues.get(0)).isSameAs(allValues.get(1));
145   }
146
147   @Test
148   @UseDataProvider("booleanValues")
149   public void organization_is_null_when_organization_are_disabled(boolean allStepsExecuted) {
150     analysisMetadataHolder
151       .setOrganizationsEnabled(false)
152       .setOrganization(Organization.from(
153         new OrganizationDto().setKey(organizationKey).setName(organizationName).setUuid(organizationUuid).setDefaultQualityGateUuid("foo")));
154     underTest.finished(allStepsExecuted);
155
156     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
157
158     assertThat(projectAnalysisArgumentCaptor.getValue().getOrganization()).isEmpty();
159   }
160
161   @Test
162   @UseDataProvider("booleanValues")
163   public void organization_is_not_null_when_organization_are_enabled(boolean allStepsExecuted) {
164     analysisMetadataHolder
165       .setOrganizationsEnabled(true)
166       .setOrganization(Organization.from(
167         new OrganizationDto().setKey(organizationKey).setName(organizationName).setUuid(organizationUuid).setDefaultQualityGateUuid("foo")));
168     underTest.finished(allStepsExecuted);
169
170     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
171
172     org.sonar.api.ce.posttask.Organization organization = projectAnalysisArgumentCaptor.getValue().getOrganization().get();
173     assertThat(organization.getKey()).isEqualTo(organizationKey);
174     assertThat(organization.getName()).isEqualTo(organizationName);
175   }
176
177   @Test
178   @UseDataProvider("booleanValues")
179   public void CeTask_status_depends_on_finished_method_argument_is_true_or_false(boolean allStepsExecuted) {
180     underTest.finished(allStepsExecuted);
181
182     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
183
184     assertThat(projectAnalysisArgumentCaptor.getValue().getCeTask().getStatus())
185       .isEqualTo(
186         allStepsExecuted ? org.sonar.api.ce.posttask.CeTask.Status.SUCCESS : org.sonar.api.ce.posttask.CeTask.Status.FAILED);
187   }
188
189   @Test
190   public void ceTask_uuid_is_UUID_of_CeTask() {
191     underTest.finished(true);
192
193     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
194
195     assertThat(projectAnalysisArgumentCaptor.getValue().getCeTask().getId())
196       .isEqualTo(ceTask.getUuid());
197   }
198
199   @Test
200   public void project_uuid_key_and_name_come_from_CeTask() {
201     underTest.finished(true);
202
203     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
204
205     Project project = projectAnalysisArgumentCaptor.getValue().getProject();
206     assertThat(project.getUuid()).isEqualTo(ceTask.getComponent().get().getUuid());
207     assertThat(project.getKey()).isEqualTo(ceTask.getComponent().get().getKey().get());
208     assertThat(project.getName()).isEqualTo(ceTask.getComponent().get().getName().get());
209   }
210
211   @Test
212   public void date_comes_from_AnalysisMetadataHolder() {
213     analysisMetadataHolder.setAnalysisDate(8_465_132_498L);
214     analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40));
215
216     underTest.finished(true);
217
218     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
219
220     assertThat(projectAnalysisArgumentCaptor.getValue().getDate())
221       .isEqualTo(new Date(analysisMetadataHolder.getAnalysisDate()));
222   }
223
224   @Test
225   public void date_comes_from_system2_if_not_set_in_AnalysisMetadataHolder() {
226     long now = 1_999_663L;
227     when(system2.now()).thenReturn(now);
228
229     underTest.finished(false);
230
231     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
232
233     assertThat(projectAnalysisArgumentCaptor.getValue().getDate()).isEqualTo(new Date(now));
234   }
235
236   @Test
237   public void analysisDate_and_analysisUuid_comes_from_AnalysisMetadataHolder_when_set() {
238     analysisMetadataHolder.setAnalysisDate(8465132498L);
239     analysisMetadataHolder.setUuid(RandomStringUtils.randomAlphanumeric(40));
240
241     underTest.finished(true);
242
243     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
244
245     assertThat(projectAnalysisArgumentCaptor.getValue().getAnalysis().get().getDate())
246       .isEqualTo(new Date(analysisMetadataHolder.getAnalysisDate()));
247     assertThat(projectAnalysisArgumentCaptor.getValue().getAnalysis().get().getAnalysisUuid())
248       .isEqualTo(analysisMetadataHolder.getUuid());
249   }
250
251   @Test
252   public void analysis_is_empty_when_not_set_in_AnalysisMetadataHolder() {
253     underTest.finished(false);
254
255     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
256
257     assertThat(projectAnalysisArgumentCaptor.getValue().getAnalysis()).isEmpty();
258   }
259
260   @Test
261   public void branch_is_empty_when_legacy_branch_implementation_is_used() {
262     analysisMetadataHolder.setBranch(new DefaultBranchImpl("feature/foo"));
263
264     underTest.finished(true);
265
266     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
267
268     assertThat(projectAnalysisArgumentCaptor.getValue().getBranch()).isEmpty();
269   }
270
271   @Test
272   public void branch_comes_from_AnalysisMetadataHolder_when_set() {
273     analysisMetadataHolder.setBranch(new Branch() {
274       @Override
275       public BranchType getType() {
276         return BranchType.SHORT;
277       }
278
279       @Override
280       public boolean isMain() {
281         return false;
282       }
283
284       @Override
285       public boolean isLegacyFeature() {
286         return false;
287       }
288
289       @Override
290       public Optional<String> getMergeBranchUuid() {
291         return Optional.empty();
292       }
293
294       @Override
295       public String getName() {
296         return "feature/foo";
297       }
298
299       @Override
300       public boolean supportsCrossProjectCpd() {
301         throw new UnsupportedOperationException();
302       }
303
304       @Override
305       public String getPullRequestKey() {
306         throw new UnsupportedOperationException();
307       }
308
309       @Override
310       public String generateKey(ScannerReport.Component module, @Nullable ScannerReport.Component fileOrDir) {
311         throw new UnsupportedOperationException();
312       }
313     });
314
315     underTest.finished(true);
316
317     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
318
319     org.sonar.api.ce.posttask.Branch branch = projectAnalysisArgumentCaptor.getValue().getBranch().get();
320     assertThat(branch.isMain()).isFalse();
321     assertThat(branch.getName()).hasValue("feature/foo");
322     assertThat(branch.getType()).isEqualTo(BranchImpl.Type.SHORT);
323   }
324
325   @Test
326   public void qualityGate_is_null_when_finished_method_argument_is_false() {
327     underTest.finished(false);
328
329     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
330
331     assertThat(projectAnalysisArgumentCaptor.getValue().getQualityGate()).isNull();
332   }
333
334   @Test
335   public void qualityGate_is_populated_when_finished_method_argument_is_true() {
336     underTest.finished(true);
337
338     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
339
340     org.sonar.api.ce.posttask.QualityGate qualityGate = projectAnalysisArgumentCaptor.getValue().getQualityGate();
341     assertThat(qualityGate.getStatus()).isEqualTo(org.sonar.api.ce.posttask.QualityGate.Status.OK);
342     assertThat(qualityGate.getId()).isEqualTo(String.valueOf(QUALITY_GATE_ID));
343     assertThat(qualityGate.getName()).isEqualTo(QUALITY_GATE_NAME);
344     assertThat(qualityGate.getConditions()).hasSize(2);
345   }
346
347   @Test
348   public void scannerContext_loads_properties_from_scanner_report() {
349     reportReader.putContextProperties(asList(ScannerReport.ContextProperty.newBuilder().setKey("foo").setValue("bar").build()));
350     underTest.finished(true);
351
352     verify(postProjectAnalysisTask).finished(projectAnalysisArgumentCaptor.capture());
353
354     org.sonar.api.ce.posttask.ScannerContext scannerContext = projectAnalysisArgumentCaptor.getValue().getScannerContext();
355     assertThat(scannerContext.getProperties()).containsExactly(entry("foo", "bar"));
356   }
357
358   @Test
359   @UseDataProvider("booleanValues")
360   public void finished_does_not_fail_if_listener_throws_exception_and_execute_subsequent_listeners(boolean allStepsExecuted) {
361     PostProjectAnalysisTask postProjectAnalysisTask1 = mock(PostProjectAnalysisTask.class);
362     PostProjectAnalysisTask postProjectAnalysisTask2 = mock(PostProjectAnalysisTask.class);
363     PostProjectAnalysisTask postProjectAnalysisTask3 = mock(PostProjectAnalysisTask.class);
364     InOrder inOrder = inOrder(postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3);
365
366     doThrow(new RuntimeException("Faking a listener throws an exception"))
367       .when(postProjectAnalysisTask2)
368       .finished(any(PostProjectAnalysisTask.ProjectAnalysis.class));
369
370     new PostProjectAnalysisTasksExecutor(
371       ceTask, analysisMetadataHolder, qualityGateHolder, qualityGateStatusHolder, reportReader,
372       system2, new PostProjectAnalysisTask[] {postProjectAnalysisTask1, postProjectAnalysisTask2, postProjectAnalysisTask3})
373         .finished(allStepsExecuted);
374
375     inOrder.verify(postProjectAnalysisTask1).finished(projectAnalysisArgumentCaptor.capture());
376     inOrder.verify(postProjectAnalysisTask2).finished(projectAnalysisArgumentCaptor.capture());
377     inOrder.verify(postProjectAnalysisTask3).finished(projectAnalysisArgumentCaptor.capture());
378     inOrder.verifyNoMoreInteractions();
379   }
380
381   @DataProvider
382   public static Object[][] booleanValues() {
383     return new Object[][] {
384       {true},
385       {false}
386     };
387   }
388
389   private static Condition createCondition(String metricKey) {
390     Metric metric = mock(Metric.class);
391     when(metric.getKey()).thenReturn(metricKey);
392     return new Condition(metric, Condition.Operator.EQUALS.getDbValue(), "error threshold", "warn threshold", false);
393   }
394
395 }