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.pushapi.qualityprofile.QualityProfileChangeEventService;
46 import org.sonar.server.qualityprofile.QProfileExporters;
47 import org.sonar.server.qualityprofile.QProfileFactoryImpl;
48 import org.sonar.server.qualityprofile.QProfileRules;
49 import org.sonar.server.qualityprofile.QProfileRulesImpl;
50 import org.sonar.server.qualityprofile.builtin.RuleActivator;
51 import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
52 import org.sonar.server.rule.index.RuleIndex;
53 import org.sonar.server.rule.index.RuleIndexer;
54 import org.sonar.server.rule.index.RuleQuery;
55 import org.sonar.server.tester.UserSessionRule;
56 import org.sonar.server.ws.TestRequest;
57 import org.sonar.server.ws.TestResponse;
58 import org.sonar.server.ws.WsActionTester;
59 import org.sonar.test.JsonAssert;
60 import org.sonarqube.ws.MediaTypes;
61 import org.sonarqube.ws.Qualityprofiles.CreateWsResponse;
62 import org.sonarqube.ws.Qualityprofiles.CreateWsResponse.QualityProfile;
64 import static org.assertj.core.api.Assertions.assertThat;
65 import static org.assertj.core.api.Assertions.assertThatThrownBy;
66 import static org.mockito.Mockito.mock;
67 import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES;
68 import static org.sonar.db.permission.GlobalPermission.SCAN;
69 import static org.sonar.server.language.LanguageTesting.newLanguages;
71 public class CreateActionTest {
73 private static final String XOO_LANGUAGE = "xoo";
74 private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
76 .setLanguage(XOO_LANGUAGE)
80 public DbTester db = DbTester.create();
82 public EsTester es = EsTester.create();
84 public UserSessionRule userSession = UserSessionRule.standalone();
86 private DbClient dbClient = db.getDbClient();
87 private DbSession dbSession = db.getSession();
88 private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
89 private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbClient);
90 private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client());
91 private ProfileImporter[] profileImporters = createImporters();
92 private QualityProfileChangeEventService qualityProfileChangeEventService = mock(QualityProfileChangeEventService.class);
93 private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, null, userSession);
94 private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer, qualityProfileChangeEventService);
95 private QProfileExporters qProfileExporters = new QProfileExporters(dbClient, null, qProfileRules, profileImporters);
97 private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
98 qProfileExporters, newLanguages(XOO_LANGUAGE), userSession, activeRuleIndexer, profileImporters);
100 private WsActionTester ws = new WsActionTester(underTest);
103 public void definition() {
104 WebService.Action definition = ws.getDef();
106 assertThat(definition.responseExampleAsString()).isNotEmpty();
107 assertThat(definition.isPost()).isTrue();
108 assertThat(definition.params()).extracting(Param::key)
109 .containsExactlyInAnyOrder("language", "name", "backup_with_messages", "backup_with_errors", "backup_xoo_lint");
113 public void create_profile() {
114 logInAsQProfileAdministrator();
116 CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
118 QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, "New Profile", XOO_LANGUAGE);
119 assertThat(dto.getKee()).isNotNull();
120 assertThat(dto.getLanguage()).isEqualTo(XOO_LANGUAGE);
121 assertThat(dto.getName()).isEqualTo("New Profile");
123 QualityProfile profile = response.getProfile();
124 assertThat(profile.getKey()).isEqualTo(dto.getKee());
125 assertThat(profile.getName()).isEqualTo("New Profile");
126 assertThat(profile.getLanguage()).isEqualTo(XOO_LANGUAGE);
127 assertThat(profile.getIsInherited()).isFalse();
128 assertThat(profile.getIsDefault()).isFalse();
129 assertThat(profile.hasInfos()).isFalse();
130 assertThat(profile.hasWarnings()).isFalse();
134 public void create_profile_from_backup_xml() {
135 logInAsQProfileAdministrator();
138 executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
140 QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, "New Profile", XOO_LANGUAGE);
141 assertThat(dto.getKee()).isNotNull();
142 assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, dto.getKee())).hasSize(1);
143 assertThat(ruleIndex.searchAll(new RuleQuery().setQProfile(dto).setActivation(true))).toIterable().hasSize(1);
147 public void create_profile_with_messages() {
148 logInAsQProfileAdministrator();
150 CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
152 QualityProfile profile = response.getProfile();
153 assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
154 assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
158 public void fail_if_unsufficient_privileges() {
161 .addPermission(SCAN);
163 assertThatThrownBy(() -> {
164 executeRequest(ws.newRequest()
165 .setParam("name", "some Name")
166 .setParam("language", XOO_LANGUAGE));
168 .isInstanceOf(ForbiddenException.class)
169 .hasMessage("Insufficient privileges");
173 public void fail_if_import_generate_error() {
174 logInAsQProfileAdministrator();
176 assertThatThrownBy(() -> {
177 executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
179 .isInstanceOf(BadRequestException.class);
183 public void test_json() {
184 logInAsQProfileAdministrator();
186 TestResponse response = ws.newRequest()
188 .setMediaType(MediaTypes.JSON)
189 .setParam("language", XOO_LANGUAGE)
190 .setParam("name", "Yeehaw!")
193 JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionTest/test_json.json"));
194 assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
197 private void insertRule(RuleDefinitionDto ruleDto) {
198 dbClient.ruleDao().insert(dbSession, ruleDto);
200 ruleIndexer.commitAndIndex(dbSession, ruleDto.getUuid());
203 private CreateWsResponse executeRequest(String name, String language) {
204 return executeRequest(name, language, Collections.emptyMap());
207 private CreateWsResponse executeRequest(String name, String language, Map<String, String> xmls) {
208 TestRequest request = ws.newRequest()
209 .setParam("name", name)
210 .setParam("language", language);
211 for (Map.Entry<String, String> entry : xmls.entrySet()) {
212 request.setParam("backup_" + entry.getKey(), entry.getValue());
214 return executeRequest(request);
217 private CreateWsResponse executeRequest(TestRequest request) {
218 return request.executeProtobuf(CreateWsResponse.class);
221 private ProfileImporter[] createImporters() {
222 class DefaultProfileImporter extends ProfileImporter {
223 private DefaultProfileImporter() {
224 super("xoo_lint", "Xoo Lint");
225 setSupportedLanguages(XOO_LANGUAGE);
229 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
230 RulesProfile rulesProfile = RulesProfile.create();
231 rulesProfile.activateRule(org.sonar.api.rules.Rule.create(RULE.getRepositoryKey(), RULE.getRuleKey()), RulePriority.BLOCKER);
236 class ProfileImporterGeneratingMessages extends ProfileImporter {
237 private ProfileImporterGeneratingMessages() {
238 super("with_messages", "With messages");
239 setSupportedLanguages(XOO_LANGUAGE);
243 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
244 RulesProfile rulesProfile = RulesProfile.create();
245 messages.addWarningText("a warning");
246 messages.addInfoText("an info");
251 class ProfileImporterGeneratingErrors extends ProfileImporter {
252 private ProfileImporterGeneratingErrors() {
253 super("with_errors", "With errors");
254 setSupportedLanguages(XOO_LANGUAGE);
258 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
259 RulesProfile rulesProfile = RulesProfile.create();
260 messages.addErrorText("error!");
265 return new ProfileImporter[] {
266 new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
270 private void logInAsQProfileAdministrator() {
273 .addPermission(ADMINISTER_QUALITY_PROFILES);