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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  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. private GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class);
  68. private ScanProperties properties = mock(ScanProperties.class);
  69. private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS);
  70. private Server server = mock(Server.class);
  71. private InputModuleHierarchy moduleHierarchy = mock(InputModuleHierarchy.class);
  72. private DefaultInputModule root;
  73. private AnalysisContextReportPublisher contextPublisher = mock(AnalysisContextReportPublisher.class);
  74. private BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
  75. private CeTaskReportDataHolder reportMetadataHolder = mock(CeTaskReportDataHolder.class);
  76. private 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 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))).thenThrow(new IllegalStateException("timeout"));
  115. exception.expect(IllegalStateException.class);
  116. exception.expectMessage("Failed to upload report: timeout");
  117. underTest.upload(reportTempFolder.newFile());
  118. }
  119. @Test
  120. public void parse_upload_error_message() {
  121. HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}");
  122. WsResponse response = mock(WsResponse.class);
  123. when(response.failIfNotSuccessful()).thenThrow(ex);
  124. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  125. exception.expect(MessageException.class);
  126. exception.expectMessage("Server failed to process report. Please check server logs: Organization with key 'MyOrg' does not exist");
  127. underTest.upload(reportTempFolder.newFile());
  128. }
  129. @Test
  130. public void dump_public_url_if_defined_for_main_branch() throws IOException {
  131. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  132. underTest.prepareAndDumpMetadata("TASK-123");
  133. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  134. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  135. "serverUrl=https://publicserver/sonarqube\n" +
  136. "serverVersion=6.4\n" +
  137. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
  138. "ceTaskId=TASK-123\n" +
  139. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  140. }
  141. @Test
  142. public void dump_public_url_if_defined_for_branches() throws IOException {
  143. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  144. when(branchConfiguration.branchType()).thenReturn(BRANCH);
  145. when(branchConfiguration.branchName()).thenReturn("branch-6.7");
  146. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
  147. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder);
  148. underTest.prepareAndDumpMetadata("TASK-123");
  149. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  150. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  151. "serverUrl=https://publicserver/sonarqube\n" +
  152. "serverVersion=6.4\n" +
  153. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&branch=branch-6.7\n" +
  154. "ceTaskId=TASK-123\n" +
  155. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  156. }
  157. @Test
  158. public void dump_public_url_if_defined_for_pull_request() throws IOException {
  159. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  160. when(branchConfiguration.branchName()).thenReturn("Bitbucket cloud Widget");
  161. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  162. when(branchConfiguration.pullRequestKey()).thenReturn("105");
  163. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
  164. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder);
  165. underTest.prepareAndDumpMetadata("TASK-123");
  166. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  167. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  168. "serverUrl=https://publicserver/sonarqube\n" +
  169. "serverVersion=6.4\n" +
  170. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&pullRequest=105\n" +
  171. "ceTaskId=TASK-123\n" +
  172. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  173. }
  174. @Test
  175. public void fail_if_public_url_malformed() {
  176. when(server.getPublicRootUrl()).thenReturn("invalid");
  177. exception.expect(MessageException.class);
  178. exception.expectMessage("Failed to parse public URL set in SonarQube server: invalid");
  179. underTest.start();
  180. }
  181. @Test
  182. public void should_not_dump_information_when_medium_test_enabled() {
  183. when(mode.isMediumTest()).thenReturn(true);
  184. underTest.start();
  185. underTest.execute();
  186. assertThat(logTester.logs(LoggerLevel.INFO))
  187. .contains("ANALYSIS SUCCESSFUL")
  188. .doesNotContain("dashboard/index");
  189. assertThat(properties.metadataFilePath()).doesNotExist();
  190. }
  191. @Test
  192. public void should_upload_and_dump_information() {
  193. when(reportMetadataHolder.getDashboardUrl()).thenReturn("https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube");
  194. when(reportMetadataHolder.getCeTaskUrl()).thenReturn("https://publicserver/sonarqube/api/ce/task?id=TASK-123");
  195. MockWsResponse submitMockResponse = new MockWsResponse();
  196. submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
  197. when(wsClient.call(any())).thenReturn(submitMockResponse);
  198. underTest.start();
  199. underTest.execute();
  200. assertThat(properties.metadataFilePath()).exists();
  201. assertThat(logTester.logs(LoggerLevel.DEBUG))
  202. .contains("Report metadata written to " + properties.metadataFilePath());
  203. assertThat(logTester.logs(LoggerLevel.INFO))
  204. .contains("ANALYSIS SUCCESSFUL, you can browse https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube")
  205. .contains("More about the report processing at https://publicserver/sonarqube/api/ce/task?id=TASK-123");
  206. }
  207. @Test
  208. public void dump_information_to_custom_path() {
  209. underTest.prepareAndDumpMetadata("TASK-123");
  210. assertThat(properties.metadataFilePath()).exists();
  211. assertThat(logTester.logs(LoggerLevel.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath());
  212. }
  213. @Test
  214. public void should_not_delete_report_if_property_is_set() throws IOException {
  215. when(properties.shouldKeepReport()).thenReturn(true);
  216. Path reportDir = reportTempFolder.getRoot().toPath().resolve("scanner-report");
  217. Files.createDirectory(reportDir);
  218. underTest.start();
  219. underTest.stop();
  220. assertThat(reportDir).isDirectory();
  221. }
  222. @Test
  223. public void should_delete_report_by_default() throws IOException {
  224. Path reportDir = reportTempFolder.getRoot().toPath().resolve("scanner-report");
  225. Files.createDirectory(reportDir);
  226. underTest.start();
  227. underTest.stop();
  228. assertThat(reportDir).doesNotExist();
  229. }
  230. @Test
  231. public void test_ws_parameters() throws Exception {
  232. WsResponse response = mock(WsResponse.class);
  233. PipedOutputStream out = new PipedOutputStream();
  234. PipedInputStream in = new PipedInputStream(out);
  235. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  236. out.close();
  237. when(response.failIfNotSuccessful()).thenReturn(response);
  238. when(response.contentStream()).thenReturn(in);
  239. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  240. underTest.upload(reportTempFolder.newFile());
  241. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  242. verify(wsClient).call(capture.capture());
  243. WsRequest wsRequest = capture.getValue();
  244. assertThat(wsRequest.getParameters().getKeys()).containsOnly("projectKey");
  245. assertThat(wsRequest.getParameters().getValue("projectKey")).isEqualTo("org.sonarsource.sonarqube:sonarqube");
  246. }
  247. @Test
  248. public void test_send_branches_characteristics() throws Exception {
  249. String branchName = "feature";
  250. when(branchConfiguration.branchName()).thenReturn(branchName);
  251. when(branchConfiguration.branchType()).thenReturn(BRANCH);
  252. WsResponse response = mock(WsResponse.class);
  253. PipedOutputStream out = new PipedOutputStream();
  254. PipedInputStream in = new PipedInputStream(out);
  255. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  256. out.close();
  257. when(response.failIfNotSuccessful()).thenReturn(response);
  258. when(response.contentStream()).thenReturn(in);
  259. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  260. underTest.upload(reportTempFolder.newFile());
  261. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  262. verify(wsClient).call(capture.capture());
  263. WsRequest wsRequest = capture.getValue();
  264. assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
  265. assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
  266. assertThat(wsRequest.getParameters().getValues("characteristic"))
  267. .containsExactlyInAnyOrder("branch=" + branchName, "branchType=" + BRANCH.name());
  268. }
  269. @Test
  270. public void send_pull_request_characteristic() throws Exception {
  271. String branchName = "feature";
  272. String pullRequestId = "pr-123";
  273. when(branchConfiguration.branchName()).thenReturn(branchName);
  274. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  275. when(branchConfiguration.pullRequestKey()).thenReturn(pullRequestId);
  276. WsResponse response = mock(WsResponse.class);
  277. PipedOutputStream out = new PipedOutputStream();
  278. PipedInputStream in = new PipedInputStream(out);
  279. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  280. out.close();
  281. when(response.failIfNotSuccessful()).thenReturn(response);
  282. when(response.contentStream()).thenReturn(in);
  283. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  284. underTest.upload(reportTempFolder.newFile());
  285. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  286. verify(wsClient).call(capture.capture());
  287. WsRequest wsRequest = capture.getValue();
  288. assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
  289. assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
  290. assertThat(wsRequest.getParameters().getValues("characteristic"))
  291. .containsExactlyInAnyOrder("pullRequest=" + pullRequestId);
  292. }
  293. }