You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ReportPublisherTest.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2021 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.scanner.report;
  21. import java.io.IOException;
  22. import java.io.PipedInputStream;
  23. import java.io.PipedOutputStream;
  24. import java.nio.charset.StandardCharsets;
  25. import java.nio.file.Files;
  26. import java.nio.file.Path;
  27. import org.junit.Before;
  28. import org.junit.Rule;
  29. import org.junit.Test;
  30. import org.junit.rules.ExpectedException;
  31. import org.mockito.ArgumentCaptor;
  32. import org.mockito.Mockito;
  33. import org.sonar.api.batch.bootstrap.ProjectDefinition;
  34. import org.sonar.api.batch.fs.internal.DefaultInputModule;
  35. import org.sonar.api.impl.utils.JUnitTempFolder;
  36. import org.sonar.api.platform.Server;
  37. import org.sonar.api.utils.MessageException;
  38. import org.sonar.api.utils.TempFolder;
  39. import org.sonar.api.utils.log.LogTester;
  40. import org.sonar.api.utils.log.LoggerLevel;
  41. import org.sonar.scanner.bootstrap.DefaultScannerWsClient;
  42. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  43. import org.sonar.scanner.fs.InputModuleHierarchy;
  44. import org.sonar.scanner.scan.ScanProperties;
  45. import org.sonar.scanner.scan.branch.BranchConfiguration;
  46. import org.sonarqube.ws.Ce;
  47. import org.sonarqube.ws.client.HttpException;
  48. import org.sonarqube.ws.client.MockWsResponse;
  49. import org.sonarqube.ws.client.WsRequest;
  50. import org.sonarqube.ws.client.WsResponse;
  51. import static org.apache.commons.io.FileUtils.readFileToString;
  52. import static org.assertj.core.api.Assertions.assertThat;
  53. import static org.mockito.ArgumentMatchers.any;
  54. import static org.mockito.ArgumentMatchers.argThat;
  55. import static org.mockito.Mockito.mock;
  56. import static org.mockito.Mockito.verify;
  57. import static org.mockito.Mockito.when;
  58. import static org.sonar.scanner.scan.branch.BranchType.BRANCH;
  59. import static org.sonar.scanner.scan.branch.BranchType.PULL_REQUEST;
  60. public class ReportPublisherTest {
  61. @Rule
  62. public LogTester logTester = new LogTester();
  63. @Rule
  64. public JUnitTempFolder reportTempFolder = new JUnitTempFolder();
  65. @Rule
  66. public ExpectedException exception = ExpectedException.none();
  67. GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class);
  68. ScanProperties properties = mock(ScanProperties.class);
  69. DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS);
  70. Server server = mock(Server.class);
  71. InputModuleHierarchy moduleHierarchy = mock(InputModuleHierarchy.class);
  72. DefaultInputModule root;
  73. AnalysisContextReportPublisher contextPublisher = mock(AnalysisContextReportPublisher.class);
  74. BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
  75. CeTaskReportDataHolder reportMetadataHolder = mock(CeTaskReportDataHolder.class);
  76. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, reportTempFolder,
  77. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder);
  78. @Before
  79. public void setUp() {
  80. root = new DefaultInputModule(
  81. ProjectDefinition.create().setKey("org.sonarsource.sonarqube:sonarqube").setBaseDir(reportTempFolder.newDir()).setWorkDir(reportTempFolder.getRoot()));
  82. when(moduleHierarchy.root()).thenReturn(root);
  83. when(server.getPublicRootUrl()).thenReturn("https://localhost");
  84. when(server.getVersion()).thenReturn("6.4");
  85. when(properties.metadataFilePath()).thenReturn(reportTempFolder.newDir().toPath()
  86. .resolve("folder")
  87. .resolve("report-task.txt"));
  88. }
  89. @Test
  90. public void use_30s_write_timeout() {
  91. MockWsResponse submitMockResponse = new MockWsResponse();
  92. submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
  93. when(wsClient.call(any())).thenReturn(submitMockResponse);
  94. underTest.start();
  95. underTest.execute();
  96. verify(wsClient).call(argThat(req -> req.getWriteTimeOutInMs().orElse(0) == 30_000));
  97. }
  98. @Test
  99. public void dump_information_about_report_uploading() throws IOException {
  100. underTest.prepareAndDumpMetadata("TASK-123");
  101. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  102. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  103. "serverUrl=https://localhost\n" +
  104. "serverVersion=6.4\n" +
  105. "dashboardUrl=https://localhost/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
  106. "ceTaskId=TASK-123\n" +
  107. "ceTaskUrl=https://localhost/api/ce/task?id=TASK-123\n");
  108. }
  109. @Test
  110. public void parse_upload_error_message() {
  111. HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}");
  112. WsResponse response = mock(WsResponse.class);
  113. when(response.failIfNotSuccessful()).thenThrow(ex);
  114. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  115. exception.expect(MessageException.class);
  116. exception.expectMessage("Failed to upload report - Organization with key 'MyOrg' does not exist");
  117. underTest.upload(reportTempFolder.newFile());
  118. }
  119. @Test
  120. public void dump_public_url_if_defined_for_main_branch() throws IOException {
  121. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  122. underTest.prepareAndDumpMetadata("TASK-123");
  123. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  124. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  125. "serverUrl=https://publicserver/sonarqube\n" +
  126. "serverVersion=6.4\n" +
  127. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
  128. "ceTaskId=TASK-123\n" +
  129. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  130. }
  131. @Test
  132. public void dump_public_url_if_defined_for_branches() throws IOException {
  133. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  134. when(branchConfiguration.branchType()).thenReturn(BRANCH);
  135. when(branchConfiguration.branchName()).thenReturn("branch-6.7");
  136. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
  137. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder);
  138. underTest.prepareAndDumpMetadata("TASK-123");
  139. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  140. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  141. "serverUrl=https://publicserver/sonarqube\n" +
  142. "serverVersion=6.4\n" +
  143. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&branch=branch-6.7\n" +
  144. "ceTaskId=TASK-123\n" +
  145. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  146. }
  147. @Test
  148. public void dump_public_url_if_defined_for_pull_request() throws IOException {
  149. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  150. when(branchConfiguration.branchName()).thenReturn("Bitbucket cloud Widget");
  151. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  152. when(branchConfiguration.pullRequestKey()).thenReturn("105");
  153. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
  154. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder);
  155. underTest.prepareAndDumpMetadata("TASK-123");
  156. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  157. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  158. "serverUrl=https://publicserver/sonarqube\n" +
  159. "serverVersion=6.4\n" +
  160. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&pullRequest=105\n" +
  161. "ceTaskId=TASK-123\n" +
  162. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  163. }
  164. @Test
  165. public void fail_if_public_url_malformed() {
  166. when(server.getPublicRootUrl()).thenReturn("invalid");
  167. exception.expect(MessageException.class);
  168. exception.expectMessage("Failed to parse public URL set in SonarQube server: invalid");
  169. underTest.start();
  170. }
  171. @Test
  172. public void should_not_dump_information_when_medium_test_enabled() {
  173. when(mode.isMediumTest()).thenReturn(true);
  174. underTest.start();
  175. underTest.execute();
  176. assertThat(logTester.logs(LoggerLevel.INFO))
  177. .contains("ANALYSIS SUCCESSFUL")
  178. .doesNotContain("dashboard/index");
  179. assertThat(properties.metadataFilePath()).doesNotExist();
  180. }
  181. @Test
  182. public void should_upload_and_dump_information() {
  183. when(reportMetadataHolder.getDashboardUrl()).thenReturn("https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube");
  184. when(reportMetadataHolder.getCeTaskUrl()).thenReturn("https://publicserver/sonarqube/api/ce/task?id=TASK-123");
  185. MockWsResponse submitMockResponse = new MockWsResponse();
  186. submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
  187. when(wsClient.call(any())).thenReturn(submitMockResponse);
  188. underTest.start();
  189. underTest.execute();
  190. assertThat(properties.metadataFilePath()).exists();
  191. assertThat(logTester.logs(LoggerLevel.DEBUG))
  192. .contains("Report metadata written to " + properties.metadataFilePath());
  193. assertThat(logTester.logs(LoggerLevel.INFO))
  194. .contains("ANALYSIS SUCCESSFUL, you can browse https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube")
  195. .contains("More about the report processing at https://publicserver/sonarqube/api/ce/task?id=TASK-123");
  196. }
  197. @Test
  198. public void dump_information_to_custom_path() {
  199. underTest.prepareAndDumpMetadata("TASK-123");
  200. assertThat(properties.metadataFilePath()).exists();
  201. assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath());
  202. }
  203. @Test
  204. public void should_not_delete_report_if_property_is_set() throws IOException {
  205. when(properties.shouldKeepReport()).thenReturn(true);
  206. Path reportDir = reportTempFolder.getRoot().toPath().resolve("scanner-report");
  207. Files.createDirectory(reportDir);
  208. underTest.start();
  209. underTest.stop();
  210. assertThat(reportDir).isDirectory();
  211. }
  212. @Test
  213. public void should_delete_report_by_default() throws IOException {
  214. Path reportDir = reportTempFolder.getRoot().toPath().resolve("scanner-report");
  215. Files.createDirectory(reportDir);
  216. underTest.start();
  217. underTest.stop();
  218. assertThat(reportDir).doesNotExist();
  219. }
  220. @Test
  221. public void test_ws_parameters() throws Exception {
  222. WsResponse response = mock(WsResponse.class);
  223. PipedOutputStream out = new PipedOutputStream();
  224. PipedInputStream in = new PipedInputStream(out);
  225. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  226. out.close();
  227. when(response.failIfNotSuccessful()).thenReturn(response);
  228. when(response.contentStream()).thenReturn(in);
  229. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  230. underTest.upload(reportTempFolder.newFile());
  231. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  232. verify(wsClient).call(capture.capture());
  233. WsRequest wsRequest = capture.getValue();
  234. assertThat(wsRequest.getParameters().getKeys()).containsOnly("projectKey");
  235. assertThat(wsRequest.getParameters().getValue("projectKey")).isEqualTo("org.sonarsource.sonarqube:sonarqube");
  236. }
  237. @Test
  238. public void test_send_branches_characteristics() throws Exception {
  239. String branchName = "feature";
  240. when(branchConfiguration.branchName()).thenReturn(branchName);
  241. when(branchConfiguration.branchType()).thenReturn(BRANCH);
  242. WsResponse response = mock(WsResponse.class);
  243. PipedOutputStream out = new PipedOutputStream();
  244. PipedInputStream in = new PipedInputStream(out);
  245. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  246. out.close();
  247. when(response.failIfNotSuccessful()).thenReturn(response);
  248. when(response.contentStream()).thenReturn(in);
  249. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  250. underTest.upload(reportTempFolder.newFile());
  251. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  252. verify(wsClient).call(capture.capture());
  253. WsRequest wsRequest = capture.getValue();
  254. assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
  255. assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
  256. assertThat(wsRequest.getParameters().getValues("characteristic"))
  257. .containsExactlyInAnyOrder("branch=" + branchName, "branchType=" + BRANCH.name());
  258. }
  259. @Test
  260. public void send_pull_request_characteristic() throws Exception {
  261. String branchName = "feature";
  262. String pullRequestId = "pr-123";
  263. when(branchConfiguration.branchName()).thenReturn(branchName);
  264. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  265. when(branchConfiguration.pullRequestKey()).thenReturn(pullRequestId);
  266. WsResponse response = mock(WsResponse.class);
  267. PipedOutputStream out = new PipedOutputStream();
  268. PipedInputStream in = new PipedInputStream(out);
  269. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  270. out.close();
  271. when(response.failIfNotSuccessful()).thenReturn(response);
  272. when(response.contentStream()).thenReturn(in);
  273. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  274. underTest.upload(reportTempFolder.newFile());
  275. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  276. verify(wsClient).call(capture.capture());
  277. WsRequest wsRequest = capture.getValue();
  278. assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
  279. assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
  280. assertThat(wsRequest.getParameters().getValues("characteristic"))
  281. .containsExactlyInAnyOrder("pullRequest=" + pullRequestId);
  282. }
  283. }