]> source.dussan.org Git - sonarqube.git/blob
942de489af8ff3a0759c03f2599428aaee4a4329
[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;
21
22 import com.google.common.io.Resources;
23 import java.io.Reader;
24 import java.io.StringReader;
25 import java.io.StringWriter;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import org.junit.Rule;
31 import org.junit.Test;
32 import org.junit.rules.ExpectedException;
33 import org.sonar.api.impl.utils.AlwaysIncreasingSystem2;
34 import org.sonar.api.rule.RuleKey;
35 import org.sonar.api.rule.RuleStatus;
36 import org.sonar.api.rules.RuleType;
37 import org.sonar.api.utils.System2;
38 import org.sonar.db.DbSession;
39 import org.sonar.db.DbTester;
40 import org.sonar.db.organization.OrganizationDto;
41 import org.sonar.db.qualityprofile.ActiveRuleDto;
42 import org.sonar.db.qualityprofile.ActiveRuleParamDto;
43 import org.sonar.db.qualityprofile.QProfileDto;
44 import org.sonar.db.qualityprofile.QualityProfileTesting;
45 import org.sonar.db.rule.RuleDefinitionDto;
46 import org.sonar.db.rule.RuleMetadataDto;
47 import org.sonar.db.rule.RuleParamDto;
48 import org.sonar.server.rule.RuleCreator;
49
50 import static java.nio.charset.StandardCharsets.UTF_8;
51 import static org.assertj.core.api.Assertions.assertThat;
52 import static org.junit.Assert.fail;
53 import static org.junit.rules.ExpectedException.none;
54 import static org.mockito.ArgumentMatchers.any;
55 import static org.mockito.ArgumentMatchers.anyList;
56 import static org.mockito.Mockito.mock;
57 import static org.mockito.Mockito.when;
58
59 public class QProfileBackuperImplTest {
60
61   private static final String EMPTY_BACKUP = "<?xml version='1.0' encoding='UTF-8'?>" +
62     "<profile><name>foo</name>" +
63     "<language>js</language>" +
64     "<rules/>" +
65     "</profile>";
66
67   private System2 system2 = new AlwaysIncreasingSystem2();
68
69   @Rule
70   public ExpectedException expectedException = none();
71   @Rule
72   public DbTester db = DbTester.create(system2);
73
74   private DummyReset reset = new DummyReset();
75   private QProfileFactory profileFactory = new DummyProfileFactory();
76   private RuleCreator ruleCreator = mock(RuleCreator.class);
77
78   private QProfileBackuper underTest = new QProfileBackuperImpl(db.getDbClient(), reset, profileFactory, ruleCreator, new QProfileParser());
79
80   @Test
81   public void backup_generates_xml_file() {
82     RuleDefinitionDto rule = createRule();
83     QProfileDto profile = createProfile(rule);
84     ActiveRuleDto activeRule = activate(profile, rule);
85
86     StringWriter writer = new StringWriter();
87     underTest.backup(db.getSession(), profile, writer);
88
89     assertThat(writer.toString()).isEqualTo("<?xml version='1.0' encoding='UTF-8'?>" +
90       "<profile><name>" + profile.getName() + "</name>" +
91       "<language>" + profile.getLanguage() + "</language>" +
92       "<rules>" +
93       "<rule>" +
94       "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" +
95       "<key>" + rule.getRuleKey() + "</key>" +
96       "<type>" + RuleType.valueOf(rule.getType()).name() + "</type>" +
97       "<priority>" + activeRule.getSeverityString() + "</priority>" +
98       "<parameters/>" +
99       "</rule>" +
100       "</rules>" +
101       "</profile>");
102   }
103
104   @Test
105   public void backup_rules_having_parameters() {
106     RuleDefinitionDto rule = createRule();
107     RuleParamDto param = db.rules().insertRuleParam(rule);
108     QProfileDto profile = createProfile(rule);
109     ActiveRuleDto activeRule = activate(profile, rule, param);
110
111     StringWriter writer = new StringWriter();
112     underTest.backup(db.getSession(), profile, writer);
113
114     assertThat(writer.toString()).contains(
115       "<rule>" +
116         "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" +
117         "<key>" + rule.getRuleKey() + "</key>" +
118         "<type>" + RuleType.valueOf(rule.getType()).name() + "</type>" +
119         "<priority>" + activeRule.getSeverityString() + "</priority>" +
120         "<parameters><parameter>" +
121         "<key>" + param.getName() + "</key>" +
122         "<value>20</value>" +
123         "</parameter></parameters>" +
124         "</rule>");
125   }
126
127   @Test
128   public void backup_empty_profile() {
129     RuleDefinitionDto rule = createRule();
130     QProfileDto profile = createProfile(rule);
131
132     StringWriter writer = new StringWriter();
133     underTest.backup(db.getSession(), profile, writer);
134
135     assertThat(writer.toString()).isEqualTo("<?xml version='1.0' encoding='UTF-8'?>" +
136       "<profile><name>" + profile.getName() + "</name>" +
137       "<language>" + profile.getLanguage() + "</language>" +
138       "<rules/>" +
139       "</profile>");
140   }
141
142   @Test
143   public void backup_custom_rules_with_params() {
144     RuleDefinitionDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto
145       .setIsTemplate(true));
146     RuleDefinitionDto rule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto
147       .setDescription("custom rule description")
148       .setName("custom rule name")
149       .setStatus(RuleStatus.READY)
150       .setTemplateId(templateRule.getId()));
151     RuleParamDto param = db.rules().insertRuleParam(rule);
152     QProfileDto profile = createProfile(rule);
153     ActiveRuleDto activeRule = activate(profile, rule, param);
154
155     StringWriter writer = new StringWriter();
156     underTest.backup(db.getSession(), profile, writer);
157
158     assertThat(writer.toString()).isEqualTo("<?xml version='1.0' encoding='UTF-8'?>" +
159       "<profile>" +
160       "<name>" + profile.getName() + "</name>" +
161       "<language>" + profile.getLanguage() + "</language>" +
162       "<rules><rule>" +
163       "<repositoryKey>" + rule.getRepositoryKey() + "</repositoryKey>" +
164       "<key>" + rule.getKey().rule() + "</key>" +
165       "<type>" + RuleType.valueOf(rule.getType()) + "</type>" +
166       "<priority>" + activeRule.getSeverityString() + "</priority>" +
167       "<name>" + rule.getName() + "</name>" +
168       "<templateKey>" + templateRule.getKey().rule() + "</templateKey>" +
169       "<description>" + rule.getDescription() + "</description>" +
170       "<parameters><parameter>" +
171       "<key>" + param.getName() + "</key>" +
172       "<value>20</value>" +
173       "</parameter></parameters>" +
174       "</rule></rules></profile>");
175   }
176
177   @Test
178   public void restore_backup_on_the_profile_specified_in_backup() {
179     OrganizationDto organization = db.organizations().insert();
180     Reader backup = new StringReader(EMPTY_BACKUP);
181
182     QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, organization, null);
183
184     assertThat(summary.getProfile().getName()).isEqualTo("foo");
185     assertThat(summary.getProfile().getLanguage()).isEqualTo("js");
186
187     assertThat(reset.calledProfile.getKee()).isEqualTo(summary.getProfile().getKee());
188     assertThat(reset.calledActivations).isEmpty();
189   }
190
191   @Test
192   public void restore_backup_on_profile_having_different_name() {
193     OrganizationDto organization = db.organizations().insert();
194     Reader backup = new StringReader(EMPTY_BACKUP);
195
196     QProfileRestoreSummary summary = underTest.restore(db.getSession(), backup, organization, "bar");
197
198     assertThat(summary.getProfile().getName()).isEqualTo("bar");
199     assertThat(summary.getProfile().getLanguage()).isEqualTo("js");
200
201     assertThat(reset.calledProfile.getKee()).isEqualTo(summary.getProfile().getKee());
202     assertThat(reset.calledActivations).isEmpty();
203   }
204
205   @Test
206   public void restore_resets_the_activated_rules() {
207     Integer ruleId = db.rules().insert(RuleKey.of("sonarjs", "s001")).getId();
208     OrganizationDto organization = db.organizations().insert();
209     Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
210       "<profile><name>foo</name>" +
211       "<language>js</language>" +
212       "<rules>" +
213       "<rule>" +
214       "<repositoryKey>sonarjs</repositoryKey>" +
215       "<key>s001</key>" +
216       "<priority>BLOCKER</priority>" +
217       "<parameters>" +
218       "<parameter><key>bar</key><value>baz</value></parameter>" +
219       "</parameters>" +
220       "</rule>" +
221       "</rules>" +
222       "</profile>");
223
224     underTest.restore(db.getSession(), backup, organization, null);
225
226     assertThat(reset.calledActivations).hasSize(1);
227     RuleActivation activation = reset.calledActivations.get(0);
228     assertThat(activation.getSeverity()).isEqualTo("BLOCKER");
229     assertThat(activation.getRuleId()).isEqualTo(ruleId);
230     assertThat(activation.getParameter("bar")).isEqualTo("baz");
231   }
232
233   @Test
234   public void restore_custom_rule() {
235     when(ruleCreator.create(any(), anyList())).then(invocation ->
236       Collections.singletonList(db.rules().insert(RuleKey.of("sonarjs", "s001")).getKey()));
237
238     OrganizationDto organization = db.organizations().insert();
239     Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
240       "<profile>" +
241       "<name>custom rule</name>" +
242       "<language>js</language>" +
243       "<rules><rule>" +
244       "<repositoryKey>sonarjs</repositoryKey>" +
245       "<key>s001</key>" +
246       "<type>CODE_SMELL</type>" +
247       "<priority>CRITICAL</priority>" +
248       "<name>custom rule name</name>" +
249       "<templateKey>rule_mc8</templateKey>" +
250       "<description>custom rule description</description>" +
251       "<parameters><parameter>" +
252       "<key>bar</key>" +
253       "<value>baz</value>" +
254       "</parameter>" +
255       "</parameters>" +
256       "</rule></rules></profile>");
257
258     underTest.restore(db.getSession(), backup, organization, null);
259
260     assertThat(reset.calledActivations).hasSize(1);
261     RuleActivation activation = reset.calledActivations.get(0);
262     assertThat(activation.getSeverity()).isEqualTo("CRITICAL");
263     assertThat(activation.getParameter("bar")).isEqualTo("baz");
264   }
265
266   @Test
267   public void restore_skips_rule_without_template_key_and_db_definition() {
268     Integer ruleId = db.rules().insert(RuleKey.of("sonarjs", "s001")).getId();
269     OrganizationDto organization = db.organizations().insert();
270     Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
271       "<profile><name>foo</name>" +
272       "<language>js</language>" +
273       "<rules>" +
274       "<rule>" +
275       "<repositoryKey>sonarjs</repositoryKey>" +
276       "<key>s001</key>" +
277       "<priority>BLOCKER</priority>" +
278       "<parameters>" +
279       "<parameter><key>bar</key><value>baz</value></parameter>" +
280       "</parameters>" +
281       "</rule>" +
282       "<rule>" +
283       "<repositoryKey>sonarjs</repositoryKey>" +
284       "<key>s002</key>" +
285       "<priority>MAJOR</priority>" +
286       "</rule>" +
287       "</rules>" +
288       "</profile>");
289
290     underTest.restore(db.getSession(), backup, organization, null);
291
292     assertThat(reset.calledActivations).hasSize(1);
293     RuleActivation activation = reset.calledActivations.get(0);
294     assertThat(activation.getRuleId()).isEqualTo(ruleId);
295     assertThat(activation.getSeverity()).isEqualTo("BLOCKER");
296     assertThat(activation.getParameter("bar")).isEqualTo("baz");
297   }
298
299   @Test
300   public void fail_to_restore_if_bad_xml_format() {
301     OrganizationDto organization = db.organizations().insert();
302     try {
303       underTest.restore(db.getSession(), new StringReader("<rules><rule></rules>"), organization, null);
304       fail();
305     } catch (IllegalArgumentException e) {
306       assertThat(e).hasMessage("Backup XML is not valid. Root element must be <profile>.");
307       assertThat(reset.calledProfile).isNull();
308     }
309   }
310
311   @Test
312   public void fail_to_restore_if_not_xml_backup() {
313     OrganizationDto organization = db.organizations().insert();
314     try {
315       underTest.restore(db.getSession(), new StringReader("foo"), organization, null);
316       fail();
317     } catch (IllegalArgumentException e) {
318       assertThat(reset.calledProfile).isNull();
319     }
320   }
321
322   @Test
323   public void fail_to_restore_if_xml_is_not_well_formed() {
324     expectedException.expect(IllegalArgumentException.class);
325     expectedException.expectMessage("Fail to restore Quality profile backup, XML document is not well formed");
326     OrganizationDto organization = db.organizations().insert();
327     String notWellFormedXml = "<?xml version='1.0' encoding='UTF-8'?><profile><name>\"profil\"</name><language>\"language\"</language><rules/></profile";
328
329     underTest.restore(db.getSession(), new StringReader(notWellFormedXml), organization, null);
330   }
331
332   @Test
333   public void fail_to_restore_if_duplicate_rule() throws Exception {
334     OrganizationDto organization = db.organizations().insert();
335     try {
336       String xml = Resources.toString(getClass().getResource("QProfileBackuperTest/duplicates-xml-backup.xml"), UTF_8);
337       underTest.restore(db.getSession(), new StringReader(xml), organization, null);
338       fail();
339     } catch (IllegalArgumentException e) {
340       assertThat(e).hasMessage("The quality profile cannot be restored as it contains duplicates for the following rules: xoo:x1, xoo:x2");
341       assertThat(reset.calledProfile).isNull();
342     }
343   }
344
345   @Test
346   public void fail_to_restore_external_rule() {
347     db.rules().insert(RuleKey.of("sonarjs", "s001"), r -> r.setIsExternal(true)).getId();
348     OrganizationDto organization = db.organizations().insert();
349     Reader backup = new StringReader("<?xml version='1.0' encoding='UTF-8'?>" +
350       "<profile><name>foo</name>" +
351       "<language>js</language>" +
352       "<rules>" +
353       "<rule>" +
354       "<repositoryKey>sonarjs</repositoryKey>" +
355       "<key>s001</key>" +
356       "<priority>BLOCKER</priority>" +
357       "<parameters>" +
358       "<parameter><key>bar</key><value>baz</value></parameter>" +
359       "</parameters>" +
360       "</rule>" +
361       "</rules>" +
362       "</profile>");
363
364     expectedException.expect(IllegalArgumentException.class);
365     expectedException.expectMessage("The quality profile cannot be restored as it contains rules from external rule engines: sonarjs:s001");
366     underTest.restore(db.getSession(), backup, organization, null);
367   }
368
369   private RuleDefinitionDto createRule() {
370     return db.rules().insert();
371   }
372
373   private RuleMetadataDto createRuleMetadata(RuleMetadataDto metadataDto) {
374     return db.rules().insertOrUpdateMetadata(metadataDto);
375   }
376
377   private QProfileDto createProfile(RuleDefinitionDto rule) {
378     return db.qualityProfiles().insert(db.getDefaultOrganization(), p -> p.setLanguage(rule.getLanguage()));
379   }
380
381   private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule) {
382     return db.qualityProfiles().activateRule(profile, rule);
383   }
384
385   private ActiveRuleDto activate(QProfileDto profile, RuleDefinitionDto rule, RuleParamDto param) {
386     ActiveRuleDto activeRule = db.qualityProfiles().activateRule(profile, rule);
387     ActiveRuleParamDto dto = ActiveRuleParamDto.createFor(param)
388       .setValue("20")
389       .setActiveRuleId(activeRule.getId());
390     db.getDbClient().activeRuleDao().insertParam(db.getSession(), activeRule, dto);
391     return activeRule;
392   }
393
394   private static class DummyReset implements QProfileReset {
395     private QProfileDto calledProfile;
396     private List<RuleActivation> calledActivations;
397
398     @Override
399     public BulkChangeResult reset(DbSession dbSession, QProfileDto profile, Collection<RuleActivation> activations) {
400       this.calledProfile = profile;
401       this.calledActivations = new ArrayList<>(activations);
402       return new BulkChangeResult();
403     }
404   }
405
406   private static class DummyProfileFactory implements QProfileFactory {
407     @Override
408     public QProfileDto getOrCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName key) {
409       return QualityProfileTesting.newQualityProfileDto()
410         .setOrganizationUuid(organization.getUuid())
411         .setLanguage(key.getLanguage())
412         .setName(key.getName());
413     }
414
415     @Override
416     public QProfileDto checkAndCreateCustom(DbSession dbSession, OrganizationDto organization, QProfileName name) {
417       throw new UnsupportedOperationException();
418     }
419
420     @Override
421     public void delete(DbSession dbSession, Collection<QProfileDto> profiles) {
422       throw new UnsupportedOperationException();
423     }
424   }
425 }