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 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2024 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.util.List;
  26. import java.util.Optional;
  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.slf4j.event.Level;
  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.notifications.AnalysisWarnings;
  37. import org.sonar.api.platform.Server;
  38. import org.sonar.api.testfixtures.log.LogTester;
  39. import org.sonar.api.utils.MessageException;
  40. import org.sonar.api.utils.TempFolder;
  41. import org.sonar.scanner.http.DefaultScannerWsClient;
  42. import org.sonar.scanner.bootstrap.GlobalAnalysisMode;
  43. import org.sonar.scanner.ci.CiConfiguration;
  44. import org.sonar.scanner.ci.DevOpsPlatformInfo;
  45. import org.sonar.scanner.fs.InputModuleHierarchy;
  46. import org.sonar.scanner.protocol.output.FileStructure;
  47. import org.sonar.scanner.protocol.output.ScannerReport;
  48. import org.sonar.scanner.scan.ScanProperties;
  49. import org.sonar.scanner.scan.branch.BranchConfiguration;
  50. import org.sonarqube.ws.Ce;
  51. import org.sonarqube.ws.client.HttpException;
  52. import org.sonarqube.ws.client.MockWsResponse;
  53. import org.sonarqube.ws.client.WsRequest;
  54. import org.sonarqube.ws.client.WsResponse;
  55. import static org.apache.commons.io.FileUtils.readFileToString;
  56. import static org.assertj.core.api.Assertions.assertThat;
  57. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  58. import static org.mockito.ArgumentMatchers.any;
  59. import static org.mockito.ArgumentMatchers.argThat;
  60. import static org.mockito.Mockito.mock;
  61. import static org.mockito.Mockito.verify;
  62. import static org.mockito.Mockito.verifyNoInteractions;
  63. import static org.mockito.Mockito.when;
  64. import static org.sonar.scanner.report.ReportPublisher.SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE;
  65. import static org.sonar.scanner.scan.branch.BranchType.BRANCH;
  66. import static org.sonar.scanner.scan.branch.BranchType.PULL_REQUEST;
  67. public class ReportPublisherTest {
  68. @Rule
  69. public LogTester logTester = new LogTester();
  70. @Rule
  71. public JUnitTempFolder reportTempFolder = new JUnitTempFolder();
  72. private GlobalAnalysisMode mode = mock(GlobalAnalysisMode.class);
  73. private ScanProperties properties = mock(ScanProperties.class);
  74. private DefaultScannerWsClient wsClient = mock(DefaultScannerWsClient.class, Mockito.RETURNS_DEEP_STUBS);
  75. private Server server = mock(Server.class);
  76. private InputModuleHierarchy moduleHierarchy = mock(InputModuleHierarchy.class);
  77. private DefaultInputModule root;
  78. private AnalysisContextReportPublisher contextPublisher = mock(AnalysisContextReportPublisher.class);
  79. private BranchConfiguration branchConfiguration = mock(BranchConfiguration.class);
  80. private CeTaskReportDataHolder reportMetadataHolder = mock(CeTaskReportDataHolder.class);
  81. private CiConfiguration ciConfiguration = mock(CiConfiguration.class);
  82. private ReportPublisher underTest;
  83. private AnalysisWarnings analysisWarnings = mock(AnalysisWarnings.class);
  84. private FileStructure fileStructure;
  85. private JavaArchitectureInformationProvider javaArchitectureInformationProvider = mock(JavaArchitectureInformationProvider.class);
  86. @Before
  87. public void setUp() {
  88. logTester.setLevel(Level.DEBUG);
  89. root = new DefaultInputModule(
  90. ProjectDefinition.create().setKey("org.sonarsource.sonarqube:sonarqube").setBaseDir(reportTempFolder.newDir()).setWorkDir(reportTempFolder.getRoot()));
  91. when(moduleHierarchy.root()).thenReturn(root);
  92. fileStructure = new FileStructure(reportTempFolder.getRoot());
  93. when(server.getPublicRootUrl()).thenReturn("https://localhost");
  94. when(server.getVersion()).thenReturn("6.4");
  95. when(properties.metadataFilePath()).thenReturn(reportTempFolder.newDir().toPath()
  96. .resolve("folder")
  97. .resolve("report-task.txt"));
  98. underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, reportTempFolder,
  99. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder, analysisWarnings, javaArchitectureInformationProvider, fileStructure, ciConfiguration);
  100. }
  101. @Test
  102. public void checks_if_component_has_issues() {
  103. underTest.getWriter().writeComponentIssues(1, List.of(ScannerReport.Issue.newBuilder().build()));
  104. assertThat(underTest.getReader().hasIssues(1)).isTrue();
  105. assertThat(underTest.getReader().hasIssues(2)).isFalse();
  106. }
  107. @Test
  108. public void use_write_timeout_from_properties() {
  109. when(properties.reportPublishTimeout()).thenReturn(60);
  110. MockWsResponse submitMockResponse = new MockWsResponse();
  111. submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
  112. when(wsClient.call(any())).thenReturn(submitMockResponse);
  113. underTest.start();
  114. underTest.execute();
  115. verify(wsClient).call(argThat(req -> (req).getWriteTimeOutInMs().orElse(0) == 60_000));
  116. }
  117. @Test
  118. public void should_not_log_success_when_should_wait_for_QG() {
  119. when(properties.shouldWaitForQualityGate()).thenReturn(true);
  120. MockWsResponse submitMockResponse = new MockWsResponse();
  121. submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
  122. when(wsClient.call(any())).thenReturn(submitMockResponse);
  123. underTest.start();
  124. underTest.execute();
  125. assertThat(logTester.logs()).noneMatch(s -> s.contains("ANALYSIS SUCCESSFUL"));
  126. }
  127. @Test
  128. public void dump_information_about_report_uploading() throws IOException {
  129. underTest.prepareAndDumpMetadata("TASK-123");
  130. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  131. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  132. "serverUrl=https://localhost\n" +
  133. "serverVersion=6.4\n" +
  134. "dashboardUrl=https://localhost/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
  135. "ceTaskId=TASK-123\n" +
  136. "ceTaskUrl=https://localhost/api/ce/task?id=TASK-123\n");
  137. }
  138. @Test
  139. public void upload_error_message() {
  140. HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}");
  141. WsResponse response = mock(WsResponse.class);
  142. when(response.failIfNotSuccessful()).thenThrow(ex);
  143. when(wsClient.call(any(WsRequest.class))).thenThrow(new IllegalStateException("timeout"));
  144. assertThatThrownBy(() -> underTest.upload(reportTempFolder.newFile()))
  145. .isInstanceOf(IllegalStateException.class)
  146. .hasMessage("Failed to upload report: timeout");
  147. }
  148. @Test
  149. public void parse_upload_error_message() {
  150. HttpException ex = new HttpException("url", 404, "{\"errors\":[{\"msg\":\"Organization with key 'MyOrg' does not exist\"}]}");
  151. WsResponse response = mock(WsResponse.class);
  152. when(response.failIfNotSuccessful()).thenThrow(ex);
  153. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  154. assertThatThrownBy(() -> underTest.upload(reportTempFolder.newFile()))
  155. .isInstanceOf(MessageException.class)
  156. .hasMessage("Server failed to process report. Please check server logs: Organization with key 'MyOrg' does not exist");
  157. }
  158. @Test
  159. public void dump_public_url_if_defined_for_main_branch() throws IOException {
  160. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  161. underTest.prepareAndDumpMetadata("TASK-123");
  162. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  163. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  164. "serverUrl=https://publicserver/sonarqube\n" +
  165. "serverVersion=6.4\n" +
  166. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube\n" +
  167. "ceTaskId=TASK-123\n" +
  168. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  169. }
  170. @Test
  171. public void dump_public_url_if_defined_for_branches() throws IOException {
  172. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  173. when(branchConfiguration.branchType()).thenReturn(BRANCH);
  174. when(branchConfiguration.branchName()).thenReturn("branch-6.7");
  175. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
  176. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder, analysisWarnings, javaArchitectureInformationProvider, fileStructure, ciConfiguration);
  177. underTest.prepareAndDumpMetadata("TASK-123");
  178. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  179. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  180. "serverUrl=https://publicserver/sonarqube\n" +
  181. "serverVersion=6.4\n" +
  182. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&branch=branch-6.7\n" +
  183. "ceTaskId=TASK-123\n" +
  184. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  185. }
  186. @Test
  187. public void dump_public_url_if_defined_for_pull_request() throws IOException {
  188. when(server.getPublicRootUrl()).thenReturn("https://publicserver/sonarqube");
  189. when(branchConfiguration.branchName()).thenReturn("Bitbucket cloud Widget");
  190. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  191. when(branchConfiguration.pullRequestKey()).thenReturn("105");
  192. ReportPublisher underTest = new ReportPublisher(properties, wsClient, server, contextPublisher, moduleHierarchy, mode, mock(TempFolder.class),
  193. new ReportPublisherStep[0], branchConfiguration, reportMetadataHolder, analysisWarnings, javaArchitectureInformationProvider, fileStructure, ciConfiguration);
  194. underTest.prepareAndDumpMetadata("TASK-123");
  195. assertThat(readFileToString(properties.metadataFilePath().toFile(), StandardCharsets.UTF_8)).isEqualTo(
  196. "projectKey=org.sonarsource.sonarqube:sonarqube\n" +
  197. "serverUrl=https://publicserver/sonarqube\n" +
  198. "serverVersion=6.4\n" +
  199. "dashboardUrl=https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube&pullRequest=105\n" +
  200. "ceTaskId=TASK-123\n" +
  201. "ceTaskUrl=https://publicserver/sonarqube/api/ce/task?id=TASK-123\n");
  202. }
  203. @Test
  204. public void fail_if_public_url_malformed() {
  205. when(server.getPublicRootUrl()).thenReturn("invalid");
  206. assertThatThrownBy(() -> underTest.start())
  207. .isInstanceOf(MessageException.class)
  208. .hasMessage("Failed to parse public URL set in SonarQube server: invalid");
  209. }
  210. @Test
  211. public void should_not_dump_information_when_medium_test_enabled() {
  212. when(mode.isMediumTest()).thenReturn(true);
  213. underTest.start();
  214. underTest.execute();
  215. assertThat(logTester.logs(Level.INFO))
  216. .contains("ANALYSIS SUCCESSFUL")
  217. .doesNotContain("dashboard/index");
  218. assertThat(properties.metadataFilePath()).doesNotExist();
  219. }
  220. @Test
  221. public void should_upload_and_dump_information() {
  222. when(reportMetadataHolder.getDashboardUrl()).thenReturn("https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube");
  223. when(reportMetadataHolder.getCeTaskUrl()).thenReturn("https://publicserver/sonarqube/api/ce/task?id=TASK-123");
  224. MockWsResponse submitMockResponse = new MockWsResponse();
  225. submitMockResponse.setContent(Ce.SubmitResponse.newBuilder().setTaskId("task-1234").build().toByteArray());
  226. when(wsClient.call(any())).thenReturn(submitMockResponse);
  227. underTest.start();
  228. underTest.execute();
  229. assertThat(properties.metadataFilePath()).exists();
  230. assertThat(logTester.logs(Level.DEBUG))
  231. .contains("Report metadata written to " + properties.metadataFilePath());
  232. assertThat(logTester.logs(Level.INFO))
  233. .contains("ANALYSIS SUCCESSFUL, you can find the results at: https://publicserver/sonarqube/dashboard?id=org.sonarsource.sonarqube%3Asonarqube")
  234. .contains("More about the report processing at https://publicserver/sonarqube/api/ce/task?id=TASK-123");
  235. }
  236. @Test
  237. public void dump_information_to_custom_path() {
  238. underTest.prepareAndDumpMetadata("TASK-123");
  239. assertThat(properties.metadataFilePath()).exists();
  240. assertThat(logTester.logs(Level.DEBUG)).contains("Report metadata written to " + properties.metadataFilePath());
  241. }
  242. @Test
  243. public void should_not_delete_report_if_property_is_set() throws IOException {
  244. when(properties.shouldKeepReport()).thenReturn(true);
  245. underTest.start();
  246. underTest.stop();
  247. assertThat(fileStructure.root()).isDirectory();
  248. }
  249. @Test
  250. public void should_delete_report_by_default() throws IOException {
  251. underTest.start();
  252. underTest.stop();
  253. assertThat(fileStructure.root()).doesNotExist();
  254. }
  255. @Test
  256. public void test_ws_parameters() throws Exception {
  257. WsResponse response = mock(WsResponse.class);
  258. PipedOutputStream out = new PipedOutputStream();
  259. PipedInputStream in = new PipedInputStream(out);
  260. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  261. out.close();
  262. when(response.failIfNotSuccessful()).thenReturn(response);
  263. when(response.contentStream()).thenReturn(in);
  264. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  265. underTest.upload(reportTempFolder.newFile());
  266. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  267. verify(wsClient).call(capture.capture());
  268. WsRequest wsRequest = capture.getValue();
  269. assertThat(wsRequest.getParameters().getKeys()).containsOnly("projectKey");
  270. assertThat(wsRequest.getParameters().getValue("projectKey")).isEqualTo("org.sonarsource.sonarqube:sonarqube");
  271. assertThat(wsRequest.getParameters().getValues("characteristic")).isEmpty();
  272. }
  273. @Test
  274. public void test_send_branches_characteristics() throws Exception {
  275. String branchName = "feature";
  276. when(branchConfiguration.branchName()).thenReturn(branchName);
  277. when(branchConfiguration.branchType()).thenReturn(BRANCH);
  278. WsResponse response = mock(WsResponse.class);
  279. PipedOutputStream out = new PipedOutputStream();
  280. PipedInputStream in = new PipedInputStream(out);
  281. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  282. out.close();
  283. when(response.failIfNotSuccessful()).thenReturn(response);
  284. when(response.contentStream()).thenReturn(in);
  285. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  286. underTest.upload(reportTempFolder.newFile());
  287. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  288. verify(wsClient).call(capture.capture());
  289. WsRequest wsRequest = capture.getValue();
  290. assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
  291. assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
  292. assertThat(wsRequest.getParameters().getValues("characteristic"))
  293. .containsExactlyInAnyOrder("branch=" + branchName, "branchType=" + BRANCH.name());
  294. }
  295. @Test
  296. public void send_pull_request_characteristic() throws Exception {
  297. String branchName = "feature";
  298. String pullRequestId = "pr-123";
  299. when(branchConfiguration.branchName()).thenReturn(branchName);
  300. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  301. when(branchConfiguration.pullRequestKey()).thenReturn(pullRequestId);
  302. WsResponse response = mock(WsResponse.class);
  303. PipedOutputStream out = new PipedOutputStream();
  304. PipedInputStream in = new PipedInputStream(out);
  305. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  306. out.close();
  307. when(response.failIfNotSuccessful()).thenReturn(response);
  308. when(response.contentStream()).thenReturn(in);
  309. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  310. underTest.upload(reportTempFolder.newFile());
  311. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  312. verify(wsClient).call(capture.capture());
  313. WsRequest wsRequest = capture.getValue();
  314. assertThat(wsRequest.getParameters().getKeys()).hasSize(2);
  315. assertThat(wsRequest.getParameters().getValues("projectKey")).containsExactly("org.sonarsource.sonarqube:sonarqube");
  316. assertThat(wsRequest.getParameters().getValues("characteristic"))
  317. .containsExactlyInAnyOrder("pullRequest=" + pullRequestId);
  318. }
  319. @Test
  320. public void upload_whenDevOpsPlatformInformationPresentInCiConfiguration_shouldUploadDevOpsPlatformInfoAsCharacteristic() throws Exception {
  321. String branchName = "feature";
  322. String pullRequestId = "pr-123";
  323. DevOpsPlatformInfo devOpsPlatformInfo = new DevOpsPlatformInfo("https://devops.example.com", "projectId");
  324. when(branchConfiguration.branchName()).thenReturn(branchName);
  325. when(branchConfiguration.branchType()).thenReturn(PULL_REQUEST);
  326. when(branchConfiguration.pullRequestKey()).thenReturn(pullRequestId);
  327. when(ciConfiguration.getDevOpsPlatformInfo()).thenReturn(Optional.of(devOpsPlatformInfo));
  328. WsResponse response = mock(WsResponse.class);
  329. PipedOutputStream out = new PipedOutputStream();
  330. PipedInputStream in = new PipedInputStream(out);
  331. Ce.SubmitResponse.newBuilder().build().writeTo(out);
  332. out.close();
  333. when(response.failIfNotSuccessful()).thenReturn(response);
  334. when(response.contentStream()).thenReturn(in);
  335. when(wsClient.call(any(WsRequest.class))).thenReturn(response);
  336. underTest.upload(reportTempFolder.newFile());
  337. ArgumentCaptor<WsRequest> capture = ArgumentCaptor.forClass(WsRequest.class);
  338. verify(wsClient).call(capture.capture());
  339. WsRequest wsRequest = capture.getValue();
  340. assertThat(wsRequest.getParameters().getValues("characteristic"))
  341. .contains(
  342. "devOpsPlatformUrl=" + devOpsPlatformInfo.getUrl(),
  343. "devOpsPlatformProjectIdentifier=" + devOpsPlatformInfo.getProjectIdentifier());
  344. }
  345. @Test
  346. public void test_do_not_log_or_add_warning_if_using_64bit_jre() {
  347. when(javaArchitectureInformationProvider.is64bitJavaVersion()).thenReturn(true);
  348. when(mode.isMediumTest()).thenReturn(true);
  349. underTest.start();
  350. underTest.execute();
  351. assertThat(logTester.logs(Level.WARN)).isEmpty();
  352. verifyNoInteractions(analysisWarnings);
  353. }
  354. @Test
  355. public void test_log_and_add_warning_if_using_non64bit_jre() {
  356. when(javaArchitectureInformationProvider.is64bitJavaVersion()).thenReturn(false);
  357. when(mode.isMediumTest()).thenReturn(true);
  358. underTest.start();
  359. underTest.execute();
  360. assertThat(logTester.logs(Level.WARN)).containsOnly(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
  361. verify(analysisWarnings).addUnique(SUPPORT_OF_32_BIT_JRE_IS_DEPRECATED_MESSAGE);
  362. }
  363. }