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.

SetTypeActionTest.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2020 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.server.issue.ws;
  21. import com.google.common.collect.Sets;
  22. import com.tngtech.java.junit.dataprovider.DataProvider;
  23. import com.tngtech.java.junit.dataprovider.DataProviderRunner;
  24. import com.tngtech.java.junit.dataprovider.UseDataProvider;
  25. import java.util.EnumSet;
  26. import java.util.List;
  27. import java.util.Set;
  28. import java.util.stream.Collectors;
  29. import javax.annotation.Nullable;
  30. import org.junit.Rule;
  31. import org.junit.Test;
  32. import org.junit.rules.ExpectedException;
  33. import org.junit.runner.RunWith;
  34. import org.mockito.ArgumentCaptor;
  35. import org.sonar.api.rules.RuleType;
  36. import org.sonar.api.server.ws.Request;
  37. import org.sonar.api.server.ws.Response;
  38. import org.sonar.api.server.ws.WebService;
  39. import org.sonar.api.utils.System2;
  40. import org.sonar.core.issue.FieldDiffs;
  41. import org.sonar.db.DbClient;
  42. import org.sonar.db.DbTester;
  43. import org.sonar.db.component.ComponentDto;
  44. import org.sonar.db.issue.IssueDbTester;
  45. import org.sonar.db.issue.IssueDto;
  46. import org.sonar.db.rule.RuleDefinitionDto;
  47. import org.sonar.server.es.EsTester;
  48. import org.sonar.server.exceptions.ForbiddenException;
  49. import org.sonar.server.exceptions.NotFoundException;
  50. import org.sonar.server.exceptions.UnauthorizedException;
  51. import org.sonar.server.issue.IssueFieldsSetter;
  52. import org.sonar.server.issue.IssueFinder;
  53. import org.sonar.server.issue.TestIssueChangePostProcessor;
  54. import org.sonar.server.issue.WebIssueStorage;
  55. import org.sonar.server.issue.index.IssueIndexer;
  56. import org.sonar.server.issue.index.IssueIteratorFactory;
  57. import org.sonar.server.issue.notification.IssuesChangesNotificationSerializer;
  58. import org.sonar.server.notification.NotificationManager;
  59. import org.sonar.server.organization.DefaultOrganizationProvider;
  60. import org.sonar.server.organization.TestDefaultOrganizationProvider;
  61. import org.sonar.server.rule.DefaultRuleFinder;
  62. import org.sonar.server.tester.UserSessionRule;
  63. import org.sonar.server.ws.TestRequest;
  64. import org.sonar.server.ws.TestResponse;
  65. import org.sonar.server.ws.WsActionTester;
  66. import static java.util.Optional.ofNullable;
  67. import static org.assertj.core.api.Assertions.assertThat;
  68. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  69. import static org.mockito.ArgumentMatchers.any;
  70. import static org.mockito.ArgumentMatchers.eq;
  71. import static org.mockito.Mockito.mock;
  72. import static org.mockito.Mockito.verify;
  73. import static org.mockito.Mockito.when;
  74. import static org.sonar.api.rules.RuleType.BUG;
  75. import static org.sonar.api.rules.RuleType.CODE_SMELL;
  76. import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT;
  77. import static org.sonar.api.web.UserRole.ISSUE_ADMIN;
  78. import static org.sonar.api.web.UserRole.USER;
  79. import static org.sonar.db.component.ComponentTesting.newFileDto;
  80. @RunWith(DataProviderRunner.class)
  81. public class SetTypeActionTest {
  82. @Rule
  83. public ExpectedException expectedException = ExpectedException.none();
  84. @Rule
  85. public DbTester dbTester = DbTester.create();
  86. @Rule
  87. public EsTester es = EsTester.create();
  88. @Rule
  89. public UserSessionRule userSession = UserSessionRule.standalone();
  90. private System2 system2 = mock(System2.class);
  91. private DbClient dbClient = dbTester.getDbClient();
  92. private IssueDbTester issueDbTester = new IssueDbTester(dbTester);
  93. private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(dbTester);
  94. private OperationResponseWriter responseWriter = mock(OperationResponseWriter.class);
  95. private ArgumentCaptor<SearchResponseData> preloadedSearchResponseDataCaptor = ArgumentCaptor.forClass(SearchResponseData.class);
  96. private IssueIndexer issueIndexer = new IssueIndexer(es.client(), dbClient, new IssueIteratorFactory(dbClient));
  97. private TestIssueChangePostProcessor issueChangePostProcessor = new TestIssueChangePostProcessor();
  98. private IssuesChangesNotificationSerializer issuesChangesSerializer = new IssuesChangesNotificationSerializer();
  99. private WsActionTester tester = new WsActionTester(new SetTypeAction(userSession, dbClient, new IssueFinder(dbClient, userSession), new IssueFieldsSetter(),
  100. new IssueUpdater(dbClient,
  101. new WebIssueStorage(system2, dbClient, new DefaultRuleFinder(dbClient, defaultOrganizationProvider), issueIndexer), mock(NotificationManager.class),
  102. issueChangePostProcessor, issuesChangesSerializer),
  103. responseWriter, system2));
  104. @Test
  105. @UseDataProvider("allTypesFromToExceptHotspots")
  106. public void set_type(RuleType from, RuleType to) {
  107. long now = 1_999_777_234L;
  108. when(system2.now()).thenReturn(now);
  109. IssueDto issueDto = newIssueWithProject(from);
  110. setUserWithBrowseAndAdministerIssuePermission(issueDto);
  111. call(issueDto.getKey(), to.name());
  112. verify(responseWriter).write(eq(issueDto.getKey()), preloadedSearchResponseDataCaptor.capture(), any(Request.class), any(Response.class));
  113. IssueDto issueReloaded = dbClient.issueDao().selectByKey(dbTester.getSession(), issueDto.getKey()).get();
  114. assertThat(issueReloaded.getType()).isEqualTo(to.getDbConstant());
  115. if (from != to) {
  116. verifyContentOfPreloadedSearchResponseData(issueDto);
  117. assertThat(issueChangePostProcessor.calledComponents())
  118. .extracting(ComponentDto::uuid)
  119. .containsExactlyInAnyOrder(issueDto.getComponentUuid());
  120. } else {
  121. assertThat(issueChangePostProcessor.wasCalled())
  122. .isFalse();
  123. }
  124. }
  125. @Test
  126. public void insert_entry_in_changelog_when_setting_type() {
  127. IssueDto issueDto = newIssueWithProject(CODE_SMELL);
  128. setUserWithBrowseAndAdministerIssuePermission(issueDto);
  129. call(issueDto.getKey(), BUG.name());
  130. List<FieldDiffs> fieldDiffs = dbClient.issueChangeDao().selectChangelogByIssue(dbTester.getSession(), issueDto.getKey());
  131. assertThat(fieldDiffs).hasSize(1);
  132. assertThat(fieldDiffs.get(0).diffs()).hasSize(1);
  133. assertThat(fieldDiffs.get(0).diffs().get("type").newValue()).isEqualTo(BUG.name());
  134. assertThat(fieldDiffs.get(0).diffs().get("type").oldValue()).isEqualTo(CODE_SMELL.name());
  135. }
  136. @Test
  137. public void fail_if_bad_type_value() {
  138. IssueDto issueDto = newIssueWithProject(CODE_SMELL);
  139. setUserWithBrowseAndAdministerIssuePermission(issueDto);
  140. assertThatThrownBy(() -> call(issueDto.getKey(), "unknown"))
  141. .isInstanceOf(IllegalArgumentException.class)
  142. .hasMessage("Value of parameter 'type' (unknown) must be one of: [CODE_SMELL, BUG, VULNERABILITY]");
  143. }
  144. @Test
  145. public void fail_if_SECURITY_HOTSPOT_value() {
  146. IssueDto issueDto = newIssueWithProject(CODE_SMELL);
  147. setUserWithBrowseAndAdministerIssuePermission(issueDto);
  148. assertThatThrownBy(() -> call(issueDto.getKey(), "SECURITY_HOTSPOT"))
  149. .isInstanceOf(IllegalArgumentException.class)
  150. .hasMessage("Value of parameter 'type' (SECURITY_HOTSPOT) must be one of: [CODE_SMELL, BUG, VULNERABILITY]");
  151. }
  152. @Test
  153. public void fail_when_not_authenticated() {
  154. expectedException.expect(UnauthorizedException.class);
  155. call("ABCD", BUG.name());
  156. }
  157. @Test
  158. public void fail_when_missing_browse_permission() {
  159. IssueDto issueDto = issueDbTester.insertIssue();
  160. String login = "john";
  161. String permission = ISSUE_ADMIN;
  162. logInAndAddProjectPermission(login, issueDto, permission);
  163. expectedException.expect(ForbiddenException.class);
  164. call(issueDto.getKey(), BUG.name());
  165. }
  166. @Test
  167. @UseDataProvider("allTypesExceptSecurityHotspot")
  168. public void fail_type_except_hotspot_when_missing_administer_issue_permission(RuleType type) {
  169. IssueDto issueDto = issueDbTester.insertIssue(issue -> issue.setType(type));
  170. logInAndAddProjectPermission("john", issueDto, USER);
  171. expectedException.expect(ForbiddenException.class);
  172. call(issueDto.getKey(), type.name());
  173. }
  174. @Test
  175. @UseDataProvider("allTypesExceptSecurityHotspot")
  176. public void fail_NFE_if_trying_to_change_type_of_a_hotspot(RuleType type) {
  177. long now = 1_999_777_234L;
  178. when(system2.now()).thenReturn(now);
  179. IssueDto hotspot = issueDbTester.insertHotspot();
  180. setUserWithBrowseAndAdministerIssuePermission(hotspot);
  181. assertThatThrownBy(() -> call(hotspot.getKey(), type.name()))
  182. .isInstanceOf(NotFoundException.class)
  183. .hasMessage("Issue with key '%s' does not exist", hotspot.getKey());
  184. }
  185. @Test
  186. public void test_definition() {
  187. WebService.Action action = tester.getDef();
  188. assertThat(action.key()).isEqualTo("set_type");
  189. assertThat(action.isPost()).isTrue();
  190. assertThat(action.isInternal()).isFalse();
  191. assertThat(action.params()).hasSize(2);
  192. assertThat(action.responseExample()).isNotNull();
  193. }
  194. private TestResponse call(@Nullable String issueKey, @Nullable String type) {
  195. TestRequest request = tester.newRequest();
  196. ofNullable(issueKey).ifPresent(issue -> request.setParam("issue", issue));
  197. ofNullable(type).ifPresent(t -> request.setParam("type", t));
  198. return request.execute();
  199. }
  200. private IssueDto newIssueWithProject(RuleType type) {
  201. RuleDefinitionDto rule = dbTester.rules().insert();
  202. ComponentDto project = dbTester.components().insertMainBranch();
  203. ComponentDto file = dbTester.components().insertComponent(newFileDto(project));
  204. return issueDbTester.insert(rule, project, file, i -> i.setType(type));
  205. }
  206. private void setUserWithBrowseAndAdministerIssuePermission(IssueDto issueDto) {
  207. ComponentDto project = dbClient.componentDao().selectByUuid(dbTester.getSession(), issueDto.getProjectUuid()).get();
  208. userSession.logIn(dbTester.users().insertUser("john"))
  209. .addProjectPermission(ISSUE_ADMIN, project)
  210. .addProjectPermission(USER, project);
  211. }
  212. private void logInAndAddProjectPermission(String login, IssueDto issueDto, String permission) {
  213. userSession.logIn(login).addProjectPermission(permission, dbClient.componentDao().selectByUuid(dbTester.getSession(), issueDto.getProjectUuid()).get());
  214. }
  215. private void verifyContentOfPreloadedSearchResponseData(IssueDto issue) {
  216. SearchResponseData preloadedSearchResponseData = preloadedSearchResponseDataCaptor.getValue();
  217. assertThat(preloadedSearchResponseData.getIssues())
  218. .extracting(IssueDto::getKey)
  219. .containsOnly(issue.getKey());
  220. assertThat(preloadedSearchResponseData.getRules())
  221. .extracting(RuleDefinitionDto::getKey)
  222. .containsOnly(issue.getRuleKey());
  223. assertThat(preloadedSearchResponseData.getComponents())
  224. .extracting(ComponentDto::uuid)
  225. .containsOnly(issue.getComponentUuid(), issue.getProjectUuid());
  226. }
  227. @DataProvider
  228. public static Object[][] allTypesExceptSecurityHotspot() {
  229. return EnumSet.allOf(RuleType.class)
  230. .stream()
  231. .filter(ruleType -> SECURITY_HOTSPOT != ruleType)
  232. .map(t -> new Object[] {t})
  233. .toArray(Object[][]::new);
  234. }
  235. @DataProvider
  236. public static Object[][] allTypesFromToExceptHotspots() {
  237. Set<RuleType> set = EnumSet.allOf(RuleType.class)
  238. .stream()
  239. .filter(ruleType -> SECURITY_HOTSPOT != ruleType)
  240. .collect(Collectors.toSet());
  241. return Sets.cartesianProduct(set, set)
  242. .stream()
  243. .map(ruleTypes -> new Object[] {ruleTypes.get(0), ruleTypes.get(1)})
  244. .toArray(Object[][]::new);
  245. }
  246. }