]> source.dussan.org Git - sonarqube.git/blob
d71fe8bc7064a23b372c4a4ac37126947b1872a8
[sonarqube.git] /
1 /*
2  * SonarQube
3  * Copyright (C) 2009-2022 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.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;
62
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;
68
69 public class CreateActionTest {
70
71   private static final String XOO_LANGUAGE = "xoo";
72   private static final RuleDefinitionDto RULE = RuleTesting.newXooX1()
73     .setSeverity("MINOR")
74     .setLanguage(XOO_LANGUAGE)
75     .getDefinition();
76
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
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);
93
94   private CreateAction underTest = new CreateAction(dbClient, new QProfileFactoryImpl(dbClient, UuidFactoryFast.getInstance(), System2.INSTANCE, activeRuleIndexer),
95     qProfileExporters, newLanguages(XOO_LANGUAGE), userSession, activeRuleIndexer, profileImporters);
96
97   private WsActionTester ws = new WsActionTester(underTest);
98
99   @Test
100   public void definition() {
101     WebService.Action definition = ws.getDef();
102
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");
107   }
108
109   @Test
110   public void create_profile() {
111     logInAsQProfileAdministrator();
112
113     CreateWsResponse response = executeRequest("New Profile", XOO_LANGUAGE);
114
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");
119
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
130   @Test
131   public void create_profile_from_backup_xml() {
132     logInAsQProfileAdministrator();
133     insertRule(RULE);
134
135     executeRequest("New Profile", XOO_LANGUAGE, ImmutableMap.of("xoo_lint", "<xml/>"));
136
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);
141   }
142
143   @Test
144   public void create_profile_with_messages() {
145     logInAsQProfileAdministrator();
146
147     CreateWsResponse response = executeRequest("Profile with messages", XOO_LANGUAGE, ImmutableMap.of("with_messages", "<xml/>"));
148
149     QualityProfile profile = response.getProfile();
150     assertThat(profile.getInfos().getInfosList()).containsOnly("an info");
151     assertThat(profile.getWarnings().getWarningsList()).containsOnly("a warning");
152   }
153
154   @Test
155   public void fail_if_unsufficient_privileges() {
156     userSession
157       .logIn()
158       .addPermission(SCAN);
159
160     assertThatThrownBy(() -> {
161       executeRequest(ws.newRequest()
162         .setParam("name", "some Name")
163         .setParam("language", XOO_LANGUAGE));
164     })
165       .isInstanceOf(ForbiddenException.class)
166       .hasMessage("Insufficient privileges");
167   }
168
169   @Test
170   public void fail_if_import_generate_error() {
171     logInAsQProfileAdministrator();
172
173     assertThatThrownBy(() -> {
174       executeRequest("Profile with errors", XOO_LANGUAGE, ImmutableMap.of("with_errors", "<xml/>"));
175     })
176       .isInstanceOf(BadRequestException.class);
177   }
178
179   @Test
180   public void test_json() {
181     logInAsQProfileAdministrator();
182
183     TestResponse response = ws.newRequest()
184       .setMethod("POST")
185       .setMediaType(MediaTypes.JSON)
186       .setParam("language", XOO_LANGUAGE)
187       .setParam("name", "Yeehaw!")
188       .execute();
189
190     JsonAssert.assertJson(response.getInput()).isSimilarTo(getClass().getResource("CreateActionTest/test_json.json"));
191     assertThat(response.getMediaType()).isEqualTo(MediaTypes.JSON);
192   }
193
194   private void insertRule(RuleDefinitionDto ruleDto) {
195     dbClient.ruleDao().insert(dbSession, ruleDto);
196     dbSession.commit();
197     ruleIndexer.commitAndIndex(dbSession, ruleDto.getUuid());
198   }
199
200   private CreateWsResponse executeRequest(String name, String language) {
201     return executeRequest(name, language, Collections.emptyMap());
202   }
203
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());
210     }
211     return executeRequest(request);
212   }
213
214   private CreateWsResponse executeRequest(TestRequest request) {
215     return request.executeProtobuf(CreateWsResponse.class);
216   }
217
218   private ProfileImporter[] createImporters() {
219     class DefaultProfileImporter extends ProfileImporter {
220       private DefaultProfileImporter() {
221         super("xoo_lint", "Xoo Lint");
222         setSupportedLanguages(XOO_LANGUAGE);
223       }
224
225       @Override
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);
229         return rulesProfile;
230       }
231     }
232
233     class ProfileImporterGeneratingMessages extends ProfileImporter {
234       private ProfileImporterGeneratingMessages() {
235         super("with_messages", "With messages");
236         setSupportedLanguages(XOO_LANGUAGE);
237       }
238
239       @Override
240       public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
241         RulesProfile rulesProfile = RulesProfile.create();
242         messages.addWarningText("a warning");
243         messages.addInfoText("an info");
244         return rulesProfile;
245       }
246     }
247
248     class ProfileImporterGeneratingErrors extends ProfileImporter {
249       private ProfileImporterGeneratingErrors() {
250         super("with_errors", "With errors");
251         setSupportedLanguages(XOO_LANGUAGE);
252       }
253
254       @Override
255       public RulesProfile importProfile(Reader reader, ValidationMessages messages) {
256         RulesProfile rulesProfile = RulesProfile.create();
257         messages.addErrorText("error!");
258         return rulesProfile;
259       }
260     }
261
262     return new ProfileImporter[] {
263       new DefaultProfileImporter(), new ProfileImporterGeneratingMessages(), new ProfileImporterGeneratingErrors()
264     };
265   }
266
267   private void logInAsQProfileAdministrator() {
268     userSession
269       .logIn()
270       .addPermission(ADMINISTER_QUALITY_PROFILES);
271   }
272 }