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.

CreateActionTest.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2019 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.qualityprofile.ws;
  21. import com.google.common.collect.ImmutableMap;
  22. import java.io.Reader;
  23. import java.util.Collections;
  24. import java.util.Map;
  25. import org.junit.Before;
  26. import org.junit.Rule;
  27. import org.junit.Test;
  28. import org.junit.rules.ExpectedException;
  29. import org.sonar.api.profiles.ProfileImporter;
  30. import org.sonar.api.profiles.RulesProfile;
  31. import org.sonar.api.rules.RulePriority;
  32. import org.sonar.api.server.ws.WebService;
  33. import org.sonar.api.server.ws.WebService.Param;
  34. import org.sonar.api.utils.System2;
  35. import org.sonar.api.utils.ValidationMessages;
  36. import org.sonar.core.util.UuidFactoryFast;
  37. import org.sonar.db.DbClient;
  38. import org.sonar.db.DbSession;
  39. import org.sonar.db.DbTester;
  40. import org.sonar.db.organization.OrganizationDto;
  41. import org.sonar.db.qualityprofile.QProfileDto;
  42. import org.sonar.db.rule.RuleDefinitionDto;
  43. import org.sonar.db.rule.RuleTesting;
  44. import org.sonar.server.es.EsTester;
  45. import org.sonar.server.exceptions.BadRequestException;
  46. import org.sonar.server.exceptions.ForbiddenException;
  47. import org.sonar.server.organization.DefaultOrganizationProvider;
  48. import org.sonar.server.organization.TestDefaultOrganizationProvider;
  49. import org.sonar.server.qualityprofile.QProfileExporters;
  50. import org.sonar.server.qualityprofile.QProfileFactoryImpl;
  51. import org.sonar.server.qualityprofile.QProfileRules;
  52. import org.sonar.server.qualityprofile.QProfileRulesImpl;
  53. import org.sonar.server.qualityprofile.RuleActivator;
  54. import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
  55. import org.sonar.server.rule.index.RuleIndex;
  56. import org.sonar.server.rule.index.RuleIndexer;
  57. import org.sonar.server.rule.index.RuleQuery;
  58. import org.sonar.server.tester.UserSessionRule;
  59. import org.sonar.server.ws.TestRequest;
  60. import org.sonar.server.ws.TestResponse;
  61. import org.sonar.server.ws.WsActionTester;
  62. import org.sonar.test.JsonAssert;
  63. import org.sonarqube.ws.MediaTypes;
  64. import org.sonarqube.ws.Qualityprofiles.CreateWsResponse;
  65. import org.sonarqube.ws.Qualityprofiles.CreateWsResponse.QualityProfile;
  66. import static org.assertj.core.api.Assertions.assertThat;
  67. import static org.sonar.db.permission.OrganizationPermission.ADMINISTER_QUALITY_PROFILES;
  68. import static org.sonar.server.language.LanguageTesting.newLanguages;
  69. public class CreateActionTest {
  70. private static final String XOO_LANGUAGE = "xoo";
  71. private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
  72. .setSeverity("MINOR")
  73. .setLanguage(XOO_LANGUAGE)
  74. .getDefinition();
  75. @Rule
  76. public ExpectedException expectedException = ExpectedException.none();
  77. @Rule
  78. public DbTester db = DbTester.create();
  79. @Rule
  80. public EsTester es = EsTester.create();
  81. @Rule
  82. public UserSessionRule userSession = UserSessionRule.standalone();
  83. private DbClient dbClient = db.getDbClient();
  84. private DbSession dbSession = db.getSession();
  85. private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
  86. private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbClient);
  87. private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client());
  88. private ProfileImporter[] profileImporters = createImporters();
  89. private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, null, userSession);
  90. private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer);
  91. private QProfileExporters qProfileExporters = new QProfileExporters(dbClient, null, qProfileRules, profileImporters);
  92. private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
  93. private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
  94. qProfileExporters, newLanguages(XOO_LANGUAGE), new QProfileWsSupport(dbClient, userSession, defaultOrganizationProvider), userSession, activeRuleIndexer, profileImporters);
  95. private WsActionTester ws = new WsActionTester(underTest);
  96. private OrganizationDto organization;
  97. @Before
  98. public void setUp() {
  99. organization = db.organizations().insert();
  100. }
  101. @Test
  102. public void definition() {
  103. WebService.Action definition = ws.getDef();
  104. assertThat(definition.responseExampleAsString()).isNotEmpty();
  105. assertThat(definition.isPost()).isTrue();
  106. assertThat(definition.params()).extracting(Param::key)
  107. .containsExactlyInAnyOrder("language", "organization", "name", "backup_with_messages", "backup_with_errors", "backup_xoo_lint");
  108. Param name = definition.param("name");
  109. assertThat(name.deprecatedKey()).isEqualTo("profileName");
  110. assertThat(name.deprecatedKeySince()).isEqualTo("6.6");
  111. }
  112. @Test
  113. public void create_profile() {
  114. logInAsQProfileAdministrator();
  115. CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
  116. QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "New Profile", XOO_LANGUAGE);
  117. assertThat(dto.getKee()).isNotNull();
  118. assertThat(dto.getLanguage()).isEqualTo(XOO_LANGUAGE);
  119. assertThat(dto.getName()).isEqualTo("New Profile");
  120. QualityProfile profile = response.getProfile();
  121. assertThat(profile.getKey()).isEqualTo(dto.getKee());
  122. assertThat(profile.getName()).isEqualTo("New Profile");
  123. assertThat(profile.getLanguage()).isEqualTo(XOO_LANGUAGE);
  124. assertThat(profile.getIsInherited()).isFalse();
  125. assertThat(profile.getIsDefault()).isFalse();
  126. assertThat(profile.hasInfos()).isFalse();
  127. assertThat(profile.hasWarnings()).isFalse();
  128. }
  129. @Test
  130. public void create_profile_from_backup_xml() {
  131. logInAsQProfileAdministrator();
  132. insertRule(RULE);
  133. executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
  134. QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "New Profile", XOO_LANGUAGE);
  135. assertThat(dto.getKee()).isNotNull();
  136. assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, dto.getKee())).hasSize(1);
  137. assertThat(ruleIndex.searchAll(new RuleQuery().setQProfile(dto).setActivation(true))).toIterable().hasSize(1);
  138. }
  139. @Test
  140. public void create_profile_with_messages() {
  141. logInAsQProfileAdministrator();
  142. CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
  143. QualityProfile profile = response.getProfile();
  144. assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
  145. assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
  146. }
  147. @Test
  148. public void create_profile_for_specific_organization() {
  149. logInAsQProfileAdministrator();
  150. String orgKey = organization.getKey();
  151. TestRequest request = ws.newRequest()
  152. .setParam("organization", orgKey)
  153. .setParam("name", "Profile with messages")
  154. .setParam("language", XOO_LANGUAGE)
  155. .setParam("backup_with_messages", "<xml/>");
  156. assertThat(executeRequest(request).getProfile().getOrganization())
  157. .isEqualTo(orgKey);
  158. }
  159. @Test
  160. public void create_two_qprofiles_in_different_organizations_with_same_name_and_language() {
  161. // this name will be used twice
  162. String profileName = "Profile123";
  163. OrganizationDto organization1 = db.organizations().insert();
  164. logInAsQProfileAdministrator(organization1);
  165. TestRequest request1 = ws.newRequest()
  166. .setParam("organization", organization1.getKey())
  167. .setParam("name", profileName)
  168. .setParam("language", XOO_LANGUAGE);
  169. assertThat(executeRequest(request1).getProfile().getOrganization())
  170. .isEqualTo(organization1.getKey());
  171. OrganizationDto organization2 = db.organizations().insert();
  172. logInAsQProfileAdministrator(organization2);
  173. TestRequest request2 = ws.newRequest()
  174. .setParam("organization", organization2.getKey())
  175. .setParam("name", profileName)
  176. .setParam("language", XOO_LANGUAGE);
  177. assertThat(executeRequest(request2).getProfile().getOrganization())
  178. .isEqualTo(organization2.getKey());
  179. }
  180. @Test
  181. public void fail_if_unsufficient_privileges() {
  182. OrganizationDto organizationX = db.organizations().insert();
  183. OrganizationDto organizationY = db.organizations().insert();
  184. logInAsQProfileAdministrator(organizationX);
  185. expectedException.expect(ForbiddenException.class);
  186. expectedException.expectMessage("Insufficient privileges");
  187. executeRequest(ws.newRequest()
  188. .setParam("organization", organizationY.getKey())
  189. .setParam("name", "some Name")
  190. .setParam("language", XOO_LANGUAGE));
  191. }
  192. @Test
  193. public void fail_if_import_generate_error() {
  194. logInAsQProfileAdministrator();
  195. expectedException.expect(BadRequestException.class);
  196. executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
  197. }
  198. @Test
  199. public void test_json() {
  200. logInAsQProfileAdministrator(db.getDefaultOrganization());
  201. TestResponse response = ws.newRequest()
  202. .setMethod("POST")
  203. .setMediaType(MediaTypes.JSON)
  204. .setParam("language", XOO_LANGUAGE)
  205. .setParam("name", "Yeehaw!")
  206. .execute();
  207. JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionTest/test_json.json"));
  208. assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
  209. }
  210. private void insertRule(RuleDefinitionDto ruleDto) {
  211. dbClient.ruleDao().insert(dbSession, ruleDto);
  212. dbSession.commit();
  213. ruleIndexer.commitAndIndex(dbSession, ruleDto.getId());
  214. }
  215. private CreateWsResponse executeRequest(String name, String language) {
  216. return executeRequest(name, language, Collections.emptyMap());
  217. }
  218. private CreateWsResponse executeRequest(String name, String language, Map<String, String> xmls) {
  219. TestRequest request = ws.newRequest()
  220. .setParam("organization", organization.getKey())
  221. .setParam("name", name)
  222. .setParam("language", language);
  223. for (Map.Entry<String, String> entry : xmls.entrySet()) {
  224. request.setParam("backup_" + entry.getKey(), entry.getValue());
  225. }
  226. return executeRequest(request);
  227. }
  228. private CreateWsResponse executeRequest(TestRequest request) {
  229. return request.executeProtobuf(CreateWsResponse.class);
  230. }
  231. private ProfileImporter[] createImporters() {
  232. class DefaultProfileImporter extends ProfileImporter {
  233. private DefaultProfileImporter() {
  234. super("xoo_lint", "Xoo Lint");
  235. setSupportedLanguages(XOO_LANGUAGE);
  236. }
  237. @Override
  238. public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
  239. RulesProfile rulesProfile = RulesProfile.create();
  240. rulesProfile.activateRule(org.sonar.api.rules.Rule.create(RULE.getRepositoryKey(), RULE.getRuleKey()), RulePriority.BLOCKER);
  241. return rulesProfile;
  242. }
  243. }
  244. class ProfileImporterGeneratingMessages extends ProfileImporter {
  245. private ProfileImporterGeneratingMessages() {
  246. super("with_messages", "With messages");
  247. setSupportedLanguages(XOO_LANGUAGE);
  248. }
  249. @Override
  250. public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
  251. RulesProfile rulesProfile = RulesProfile.create();
  252. messages.addWarningText("a warning");
  253. messages.addInfoText("an info");
  254. return rulesProfile;
  255. }
  256. }
  257. class ProfileImporterGeneratingErrors extends ProfileImporter {
  258. private ProfileImporterGeneratingErrors() {
  259. super("with_errors", "With errors");
  260. setSupportedLanguages(XOO_LANGUAGE);
  261. }
  262. @Override
  263. public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
  264. RulesProfile rulesProfile = RulesProfile.create();
  265. messages.addErrorText("error!");
  266. return rulesProfile;
  267. }
  268. }
  269. return new ProfileImporter[] {
  270. new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
  271. };
  272. }
  273. private void logInAsQProfileAdministrator() {
  274. logInAsQProfileAdministrator(organization);
  275. }
  276. private void logInAsQProfileAdministrator(OrganizationDto organization) {
  277. userSession
  278. .logIn()
  279. .addPermission(ADMINISTER_QUALITY_PROFILES, organization);
  280. }
  281. }