From 4eb7b91c56a57096ae44f64b34311cdeaac9b501 Mon Sep 17 00:00:00 2001 From: Antoine Vinot Date: Mon, 27 Jun 2022 20:14:29 +0200 Subject: [PATCH] SONAR-16518 Remove replaceRuleDescriptionSectionDtos method --- .../main/java/org/sonar/db/rule/RuleDto.java | 12 +- .../java/org/sonar/db/rule/RuleDaoTest.java | 18 +- .../java/org/sonar/db/rule/RuleTesting.java | 26 +- .../sonar/server/rule/index/RuleDocTest.java | 25 +- .../server/rule/index/RuleIndexTest.java | 50 +- .../server/rule/index/RuleIndexerTest.java | 43 +- ...lityProfileChangeEventServiceImplTest.java | 8 +- .../server/issue/ws/SearchActionTest.java | 11 +- .../QProfileBackuperImplTest.java | 38 +- .../sonar/server/rule/RuleCreatorTest.java | 1108 ++++++++--------- .../sonar/server/rule/RuleUpdaterTest.java | 27 +- .../server/rule/ws/CreateActionTest.java | 9 +- .../server/rule/ws/SearchActionTest.java | 9 +- .../sonar/server/rule/ws/ShowActionTest.java | 36 +- .../server/rule/ws/UpdateActionTest.java | 56 +- 15 files changed, 722 insertions(+), 754 deletions(-) diff --git a/server/sonar-db-dao/src/main/java/org/sonar/db/rule/RuleDto.java b/server/sonar-db-dao/src/main/java/org/sonar/db/rule/RuleDto.java index 907f8ab6079..2655b8e8f31 100644 --- a/server/sonar-db-dao/src/main/java/org/sonar/db/rule/RuleDto.java +++ b/server/sonar-db-dao/src/main/java/org/sonar/db/rule/RuleDto.java @@ -19,13 +19,11 @@ */ package org.sonar.db.rule; -import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableSet; import java.util.Arrays; import java.util.Collection; import java.util.HashSet; -import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.Set; @@ -215,12 +213,6 @@ public class RuleDto { return this; } - @VisibleForTesting - public RuleDto replaceRuleDescriptionSectionDtos(RuleDescriptionSectionDto ruleDescriptionSectionDto) { - replaceRuleDescriptionSectionDtos(List.of(ruleDescriptionSectionDto)); - return this; - } - public RuleDto addRuleDescriptionSectionDto(RuleDescriptionSectionDto ruleDescriptionSectionDto) { checkArgument(!hasDescriptionSectionWithSameKeyAndContext(ruleDescriptionSectionDto), ERROR_MESSAGE_SECTION_ALREADY_EXISTS, ruleDescriptionSectionDto.getKey(), @@ -235,12 +227,12 @@ public class RuleDto { } private static boolean hasSameKeyAndContextKey(RuleDescriptionSectionDto ruleDescriptionSectionDto, RuleDescriptionSectionDto other) { - if (!ruleDescriptionSectionDto.getKey().equals(other.getKey())){ + if (!ruleDescriptionSectionDto.getKey().equals(other.getKey())) { return false; } String contextKey = ofNullable(ruleDescriptionSectionDto.getContext()).map(RuleDescriptionSectionContextDto::getKey).orElse(null); - String otherContextKey = ofNullable(other.getContext()).map(RuleDescriptionSectionContextDto::getKey).orElse(null); + String otherContextKey = ofNullable(other.getContext()).map(RuleDescriptionSectionContextDto::getKey).orElse(null); return Objects.equals(contextKey, otherContextKey); } diff --git a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java index 9f3a728b5f5..bea1f12db93 100644 --- a/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java +++ b/server/sonar-db-dao/src/test/java/org/sonar/db/rule/RuleDaoTest.java @@ -574,20 +574,19 @@ public class RuleDaoTest { @Test public void update_rule_sections_replaces_section() { RuleDto rule = db.rules().insert(); - RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next(); + Set ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos(); + RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next(); RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder() .uuid(randomAlphanumeric(20)) .key(existingSection.getKey()) .content(randomAlphanumeric(1000)) .build(); - rule.replaceRuleDescriptionSectionDtos(replacingSection); - + rule.replaceRuleDescriptionSectionDtos(List.of(replacingSection)); underTest.update(db.getSession(), rule); db.getSession().commit(); RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey())); - assertThat(ruleDto.getRuleDescriptionSectionDtos()) .usingRecursiveFieldByFieldElementComparator() .containsOnly(replacingSection); @@ -596,20 +595,21 @@ public class RuleDaoTest { @Test public void update_rule_sections_replaces_section_with_context() { RuleDto rule = db.rules().insert(); - RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next(); + Set ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos(); + RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next(); + RuleDescriptionSectionContextDto contextDto = RuleDescriptionSectionContextDto.of(randomAlphanumeric(10), randomAlphanumeric(10)); RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder() .uuid(randomAlphanumeric(20)) .key(existingSection.getKey()) .content(randomAlphanumeric(1000)) + .context(contextDto) .build(); - rule.replaceRuleDescriptionSectionDtos(replacingSection); - + rule.replaceRuleDescriptionSectionDtos(List.of(replacingSection)); underTest.update(db.getSession(), rule); db.getSession().commit(); RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey())); - assertThat(ruleDto.getRuleDescriptionSectionDtos()) .usingRecursiveFieldByFieldElementComparator() .containsOnly(replacingSection); @@ -742,7 +742,7 @@ public class RuleDaoTest { List ruleDtos = underTest.selectAllRuleParams(db.getSession()); - assertThat(ruleDtos.size()).isEqualTo(4); + assertThat(ruleDtos).hasSize(4); assertThat(ruleDtos).extracting(RuleParamDto::getUuid) .containsExactlyInAnyOrder(ruleParam1.getUuid(), ruleParam12.getUuid(), ruleParam2.getUuid(), ruleParam3.getUuid()); diff --git a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java index 57bdd634f10..59d21db54c2 100644 --- a/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java +++ b/server/sonar-db-dao/src/testFixtures/java/org/sonar/db/rule/RuleTesting.java @@ -37,10 +37,12 @@ import org.sonar.db.rule.RuleDto.Scope; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.ImmutableSet.copyOf; import static com.google.common.collect.Sets.newHashSet; +import static java.util.Arrays.stream; import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.apache.commons.lang.math.RandomUtils.nextInt; import static org.sonar.api.rule.RuleKey.EXTERNAL_RULE_REPO_PREFIX; +import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; /** @@ -59,13 +61,17 @@ public class RuleTesting { // only static helpers } - public static RuleDto newRule() { - return newRule(randomRuleKey()); + public static RuleDto newRule(RuleDescriptionSectionDto... ruleDescriptionSectionDtos) { + return newRule(randomRuleKey(), ruleDescriptionSectionDtos); } - public static RuleDto newRule(RuleKey key) { + public static RuleDto newRule(RuleKey key, RuleDescriptionSectionDto... ruleDescriptionSectionDtos) { RuleDto ruleDto = newRuleWithoutDescriptionSection(key); - ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5))); + if (ruleDescriptionSectionDtos.length == 0) { + ruleDto.addRuleDescriptionSectionDto(createDefaultRuleDescriptionSection(uuidFactory.create(), "description_" + randomAlphabetic(5))); + } else { + stream(ruleDescriptionSectionDtos).forEach(ruleDto::addRuleDescriptionSectionDto); + } return ruleDto; } @@ -81,7 +87,7 @@ public class RuleTesting { .setUuid("rule_uuid_" + randomAlphanumeric(5)) .setName("name_" + randomAlphanumeric(5)) .setDescriptionFormat(RuleDto.Format.HTML) - .setType(RuleType.values()[nextInt(RuleType.values().length)]) + .setType(CODE_SMELL) .setStatus(RuleStatus.READY) .setConfigKey("configKey_" + randomAlphanumeric(5)) .setSeverity(Severity.ALL.get(nextInt(Severity.ALL.size()))) @@ -177,7 +183,7 @@ public class RuleTesting { .setDefRemediationGapMultiplier("5d") .setDefRemediationBaseEffort("10h") .setGapDescription(ruleKey.repository() + "." + ruleKey.rule() + ".effortToFix") - .setType(RuleType.CODE_SMELL) + .setType(CODE_SMELL) .setCreatedAt(new Date().getTime()) .setUpdatedAt(new Date().getTime()) .setScope(Scope.MAIN) @@ -199,10 +205,14 @@ public class RuleTesting { .setIsTemplate(true); } - public static RuleDto newCustomRule(RuleDto templateRule) { + return newCustomRule(templateRule, "description_" + randomAlphabetic(5)); + } + + public static RuleDto newCustomRule(RuleDto templateRule, String description) { checkNotNull(templateRule.getUuid(), "The template rule need to be persisted before creating this custom rule."); - return newRule(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis())) + RuleDescriptionSectionDto defaultRuleDescriptionSection = createDefaultRuleDescriptionSection(uuidFactory.create(), description); + return newRule(RuleKey.of(templateRule.getRepositoryKey(), templateRule.getRuleKey() + "_" + System.currentTimeMillis()), defaultRuleDescriptionSection) .setLanguage(templateRule.getLanguage()) .setTemplateUuid(templateRule.getUuid()) .setType(templateRule.getType()); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleDocTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleDocTest.java index 26fa5c76cd4..2c706afb7eb 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleDocTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleDocTest.java @@ -24,10 +24,11 @@ import org.sonar.db.rule.RuleDescriptionSectionContextDto; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleForIndexingDto; -import org.sonar.db.rule.RuleTesting; import org.sonar.server.security.SecurityStandards; import static org.assertj.core.api.Assertions.assertThat; +import static org.sonar.db.rule.RuleTesting.newRule; +import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection; import static org.sonar.markdown.Markdown.convertToHtml; import static org.sonar.server.security.SecurityStandards.fromSecurityStandards; @@ -35,7 +36,7 @@ public class RuleDocTest { @Test public void ruleDocOf_mapsFieldCorrectly() { - RuleDto ruleDto = RuleTesting.newRule(); + RuleDto ruleDto = newRule(); RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto); ruleForIndexingDto.setTemplateRuleKey("templateKey"); ruleForIndexingDto.setTemplateRepository("repoKey"); @@ -72,9 +73,8 @@ public class RuleDocTest { @Test public void ruleDocOf_whenGivenNoHtmlSections_hasEmptyStringInHtmlDescription() { - RuleDto ruleDto = RuleTesting.newRule(); + RuleDto ruleDto = newRuleWithoutDescriptionSection(); ruleDto.setDescriptionFormat(RuleDto.Format.HTML); - ruleDto.getRuleDescriptionSectionDtos().clear(); RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto); SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards()); @@ -85,17 +85,12 @@ public class RuleDocTest { @Test public void ruleDocOf_whenGivenMultipleHtmlSections_hasConcatenationInHtmlDescription() { - RuleDto ruleDto = RuleTesting.newRule(); - ruleDto.setDescriptionFormat(RuleDto.Format.HTML); - ruleDto.getRuleDescriptionSectionDtos().clear(); RuleDescriptionSectionDto section1 = buildRuleDescriptionSectionDto("section1", "

html content 1

"); RuleDescriptionSectionDto section2 = buildRuleDescriptionSectionDto("section2", "

html content 2

"); RuleDescriptionSectionDto section3ctx1 = buildRuleDescriptionSectionDtoWithContext("section3", "

html content 3.1

", "ctx1"); RuleDescriptionSectionDto section3ctx2 = buildRuleDescriptionSectionDtoWithContext("section3", "

html content 3.2

", "ctx2"); - ruleDto.addRuleDescriptionSectionDto(section1); - ruleDto.addRuleDescriptionSectionDto(section2); - ruleDto.addRuleDescriptionSectionDto(section3ctx1); - ruleDto.addRuleDescriptionSectionDto(section3ctx2); + RuleDto ruleDto = newRule(section1, section2, section3ctx1, section3ctx2); + ruleDto.setDescriptionFormat(RuleDto.Format.HTML); RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto); SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards()); @@ -111,13 +106,11 @@ public class RuleDocTest { @Test public void ruleDocOf_whenGivenMultipleMarkdownSections_transformToHtmlAndConcatenatesInHtmlDescription() { - RuleDto ruleDto = RuleTesting.newRule(); - ruleDto.setDescriptionFormat(RuleDto.Format.MARKDOWN); - ruleDto.getRuleDescriptionSectionDtos().clear(); RuleDescriptionSectionDto section1 = buildRuleDescriptionSectionDto("section1", "*html content 1*"); RuleDescriptionSectionDto section2 = buildRuleDescriptionSectionDto("section2", "*html content 2*"); - ruleDto.addRuleDescriptionSectionDto(section1); - ruleDto.addRuleDescriptionSectionDto(section2); + + RuleDto ruleDto = newRule(section1, section2); + ruleDto.setDescriptionFormat(RuleDto.Format.MARKDOWN); RuleForIndexingDto ruleForIndexingDto = RuleForIndexingDto.fromRuleDto(ruleDto); SecurityStandards securityStandards = fromSecurityStandards(ruleDto.getSecurityStandards()); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java index 94f38180b32..7ee6a96160a 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexTest.java @@ -65,6 +65,7 @@ import static org.sonar.api.rules.RuleType.CODE_SMELL; import static org.sonar.api.rules.RuleType.SECURITY_HOTSPOT; import static org.sonar.api.rules.RuleType.VULNERABILITY; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.setCreatedAt; import static org.sonar.db.rule.RuleTesting.setIsExternal; import static org.sonar.db.rule.RuleTesting.setIsTemplate; @@ -93,18 +94,18 @@ import static org.sonar.server.security.SecurityStandards.SANS_TOP_25_RISKY_RESO public class RuleIndexTest { - private System2 system2 = new AlwaysIncreasingSystem2(); + private final System2 system2 = new AlwaysIncreasingSystem2(); @Rule public EsTester es = EsTester.create(); @Rule public DbTester db = DbTester.create(system2); - private RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); - private ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); + private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), db.getDbClient()); + private final ActiveRuleIndexer activeRuleIndexer = new ActiveRuleIndexer(db.getDbClient(), es.client()); - private RuleIndex underTest = new RuleIndex(es.client(), system2); - private UuidFactory uuidFactory = UuidFactoryFast.getInstance(); + private final RuleIndex underTest = new RuleIndex(es.client(), system2); + private final UuidFactory uuidFactory = UuidFactoryFast.getInstance(); @Test public void search_all_rules() { @@ -214,22 +215,11 @@ public class RuleIndexTest { public void search_content_by_query() { // it's important to set all the fields being used by the search (name, desc, key, lang, ...), // otherwise the generated random values may raise false-positives - RuleDto rule1 = createJavaRule(rule -> rule.setRuleKey("123") - .setName("rule 123") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "My great rule CWE-123 which makes your code 1000 times better!"))); - RuleDto rule2 = createJavaRule(rule -> rule.setRuleKey("124") - .setName("rule 124") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Another great and shiny rule CWE-124"))); - RuleDto rule3 = createJavaRule(rule -> rule.setRuleKey("1000") - .setName("rule 1000") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Another great rule CWE-1000"))); - RuleDto rule4 = createJavaRule(rule -> rule.setRuleKey("404") - .setName("rule 404") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), - "

HTML-Geeks

special formatting!

insidetables
"))); - RuleDto rule5 = createJavaRule(rule -> rule.setRuleKey("405") - .setName("rule 405") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "internationalization missunderstandings alsdkjfnadklsjfnadkdfnsksdjfn"))); + RuleDto rule1 = insertJavaRule("My great rule CWE-123 which makes your code 1000 times better!", "123", "rule 123"); + RuleDto rule2 = insertJavaRule("Another great and shiny rule CWE-124", "124", "rule 124"); + RuleDto rule3 = insertJavaRule("Another great rule CWE-1000", "1000", "rule 1000"); + RuleDto rule4 = insertJavaRule("

HTML-Geeks

special formatting!

insidetables
", "404", "rule 404"); + RuleDto rule5 = insertJavaRule("internationalization missunderstandings alsdkjfnadklsjfnadkdfnsksdjfn", "405", "rule 405"); index(); // partial match at word boundary @@ -269,6 +259,14 @@ public class RuleIndexTest { assertThat(underTest.search(new RuleQuery().setQueryText("internationalizationBlaBla"), new SearchOptions()).getUuids()).isEmpty(); } + private RuleDto insertJavaRule(String description, String ruleKey, String name) { + RuleDto javaRule = newRule(createDefaultRuleDescriptionSection(uuidFactory.create(), description)) + .setLanguage("java") + .setRuleKey(ruleKey) + .setName(name); + return db.rules().insert(javaRule); + } + @Test public void search_by_any_of_repositories() { RuleDto findbugs = createRule( @@ -555,7 +553,7 @@ public class RuleIndexTest { } @SafeVarargs - private final RuleDto createRule(Consumer... consumers) { + private RuleDto createRule(Consumer... consumers) { return db.rules().insert(consumers); } @@ -563,10 +561,6 @@ public class RuleIndexTest { return createRule(r -> r.setLanguage("java")); } - private RuleDto createJavaRule(Consumer consumer) { - return createRule(r -> r.setLanguage("java"), consumer); - } - @Test public void search_by_any_of_severities() { createRule(setSeverity(BLOCKER)); @@ -592,7 +586,7 @@ public class RuleIndexTest { @Test public void search_by_any_of_statuses() { - RuleDto beta = createRule(setStatus(RuleStatus.BETA)); + createRule(setStatus(RuleStatus.BETA)); RuleDto ready = createRule(setStatus(RuleStatus.READY)); index(); @@ -710,7 +704,7 @@ public class RuleIndexTest { public void search_by_activation_and_severity() { RuleDto major = createRule(setSeverity(MAJOR)); RuleDto minor = createRule(setSeverity(MINOR)); - RuleDto info = createRule(setSeverity(INFO)); + createRule(setSeverity(INFO)); QProfileDto profile1 = createJavaProfile(); QProfileDto profile2 = createJavaProfile(); db.qualityProfiles().activateRule(profile1, major, ar -> ar.setSeverity(BLOCKER)); diff --git a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java index 348a1f4c3d3..1bb3603be73 100644 --- a/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java +++ b/server/sonar-server-common/src/test/java/org/sonar/server/rule/index/RuleIndexerTest.java @@ -23,6 +23,11 @@ import com.google.common.collect.ImmutableSet; import com.tngtech.java.junit.dataprovider.DataProvider; import com.tngtech.java.junit.dataprovider.DataProviderRunner; import com.tngtech.java.junit.dataprovider.UseDataProvider; +import java.util.EnumSet; +import java.util.List; +import java.util.Random; +import java.util.Set; +import java.util.stream.Stream; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -38,25 +43,19 @@ import org.sonar.db.DbTester; import org.sonar.db.rule.RuleDescriptionSectionDto; import org.sonar.db.rule.RuleDto; import org.sonar.db.rule.RuleDto.Scope; -import org.sonar.db.rule.RuleTesting; import org.sonar.server.es.EsTester; import org.sonar.server.security.SecurityStandards; import org.sonar.server.security.SecurityStandards.SQCategory; -import java.util.EnumSet; -import java.util.List; -import java.util.Random; -import java.util.Set; -import java.util.stream.IntStream; -import java.util.stream.Stream; - import static com.google.common.collect.Sets.newHashSet; import static java.lang.String.format; import static java.util.Collections.emptyList; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toSet; +import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.server.rule.index.RuleIndexDefinition.TYPE_RULE; import static org.sonar.server.security.SecurityStandards.CWES_BY_SQ_CATEGORY; import static org.sonar.server.security.SecurityStandards.SQ_CATEGORY_KEYS_ORDERING; @@ -85,10 +84,10 @@ public class RuleIndexerTest { @Rule public LogTester logTester = new LogTester(); - private DbClient dbClient = dbTester.getDbClient(); + private final DbClient dbClient = dbTester.getDbClient(); private final RuleIndexer underTest = new RuleIndexer(es.client(), dbClient); - private DbSession dbSession = dbTester.getSession(); - private RuleDto rule = new RuleDto() + private final DbSession dbSession = dbTester.getSession(); + private final RuleDto rule = new RuleDto() .setUuid("rule-uuid") .setRuleKey("S001") .setRepositoryKey("xoo") @@ -137,10 +136,9 @@ public class RuleIndexerTest { @Test public void index_long_rule_description() { - String description = IntStream.range(0, 100000).map(i -> i % 100).mapToObj(Integer::toString).collect(joining(" ")); - RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), description); + RuleDescriptionSectionDto ruleDescriptionSectionDto = createDefaultRuleDescriptionSection(uuidFactory.create(), randomAlphanumeric(100000)); + RuleDto rule = dbTester.rules().insert(newRule(ruleDescriptionSectionDto)); - RuleDto rule = dbTester.rules().insert(r -> r.replaceRuleDescriptionSectionDtos(ruleDescriptionSectionDto)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); assertThat(es.countDocuments(TYPE_RULE)).isOne(); @@ -148,10 +146,7 @@ public class RuleIndexerTest { @Test public void index_long_rule_with_several_sections() { - RuleDto rule = dbTester.rules().insert(r -> { - r.replaceRuleDescriptionSectionDtos(RULE_DESCRIPTION_SECTION_DTO); - r.addRuleDescriptionSectionDto(RULE_DESCRIPTION_SECTION_DTO2); - }); + RuleDto rule = dbTester.rules().insert(newRule(RULE_DESCRIPTION_SECTION_DTO, RULE_DESCRIPTION_SECTION_DTO2)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); @@ -165,10 +160,7 @@ public class RuleIndexerTest { @Test public void index_long_rule_with_section_in_markdown() { - RuleDto rule = dbTester.rules().insert(r -> { - r.setDescriptionFormat(RuleDto.Format.MARKDOWN); - r.replaceRuleDescriptionSectionDtos(RULE_DESCRIPTION_SECTION_DTO); - }); + RuleDto rule = dbTester.rules().insert(newRule(RULE_DESCRIPTION_SECTION_DTO).setDescriptionFormat(RuleDto.Format.MARKDOWN)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); @@ -186,10 +178,9 @@ public class RuleIndexerTest { .flatMap(t -> CWES_BY_SQ_CATEGORY.get(t).stream().map(e -> "cwe:" + e)) .collect(toSet()); SecurityStandards securityStandards = SecurityStandards.fromSecurityStandards(standards); - RuleDto rule = dbTester.rules().insert(RuleTesting.newRuleWithoutDescriptionSection() + RuleDto rule = dbTester.rules().insert(newRule(RULE_DESCRIPTION_SECTION_DTO) .setType(RuleType.SECURITY_HOTSPOT) - .setSecurityStandards(standards) - .addRuleDescriptionSectionDto(RULE_DESCRIPTION_SECTION_DTO)); + .setSecurityStandards(standards)); underTest.commitAndIndex(dbTester.getSession(), rule.getUuid()); assertThat(logTester.getLogs()).hasSize(1); @@ -214,7 +205,7 @@ public class RuleIndexerTest { SQCategory sqCategory1 = sqCategories.toArray(new SQCategory[0])[random.nextInt(sqCategories.size())]; sqCategories.remove(sqCategory1); SQCategory sqCategory2 = sqCategories.toArray(new SQCategory[0])[random.nextInt(sqCategories.size())]; - return new Object[][] { + return new Object[][]{ {sqCategory1, sqCategory2} }; } diff --git a/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java b/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java index f2413b3d519..3484c38d878 100644 --- a/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java +++ b/server/sonar-webserver-pushapi/src/test/java/org/sonar/server/pushapi/qualityprofile/QualityProfileChangeEventServiceImplTest.java @@ -62,16 +62,14 @@ public class QualityProfileChangeEventServiceImplTest { public void distributeRuleChangeEvent() { QProfileDto qualityProfileDto = QualityProfileTesting.newQualityProfileDto(); - // Template rule RuleDto templateRule = newTemplateRule(RuleKey.of("xoo", "template-key")); db.rules().insert(templateRule); - // Custom rule - RuleDto rule1 = newCustomRule(templateRule) + + RuleDto rule1 = newCustomRule(templateRule, "
line1\nline2
") .setLanguage("xoo") .setRepositoryKey("repo") .setRuleKey("ruleKey") - .setDescriptionFormat(RuleDto.Format.MARKDOWN) - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection("uuid", "
line1\nline2
")); + .setDescriptionFormat(RuleDto.Format.MARKDOWN); db.rules().insert(rule1); ActiveRuleDto activeRuleDto = ActiveRuleDto.createFor(qualityProfileDto, rule1); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java index 21fbd555e27..03ecfc9eaea 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/issue/ws/SearchActionTest.java @@ -101,6 +101,9 @@ import static org.sonar.db.component.ComponentDto.PULL_REQUEST_SEPARATOR; import static org.sonar.db.component.ComponentTesting.newFileDto; import static org.sonar.db.issue.IssueTesting.newDto; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.XOO_X1; +import static org.sonar.db.rule.RuleTesting.XOO_X2; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.server.issue.CommentAction.COMMENT_KEY; import static org.sonar.server.tester.UserSessionRule.standalone; import static org.sonarqube.ws.Common.RuleType.BUG; @@ -1487,18 +1490,18 @@ public class SearchActionTest { } private RuleDto newIssueRule() { - RuleDto rule = RuleTesting.newXooX1() + RuleDto rule = newRule(XOO_X1, createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule desc")) + .setLanguage("xoo") .setName("Rule name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule desc")) .setStatus(RuleStatus.READY); db.rules().insert(rule); return rule; } private RuleDto newHotspotRule() { - RuleDto rule = RuleTesting.newXooX2() + RuleDto rule = newRule(XOO_X2, createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule desc")) + .setLanguage("xoo") .setName("Rule name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Rule desc")) .setStatus(RuleStatus.READY) .setType(SECURITY_HOTSPOT_VALUE); db.rules().insert(rule); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java index d9fe3768c0b..704fe8f7571 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/qualityprofile/QProfileBackuperImplTest.java @@ -20,6 +20,14 @@ package org.sonar.server.qualityprofile; import com.google.common.io.Resources; +import java.io.Reader; +import java.io.StringReader; +import java.io.StringWriter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import javax.annotation.Nullable; import org.junit.Rule; import org.junit.Test; import org.sonar.api.impl.utils.AlwaysIncreasingSystem2; @@ -39,15 +47,6 @@ import org.sonar.db.rule.RuleParamDto; import org.sonar.server.qualityprofile.builtin.QProfileName; import org.sonar.server.rule.RuleCreator; -import javax.annotation.Nullable; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; @@ -57,6 +56,7 @@ import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection; public class QProfileBackuperImplTest { @@ -144,11 +144,11 @@ public class QProfileBackuperImplTest { public void backup_custom_rules_with_params() { RuleDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto .setIsTemplate(true)); - RuleDto rule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description")) - .setName("custom rule name") - .setStatus(RuleStatus.READY) - .setTemplateUuid(templateRule.getUuid())); + RuleDto rule = db.rules().insert( + newRule(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description")) + .setName("custom rule name") + .setStatus(RuleStatus.READY) + .setTemplateUuid(templateRule.getUuid())); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto profile = createProfile(rule.getLanguage()); ActiveRuleDto activeRule = activate(profile, rule, param); @@ -403,11 +403,11 @@ public class QProfileBackuperImplTest { public void copy_profile_with_custom_rule() { RuleDto templateRule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto .setIsTemplate(true)); - RuleDto rule = db.rules().insert(ruleDefinitionDto -> ruleDefinitionDto - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description")) - .setName("custom rule name") - .setStatus(RuleStatus.READY) - .setTemplateUuid(templateRule.getUuid())); + RuleDto rule = db.rules().insert( + newRule(createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), "custom rule description")) + .setName("custom rule name") + .setStatus(RuleStatus.READY) + .setTemplateUuid(templateRule.getUuid())); RuleParamDto param = db.rules().insertRuleParam(rule); QProfileDto from = createProfile(rule.getLanguage()); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java index 76729573d0b..3de25849cb7 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleCreatorTest.java @@ -56,567 +56,565 @@ import static org.assertj.core.api.Assertions.assertThatExceptionOfType; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.newCustomRule; import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.server.util.TypeValidationsTesting.newFullTypeValidations; public class RuleCreatorTest { - private final System2 system2 = new TestSystem2().setNow(Instant.now().toEpochMilli()); - - @Rule - public DbTester dbTester = DbTester.create(system2); - - @Rule - public EsTester es = EsTester.create(); - - private final RuleIndex ruleIndex = new RuleIndex(es.client(), system2); - private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbTester.getDbClient()); - private final DbSession dbSession = dbTester.getSession(); - private final UuidFactory uuidFactory = new SequenceUuidFactory(); - - private final RuleCreator underTest = new RuleCreator(system2, new RuleIndexer(es.client(), dbTester.getDbClient()), dbTester.getDbClient(), newFullTypeValidations(), uuidFactory); - - @Test - public void create_custom_rule() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - RuleKey customRuleKey = underTest.create(dbSession, newRule); - - RuleDto rule = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey); - assertThat(rule).isNotNull(); - assertThat(rule.getKey()).isEqualTo(RuleKey.of("java", "CUSTOM_RULE")); - assertThat(rule.getPluginKey()).isEqualTo("sonarjava"); - assertThat(rule.getTemplateUuid()).isEqualTo(templateRule.getUuid()); - assertThat(rule.getName()).isEqualTo("My custom"); - assertThat(rule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Some description"); - assertThat(rule.getSeverityString()).isEqualTo("MAJOR"); - assertThat(rule.getStatus()).isEqualTo(RuleStatus.READY); - assertThat(rule.getLanguage()).isEqualTo("java"); - assertThat(rule.getConfigKey()).isEqualTo("S001"); - assertThat(rule.getDefRemediationFunction()).isEqualTo("LINEAR_OFFSET"); - assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1h"); - assertThat(rule.getDefRemediationBaseEffort()).isEqualTo("5min"); - assertThat(rule.getGapDescription()).isEqualTo("desc"); - assertThat(rule.getTags()).containsOnly("usertag1", "usertag2"); - assertThat(rule.getSystemTags()).containsOnly("tag1", "tag4"); - assertThat(rule.getSecurityStandards()).containsOnly("owaspTop10:a1", "cwe:123"); - assertThat(rule.isExternal()).isFalse(); - assertThat(rule.isAdHoc()).isFalse(); - - List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); - assertThat(params).hasSize(1); - - RuleParamDto param = params.get(0); - // From template rule - assertThat(param.getName()).isEqualTo("regex"); - assertThat(param.getDescription()).isEqualTo("Reg ex"); - assertThat(param.getType()).isEqualTo("STRING"); - // From user - assertThat(param.getDefaultValue()).isEqualTo("a.*"); - - assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule.getUuid(), templateRule.getUuid()); + private final System2 system2 = new TestSystem2().setNow(Instant.now().toEpochMilli()); + + @Rule + public DbTester dbTester = DbTester.create(system2); + + @Rule + public EsTester es = EsTester.create(); + + private final RuleIndex ruleIndex = new RuleIndex(es.client(), system2); + private final RuleIndexer ruleIndexer = new RuleIndexer(es.client(), dbTester.getDbClient()); + private final DbSession dbSession = dbTester.getSession(); + private final UuidFactory uuidFactory = new SequenceUuidFactory(); + + private final RuleCreator underTest = new RuleCreator(system2, new RuleIndexer(es.client(), dbTester.getDbClient()), dbTester.getDbClient(), newFullTypeValidations(), uuidFactory); + + @Test + public void create_custom_rule() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + RuleKey customRuleKey = underTest.create(dbSession, newRule); + + RuleDto rule = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey); + assertThat(rule).isNotNull(); + assertThat(rule.getKey()).isEqualTo(RuleKey.of("java", "CUSTOM_RULE")); + assertThat(rule.getPluginKey()).isEqualTo("sonarjava"); + assertThat(rule.getTemplateUuid()).isEqualTo(templateRule.getUuid()); + assertThat(rule.getName()).isEqualTo("My custom"); + assertThat(rule.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Some description"); + assertThat(rule.getSeverityString()).isEqualTo("MAJOR"); + assertThat(rule.getStatus()).isEqualTo(RuleStatus.READY); + assertThat(rule.getLanguage()).isEqualTo("java"); + assertThat(rule.getConfigKey()).isEqualTo("S001"); + assertThat(rule.getDefRemediationFunction()).isEqualTo("LINEAR_OFFSET"); + assertThat(rule.getDefRemediationGapMultiplier()).isEqualTo("1h"); + assertThat(rule.getDefRemediationBaseEffort()).isEqualTo("5min"); + assertThat(rule.getGapDescription()).isEqualTo("desc"); + assertThat(rule.getTags()).containsOnly("usertag1", "usertag2"); + assertThat(rule.getSystemTags()).containsOnly("tag1", "tag4"); + assertThat(rule.getSecurityStandards()).containsOnly("owaspTop10:a1", "cwe:123"); + assertThat(rule.isExternal()).isFalse(); + assertThat(rule.isAdHoc()).isFalse(); + + List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); + assertThat(params).hasSize(1); + + RuleParamDto param = params.get(0); + // From template rule + assertThat(param.getName()).isEqualTo("regex"); + assertThat(param.getDescription()).isEqualTo("Reg ex"); + assertThat(param.getType()).isEqualTo("STRING"); + // From user + assertThat(param.getDefaultValue()).isEqualTo("a.*"); + + assertThat(ruleIndex.search(new RuleQuery(), new SearchOptions()).getUuids()).containsOnly(rule.getUuid(), templateRule.getUuid()); + } + + @Test + public void create_custom_rule_with_empty_parameter_value() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "")); + + RuleKey customRuleKey = underTest.create(dbSession, newRule); + + List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); + assertThat(params).hasSize(1); + RuleParamDto param = params.get(0); + assertThat(param.getName()).isEqualTo("regex"); + assertThat(param.getDescription()).isEqualTo("Reg ex"); + assertThat(param.getType()).isEqualTo("STRING"); + assertThat(param.getDefaultValue()).isNull(); + } + + @Test + public void create_custom_rule_with_no_parameter_value() { + // insert template rule + RuleDto templateRule = createTemplateRuleWithIntArrayParam(); + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + + RuleKey customRuleKey = underTest.create(dbSession, newRule); + + List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); + assertThat(params).hasSize(1); + RuleParamDto param = params.get(0); + assertThat(param.getName()).isEqualTo("myIntegers"); + assertThat(param.getDescription()).isEqualTo("My Integers"); + assertThat(param.getType()).isEqualTo("INTEGER,multiple=true,values=1;2;3"); + assertThat(param.getDefaultValue()).isNull(); + } + + @Test + public void create_custom_rule_with_multiple_parameter_values() { + // insert template rule + RuleDto templateRule = createTemplateRuleWithIntArrayParam(); + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("myIntegers", "1,3")); + + RuleKey customRuleKey = underTest.create(dbSession, newRule); + + List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); + assertThat(params).hasSize(1); + RuleParamDto param = params.get(0); + assertThat(param.getName()).isEqualTo("myIntegers"); + assertThat(param.getDescription()).isEqualTo("My Integers"); + assertThat(param.getType()).isEqualTo("INTEGER,multiple=true,values=1;2;3"); + assertThat(param.getDefaultValue()).isEqualTo("1,3"); + } + + @Test + public void batch_create_custom_rules() { + // insert template rule + RuleDto templateRule = createTemplateRuleWithIntArrayParam(); + + NewCustomRule firstRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_1", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + + NewCustomRule secondRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_2", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + + List customRuleKeys = underTest.create(dbSession, Arrays.asList(firstRule, secondRule)); + + List rules = dbTester.getDbClient().ruleDao().selectByKeys(dbSession, customRuleKeys); + + assertThat(rules).hasSize(2); + assertThat(rules).asList() + .extracting("ruleKey") + .containsOnly("CUSTOM_RULE_1", "CUSTOM_RULE_2"); + } + + @Test + public void fail_to_create_custom_rules_when_wrong_rule_template() { + // insert rule + RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false); + dbTester.rules().insert(rule); + dbSession.commit(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, singletonList(newRule))) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("This rule is not a template rule: java:S001"); + } + + @Test + public void fail_to_create_custom_rules_when_removed_rule_template() { + // insert rule + RuleDto rule = createTemplateRule(); + newRule(RuleKey.of("java", "S001")).setIsTemplate(false); + rule.setStatus(RuleStatus.REMOVED); + dbTester.rules().update(rule); + dbSession.commit(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + + List newRules = singletonList(newRule); + assertThatThrownBy(() -> underTest.create(dbSession, newRules)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The template key doesn't exist: java:S001"); + } + + @Test + public void fail_to_create_custom_rule_with_invalid_parameter() { + // insert template rule + RuleDto templateRule = createTemplateRuleWithIntArrayParam(); + + assertThatThrownBy(() -> { + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("myIntegers", "1,polop,2")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("Value 'polop' must be an integer."); + } + + @Test + public void fail_to_create_custom_rule_with_invalid_parameters() { + // insert template rule + RuleDto templateRule = createTemplateRuleWithTwoIntParams(); + + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("first", "polop", "second", "palap")); + try { + underTest.create(dbSession, newRule); + Fail.failBecauseExceptionWasNotThrown(BadRequestException.class); + } catch (BadRequestException badRequest) { + assertThat(badRequest.errors().toString()).contains("palap").contains("polop"); } - - @Test - public void create_custom_rule_with_empty_parameter_value() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "")); - - RuleKey customRuleKey = underTest.create(dbSession, newRule); - - List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); - assertThat(params).hasSize(1); - RuleParamDto param = params.get(0); - assertThat(param.getName()).isEqualTo("regex"); - assertThat(param.getDescription()).isEqualTo("Reg ex"); - assertThat(param.getType()).isEqualTo("STRING"); - assertThat(param.getDefaultValue()).isNull(); - } - - @Test - public void create_custom_rule_with_no_parameter_value() { - // insert template rule - RuleDto templateRule = createTemplateRuleWithIntArrayParam(); - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - - RuleKey customRuleKey = underTest.create(dbSession, newRule); - - List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); - assertThat(params).hasSize(1); - RuleParamDto param = params.get(0); - assertThat(param.getName()).isEqualTo("myIntegers"); - assertThat(param.getDescription()).isEqualTo("My Integers"); - assertThat(param.getType()).isEqualTo("INTEGER,multiple=true,values=1;2;3"); - assertThat(param.getDefaultValue()).isNull(); - } - - @Test - public void create_custom_rule_with_multiple_parameter_values() { - // insert template rule - RuleDto templateRule = createTemplateRuleWithIntArrayParam(); - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("myIntegers", "1,3")); - - RuleKey customRuleKey = underTest.create(dbSession, newRule); - - List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); - assertThat(params).hasSize(1); - RuleParamDto param = params.get(0); - assertThat(param.getName()).isEqualTo("myIntegers"); - assertThat(param.getDescription()).isEqualTo("My Integers"); - assertThat(param.getType()).isEqualTo("INTEGER,multiple=true,values=1;2;3"); - assertThat(param.getDefaultValue()).isEqualTo("1,3"); - } - - @Test - public void batch_create_custom_rules() { - // insert template rule - RuleDto templateRule = createTemplateRuleWithIntArrayParam(); - - NewCustomRule firstRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_1", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - - NewCustomRule secondRule = NewCustomRule.createForCustomRule("CUSTOM_RULE_2", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - - List customRuleKeys = underTest.create(dbSession, Arrays.asList(firstRule, secondRule)); - - List rules = dbTester.getDbClient().ruleDao().selectByKeys(dbSession, customRuleKeys); - - assertThat(rules).hasSize(2); - assertThat(rules).asList() - .extracting("ruleKey") - .containsOnly("CUSTOM_RULE_1", "CUSTOM_RULE_2"); - } - - @Test - public void fail_to_create_custom_rules_when_wrong_rule_template() { - // insert rule - RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false); - dbTester.rules().insert(rule); - dbSession.commit(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, singletonList(newRule))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("This rule is not a template rule: java:S001"); - } - - @Test - public void fail_to_create_custom_rules_when_removed_rule_template() { - // insert rule - RuleDto rule = createTemplateRule(); newRule(RuleKey.of("java", "S001")).setIsTemplate(false); - rule.setStatus(RuleStatus.REMOVED); - dbTester.rules().update(rule); - dbSession.commit(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - - List newRules = singletonList(newRule); - assertThatThrownBy(() -> underTest.create(dbSession, newRules)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The template key doesn't exist: java:S001"); - } - - @Test - public void fail_to_create_custom_rule_with_invalid_parameter() { - // insert template rule - RuleDto templateRule = createTemplateRuleWithIntArrayParam(); - - assertThatThrownBy(() -> { - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("myIntegers", "1,polop,2")); - underTest.create(dbSession, newRule); - }) - .isInstanceOf(BadRequestException.class) - .hasMessage("Value 'polop' must be an integer."); - } - - @Test - public void fail_to_create_custom_rule_with_invalid_parameters() { - // insert template rule - RuleDto templateRule = createTemplateRuleWithTwoIntParams(); - - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("first", "polop", "second", "palap")); - try { - underTest.create(dbSession, newRule); - Fail.failBecauseExceptionWasNotThrown(BadRequestException.class); - } catch (BadRequestException badRequest) { - assertThat(badRequest.errors().toString()).contains("palap").contains("polop"); - } - } - - @Test - public void fail_to_create_custom_rule_with_empty_description() { - // insert template rule - RuleDto templateRule = createTemplateRuleWithTwoIntParams(); - - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setMarkdownDescription(""); - assertThatExceptionOfType(BadRequestException.class) - .isThrownBy(() -> underTest.create(dbSession, newRule)) - .withMessage("The description is missing"); - } - - @Test - public void reactivate_custom_rule_if_already_exists_in_removed_status() { - String key = "CUSTOM_RULE"; - - // insert template rule - RuleDto templateRule = createTemplateRule(); - - // insert a removed rule - RuleDto rule = RuleTesting.newCustomRule(templateRule) - .setRuleKey(key) - .setStatus(RuleStatus.REMOVED) - .setName("Old name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description")) - .setDescriptionFormat(Format.MARKDOWN) - .setSeverity(Severity.INFO); - dbTester.rules().insert(rule); - dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*")); - dbSession.commit(); - - // Create custom rule with same key, but with different values - NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey()) - .setName("New name") - .setMarkdownDescription("New description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "c.*")); - RuleKey customRuleKey = underTest.create(dbSession, newRule); - - RuleDto result = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey); - assertThat(result.getKey()).isEqualTo(RuleKey.of("java", key)); - assertThat(result.getStatus()).isEqualTo(RuleStatus.READY); - - // These values should be the same than before - assertThat(result.getName()).isEqualTo("Old name"); - assertThat(result.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Old description"); - assertThat(result.getSeverityString()).isEqualTo(Severity.INFO); - - List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); - assertThat(params).hasSize(1); - assertThat(params.get(0).getDefaultValue()).isEqualTo("a.*"); - } - - @Test - public void generate_reactivation_exception_when_rule_exists_in_removed_status_and_prevent_reactivation_parameter_is_true() { - String key = "CUSTOM_RULE"; - // insert template rule - RuleDto templateRule = createTemplateRule(); - // insert a removed rule - RuleDto rule = RuleTesting.newCustomRule(templateRule) - .setRuleKey(key) - .setStatus(RuleStatus.REMOVED) - .setName("Old name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description")) - .setSeverity(Severity.INFO); - dbTester.rules().insert(rule); - dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*")); - dbSession.commit(); - - // Create custom rule with same key, but with different values - NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey()) - .setName("New name") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "c.*")) - .setPreventReactivation(true); - - try { - underTest.create(dbSession, newRule); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(ReactivationException.class); - ReactivationException reactivationException = (ReactivationException) e; - assertThat(reactivationException.ruleKey()).isEqualTo(rule.getKey()); - } - } - - @Test - public void fail_to_create_custom_rule_when_invalid_key() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("*INVALID*", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule)) - .isInstanceOf(BadRequestException.class) - .hasMessage("The rule key \"*INVALID*\" is invalid, it should only contain: a-z, 0-9, \"_\""); - } - - @Test - public void fail_to_create_custom_rule_when_rule_key_already_exists() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - // Create a custom rule - AtomicReference newRule = new AtomicReference<>(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*"))); - underTest.create(dbSession, newRule.get()); - - // Create another custom rule having same key - newRule.set(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My another custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*"))); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule.get())) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("A rule with the key 'CUSTOM_RULE' already exists"); - } - - @Test - public void fail_to_create_custom_rule_when_missing_name() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule)) - .isInstanceOf(BadRequestException.class) - .hasMessage("The name is missing"); - } - - @Test - public void fail_to_create_custom_rule_when_missing_description() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - - assertThatThrownBy(() -> { - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - underTest.create(dbSession, newRule); - }) - .isInstanceOf(BadRequestException.class) - .hasMessage("The description is missing"); - } - - @Test - public void fail_to_create_custom_rule_when_missing_severity() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule)) - .isInstanceOf(BadRequestException.class) - .hasMessage("The severity is missing"); - } - - @Test - public void fail_to_create_custom_rule_when_invalid_severity() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity("INVALID") - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule)) - .isInstanceOf(BadRequestException.class) - .hasMessage("Severity \"INVALID\" is invalid"); - } - - @Test - public void fail_to_create_custom_rule_when_missing_status() { - // insert template rule - RuleDto templateRule = createTemplateRule(); - - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule)) - .isInstanceOf(BadRequestException.class) - .hasMessage("The status is missing"); - } - - @Test - public void fail_to_create_custom_rule_when_wrong_rule_template() { - // insert rule - RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false); - dbTester.rules().insert(rule); - dbSession.commit(); - - // Create custom rule with unknown template rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) - .setName("My custom") - .setMarkdownDescription("some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY) - .setParameters(ImmutableMap.of("regex", "a.*")); - - assertThatThrownBy(() -> underTest.create(dbSession, newRule)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("This rule is not a template rule: java:S001"); - } - - @Test - public void fail_to_create_custom_rule_when_null_template() { - assertThatThrownBy(() -> { - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", null) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - underTest.create(dbSession, newRule); - }) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Template key should be set"); - } - - @Test - public void fail_to_create_custom_rule_when_unknown_template() { - assertThatThrownBy(() -> { - // Create custom rule - NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", RuleKey.of("java", "S001")) - .setName("My custom") - .setMarkdownDescription("Some description") - .setSeverity(Severity.MAJOR) - .setStatus(RuleStatus.READY); - underTest.create(dbSession, newRule); - }) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The template key doesn't exist: java:S001"); - } - - private RuleDto createTemplateRule() { - RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")) - .setIsTemplate(true) - .setLanguage("java") - .setPluginKey("sonarjava") - .setConfigKey("S001") - .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) - .setDefRemediationGapMultiplier("1h") - .setDefRemediationBaseEffort("5min") - .setGapDescription("desc") - .setTags(Sets.newHashSet("usertag1", "usertag2")) - .setSystemTags(Sets.newHashSet("tag1", "tag4")) - .setSecurityStandards(Sets.newHashSet("owaspTop10:a1", "cwe:123")) - .setCreatedAt(new Date().getTime()) - .setUpdatedAt(new Date().getTime()); - dbTester.rules().insert(templateRule); - dbTester.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*")); - ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid()); - return templateRule; - } - - private RuleDto createTemplateRuleWithIntArrayParam() { - RuleDto templateRule = newRule(RuleKey.of("java", "S002")) - .setIsTemplate(true) - .setLanguage("java") - .setConfigKey("S002") - .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) - .setDefRemediationGapMultiplier("1h") - .setDefRemediationBaseEffort("5min") - .setGapDescription("desc") - .setCreatedAt(new Date().getTime()) - .setUpdatedAt(new Date().getTime()); - dbTester.rules().insert(templateRule); - dbTester.rules().insertRuleParam(templateRule, - param -> param.setName("myIntegers").setType("INTEGER,multiple=true,values=1;2;3").setDescription("My Integers").setDefaultValue("1")); - ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid()); - return templateRule; - } - - private RuleDto createTemplateRuleWithTwoIntParams() { - RuleDto templateRule = newRule(RuleKey.of("java", "S003")) - .setIsTemplate(true) - .setLanguage("java") - .setConfigKey("S003") - .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) - .setDefRemediationGapMultiplier("1h") - .setDefRemediationBaseEffort("5min") - .setGapDescription("desc") - .setCreatedAt(new Date().getTime()) - .setUpdatedAt(new Date().getTime()); - dbTester.rules().insert(templateRule); - dbTester.rules().insertRuleParam(templateRule, param -> param.setName("first").setType("INTEGER").setDescription("First integer").setDefaultValue("0")); - dbTester.rules().insertRuleParam(templateRule, param -> param.setName("second").setType("INTEGER").setDescription("Second integer").setDefaultValue("0")); - return templateRule; + } + + @Test + public void fail_to_create_custom_rule_with_empty_description() { + // insert template rule + RuleDto templateRule = createTemplateRuleWithTwoIntParams(); + + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setMarkdownDescription(""); + assertThatExceptionOfType(BadRequestException.class) + .isThrownBy(() -> underTest.create(dbSession, newRule)) + .withMessage("The description is missing"); + } + + @Test + public void reactivate_custom_rule_if_already_exists_in_removed_status() { + String key = "CUSTOM_RULE"; + + RuleDto templateRule = createTemplateRule(); + + RuleDto rule = newCustomRule(templateRule, "Old description") + .setRuleKey(key) + .setStatus(RuleStatus.REMOVED) + .setName("Old name") + .setDescriptionFormat(Format.MARKDOWN) + .setSeverity(Severity.INFO); + dbTester.rules().insert(rule); + dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*")); + dbSession.commit(); + + // Create custom rule with same key, but with different values + NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey()) + .setName("New name") + .setMarkdownDescription("New description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "c.*")); + RuleKey customRuleKey = underTest.create(dbSession, newRule); + + RuleDto result = dbTester.getDbClient().ruleDao().selectOrFailByKey(dbSession, customRuleKey); + assertThat(result.getKey()).isEqualTo(RuleKey.of("java", key)); + assertThat(result.getStatus()).isEqualTo(RuleStatus.READY); + + // These values should be the same than before + assertThat(result.getName()).isEqualTo("Old name"); + assertThat(result.getDefaultRuleDescriptionSection().getContent()).isEqualTo("Old description"); + assertThat(result.getSeverityString()).isEqualTo(Severity.INFO); + + List params = dbTester.getDbClient().ruleDao().selectRuleParamsByRuleKey(dbSession, customRuleKey); + assertThat(params).hasSize(1); + assertThat(params.get(0).getDefaultValue()).isEqualTo("a.*"); + } + + @Test + public void generate_reactivation_exception_when_rule_exists_in_removed_status_and_prevent_reactivation_parameter_is_true() { + String key = "CUSTOM_RULE"; + + RuleDto templateRule = createTemplateRule(); + + RuleDto rule = newCustomRule(templateRule, "Old description") + .setRuleKey(key) + .setStatus(RuleStatus.REMOVED) + .setName("Old name") + .setSeverity(Severity.INFO); + dbTester.rules().insert(rule); + dbTester.rules().insertRuleParam(rule, param -> param.setDefaultValue("a.*")); + dbSession.commit(); + + // Create custom rule with same key, but with different values + NewCustomRule newRule = NewCustomRule.createForCustomRule(key, templateRule.getKey()) + .setName("New name") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "c.*")) + .setPreventReactivation(true); + + try { + underTest.create(dbSession, newRule); + fail(); + } catch (Exception e) { + assertThat(e).isInstanceOf(ReactivationException.class); + ReactivationException reactivationException = (ReactivationException) e; + assertThat(reactivationException.ruleKey()).isEqualTo(rule.getKey()); } + } + + @Test + public void fail_to_create_custom_rule_when_invalid_key() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("*INVALID*", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule)) + .isInstanceOf(BadRequestException.class) + .hasMessage("The rule key \"*INVALID*\" is invalid, it should only contain: a-z, 0-9, \"_\""); + } + + @Test + public void fail_to_create_custom_rule_when_rule_key_already_exists() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + // Create a custom rule + AtomicReference newRule = new AtomicReference<>(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*"))); + underTest.create(dbSession, newRule.get()); + + // Create another custom rule having same key + newRule.set(NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My another custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*"))); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule.get())) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("A rule with the key 'CUSTOM_RULE' already exists"); + } + + @Test + public void fail_to_create_custom_rule_when_missing_name() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule)) + .isInstanceOf(BadRequestException.class) + .hasMessage("The name is missing"); + } + + @Test + public void fail_to_create_custom_rule_when_missing_description() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + + assertThatThrownBy(() -> { + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(BadRequestException.class) + .hasMessage("The description is missing"); + } + + @Test + public void fail_to_create_custom_rule_when_missing_severity() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule)) + .isInstanceOf(BadRequestException.class) + .hasMessage("The severity is missing"); + } + + @Test + public void fail_to_create_custom_rule_when_invalid_severity() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity("INVALID") + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule)) + .isInstanceOf(BadRequestException.class) + .hasMessage("Severity \"INVALID\" is invalid"); + } + + @Test + public void fail_to_create_custom_rule_when_missing_status() { + // insert template rule + RuleDto templateRule = createTemplateRule(); + + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", templateRule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule)) + .isInstanceOf(BadRequestException.class) + .hasMessage("The status is missing"); + } + + @Test + public void fail_to_create_custom_rule_when_wrong_rule_template() { + // insert rule + RuleDto rule = newRule(RuleKey.of("java", "S001")).setIsTemplate(false); + dbTester.rules().insert(rule); + dbSession.commit(); + + // Create custom rule with unknown template rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", rule.getKey()) + .setName("My custom") + .setMarkdownDescription("some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY) + .setParameters(ImmutableMap.of("regex", "a.*")); + + assertThatThrownBy(() -> underTest.create(dbSession, newRule)) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("This rule is not a template rule: java:S001"); + } + + @Test + public void fail_to_create_custom_rule_when_null_template() { + assertThatThrownBy(() -> { + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", null) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("Template key should be set"); + } + + @Test + public void fail_to_create_custom_rule_when_unknown_template() { + assertThatThrownBy(() -> { + // Create custom rule + NewCustomRule newRule = NewCustomRule.createForCustomRule("CUSTOM_RULE", RuleKey.of("java", "S001")) + .setName("My custom") + .setMarkdownDescription("Some description") + .setSeverity(Severity.MAJOR) + .setStatus(RuleStatus.READY); + underTest.create(dbSession, newRule); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("The template key doesn't exist: java:S001"); + } + + private RuleDto createTemplateRule() { + RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")) + .setIsTemplate(true) + .setLanguage("java") + .setPluginKey("sonarjava") + .setConfigKey("S001") + .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) + .setDefRemediationGapMultiplier("1h") + .setDefRemediationBaseEffort("5min") + .setGapDescription("desc") + .setTags(Sets.newHashSet("usertag1", "usertag2")) + .setSystemTags(Sets.newHashSet("tag1", "tag4")) + .setSecurityStandards(Sets.newHashSet("owaspTop10:a1", "cwe:123")) + .setCreatedAt(new Date().getTime()) + .setUpdatedAt(new Date().getTime()); + dbTester.rules().insert(templateRule); + dbTester.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*")); + ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid()); + return templateRule; + } + + private RuleDto createTemplateRuleWithIntArrayParam() { + RuleDto templateRule = newRule(RuleKey.of("java", "S002")) + .setIsTemplate(true) + .setLanguage("java") + .setConfigKey("S002") + .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) + .setDefRemediationGapMultiplier("1h") + .setDefRemediationBaseEffort("5min") + .setGapDescription("desc") + .setCreatedAt(new Date().getTime()) + .setUpdatedAt(new Date().getTime()); + dbTester.rules().insert(templateRule); + dbTester.rules().insertRuleParam(templateRule, + param -> param.setName("myIntegers").setType("INTEGER,multiple=true,values=1;2;3").setDescription("My Integers").setDefaultValue("1")); + ruleIndexer.commitAndIndex(dbTester.getSession(), templateRule.getUuid()); + return templateRule; + } + + private RuleDto createTemplateRuleWithTwoIntParams() { + RuleDto templateRule = newRule(RuleKey.of("java", "S003")) + .setIsTemplate(true) + .setLanguage("java") + .setConfigKey("S003") + .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) + .setDefRemediationGapMultiplier("1h") + .setDefRemediationBaseEffort("5min") + .setGapDescription("desc") + .setCreatedAt(new Date().getTime()) + .setUpdatedAt(new Date().getTime()); + dbTester.rules().insert(templateRule); + dbTester.rules().insertRuleParam(templateRule, param -> param.setName("first").setType("INTEGER").setDescription("First integer").setDefaultValue("0")); + dbTester.rules().insertRuleParam(templateRule, param -> param.setName("second").setType("INTEGER").setDescription("Second integer").setDefaultValue("0")); + return templateRule; + } } diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java index 87740b34044..6a6187d642e 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/RuleUpdaterTest.java @@ -60,6 +60,7 @@ import static org.sonar.api.rule.Severity.CRITICAL; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.db.rule.RuleTesting.newCustomRule; import static org.sonar.db.rule.RuleTesting.newRule; +import static org.sonar.db.rule.RuleTesting.newTemplateRule; import static org.sonar.server.rule.RuleUpdate.createForCustomRule; import static org.sonar.server.rule.RuleUpdate.createForPluginRule; @@ -329,19 +330,15 @@ public class RuleUpdaterTest { @Test public void update_custom_rule() { - // Create template rule - RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")); + RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")); db.rules().insert(templateRule); db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*")); db.rules().insertRuleParam(templateRule, param -> param.setName("format").setType("STRING").setDescription("Format")); - // Create custom rule - RuleDto customRule = newCustomRule(templateRule) + RuleDto customRule = newCustomRule(templateRule, "Old description") .setName("Old name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description")) .setSeverity(Severity.MINOR) - .setStatus(RuleStatus.BETA) - ; + .setStatus(RuleStatus.BETA); db.rules().insert(customRule); db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue("a.*")); db.rules().insertRuleParam(customRule, param -> param.setName("format").setType("STRING").setDescription("Format").setDefaultValue(null)); @@ -378,15 +375,12 @@ public class RuleUpdaterTest { @Test public void update_custom_rule_with_empty_parameter() { - // Create template rule - RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")); + RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")); db.rules().insert(templateRule); db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(null)); - // Create custom rule - RuleDto customRule = newCustomRule(templateRule) + RuleDto customRule = newCustomRule(templateRule, "Old description") .setName("Old name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Old description")) .setSeverity(Severity.MINOR) .setStatus(RuleStatus.BETA); db.rules().insert(customRule); @@ -412,7 +406,7 @@ public class RuleUpdaterTest { @Test public void update_active_rule_parameters_when_updating_custom_rule() { // Create template rule with 3 parameters - RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")).setLanguage("xoo"); + RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")).setLanguage("xoo"); RuleDto templateRuleDefinition = templateRule; db.rules().insert(templateRuleDefinition); db.rules().insertRuleParam(templateRuleDefinition, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*")); @@ -422,8 +416,7 @@ public class RuleUpdaterTest { // Create custom rule RuleDto customRule = newCustomRule(templateRule) .setSeverity(Severity.MAJOR) - .setLanguage("xoo") - ; + .setLanguage("xoo"); db.rules().insert(customRule); RuleParamDto ruleParam1 = db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue("a.*")); db.rules().insertRuleParam(customRule, param -> param.setName("format").setType("STRING").setDescription("format").setDefaultValue("txt")); @@ -481,7 +474,7 @@ public class RuleUpdaterTest { @Test public void fail_to_update_custom_rule_when_empty_name() { // Create template rule - RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")); + RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")); db.rules().insert(templateRule); // Create custom rule @@ -505,7 +498,7 @@ public class RuleUpdaterTest { @Test public void fail_to_update_custom_rule_when_empty_description() { // Create template rule - RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001")); + RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")); db.rules().insert(templateRule); // Create custom rule diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java index 224ded60971..a7049f16270 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/CreateActionTest.java @@ -59,7 +59,7 @@ import static org.sonar.test.JsonAssert.assertJson; public class CreateActionTest { - private System2 system2 = mock(System2.class); + private final System2 system2 = mock(System2.class); @Rule public UserSessionRule userSession = UserSessionRule.standalone(); @@ -70,9 +70,9 @@ public class CreateActionTest { @Rule public EsTester es = EsTester.create(); - private UuidFactory uuidFactory = new SequenceUuidFactory(); + private final UuidFactory uuidFactory = new SequenceUuidFactory(); - private WsActionTester ws = new WsActionTester(new CreateAction(db.getDbClient(), + private final WsActionTester ws = new WsActionTester(new CreateAction(db.getDbClient(), new RuleCreator(system2, new RuleIndexer(es.client(), db.getDbClient()), db.getDbClient(), newFullTypeValidations(), uuidFactory), new RuleMapper(new Languages(), createMacroInterpreter(), new RuleDescriptionFormatter()), new RuleWsSupport(db.getDbClient(), userSession))); @@ -136,11 +136,10 @@ public class CreateActionTest { RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")); db.rules().insert(templateRule); // insert a removed rule - RuleDto customRule = newCustomRule(templateRule) + RuleDto customRule = newCustomRule(templateRule, "Description") .setRuleKey("MY_CUSTOM") .setStatus(RuleStatus.REMOVED) .setName("My custom rule") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "Description")) .setDescriptionFormat(RuleDto.Format.MARKDOWN) .setSeverity(Severity.MAJOR); db.rules().insert(customRule); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java index 8473e39c506..de9ff93ddda 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/SearchActionTest.java @@ -89,6 +89,7 @@ import static org.mockito.Mockito.mock; import static org.sonar.api.rule.Severity.BLOCKER; import static org.sonar.api.server.rule.RuleDescriptionSection.RuleDescriptionSectionKeys.RESOURCES_SECTION_KEY; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection; import static org.sonar.db.rule.RuleTesting.setSystemTags; import static org.sonar.db.rule.RuleTesting.setTags; @@ -242,11 +243,9 @@ public class SearchActionTest { @Test public void filter_by_rule_description() { - RuleDto rule1 = db.rules() - .insert( - r1 -> r1 - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "This is the best rule now&forever")) - .setNoteUserUuid(null)); + RuleDto rule1 = db.rules().insert( + newRule(createDefaultRuleDescriptionSection(uuidFactory.create(), "This is the best rule now&forever")) + .setNoteUserUuid(null)); db.rules().insert(r1 -> r1.setName("Some other stuff").setNoteUserUuid(null)); indexRules(); diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java index ca5824417d0..2645ff9c990 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/ShowActionTest.java @@ -64,6 +64,7 @@ import static org.sonar.db.rule.RuleDescriptionSectionDto.DEFAULT_KEY; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; import static org.sonar.db.rule.RuleDto.Format.MARKDOWN; import static org.sonar.db.rule.RuleTesting.newCustomRule; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.newRuleWithoutDescriptionSection; import static org.sonar.db.rule.RuleTesting.newTemplateRule; import static org.sonar.db.rule.RuleTesting.setTags; @@ -296,12 +297,10 @@ public class ShowActionTest { @Test public void encode_html_description_of_custom_rule() { - // Template rule RuleDto templateRule = newTemplateRule(RuleKey.of("java", "S001")); db.rules().insert(templateRule); - // Custom rule - RuleDto customRule = newCustomRule(templateRule) - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "
line1\nline2
")) + + RuleDto customRule = newCustomRule(templateRule, "
line1\nline2
") .setDescriptionFormat(MARKDOWN) .setNoteUserUuid(userDto.getUuid()); db.rules().insert(customRule); @@ -333,19 +332,16 @@ public class ShowActionTest { @Test public void show_adhoc_rule() { - RuleDto externalRule = db.rules().insert(r -> { - r.setIsExternal(true) - .setIsAdHoc(true) - .setAdHocName("adhoc name") - .setAdHocDescription("
desc
") - .setAdHocSeverity(Severity.BLOCKER) - .setAdHocType(RuleType.VULNERABILITY) - .setNoteData(null) - .setNoteUserUuid(null); - //Ad-hoc description has no description sections defined - r.getRuleDescriptionSectionDtos().clear(); - } - ); + //Ad-hoc description has no description sections defined + RuleDto externalRule = db.rules().insert(newRuleWithoutDescriptionSection() + .setIsExternal(true) + .setIsAdHoc(true) + .setAdHocName("adhoc name") + .setAdHocDescription("
desc
") + .setAdHocSeverity(Severity.BLOCKER) + .setAdHocType(RuleType.VULNERABILITY) + .setNoteData(null) + .setNoteUserUuid(null)); doReturn("<div>desc2</div>").when(macroInterpreter).interpret(externalRule.getAdHocDescription()); @@ -435,11 +431,10 @@ public class ShowActionTest { @Test public void ignore_predefined_info_on_adhoc_rule() { - RuleDto externalRule = db.rules().insert(r -> r + RuleDto externalRule = newRule(createDefaultRuleDescriptionSection(uuidFactory.create(), "
predefined desc
")) .setIsExternal(true) .setIsAdHoc(true) .setName("predefined name") - .replaceRuleDescriptionSectionDtos(createDefaultRuleDescriptionSection(uuidFactory.create(), "
predefined desc
")) .setSeverity(Severity.BLOCKER) .setType(RuleType.VULNERABILITY) .setAdHocName("adhoc name") @@ -447,7 +442,8 @@ public class ShowActionTest { .setAdHocSeverity(Severity.MAJOR) .setAdHocType(RuleType.CODE_SMELL) .setNoteData(null) - .setNoteUserUuid(null)); + .setNoteUserUuid(null); + externalRule = db.rules().insert(externalRule); doReturn("<div>adhoc desc</div>").when(macroInterpreter).interpret(externalRule.getAdHocDescription()); ShowResponse result = ws.newRequest() diff --git a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java index c2c6065d7e4..dbfa793c7ee 100644 --- a/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java +++ b/server/sonar-webserver-webapi/src/test/java/org/sonar/server/rule/ws/UpdateActionTest.java @@ -56,6 +56,7 @@ import static org.sonar.api.server.debt.DebtRemediationFunction.Type.LINEAR; import static org.sonar.api.server.debt.DebtRemediationFunction.Type.LINEAR_OFFSET; import static org.sonar.db.permission.GlobalPermission.ADMINISTER_QUALITY_PROFILES; import static org.sonar.db.rule.RuleDescriptionSectionDto.createDefaultRuleDescriptionSection; +import static org.sonar.db.rule.RuleTesting.newRule; import static org.sonar.db.rule.RuleTesting.setSystemTags; import static org.sonar.db.rule.RuleTesting.setTags; import static org.sonar.server.rule.ws.UpdateAction.PARAM_KEY; @@ -79,18 +80,18 @@ public class UpdateActionTest { @Rule public UserSessionRule userSession = UserSessionRule.standalone(); - private DbClient dbClient = db.getDbClient(); - private EsClient esClient = es.client(); - private RuleDescriptionFormatter ruleDescriptionFormatter = new RuleDescriptionFormatter(); + private final DbClient dbClient = db.getDbClient(); + private final EsClient esClient = es.client(); + private final RuleDescriptionFormatter ruleDescriptionFormatter = new RuleDescriptionFormatter(); - private Languages languages = new Languages(); - private RuleMapper mapper = new RuleMapper(languages, createMacroInterpreter(), ruleDescriptionFormatter); - private RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient); - private UuidFactoryFast uuidFactory = UuidFactoryFast.getInstance(); + private final Languages languages = new Languages(); + private final RuleMapper mapper = new RuleMapper(languages, createMacroInterpreter(), ruleDescriptionFormatter); + private final RuleIndexer ruleIndexer = new RuleIndexer(esClient, dbClient); + private final UuidFactoryFast uuidFactory = UuidFactoryFast.getInstance(); - private RuleUpdater ruleUpdater = new RuleUpdater(dbClient, ruleIndexer, uuidFactory, System2.INSTANCE); - private WsAction underTest = new UpdateAction(dbClient, ruleUpdater, mapper, userSession, new RuleWsSupport(db.getDbClient(), userSession)); - private WsActionTester ws = new WsActionTester(underTest); + private final RuleUpdater ruleUpdater = new RuleUpdater(dbClient, ruleIndexer, uuidFactory, System2.INSTANCE); + private final WsAction underTest = new UpdateAction(dbClient, ruleUpdater, mapper, userSession, new RuleWsSupport(db.getDbClient(), userSession)); + private final WsActionTester ws = new WsActionTester(underTest); @Test public void check_definition() { @@ -110,17 +111,17 @@ public class UpdateActionTest { r -> r.setCreatedAt(PAST), r -> r.setUpdatedAt(PAST)); db.rules().insertRuleParam(templateRule, param -> param.setName("regex").setType("STRING").setDescription("Reg ex").setDefaultValue(".*")); - RuleDto customRule = db.rules().insert( - r -> r.setRuleKey(RuleKey.of("java", "MY_CUSTOM")), - r -> r.setName("Old custom"), - r -> r.replaceRuleDescriptionSectionDtos(createRuleDescriptionSectionDto()), - r -> r.setSeverity(Severity.MINOR), - r -> r.setStatus(RuleStatus.BETA), - r -> r.setTemplateUuid(templateRule.getUuid()), - r -> r.setLanguage("js"), - r -> r.setNoteUserUuid(null), - r -> r.setCreatedAt(PAST), - r -> r.setUpdatedAt(PAST)); + + RuleDto customRule = newRule(RuleKey.of("java", "MY_CUSTOM"), createRuleDescriptionSectionDto()) + .setName("Old custom") + .setSeverity(Severity.MINOR) + .setStatus(RuleStatus.BETA) + .setTemplateUuid(templateRule.getUuid()) + .setLanguage("js") + .setNoteUserUuid(null) + .setCreatedAt(PAST) + .setUpdatedAt(PAST); + customRule = db.rules().insert(customRule); db.rules().insertRuleParam(customRule, param -> param.setName("regex").setType("a").setDescription("Reg ex")); TestResponse request = ws.newRequest().setMethod("POST") @@ -246,13 +247,14 @@ public class UpdateActionTest { r -> r.setIsTemplate(true), r -> r.setCreatedAt(PAST), r -> r.setUpdatedAt(PAST)); + RuleDto customRule = db.rules().insert( - r -> r.setRuleKey(RuleKey.of("java", "MY_CUSTOM")), - r -> r.setName("Old custom"), - r -> r.replaceRuleDescriptionSectionDtos(createRuleDescriptionSectionDto()), - r -> r.setTemplateUuid(templateRule.getUuid()), - r -> r.setCreatedAt(PAST), - r -> r.setUpdatedAt(PAST)); + newRule(RuleKey.of("java", "MY_CUSTOM"), createRuleDescriptionSectionDto()) + .setRuleKey(RuleKey.of("java", "MY_CUSTOM")) + .setName("Old custom") + .setTemplateUuid(templateRule.getUuid()) + .setCreatedAt(PAST) + .setUpdatedAt(PAST)); assertThatThrownBy(() -> { ws.newRequest().setMethod("POST") -- 2.39.5