3 * Copyright (C) 2009-2019 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.Before;
27 import org.junit.Rule;
28 import org.junit.Test;
29 import org.junit.rules.ExpectedException;
30 import org.sonar.api.profiles.ProfileImporter;
31 import org.sonar.api.profiles.RulesProfile;
32 import org.sonar.api.rules.RulePriority;
33 import org.sonar.api.server.ws.WebService;
34 import org.sonar.api.server.ws.WebService.Param;
35 import org.sonar.api.utils.System2;
36 import org.sonar.api.utils.ValidationMessages;
37 import org.sonar.core.util.UuidFactoryFast;
38 import org.sonar.db.DbClient;
39 import org.sonar.db.DbSession;
40 import org.sonar.db.DbTester;
41 import org.sonar.db.organization.OrganizationDto;
42 import org.sonar.db.qualityprofile.QProfileDto;
43 import org.sonar.db.rule.RuleDefinitionDto;
44 import org.sonar.db.rule.RuleTesting;
45 import org.sonar.server.es.EsTester;
46 import org.sonar.server.exceptions.BadRequestException;
47 import org.sonar.server.exceptions.ForbiddenException;
48 import org.sonar.server.organization.DefaultOrganizationProvider;
49 import org.sonar.server.organization.TestDefaultOrganizationProvider;
50 import org.sonar.server.qualityprofile.QProfileExporters;
51 import org.sonar.server.qualityprofile.QProfileFactoryImpl;
52 import org.sonar.server.qualityprofile.QProfileRules;
53 import org.sonar.server.qualityprofile.QProfileRulesImpl;
54 import org.sonar.server.qualityprofile.RuleActivator;
55 import org.sonar.server.qualityprofile.index.ActiveRuleIndexer;
56 import org.sonar.server.rule.index.RuleIndex;
57 import org.sonar.server.rule.index.RuleIndexer;
58 import org.sonar.server.rule.index.RuleQuery;
59 import org.sonar.server.tester.UserSessionRule;
60 import org.sonar.server.ws.TestRequest;
61 import org.sonar.server.ws.TestResponse;
62 import org.sonar.server.ws.WsActionTester;
63 import org.sonar.test.JsonAssert;
64 import org.sonarqube.ws.MediaTypes;
65 import org.sonarqube.ws.Qualityprofiles.CreateWsResponse;
66 import org.sonarqube.ws.Qualityprofiles.CreateWsResponse.QualityProfile;
68 import static org.assertj.core.api.Assertions.assertThat;
69 import static org.sonar.db.permission.OrganizationPermission.ADMINISTER_QUALITY_PROFILES;
70 import static org.sonar.server.language.LanguageTesting.newLanguages;
72 public class CreateActionTest {
74 private static final String XOO_LANGUAGE = "xoo";
75 private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
77 .setLanguage(XOO_LANGUAGE)
81 public ExpectedException expectedException = ExpectedException.none();
83 public DbTester db = DbTester.create();
85 public EsTester es = EsTester.create();
87 public UserSessionRule userSession = UserSessionRule.standalone();
89 private DbClient dbClient = db.getDbClient();
90 private DbSession dbSession = db.getSession();
91 private RuleIndex ruleIndex = new RuleIndex(es.client(), System2.INSTANCE);
92 private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbClient);
93 private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(dbClient, es.client());
94 private ProfileImporter[] profileImporters = createImporters();
95 private RuleActivator ruleActivator = new RuleActivator(System2.INSTANCE, dbClient, null, userSession);
96 private QProfileRules qProfileRules = new QProfileRulesImpl(dbClient, ruleActivator, ruleIndex, activeRuleIndexer);
97 private QProfileExporters qProfileExporters = new QProfileExporters(dbClient, null, qProfileRules, profileImporters);
98 private DefaultOrganizationProvider defaultOrganizationProvider = TestDefaultOrganizationProvider.from(db);
100 private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
101 qProfileExporters, newLanguages(XOO_LANGUAGE), new QProfileWsSupport(dbClient, userSession, defaultOrganizationProvider), userSession, activeRuleIndexer, profileImporters);
103 private WsActionTester ws = new WsActionTester(underTest);
105 private OrganizationDto organization;
108 public void setUp() {
109 organization = db.organizations().insert();
113 public void definition() {
114 WebService.Action definition = ws.getDef();
116 assertThat(definition.responseExampleAsString()).isNotEmpty();
117 assertThat(definition.isPost()).isTrue();
118 assertThat(definition.params()).extracting(Param::key)
119 .containsExactlyInAnyOrder("language", "organization", "name", "backup_with_messages", "backup_with_errors", "backup_xoo_lint");
120 Param name = definition.param("name");
121 assertThat(name.deprecatedKey()).isEqualTo("profileName");
122 assertThat(name.deprecatedKeySince()).isEqualTo("6.6");
126 public void create_profile() {
127 logInAsQProfileAdministrator();
129 CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
131 QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "New Profile", XOO_LANGUAGE);
132 assertThat(dto.getKee()).isNotNull();
133 assertThat(dto.getLanguage()).isEqualTo(XOO_LANGUAGE);
134 assertThat(dto.getName()).isEqualTo("New Profile");
136 QualityProfile profile = response.getProfile();
137 assertThat(profile.getKey()).isEqualTo(dto.getKee());
138 assertThat(profile.getName()).isEqualTo("New Profile");
139 assertThat(profile.getLanguage()).isEqualTo(XOO_LANGUAGE);
140 assertThat(profile.getIsInherited()).isFalse();
141 assertThat(profile.getIsDefault()).isFalse();
142 assertThat(profile.hasInfos()).isFalse();
143 assertThat(profile.hasWarnings()).isFalse();
147 public void create_profile_from_backup_xml() {
148 logInAsQProfileAdministrator();
151 executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
153 QProfileDto dto = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "New Profile", XOO_LANGUAGE);
154 assertThat(dto.getKee()).isNotNull();
155 assertThat(dbClient.activeRuleDao().selectByProfileUuid(dbSession, dto.getKee())).hasSize(1);
156 assertThat(ruleIndex.searchAll(new RuleQuery().setQProfile(dto).setActivation(true))).toIterable().hasSize(1);
160 public void create_profile_with_messages() {
161 logInAsQProfileAdministrator();
163 CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
165 QualityProfile profile = response.getProfile();
166 assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
167 assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
171 public void create_profile_for_specific_organization() {
172 logInAsQProfileAdministrator();
174 String orgKey = organization.getKey();
176 TestRequest request = ws.newRequest()
177 .setParam("organization", orgKey)
178 .setParam("name", "Profile with messages")
179 .setParam("language", XOO_LANGUAGE)
180 .setParam("backup_with_messages", "<xml/>");
182 assertThat(executeRequest(request).getProfile().getOrganization())
187 public void create_two_qprofiles_in_different_organizations_with_same_name_and_language() {
189 // this name will be used twice
190 String profileName = "Profile123";
192 OrganizationDto organization1 = db.organizations().insert();
193 logInAsQProfileAdministrator(organization1);
194 TestRequest request1 = ws.newRequest()
195 .setParam("organization", organization1.getKey())
196 .setParam("name", profileName)
197 .setParam("language", XOO_LANGUAGE);
198 assertThat(executeRequest(request1).getProfile().getOrganization())
199 .isEqualTo(organization1.getKey());
201 OrganizationDto organization2 = db.organizations().insert();
202 logInAsQProfileAdministrator(organization2);
203 TestRequest request2 = ws.newRequest()
204 .setParam("organization", organization2.getKey())
205 .setParam("name", profileName)
206 .setParam("language", XOO_LANGUAGE);
207 assertThat(executeRequest(request2).getProfile().getOrganization())
208 .isEqualTo(organization2.getKey());
212 public void fail_if_unsufficient_privileges() {
213 OrganizationDto organizationX = db.organizations().insert();
214 OrganizationDto organizationY = db.organizations().insert();
216 logInAsQProfileAdministrator(organizationX);
218 expectedException.expect(ForbiddenException.class);
219 expectedException.expectMessage("Insufficient privileges");
221 executeRequest(ws.newRequest()
222 .setParam("organization", organizationY.getKey())
223 .setParam("name", "some Name")
224 .setParam("language", XOO_LANGUAGE));
228 public void fail_if_import_generate_error() {
229 logInAsQProfileAdministrator();
231 expectedException.expect(BadRequestException.class);
232 executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
236 public void test_json() {
237 logInAsQProfileAdministrator(db.getDefaultOrganization());
239 TestResponse response = ws.newRequest()
241 .setMediaType(MediaTypes.JSON)
242 .setParam("language", XOO_LANGUAGE)
243 .setParam("name", "Yeehaw!")
246 JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionTest/test_json.json"));
247 assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
250 private void insertRule(RuleDefinitionDto ruleDto) {
251 dbClient.ruleDao().insert(dbSession, ruleDto);
253 ruleIndexer.commitAndIndex(dbSession, ruleDto.getId());
256 private CreateWsResponse executeRequest(String name, String language) {
257 return executeRequest(name, language, Collections.emptyMap());
260 private CreateWsResponse executeRequest(String name, String language, Map<String, String> xmls) {
261 TestRequest request = ws.newRequest()
262 .setParam("organization", organization.getKey())
263 .setParam("name", name)
264 .setParam("language", language);
265 for (Map.Entry<String, String> entry : xmls.entrySet()) {
266 request.setParam("backup_" + entry.getKey(), entry.getValue());
268 return executeRequest(request);
271 private CreateWsResponse executeRequest(TestRequest request) {
272 return request.executeProtobuf(CreateWsResponse.class);
275 private ProfileImporter[] createImporters() {
276 class DefaultProfileImporter extends ProfileImporter {
277 private DefaultProfileImporter() {
278 super("xoo_lint", "Xoo Lint");
279 setSupportedLanguages(XOO_LANGUAGE);
283 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
284 RulesProfile rulesProfile = RulesProfile.create();
285 rulesProfile.activateRule(org.sonar.api.rules.Rule.create(RULE.getRepositoryKey(), RULE.getRuleKey()), RulePriority.BLOCKER);
290 class ProfileImporterGeneratingMessages extends ProfileImporter {
291 private ProfileImporterGeneratingMessages() {
292 super("with_messages", "With messages");
293 setSupportedLanguages(XOO_LANGUAGE);
297 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
298 RulesProfile rulesProfile = RulesProfile.create();
299 messages.addWarningText("a warning");
300 messages.addInfoText("an info");
305 class ProfileImporterGeneratingErrors extends ProfileImporter {
306 private ProfileImporterGeneratingErrors() {
307 super("with_errors", "With errors");
308 setSupportedLanguages(XOO_LANGUAGE);
312 public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
313 RulesProfile rulesProfile = RulesProfile.create();
314 messages.addErrorText("error!");
319 return new ProfileImporter[] {
320 new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
324 private void logInAsQProfileAdministrator() {
325 logInAsQProfileAdministrator(organization);
328 private void logInAsQProfileAdministrator(OrganizationDto organization) {
331 .addPermission(ADMINISTER_QUALITY_PROFILES, organization);