]> source.dussan.org Git - sonarqube.git/blob
7d1b67d69dcb92f3ce1a4e39cb148684b76654ae
[sonarqube.git] /
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
22 import com.google.common.collect.ImmutableMap;
23 import java.io.Reader;
24 import java.util.Collections;
25 import java.util.Map;
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;
67
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;
71
72 public class CreateActionTest {
73
74   private static final String XOO_LANGUAGE = "xoo";
75   private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
76     .setSeverity("MINOR")
77     .setLanguage(XOO_LANGUAGE)
78     .getDefinition();
79
80   @Rule
81   public ExpectedException expectedException = ExpectedException.none();
82   @Rule
83   public DbTester db = DbTester.create();
84   @Rule
85   public EsTester es = EsTester.create();
86   @Rule
87   public UserSessionRule userSession = UserSessionRule.standalone();
88
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);
99
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);
102
103   private WsActionTester ws = new WsActionTester(underTest);
104
105   private OrganizationDto organization;
106
107   @Before
108   public void setUp() {
109     organization = db.organizations().insert();
110   }
111
112   @Test
113   public void definition() {
114     WebService.Action definition = ws.getDef();
115
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");
123   }
124
125   @Test
126   public void create_profile() {
127     logInAsQProfileAdministrator();
128
129     CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
130
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");
135
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();
144   }
145
146   @Test
147   public void create_profile_from_backup_xml() {
148     logInAsQProfileAdministrator();
149     insertRule(RULE);
150
151     executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
152
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);
157   }
158
159   @Test
160   public void create_profile_with_messages() {
161     logInAsQProfileAdministrator();
162
163     CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
164
165     QualityProfile profile = response.getProfile();
166     assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
167     assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
168   }
169
170   @Test
171   public void create_profile_for_specific_organization() {
172     logInAsQProfileAdministrator();
173
174     String orgKey = organization.getKey();
175
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/>");
181
182     assertThat(executeRequest(request).getProfile().getOrganization())
183       .isEqualTo(orgKey);
184   }
185
186   @Test
187   public void create_two_qprofiles_in_different_organizations_with_same_name_and_language() {
188
189     // this name will be used twice
190     String profileName = "Profile123";
191
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());
200
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());
209   }
210
211   @Test
212   public void fail_if_unsufficient_privileges() {
213     OrganizationDto organizationX = db.organizations().insert();
214     OrganizationDto organizationY = db.organizations().insert();
215
216     logInAsQProfileAdministrator(organizationX);
217
218     expectedException.expect(ForbiddenException.class);
219     expectedException.expectMessage("Insufficient privileges");
220
221     executeRequest(ws.newRequest()
222       .setParam("organization", organizationY.getKey())
223       .setParam("name", "some Name")
224       .setParam("language", XOO_LANGUAGE));
225   }
226
227   @Test
228   public void fail_if_import_generate_error() {
229     logInAsQProfileAdministrator();
230
231     expectedException.expect(BadRequestException.class);
232     executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
233   }
234
235   @Test
236   public void test_json() {
237     logInAsQProfileAdministrator(db.getDefaultOrganization());
238
239     TestResponse response = ws.newRequest()
240       .setMethod("POST")
241       .setMediaType(MediaTypes.JSON)
242       .setParam("language", XOO_LANGUAGE)
243       .setParam("name", "Yeehaw!")
244       .execute();
245
246     JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionTest/test_json.json"));
247     assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
248   }
249
250   private void insertRule(RuleDefinitionDto ruleDto) {
251     dbClient.ruleDao().insert(dbSession, ruleDto);
252     dbSession.commit();
253     ruleIndexer.commitAndIndex(dbSession, ruleDto.getId());
254   }
255
256   private CreateWsResponse executeRequest(String name, String language) {
257     return executeRequest(name, language, Collections.emptyMap());
258   }
259
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());
267     }
268     return executeRequest(request);
269   }
270
271   private CreateWsResponse executeRequest(TestRequest request) {
272     return request.executeProtobuf(CreateWsResponse.class);
273   }
274
275   private ProfileImporter[] createImporters() {
276     class DefaultProfileImporter extends ProfileImporter {
277       private DefaultProfileImporter() {
278         super("xoo_lint", "Xoo Lint");
279         setSupportedLanguages(XOO_LANGUAGE);
280       }
281
282       @Override
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);
286         return rulesProfile;
287       }
288     }
289
290     class ProfileImporterGeneratingMessages extends ProfileImporter {
291       private ProfileImporterGeneratingMessages() {
292         super("with_messages", "With messages");
293         setSupportedLanguages(XOO_LANGUAGE);
294       }
295
296       @Override
297       public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
298         RulesProfile rulesProfile = RulesProfile.create();
299         messages.addWarningText("a warning");
300         messages.addInfoText("an info");
301         return rulesProfile;
302       }
303     }
304
305     class ProfileImporterGeneratingErrors extends ProfileImporter {
306       private ProfileImporterGeneratingErrors() {
307         super("with_errors", "With errors");
308         setSupportedLanguages(XOO_LANGUAGE);
309       }
310
311       @Override
312       public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
313         RulesProfile rulesProfile = RulesProfile.create();
314         messages.addErrorText("error!");
315         return rulesProfile;
316       }
317     }
318
319     return new ProfileImporter[] {
320       new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
321     };
322   }
323
324   private void logInAsQProfileAdministrator() {
325     logInAsQProfileAdministrator(organization);
326   }
327
328   private void logInAsQProfileAdministrator(OrganizationDto organization) {
329     userSession
330       .logIn()
331       .addPermission(ADMINISTER_QUALITY_PROFILES, organization);
332   }
333 }