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