From: Daniel Schwarz Date: Mon, 7 Aug 2017 08:45:46 +0000 (+0200) Subject: SONAR-8798 remove medium tests registration of QualityProfiles and Rules X-Git-Tag: 6.6-RC1~682 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=98267a08771edd1f1aadbf1e46a70177f603d77f;p=sonarqube.git SONAR-8798 remove medium tests registration of QualityProfiles and Rules Those tests should be added back as either unit tests or integration tests in the near future. --- diff --git a/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java b/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java index 3d9ed37b414..85eb5780b79 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java +++ b/server/sonar-server/src/test/java/org/sonar/server/batch/ProjectDataLoaderTest.java @@ -49,7 +49,6 @@ import org.sonar.server.exceptions.BadRequestException; import org.sonar.server.exceptions.ForbiddenException; import org.sonar.server.exceptions.NotFoundException; import org.sonar.server.qualityprofile.QProfileName; -import org.sonar.server.tester.ServerTester; import org.sonar.server.tester.UserSessionRule; import static java.lang.String.format; @@ -720,7 +719,7 @@ public class ProjectDataLoaderTest { private void addDefaultProfile() { OrganizationDto organizationDto = OrganizationTesting.newOrganizationDto(); dbClient.organizationDao().insert(dbSession, organizationDto, false); - QProfileDto profileDto = newQProfileDto(organizationDto, QProfileName.createFor(ServerTester.Xoo.KEY, "SonarQube way"), "abcd").setRulesUpdatedAt( + QProfileDto profileDto = newQProfileDto(organizationDto, QProfileName.createFor("xoo", "SonarQube way"), "abcd").setRulesUpdatedAt( formatDateTime(new Date())); dbClient.qualityProfileDao().insert(dbSession, profileDto); dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(profileDto)); diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTesting.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTesting.java index 7f2a905a72b..98d84cdf3e7 100644 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTesting.java +++ b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/QProfileTesting.java @@ -19,12 +19,8 @@ */ package org.sonar.server.qualityprofile; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; import org.sonar.db.organization.OrganizationDto; import org.sonar.db.qualityprofile.QProfileDto; -import org.sonar.server.organization.DefaultOrganizationProvider; -import org.sonar.server.tester.ServerTester; /** * Utility class for tests involving quality profiles @@ -96,13 +92,4 @@ public class QProfileTesting { public static QProfileDto newXooP3(OrganizationDto organization) { return newQProfileDto(organization, XOO_P3_NAME, XOO_P3_KEY); } - - /** - * Used in medium tests. - */ - public static OrganizationDto getDefaultOrganization(ServerTester tester, DbClient db, DbSession session) { - String organizationKey = tester.get(DefaultOrganizationProvider.class).get().getKey(); - return db.organizationDao().selectByKey(session, organizationKey) - .orElseThrow(() -> new IllegalStateException("Cannot load default organization (key='" + organizationKey + "')")); - } } diff --git a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesMediumTest.java deleted file mode 100644 index e068b843d82..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/server/qualityprofile/RegisterQualityProfilesMediumTest.java +++ /dev/null @@ -1,291 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.qualityprofile; - -import java.util.Map; -import org.junit.After; -import org.junit.Test; -import org.sonar.api.profiles.ProfileDefinition; -import org.sonar.api.profiles.RulesProfile; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.ActiveRule; -import org.sonar.api.rules.RuleParam; -import org.sonar.api.rules.RulePriority; -import org.sonar.api.server.rule.RuleParamType; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.utils.ValidationMessages; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.qualityprofile.ActiveRuleDao; -import org.sonar.db.qualityprofile.ActiveRuleDto; -import org.sonar.db.qualityprofile.ActiveRuleKey; -import org.sonar.db.qualityprofile.ActiveRuleParamDto; -import org.sonar.db.qualityprofile.DefaultQProfileDto; -import org.sonar.db.qualityprofile.QProfileDto; -import org.sonar.db.qualityprofile.QualityProfileDao; -import org.sonar.server.es.SearchOptions; -import org.sonar.server.platform.Platform; -import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleQuery; -import org.sonar.server.tester.ServerTester; - -import static com.google.common.collect.Lists.newArrayList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.server.qualityprofile.QProfileTesting.getDefaultOrganization; - -// TODO replace this MediumTest by DbTester and EsTester -public class RegisterQualityProfilesMediumTest { - - private ServerTester tester; - private DbSession dbSession; - - @After - public void tearDown() { - if (dbSession != null) { - dbSession.close(); - } - if (tester != null) { - tester.stop(); - } - } - - @Test - public void register_existing_profile_definitions() { - tester = new ServerTester().withEsIndexes().withStartupTasks().addXoo().addComponents(XooRulesDefinition.class, XooProfileDefinition.class); - tester.start(); - DbClient dbClient = dbClient(); - dbSession = dbClient.openSession(false); - OrganizationDto organization = getDefaultOrganization(tester, dbClient, dbSession); - - // Check Profile in DB - QualityProfileDao qualityProfileDao = dbClient.qualityProfileDao(); - assertThat(qualityProfileDao.selectOrderedByOrganizationUuid(dbSession, organization)).hasSize(1); - QProfileDto profile = qualityProfileDao.selectByNameAndLanguage(dbSession, organization, "Basic", "xoo"); - assertThat(profile).isNotNull(); - assertThat(profile.isBuiltIn()).isTrue(); - - // Check ActiveRules in DB - ActiveRuleDao activeRuleDao = dbClient.activeRuleDao(); - assertThat(activeRuleDao.selectByProfileUuid(dbSession, profile.getKee())).hasSize(2); - - RuleKey ruleKey = RuleKey.of("xoo", "x1"); - ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile, ruleKey); - assertThat(activeRuleDao.selectByKey(dbSession, activeRuleKey)).isPresent(); - - // Check in ES - assertThat(tester.get(RuleIndex.class).search(new RuleQuery().setActivation(true).setQProfile(profile), new SearchOptions()).getIds()).containsOnly(ruleKey, RuleKey.of("xoo", "x2")); - - tester.get(Platform.class).restart(); - - assertThat(profile.isBuiltIn()).isTrue(); - assertThat(activeRuleDao.selectByKey(dbSession, activeRuleKey)).isPresent(); - - // Check ActiveRules - ActiveRuleDto activeRule = activeRuleDao.selectByKey(dbSession, activeRuleKey).get(); - assertThat(activeRule.getKey().getRuleProfileUuid()).isEqualTo(profile.getRulesProfileUuid()); - assertThat(activeRule.getKey().getRuleKey()).isEqualTo(ruleKey); - assertThat(activeRule.getSeverityString()).isEqualTo(Severity.CRITICAL); - - // Check in ES - assertThat(tester.get(RuleIndex.class).search(new RuleQuery().setActivation(true).setQProfile(profile), new SearchOptions()).getIds()).containsOnly(ruleKey, RuleKey.of("xoo", "x2")); - - // TODO - // Check ActiveRuleParameters in DB - Map params = ActiveRuleParamDto.groupByKey(activeRuleDao.selectParamsByActiveRuleId(dbSession, activeRule.getId())); - assertThat(params).hasSize(2); - // set by profile - assertThat(params.get("acceptWhitespace").getValue()).isEqualTo("true"); - // default value - assertThat(params.get("max").getValue()).isEqualTo("10"); - } - - @Test - public void register_profile_definitions() { - tester = new ServerTester().withEsIndexes().withStartupTasks().addXoo().addComponents(XooRulesDefinition.class, XooProfileDefinition.class); - tester.start(); - DbClient dbClient = dbClient(); - dbSession = dbClient.openSession(false); - OrganizationDto organization = getDefaultOrganization(tester, dbClient, dbSession); - - // Check Profile in DB - QualityProfileDao qualityProfileDao = dbClient.qualityProfileDao(); - assertThat(qualityProfileDao.selectOrderedByOrganizationUuid(dbSession, organization)).hasSize(1); - QProfileDto profile = qualityProfileDao.selectByNameAndLanguage(dbSession, organization, "Basic", "xoo"); - assertThat(profile).isNotNull(); - assertThat(profile.isBuiltIn()).isTrue(); - - // Check Default Profile - verifyDefaultProfile(organization, "xoo", "Basic"); - - // Check ActiveRules in DB - ActiveRuleDao activeRuleDao = dbClient.activeRuleDao(); - assertThat(activeRuleDao.selectByProfileUuid(dbSession, profile.getKee())).hasSize(2); - RuleKey ruleKey = RuleKey.of("xoo", "x1"); - - ActiveRuleDto activeRule = activeRuleDao.selectByKey(dbSession, ActiveRuleKey.of(profile, ruleKey)).get(); - assertThat(activeRule.getKey().getRuleProfileUuid()).isEqualTo(profile.getRulesProfileUuid()); - assertThat(activeRule.getKey().getRuleKey()).isEqualTo(ruleKey); - assertThat(activeRule.getSeverityString()).isEqualTo(Severity.CRITICAL); - - // Check ActiveRuleParameters in DB - Map params = ActiveRuleParamDto.groupByKey(activeRuleDao.selectParamsByActiveRuleId(dbSession, activeRule.getId())); - assertThat(params).hasSize(2); - // set by profile - assertThat(params.get("acceptWhitespace").getValue()).isEqualTo("true"); - // default value - assertThat(params.get("max").getValue()).isEqualTo("10"); - } - - @Test - public void do_not_register_profile_if_missing_language() { - // xoo language is not installed - tester = new ServerTester().withEsIndexes().addComponents(XooRulesDefinition.class, XooProfileDefinition.class); - tester.start(); - DbClient dbClient = dbClient(); - dbSession = dbClient().openSession(false); - OrganizationDto organization = getDefaultOrganization(tester, dbClient, dbSession); - - // Check Profile in DB - QualityProfileDao qualityProfileDao = dbClient().qualityProfileDao(); - assertThat(qualityProfileDao.selectOrderedByOrganizationUuid(dbSession, organization)).hasSize(0); - } - - @Test - public void fail_if_two_definitions_are_marked_as_default_on_the_same_language() { - tester = new ServerTester().withEsIndexes().addXoo().addComponents(new SimpleProfileDefinition("one", true), new SimpleProfileDefinition("two", true)); - - try { - tester.start(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Several Quality profiles are flagged as default for the language xoo: [one, two]"); - } - } - - @Test - public void mark_profile_as_default() { - tester = new ServerTester().withEsIndexes().withStartupTasks().addXoo().addComponents(new SimpleProfileDefinition("one", false), new SimpleProfileDefinition("two", true)); - tester.start(); - DbClient dbClient = dbClient(); - dbSession = dbClient.openSession(false); - OrganizationDto organization = getDefaultOrganization(tester, dbClient, dbSession); - - verifyDefaultProfile(organization, "xoo", "two"); - } - - @Test - public void use_sonar_way_as_default_profile_if_none_are_marked_as_default() { - tester = new ServerTester().withEsIndexes().withStartupTasks().addXoo().addComponents(new SimpleProfileDefinition("Sonar way", false), - new SimpleProfileDefinition("Other way", false)); - tester.start(); - DbClient dbClient = dbClient(); - dbSession = dbClient.openSession(false); - OrganizationDto organization = getDefaultOrganization(tester, dbClient, dbSession); - - verifyDefaultProfile(organization, "xoo", "Sonar way"); - } - - @Test - public void do_not_reset_default_profile_if_still_valid() { - tester = new ServerTester().withEsIndexes().withStartupTasks().addXoo().addComponents(new SimpleProfileDefinition("one", true), new SimpleProfileDefinition("two", false)); - tester.start(); - DbClient dbClient = dbClient(); - dbSession = dbClient().openSession(false); - OrganizationDto organization = getDefaultOrganization(tester, dbClient, dbSession); - - QProfileDto profile = dbClient.qualityProfileDao().selectByNameAndLanguage(dbSession, organization, "two", "xoo"); - dbClient.defaultQProfileDao().insertOrUpdate(dbSession, DefaultQProfileDto.from(profile)); - dbSession.commit(); - - verifyDefaultProfile(organization, "xoo", "two"); - - tester.get(Platform.class).restart(); - // restart must keep "two" as default profile, even if "one" is marked as it - verifyDefaultProfile(organization, "xoo", "two"); - } - - private void verifyDefaultProfile(OrganizationDto organization, String language, String name) { - dbSession = dbClient().openSession(false); - QProfileDto defaultProfile = dbClient().qualityProfileDao().selectDefaultProfile(dbSession, organization, language); - assertThat(defaultProfile).isNotNull(); - assertThat(defaultProfile.getName()).isEqualTo(name); - } - - private DbClient dbClient() { - return tester.get(DbClient.class); - } - - public static class XooProfileDefinition extends ProfileDefinition { - @Override - public RulesProfile createProfile(ValidationMessages validation) { - final RulesProfile profile = RulesProfile.create("Basic", ServerTester.Xoo.KEY); - ActiveRule activeRule1 = profile.activateRule( - org.sonar.api.rules.Rule.create("xoo", "x1").setParams(newArrayList(new RuleParam().setKey("acceptWhitespace"))), - RulePriority.CRITICAL); - activeRule1.setParameter("acceptWhitespace", "true"); - - profile.activateRule(org.sonar.api.rules.Rule.create("xoo", "x2"), RulePriority.INFO); - return profile; - } - } - - public static class XooRulesDefinition implements RulesDefinition { - @Override - public void define(Context context) { - NewRepository repository = context.createRepository("xoo", ServerTester.Xoo.KEY).setName("Xoo Repo"); - NewRule x1 = repository.createRule("x1") - .setName("x1 name") - .setHtmlDescription("x1 desc") - .setSeverity(Severity.MINOR); - x1.createParam("acceptWhitespace") - .setDefaultValue("false") - .setType(RuleParamType.BOOLEAN) - .setDescription("Accept whitespaces on the line"); - x1.createParam("max") - .setDefaultValue("10") - .setType(RuleParamType.INTEGER) - .setDescription("Maximum"); - - repository.createRule("x2") - .setName("x2 name") - .setHtmlDescription("x2 desc") - .setSeverity(Severity.INFO); - repository.done(); - } - } - - public static class SimpleProfileDefinition extends ProfileDefinition { - private final boolean asDefault; - private final String name; - - public SimpleProfileDefinition(String name, boolean asDefault) { - this.name = name; - this.asDefault = asDefault; - } - - @Override - public RulesProfile createProfile(ValidationMessages validation) { - RulesProfile profile = RulesProfile.create(name, "xoo"); - profile.setDefaultProfile(asDefault); - return profile; - } - } -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesMediumTest.java b/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesMediumTest.java deleted file mode 100644 index 52c0b76a466..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesMediumTest.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.rule; - -import com.google.common.base.Function; -import com.google.common.collect.FluentIterable; -import com.google.common.collect.ImmutableMap; -import java.util.List; -import java.util.Map; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; -import org.junit.After; -import org.junit.Before; -import org.junit.ClassRule; -import org.junit.Test; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; -import org.sonar.api.server.debt.DebtRemediationFunction; -import org.sonar.api.server.rule.RuleParamType; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.db.DbClient; -import org.sonar.db.DbSession; -import org.sonar.db.organization.OrganizationDto; -import org.sonar.db.qualityprofile.ActiveRuleDto; -import org.sonar.db.qualityprofile.ActiveRuleKey; -import org.sonar.db.qualityprofile.ActiveRuleParamDto; -import org.sonar.db.qualityprofile.QProfileDto; -import org.sonar.db.rule.RuleDao; -import org.sonar.db.rule.RuleDefinitionDto; -import org.sonar.db.rule.RuleDto; -import org.sonar.db.rule.RuleParamDto; -import org.sonar.db.rule.RuleTesting; -import org.sonar.server.es.SearchOptions; -import org.sonar.server.organization.DefaultOrganizationProvider; -import org.sonar.server.platform.Platform; -import org.sonar.server.qualityprofile.QProfileTesting; -import org.sonar.server.qualityprofile.RuleActivation; -import org.sonar.server.qualityprofile.RuleActivator; -import org.sonar.server.rule.index.RuleIndex; -import org.sonar.server.rule.index.RuleQuery; -import org.sonar.server.tester.ServerTester; -import org.sonar.server.tester.UserSessionRule; - -import static com.google.common.collect.Sets.newHashSet; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.db.permission.OrganizationPermission.ADMINISTER_QUALITY_PROFILES; - -// TODO remaining tests should be moved to RegisterRulesTest -public class RegisterRulesMediumTest { - - static final XooRulesDefinition RULE_DEFS = new XooRulesDefinition(); - - @ClassRule - public static final ServerTester TESTER = new ServerTester() - .withEsIndexes() - .addXoo() - .addComponents(RULE_DEFS); - - @org.junit.Rule - public UserSessionRule userSessionRule = UserSessionRule.standalone(); - - private DbClient db = TESTER.get(DbClient.class); - private DbSession dbSession = TESTER.get(DbClient.class).openSession(false); - - private RuleIndex ruleIndex = TESTER.get(RuleIndex.class); - private RuleDao ruleDao = db.ruleDao(); - - private OrganizationDto defaultOrganization; - - @Before - public void before() { - TESTER.clearDbAndIndexes(); - dbSession.clearCache(); - String defaultOrganizationUuid = TESTER.get(DefaultOrganizationProvider.class).get().getUuid(); - defaultOrganization = db.organizationDao().selectByUuid(dbSession, defaultOrganizationUuid) - .orElseThrow(() -> new IllegalStateException(String.format("Cannot load default organization '%s'", defaultOrganizationUuid))); - } - - @After - public void after() { - if (dbSession != null) { - dbSession.close(); - } - } - - private void register(@Nullable Rules rules) { - if (dbSession != null) { - dbSession.close(); - } - RULE_DEFS.set(rules); - TESTER.get(Platform.class).restart(); - db = TESTER.get(DbClient.class); - dbSession = TESTER.get(DbClient.class).openSession(false); - dbSession.clearCache(); - ruleIndex = TESTER.get(RuleIndex.class); - } - - @Test - public void deactivate_removed_rules_only_if_repository_still_exists() { - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("x1").setName("x1 name").setHtmlDescription("x1 desc"); - } - }); - - // Create a profile and activate rule - logInAsQProfileAdministrator(); - QProfileDto profile = QProfileTesting.newXooP1("org-123"); - db.qualityProfileDao().insert(dbSession, profile); - dbSession.commit(); - dbSession.clearCache(); - RuleActivation activation = RuleActivation.create(RuleTesting.XOO_X1, null, null); - TESTER.get(RuleActivator.class).activate(dbSession, activation, profile); - - // Restart, repo xoo still exists -> deactivate x1 - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("x2").setName("x2 name").setHtmlDescription("x2 desc"); - } - }); - assertThat(ruleIndex.search(new RuleQuery().setKey(RuleTesting.XOO_X1.toString()), new SearchOptions()).getTotal()).isEqualTo(0); - assertThat(ruleIndex.search(new RuleQuery().setKey(RuleTesting.XOO_X2.toString()), new SearchOptions()).getTotal()).isEqualTo(1); - assertThat(ruleIndex.search(new RuleQuery().setActivation(true).setQProfile(profile), new SearchOptions()).getIds()).isEmpty(); - assertThat(db.activeRuleDao().selectByProfileUuid(dbSession, QProfileTesting.XOO_P1_KEY)).isEmpty(); - } - - @Test - public void do_not_deactivate_removed_rules_if_repository_accidentally_uninstalled() { - Rules rules = new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("x1").setName("x1 name").setHtmlDescription("x1 desc"); - } - }; - register(rules); - - // create a profile and activate rule - logInAsQProfileAdministrator(); - QProfileDto profile = QProfileTesting.newXooP1("org-123"); - db.qualityProfileDao().insert(dbSession, profile); - dbSession.commit(); - dbSession.clearCache(); - RuleActivation activation = RuleActivation.create(RuleTesting.XOO_X1, null, null); - TESTER.get(RuleActivator.class).activate(dbSession, activation, profile); - dbSession.commit(); - - // Restart without xoo - register(null); - dbSession.commit(); - dbSession.clearCache(); - - assertThat(ruleIndex.search(new RuleQuery().setKey(RuleTesting.XOO_X1.toString()), new SearchOptions()).getTotal()).isEqualTo(0); - assertThat(db.activeRuleDao().selectByProfileUuid(dbSession, QProfileTesting.XOO_P1_KEY)).isEmpty(); - - // Re-install - register(rules); - assertThat(ruleIndex.search(new RuleQuery().setKey(RuleTesting.XOO_X1.toString()), new SearchOptions()).getTotal()).isEqualTo(1); - assertThat(db.activeRuleDao().selectByProfileUuid(dbSession, QProfileTesting.XOO_P1_KEY)).hasSize(1); - } - - @Test - public void update_active_rules_on_param_changes() { - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - RulesDefinition.NewRule x1Rule = repository.createRule("x1").setName("x1 name").setHtmlDescription("x1 desc"); - // has default value - x1Rule.createParam("min").setType(RuleParamType.INTEGER).setDefaultValue("5"); - // no default value - x1Rule.createParam("format").setType(RuleParamType.STRING); - } - }); - - // Create profile and activate rule - logInAsQProfileAdministrator(); - QProfileDto profile = QProfileTesting.newXooP1("org-123"); - db.qualityProfileDao().insert(dbSession, profile); - dbSession.commit(); - dbSession.clearCache(); - RuleActivation activation = RuleActivation.create(RuleTesting.XOO_X1, null, ImmutableMap.of("format", "txt")); - TESTER.get(RuleActivator.class).activate(dbSession, activation, profile); - dbSession.commit(); - - // Default value of "min" is changed, "format" is removed, "format2" is added, "max" is added with a default value - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - RulesDefinition.NewRule x1Rule = repository.createRule("x1").setName("x1 name").setHtmlDescription("x1 desc"); - x1Rule.createParam("min").setType(RuleParamType.INTEGER).setDefaultValue("6"); - x1Rule.createParam("format2").setType(RuleParamType.STRING); - x1Rule.createParam("max").setType(RuleParamType.INTEGER).setDefaultValue("10"); - } - }); - - ActiveRuleDto activeRuleDto = db.activeRuleDao().selectByKey(dbSession, ActiveRuleKey.of(profile, RuleTesting.XOO_X1)).get(); - List params = db.activeRuleDao().selectParamsByActiveRuleId(dbSession, activeRuleDto.getId()); - assertThat(params).hasSize(2); - - Map parmsByKey = FluentIterable.from(params).uniqueIndex(ActiveRuleParamToKey.INSTANCE); - - // do not change default value on existing active rules -> keep min=5 - assertThat(parmsByKey.get("min").getValue()).isEqualTo("5"); - - // new param with default value - assertThat(parmsByKey.get("max").getValue()).isEqualTo("10"); - } - - @Test - public void remove_user_tags_that_are_newly_declared_as_system() { - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("x1").setName("x1 name").setHtmlDescription("x1 desc").setTags("tag1"); - } - }); - RuleDto rule = ruleDao.selectOrFailByKey(dbSession, defaultOrganization, RuleTesting.XOO_X1); - assertThat(rule.getSystemTags()).containsOnly("tag1"); - assertThat(rule.getTags()).isEmpty(); - - // User adds tag - RuleUpdate update = RuleUpdate.createForPluginRule(RuleTesting.XOO_X1) - .setTags(newHashSet("tag2")) - .setOrganization(defaultOrganization); - TESTER.get(RuleUpdater.class).update(dbSession, update, defaultOrganization, userSessionRule); - dbSession.commit(); - - rule = ruleDao.selectOrFailByKey(dbSession, defaultOrganization, RuleTesting.XOO_X1); - assertThat(rule.getSystemTags()).containsOnly("tag1"); - assertThat(rule.getTags()).containsOnly("tag2"); - - // FIXME: not supported anymore because information specific to an organization: Definition updated -> user tag "tag2" becomes a system tag -// register(new Rules() { -// @Override -// public void init(RulesDefinition.NewRepository repository) { -// repository.createRule("x1").setName("x1 name").setHtmlDescription("x1 desc").setTags("tag1", "tag2"); -// } -// }); -// rule = ruleDao.selectOrFailByKey(dbSession, RuleTesting.XOO_X1); -// assertThat(rule.getSystemTags()).containsOnly("tag1", "tag2"); -// assertThat(rule.getTags()).isEmpty(); - } - - @Test - public void update_custom_rule_on_template_change() { - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("T1") - .setName("template1 name") - .setHtmlDescription("template1 desc") - .setSeverity(Severity.MAJOR) - .setTemplate(true) - .createParam("format") - .setDefaultValue("csv") - .setType(RuleParamType.STRING) - .setDescription("format parameter"); - } - }); - RuleDefinitionDto template = ruleDao.selectOrFailDefinitionByKey(dbSession, RuleKey.of("xoo", "T1")); - - // Create custom rule - RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(dbSession, NewCustomRule.createForCustomRule("CUSTOM_RULE", template.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("format", "txt"))); - - // Update template and restart - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - RulesDefinition.NewRule rule = repository.createRule("T1") - .setName("template1 name") - .setHtmlDescription("template1 desc") - .setSeverity(Severity.BLOCKER) - .setStatus(RuleStatus.BETA) - .setTemplate(true) - .setInternalKey("new_internal"); - rule - .setDebtRemediationFunction(rule.debtRemediationFunctions().linearWithOffset("1h", "30min")) - .setGapDescription("Effort"); - } - }); - - // Verify custom rule has been restore from the template - RuleDefinitionDto customRule = ruleDao.selectOrFailDefinitionByKey(dbSession, customRuleKey); - assertThat(customRule.getLanguage()).isEqualTo("xoo"); - assertThat(customRule.getConfigKey()).isEqualTo("new_internal"); - assertThat(customRule.getSeverityString()).isEqualTo(Severity.BLOCKER); - assertThat(customRule.getStatus()).isEqualTo(RuleStatus.BETA); - assertThat(customRule.getDefRemediationFunction()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET.name()); - assertThat(customRule.getGapDescription()).isEqualTo("Effort"); - - assertThat(ruleIndex.search(new RuleQuery().setKey(customRuleKey.toString()), new SearchOptions()).getTotal()).isEqualTo(1); - } - - @Test - public void do_not_update_custom_rule_if_no_template_change() { - Rules rules = new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("T1") - .setName("template1 name") - .setHtmlDescription("template1 desc") - .setSeverity(Severity.MAJOR) - .setTemplate(true) - .createParam("format") - .setDefaultValue("csv") - .setType(RuleParamType.STRING) - .setDescription("format parameter"); - } - }; - register(rules); - RuleDefinitionDto template = ruleDao.selectOrFailDefinitionByKey(dbSession, RuleKey.of("xoo", "T1")); - - // Create custom rule - RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(dbSession, NewCustomRule.createForCustomRule("CUSTOM_RULE", template.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("format", "txt"))); - - Long updatedAt = ruleDao.selectOrFailDefinitionByKey(dbSession, customRuleKey).getUpdatedAt(); - - register(rules); - - // Verify custom rule has been restore from the template - RuleDefinitionDto customRuleReloaded = ruleDao.selectOrFailDefinitionByKey(dbSession, customRuleKey); - assertThat(customRuleReloaded.getUpdatedAt()).isEqualTo(updatedAt); - } - - @Test - public void do_not_update_custom_rule_params_from_template() { - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("T1") - .setName("template1 name") - .setHtmlDescription("template1 desc") - .setSeverity(Severity.MAJOR) - .setTemplate(true) - .createParam("format") - .setDefaultValue("csv") - .setType(RuleParamType.STRING) - .setDescription("format parameter"); - } - }); - RuleDefinitionDto templateRule = ruleDao.selectOrFailDefinitionByKey(dbSession, RuleKey.of("xoo", "T1")); - - // Create custom rule - RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(dbSession, NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("format", "txt"))); - - register(new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("T1") - .setName("template1 name") - .setHtmlDescription("template1 desc") - .setSeverity(Severity.MAJOR) - .setTemplate(true) - // "format" removed, "format2" added - .createParam("format2") - .setDefaultValue("csv") - .setType(RuleParamType.STRING) - .setDescription("format parameter"); - } - }); - - // Verify custom rule param has not been changed! - List customRuleParams = ruleDao.selectRuleParamsByRuleKey(dbSession, customRuleKey); - assertThat(customRuleParams.get(0).getName()).isEqualTo("format"); - } - - @Test - public void disable_custom_rules_if_template_disabled() { - Rules rules = new Rules() { - @Override - public void init(RulesDefinition.NewRepository repository) { - repository.createRule("T1") - .setName("template1 name") - .setHtmlDescription("template1 desc") - .setSeverity(Severity.MAJOR) - .setTemplate(true) - .createParam("format") - .setDefaultValue("csv") - .setType(RuleParamType.STRING) - .setDescription("format parameter"); - } - }; - register(rules); - RuleDefinitionDto templateRule = ruleDao.selectOrFailDefinitionByKey(dbSession, RuleKey.of("xoo", "T1")); - - // Create custom rule - RuleKey customRuleKey = TESTER.get(RuleCreator.class).create(dbSession, NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setHtmlDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("format", "txt"))); - assertThat(ruleDao.selectOrFailDefinitionByKey(dbSession, customRuleKey).getStatus()).isEqualTo(RuleStatus.READY); - - // Restart without template - register(null); - - // Verify custom rule is removed - assertThat(ruleDao.selectOrFailDefinitionByKey(dbSession, templateRule.getKey()).getStatus()).isEqualTo(RuleStatus.REMOVED); - assertThat(ruleDao.selectOrFailDefinitionByKey(dbSession, customRuleKey).getStatus()).isEqualTo(RuleStatus.REMOVED); - - // Re-install template - register(rules); - assertThat(ruleDao.selectOrFailDefinitionByKey(dbSession, templateRule.getKey()).getStatus()).isEqualTo(RuleStatus.READY); - assertThat(ruleDao.selectOrFailDefinitionByKey(dbSession, customRuleKey).getStatus()).isEqualTo(RuleStatus.READY); - } - - interface Rules { - void init(RulesDefinition.NewRepository repository); - } - - public static class XooRulesDefinition implements RulesDefinition { - private Rules rules = null; - - void set(@Nullable Rules rules) { - this.rules = rules; - } - - @Override - public void define(Context context) { - if (rules != null) { - NewRepository repository = context.createRepository("xoo", ServerTester.Xoo.KEY).setName("Xoo Repo"); - rules.init(repository); - repository.done(); - } - } - } - - private enum ActiveRuleParamToKey implements Function { - INSTANCE; - - @Override - public String apply(@Nonnull ActiveRuleParamDto input) { - return input.getKey(); - } - } - - private void logInAsQProfileAdministrator() { - userSessionRule.logIn().addPermission(ADMINISTER_QUALITY_PROFILES, TESTER.get(DefaultOrganizationProvider.class).get().getUuid()); - } -} diff --git a/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java b/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java deleted file mode 100644 index e18775ebcae..00000000000 --- a/server/sonar-server/src/test/java/org/sonar/server/tester/ServerTester.java +++ /dev/null @@ -1,339 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2017 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.server.tester; - -import com.google.common.base.Preconditions; -import com.google.common.base.Throwables; -import com.google.common.collect.Lists; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.nio.file.Files; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import javax.annotation.Nullable; -import javax.servlet.ServletContext; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.StringUtils; -import org.junit.rules.ExternalResource; -import org.sonar.api.database.DatabaseProperties; -import org.sonar.api.resources.Language; -import org.sonar.api.utils.log.Logger; -import org.sonar.api.utils.log.Loggers; -import org.sonar.core.platform.ComponentContainer; -import org.sonar.process.ProcessEntryPoint; -import org.sonar.process.ProcessProperties; -import org.sonar.server.es.EsServerHolder; -import org.sonar.server.platform.BackendCleanup; -import org.sonar.server.platform.Platform; -import org.sonar.server.platform.ServerTesterPlatform; -import org.sonar.server.plugins.UpdateCenterClient; -import org.sonar.server.ws.WsTester; - -import static org.sonar.server.platform.Platform.Startup.ALL; -import static org.sonar.server.platform.Platform.Startup.NO_STARTUP_TASKS; - -/** - * Entry point to implement medium tests of server components. - *

- * The system properties starting with "mediumTests." override the programmatic settings, for example: - * -DmediumTests.sonar.log.level=TRACE - * - * @since 4.4 - */ -public class ServerTester extends ExternalResource { - - private static final Logger LOG = Loggers.get(ServerTester.class); - private static final String PROP_PREFIX = "mediumTests."; - - private ServerTesterPlatform platform; - private EsServerHolder esServerHolder; - private final File homeDir = newTempDir("tmp-sq-"); - private final List components = Lists.newArrayList(WsTester.class); - private final Properties initialProps = new Properties(); - private final ServletContext servletContext = new AttributeHolderServletContext(); - private URL updateCenterUrl; - private boolean startupTasks = false; - private boolean esIndexes = false; - - public ServerTester withStartupTasks() { - this.startupTasks = true; - return this; - } - - public ServerTester withEsIndexes() { - this.esIndexes = true; - return this; - } - - /** - * Called only when JUnit @Rule or @ClassRule is used. - */ - @Override - protected void before() { - start(); - } - - /** - * This method should not be called by test when ServerTester is annotated with {@link org.junit.Rule} - */ - public void start() { - checkNotStarted(); - - try { - Properties properties = new Properties(); - properties.putAll(initialProps); - esServerHolder = EsServerHolder.get(); - properties.setProperty(ProcessProperties.CLUSTER_NAME, esServerHolder.getClusterName()); - properties.setProperty(ProcessProperties.SEARCH_PORT, String.valueOf(esServerHolder.getPort())); - properties.setProperty(ProcessProperties.SEARCH_HOST, esServerHolder.getAddress().getHostAddress()); - properties.setProperty(ProcessProperties.PATH_HOME, homeDir.getAbsolutePath()); - properties.setProperty(ProcessProperties.PATH_DATA, new File(homeDir, "data").getAbsolutePath()); - File temporaryFolderIn = createTemporaryFolderIn(); - properties.setProperty(ProcessProperties.PATH_TEMP, temporaryFolderIn.getAbsolutePath()); - properties.setProperty(ProcessEntryPoint.PROPERTY_SHARED_PATH, temporaryFolderIn.getAbsolutePath()); - properties.setProperty(ProcessEntryPoint.PROPERTY_PROCESS_INDEX, "2"); - properties.setProperty(DatabaseProperties.PROP_URL, "jdbc:h2:" + homeDir.getAbsolutePath() + "/h2"); - if (updateCenterUrl != null) { - properties.setProperty(UpdateCenterClient.URL_PROPERTY, updateCenterUrl.toString()); - } - for (Map.Entry entry : System.getProperties().entrySet()) { - String key = entry.getKey().toString(); - if (key.startsWith(PROP_PREFIX)) { - properties.put(StringUtils.substringAfter(key, PROP_PREFIX), entry.getValue()); - } - } - if (!esIndexes) { - properties.put("sonar.internal.es.disableIndexes", true); - } - platform = new ServerTesterPlatform(() -> new Platform.AutoStarter() { - private boolean running = false; - - @Override - public void execute(Runnable startCode) { - running = true; - startCode.run(); - } - - @Override - public void failure(Throwable t) { - stop(); - Throwables.propagate(t); - this.running = false; - } - - @Override - public void success() { - this.running = false; - } - - @Override - public boolean isRunning() { - return this.running; - } - - @Override - public void abort() { - // do nothing specific - } - - @Override - public boolean isAborting() { - return false; - } - - @Override - public void aborted() { - // do nothing specific - } - }); - platform.init(properties, servletContext); - platform.addComponents(components); - platform.doStart(startupTasks ? ALL : NO_STARTUP_TASKS); - } catch (Exception e) { - stop(); - Throwables.propagate(e); - } - if (!platform.isStarted()) { - throw new IllegalStateException("Server not started. You should check that db migrations " + - "are correctly declared, for example in schema-h2.sql or DatabaseVersion"); - } - } - - private File createTemporaryFolderIn() throws IOException { - File createdFolder = File.createTempFile("ServerTester", ""); - createdFolder.delete(); - createdFolder.mkdir(); - return createdFolder; - } - - /** - * Called only when JUnit @Rule or @ClassRule is used. - */ - @Override - protected void after() { - stop(); - } - - /** - * This method should not be called by test when ServerTester is annotated with {@link org.junit.Rule} - */ - public void stop() { - try { - if (platform != null) { - platform.doStop(); - platform = null; - } - } catch (Exception e) { - LOG.error("Fail to stop web server", e); - } - esServerHolder = null; - FileUtils.deleteQuietly(homeDir); - } - - public void restart() { - platform.restart(); - } - - /** - * Add classes or objects to IoC container, as it could be done by plugins. - * Must be called before {@link #start()}. - */ - public ServerTester addComponents(@Nullable Object... components) { - checkNotStarted(); - if (components != null) { - this.components.addAll(Arrays.asList(components)); - } - return this; - } - - public ServerTester addXoo() { - addComponents(Xoo.class); - return this; - } - - public ServerTester addPluginJar(File jar) { - Preconditions.checkArgument(jar.exists() && jar.isFile(), "Plugin JAR file does not exist: " + jar.getAbsolutePath()); - try { - File pluginsDir = new File(homeDir, "extensions/plugins"); - FileUtils.forceMkdir(pluginsDir); - FileUtils.copyFileToDirectory(jar, pluginsDir); - return this; - } catch (Exception e) { - throw new IllegalStateException("Fail to copy plugin JAR file: " + jar.getAbsolutePath(), e); - } - } - - public ServerTester setUpdateCenterUrl(URL url) { - this.updateCenterUrl = url; - return this; - } - - /** - * Set a property available for startup. Must be called before {@link #start()}. Does not affect - * Elasticsearch server. - */ - public ServerTester setProperty(String key, String value) { - checkNotStarted(); - initialProps.setProperty(key, value); - return this; - } - - /** - * Truncate all db tables and Elasticsearch indexes. Can be executed only if ServerTester is started. - */ - public void clearDbAndIndexes() { - checkStarted(); - get(BackendCleanup.class).clearAll(); - } - - public void clearIndexes() { - checkStarted(); - get(BackendCleanup.class).clearIndexes(); - } - - /** - * Get a component from the platform - */ - public C get(Class component) { - checkStarted(); - return platform.getContainer().getComponentByType(component); - } - - public ComponentContainer getContainer() { - return platform.getContainer(); - } - - public WsTester wsTester() { - return get(WsTester.class); - } - - public EsServerHolder getEsServerHolder() { - return esServerHolder; - } - - private void checkStarted() { - if (platform == null || !platform.isStarted()) { - throw new IllegalStateException("Not started"); - } - } - - private void checkNotStarted() { - if (platform != null && platform.isStarted()) { - throw new IllegalStateException("Already started"); - } - } - - public static class Xoo implements Language { - - public static final String KEY = "xoo"; - public static final String NAME = "Xoo"; - public static final String FILE_SUFFIX = ".xoo"; - - private static final String[] XOO_SUFFIXES = { - FILE_SUFFIX - }; - - @Override - public String getKey() { - return KEY; - } - - @Override - public String getName() { - return NAME; - } - - @Override - public String[] getFileSuffixes() { - return XOO_SUFFIXES; - } - } - - private static File newTempDir(String prefix) { - try { - return Files.createTempDirectory(prefix).toFile(); - } catch (Exception e) { - throw new IllegalStateException("Fail to create temp dir", e); - } - } -}