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

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