3 * Copyright (C) 2009-2022 SonarSource SA
4 * mailto:info AT sonarsource DOT com
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.
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.
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.
20 package org.sonar.server.qualityprofile.ws;
22 import com.google.common.collect.ImmutableMap;
23 import java.io.Reader;
24 import java.util.Collections;
26 import org.junit.Rule;
27 import org.junit.Test;
28 import org.sonar.api.profiles.ProfileImporter;
29 import org.sonar.api.profiles.RulesProfile;
30 import org.sonar.api.rules.RulePriority;
31 import org.sonar.api.server.ws.WebService;
32 import org.sonar.api.server.ws.WebService.Param;
33 import org.sonar.api.utils.System2;
34 import org.sonar.api.utils.ValidationMessages;
35 import org.sonar.core.util.UuidFactoryFast;
36 import org.sonar.db.DbClient;
37 import org.sonar.db.DbSession;
38 import org.sonar.db.DbTester;
39 import org.sonar.db.qualityprofile.QProfileDto;
40 import org.sonar.db.rule.RuleDefinitionDto;
41 import org.sonar.db.rule.RuleTesting;
42 import org.sonar.server.es.EsTester;
43 import org.sonar.server.exceptions.BadRequestException;
44 import org.sonar.server.exceptions.ForbiddenException;
45 import org.sonar.server.qualityprofile.QProfileExporters;
46 import org.sonar.server.qualityprofile.QProfileFactoryImpl;
47 import org.sonar.server.qualityprofile.QProfileRules;
48 import org.sonar.server.qualityprofile.QProfileRulesImpl;
49 import org.sonar.server.qualityprofile.RuleActivator;
50 import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
51 import org.sonar.server.rule.index.RuleIndex;
52 import org.sonar.server.rule.index.RuleIndexer;
53 import org.sonar.server.rule.index.RuleQuery;
54 import org.sonar.server.tester.UserSessionRule;
55 import org.sonar.server.ws.TestRequest;
56 import org.sonar.server.ws.TestResponse;
57 import org.sonar.server.ws.WsActionTester;
58 import org.sonar.test.JsonAssert;
59 import org.sonarqube.ws.MediaTypes;
60 import org.sonarqube.ws.Qualityprofiles.CreateWsResponse;
61 import org.sonarqube.ws.Qualityprofiles.CreateWsResponse.QualityProfile;
63 import static org.assertj.core.api.Assertions.assertThat;
64 import static org.assertj.core.api.Assertions.assertThatThrownBy;
65 import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
66 import static org.sonar.db.permission.GlobalPermission.SCAN;
67 import static org.sonar.server.language.LanguageTesting.newLanguages;
69 public class CreateActionTest {
71 private static final String XOO_LANGUAGE = "xoo";
72 private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
74 .setLanguage(XOO_LANGUAGE)
78 public DbTester db = DbTester.create();
80 public EsTester es = EsTester.create();
82 public UserSessionRule userSession = UserSessionRule.standalone();
84 private DbClient dbClient = db.getDbClient();
85 private DbSession dbSession = db.getSession();
86 private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
87 private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbClient);
88 private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client());
89 private ProfileImporter[] profileImporters = createImporters();
90 private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, null, userSession);
91 private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer);
92 private QProfileExporters qProfileExporters = new QProfileExporters(dbClient, null, qProfileRules, profileImporters);
94 private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
95 qProfileExporters, newLanguages(XOO_LANGUAGE), userSession, activeRuleIndexer, profileImporters);
97 private WsActionTester ws = new WsActionTester(underTest);
100 public void definition() {
101 WebService.Action definition = ws.getDef();
103 assertThat(definition.responseExampleAsString()).isNotEmpty();
104 assertThat(definition.isPost()).isTrue();
105 assertThat(definition.params()).extracting(Param::key)
106 .containsExactlyInAnyOrder("language", "name", "backup_with_messages", "backup_with_errors", "backup_xoo_lint");
110 public void create_profile() {
111 logInAsQProfileAdministrator();
113 CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
115 QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, "New Profile", XOO_LANGUAGE);
116 assertThat(dto.getKee()).isNotNull();
117 assertThat(dto.getLanguage()).isEqualTo(XOO_LANGUAGE);
118 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();
131 public void create_profile_from_backup_xml() {
132 logInAsQProfileAdministrator();
135 executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
137 QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, "New Profile", XOO_LANGUAGE);
138 assertThat(dto.getKee()).isNotNull();
139 assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, dto.getKee())).hasSize(1);
140 assertThat(ruleIndex.searchAll(new RuleQuery().setQProfile(dto).setActivation(true))).toIterable().hasSize(1);
144 public void create_profile_with_messages() {
145 logInAsQProfileAdministrator();
147 CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
149 QualityProfile profile = response.getProfile();
150 assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
151 assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
155 public void fail_if_unsufficient_privileges() {
158 .addPermission(SCAN);
160 assertThatThrownBy(() -> {
161 executeRequest(ws.newRequest()
162 .setParam("name", "some Name")
163 .setParam("language", XOO_LANGUAGE));
165 .isInstanceOf(ForbiddenException.class)
166 .hasMessage("Insufficient privileges");
170 public void fail_if_import_generate_error() {
171 logInAsQProfileAdministrator();
173 assertThatThrownBy(() -> {
174 executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
176 .isInstanceOf(BadRequestException.class);
180 public void test_json() {
181 logInAsQProfileAdministrator();
183 TestResponse response = ws.newRequest()
185 .setMediaType(MediaTypes.JSON)
186 .setParam("language", XOO_LANGUAGE)
187 .setParam("name", "Yeehaw!")
190 JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionTest/test_json.json"));
191 assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
194 private void insertRule(RuleDefinitionDto ruleDto) {
195 dbClient.ruleDao().insert(dbSession, ruleDto);
197 ruleIndexer.commitAndIndex(dbSession, ruleDto.getUuid());
200 private CreateWsResponse executeRequest(String name, String language) {
201 return executeRequest(name, language, Collections.emptyMap());
204 private CreateWsResponse executeRequest(String name, String language, Map<String, String> xmls) {
205 TestRequest request = ws.newRequest()
206 .setParam("name", name)
207 .setParam("language", language);
208 for (Map.Entry<String, String> entry : xmls.entrySet()) {
209 request.setParam("backup_" + entry.getKey(), entry.getValue());
211 return executeRequest(request);
214 private CreateWsResponse executeRequest(TestRequest request) {
215 return request.executeProtobuf(CreateWsResponse.class);
218 private ProfileImporter[] createImporters() {
219 class DefaultProfileImporter extends ProfileImporter {
220 private DefaultProfileImporter() {
221 super("xoo_lint", "Xoo Lint");
222 setSupportedLanguages(XOO_LANGUAGE);
226 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
227 RulesProfile rulesProfile = RulesProfile.create();
228 rulesProfile.activateRule(org.sonar.api.rules.Rule.create(RULE.getRepositoryKey(), RULE.getRuleKey()), RulePriority.BLOCKER);
233 class ProfileImporterGeneratingMessages extends ProfileImporter {
234 private ProfileImporterGeneratingMessages() {
235 super("with_messages", "With messages");
236 setSupportedLanguages(XOO_LANGUAGE);
240 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
241 RulesProfile rulesProfile = RulesProfile.create();
242 messages.addWarningText("a warning");
243 messages.addInfoText("an info");
248 class ProfileImporterGeneratingErrors extends ProfileImporter {
249 private ProfileImporterGeneratingErrors() {
250 super("with_errors", "With errors");
251 setSupportedLanguages(XOO_LANGUAGE);
255 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
256 RulesProfile rulesProfile = RulesProfile.create();
257 messages.addErrorText("error!");
262 return new ProfileImporter[] {
263 new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
267 private void logInAsQProfileAdministrator() {
270 .addPermission(ADMINISTER_QUALITY_PROFILES);