You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

RuleDaoIT.java 59KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. /*
  2. * SonarQube
  3. * Copyright (C) 2009-2023 SonarSource SA
  4. * mailto:info AT sonarsource DOT com
  5. *
  6. * This program is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation; either
  9. * version 3 of the License, or (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public License
  17. * along with this program; if not, write to the Free Software Foundation,
  18. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  19. */
  20. package org.sonar.db.rule;
  21. import com.google.common.collect.ImmutableSet;
  22. import com.google.common.collect.MoreCollectors;
  23. import java.util.ArrayList;
  24. import java.util.Arrays;
  25. import java.util.Collections;
  26. import java.util.Iterator;
  27. import java.util.List;
  28. import java.util.Optional;
  29. import java.util.Set;
  30. import java.util.function.Consumer;
  31. import java.util.function.Function;
  32. import org.apache.commons.lang.RandomStringUtils;
  33. import org.apache.ibatis.exceptions.PersistenceException;
  34. import org.jetbrains.annotations.NotNull;
  35. import org.junit.Rule;
  36. import org.junit.Test;
  37. import org.sonar.api.issue.impact.SoftwareQuality;
  38. import org.sonar.api.rule.RuleKey;
  39. import org.sonar.api.rule.RuleStatus;
  40. import org.sonar.api.rule.Severity;
  41. import org.sonar.api.rules.CleanCodeAttribute;
  42. import org.sonar.api.rules.RuleQuery;
  43. import org.sonar.api.rules.RuleType;
  44. import org.sonar.api.server.debt.DebtRemediationFunction;
  45. import org.sonar.api.utils.DateUtils;
  46. import org.sonar.api.utils.System2;
  47. import org.sonar.core.util.UuidFactoryFast;
  48. import org.sonar.db.DbSession;
  49. import org.sonar.db.DbTester;
  50. import org.sonar.db.Pagination;
  51. import org.sonar.db.RowNotFoundException;
  52. import org.sonar.db.issue.ImpactDto;
  53. import org.sonar.db.qualityprofile.QProfileDto;
  54. import org.sonar.db.rule.RuleDto.Scope;
  55. import static com.google.common.collect.Sets.newHashSet;
  56. import static java.util.Arrays.asList;
  57. import static java.util.Collections.emptyList;
  58. import static java.util.Collections.singletonList;
  59. import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
  60. import static org.assertj.core.api.Assertions.assertThat;
  61. import static org.assertj.core.api.Assertions.assertThatThrownBy;
  62. import static org.assertj.core.api.Assertions.tuple;
  63. import static org.sonar.api.issue.impact.SoftwareQuality.MAINTAINABILITY;
  64. import static org.sonar.api.issue.impact.SoftwareQuality.RELIABILITY;
  65. import static org.sonar.api.issue.impact.SoftwareQuality.SECURITY;
  66. import static org.sonar.api.rule.RuleStatus.DEPRECATED;
  67. import static org.sonar.api.rule.RuleStatus.READY;
  68. import static org.sonar.api.rule.RuleStatus.REMOVED;
  69. import static org.sonar.db.Pagination.forPage;
  70. import static org.sonar.db.rule.RuleListQuery.RuleListQueryBuilder.newRuleListQueryBuilder;
  71. public class RuleDaoIT {
  72. private static final String UNKNOWN_RULE_UUID = "unknown-uuid";
  73. @Rule
  74. public DbTester db = DbTester.create(System2.INSTANCE);
  75. private final RuleDao underTest = db.getDbClient().ruleDao();
  76. @Test
  77. public void selectByKey() {
  78. RuleDto ruleDto = db.rules().insert(r -> r.addDefaultImpact(newRuleDefaultImpact(SECURITY, org.sonar.api.issue.impact.Severity.LOW)));
  79. assertThat(underTest.selectByKey(db.getSession(), RuleKey.of("foo", "bar")))
  80. .isEmpty();
  81. RuleDto actualRule = underTest.selectByKey(db.getSession(), ruleDto.getKey()).get();
  82. assertEquals(actualRule, ruleDto);
  83. assertThat(actualRule.getDefaultImpacts())
  84. .extracting(ImpactDto::getSoftwareQuality, ImpactDto::getSeverity)
  85. .containsExactlyInAnyOrder(
  86. tuple(MAINTAINABILITY, org.sonar.api.issue.impact.Severity.HIGH),
  87. tuple(SECURITY, org.sonar.api.issue.impact.Severity.LOW));
  88. }
  89. @Test
  90. public void selectByKey_return_rule() {
  91. RuleDto ruleDto = db.rules().insert();
  92. assertThat(underTest.selectByKey(db.getSession(), ruleDto.getKey())).isNotEmpty();
  93. }
  94. @Test
  95. public void selectByUuid() {
  96. RuleDto ruleDto = db.rules().insert();
  97. assertThat(underTest.selectByUuid(ruleDto.getUuid() + 500, db.getSession())).isEmpty();
  98. RuleDto actualRule = underTest.selectByUuid(ruleDto.getUuid(), db.getSession()).get();
  99. assertEquals(actualRule, ruleDto);
  100. }
  101. @Test
  102. public void selectByUuidWithDifferentValuesOfBooleans() {
  103. for (int i = 0; i < 3; i++) {
  104. int indexBoolean = i;
  105. RuleDto ruleDto = db.rules().insert((ruleDto1 -> {
  106. ruleDto1.setIsTemplate(indexBoolean == 0);
  107. ruleDto1.setIsExternal(indexBoolean == 1);
  108. ruleDto1.setIsAdHoc(indexBoolean == 2);
  109. }));
  110. assertThat(underTest.selectByUuid(ruleDto.getUuid() + 500, db.getSession())).isEmpty();
  111. RuleDto rule = underTest.selectByUuid(ruleDto.getUuid(), db.getSession()).get();
  112. assertEquals(rule, ruleDto);
  113. }
  114. }
  115. @Test
  116. public void selectDefinitionByUuid() {
  117. RuleDto rule = db.rules().insert();
  118. assertThat(underTest.selectByUuid(UNKNOWN_RULE_UUID, db.getSession())).isEmpty();
  119. Optional<RuleDto> ruleDtoOptional = underTest.selectByUuid(rule.getUuid(), db.getSession());
  120. assertThat(ruleDtoOptional).isPresent();
  121. }
  122. @Test
  123. public void selectByUuids() {
  124. RuleDto rule1 = db.rules().insert();
  125. RuleDto rule2 = db.rules().insert();
  126. RuleDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
  127. assertThat(underTest.selectByUuids(db.getSession(), singletonList(rule1.getUuid()))).hasSize(1);
  128. assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid()))).hasSize(2);
  129. assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), UNKNOWN_RULE_UUID))).hasSize(2);
  130. assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), removedRule.getUuid()))).hasSize(3);
  131. assertThat(underTest.selectByUuids(db.getSession(), singletonList(UNKNOWN_RULE_UUID))).isEmpty();
  132. }
  133. @Test
  134. public void selectDefinitionByUuids() {
  135. RuleDto rule1 = db.rules().insert();
  136. RuleDto rule2 = db.rules().insert();
  137. assertThat(underTest.selectByUuids(db.getSession(), singletonList(rule1.getUuid()))).hasSize(1);
  138. assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid()))).hasSize(2);
  139. assertThat(underTest.selectByUuids(db.getSession(), asList(rule1.getUuid(), rule2.getUuid(), UNKNOWN_RULE_UUID))).hasSize(2);
  140. assertThat(underTest.selectByUuids(db.getSession(), singletonList(UNKNOWN_RULE_UUID))).isEmpty();
  141. }
  142. @Test
  143. public void selectOrFailByKey() {
  144. RuleDto rule1 = db.rules().insert();
  145. db.rules().insert();
  146. RuleDto rule = underTest.selectOrFailByKey(db.getSession(), rule1.getKey());
  147. assertThat(rule.getUuid()).isEqualTo(rule1.getUuid());
  148. }
  149. @Test
  150. public void selectOrFailByKey_fails_if_rule_not_found() {
  151. DbSession session = db.getSession();
  152. RuleKey ruleKey = RuleKey.of("NOT", "FOUND");
  153. assertThatThrownBy(() -> underTest.selectOrFailByKey(session, ruleKey))
  154. .isInstanceOf(RowNotFoundException.class)
  155. .hasMessage("Rule with key 'NOT:FOUND' does not exist");
  156. }
  157. @Test
  158. public void selectByKeys() {
  159. RuleDto rule1 = db.rules().insert();
  160. db.rules().insert();
  161. assertThat(underTest.selectByKeys(db.getSession(), Collections.emptyList())).isEmpty();
  162. assertThat(underTest.selectByKeys(db.getSession(), singletonList(RuleKey.of("NOT", "FOUND")))).isEmpty();
  163. List<RuleDto> rules = underTest.selectByKeys(db.getSession(), asList(rule1.getKey(), RuleKey.of("java", "OTHER")));
  164. assertThat(rules).hasSize(1);
  165. assertThat(rules.get(0).getUuid()).isEqualTo(rule1.getUuid());
  166. }
  167. @Test
  168. public void selectDefinitionByKeys() {
  169. RuleDto rule = db.rules().insert();
  170. assertThat(underTest.selectByKeys(db.getSession(), Collections.emptyList())).isEmpty();
  171. assertThat(underTest.selectByKeys(db.getSession(), singletonList(RuleKey.of("NOT", "FOUND")))).isEmpty();
  172. List<RuleDto> rules = underTest.selectByKeys(db.getSession(), asList(rule.getKey(), RuleKey.of("java", "OTHER")));
  173. assertThat(rules).hasSize(1);
  174. assertThat(rules.get(0).getUuid()).isEqualTo(rule.getUuid());
  175. }
  176. @Test
  177. public void selectAll() {
  178. RuleDto rule1 = db.rules().insertRule(r -> r.addDefaultImpact(newRuleDefaultImpact(SECURITY, org.sonar.api.issue.impact.Severity.LOW)));
  179. RuleDto rule2 = db.rules().insertRule(r -> r.addDefaultImpact(newRuleDefaultImpact(RELIABILITY, org.sonar.api.issue.impact.Severity.MEDIUM)));
  180. RuleDto rule3 = db.rules().insertRule();
  181. List<RuleDto> ruleDtos = underTest.selectAll(db.getSession());
  182. assertThat(ruleDtos)
  183. .extracting(RuleDto::getUuid)
  184. .containsExactlyInAnyOrder(rule1.getUuid(), rule2.getUuid(), rule3.getUuid());
  185. assertThat(ruleDtos)
  186. .filteredOn(ruleDto -> ruleDto.getUuid().equals(rule1.getUuid()))
  187. .extracting(RuleDto::getDefaultImpacts)
  188. .flatMap(Function.identity())
  189. .extracting(ImpactDto::getSeverity, ImpactDto::getSoftwareQuality)
  190. .containsExactlyInAnyOrder(
  191. tuple(org.sonar.api.issue.impact.Severity.HIGH, MAINTAINABILITY),
  192. tuple(org.sonar.api.issue.impact.Severity.LOW, SECURITY));
  193. assertThat(ruleDtos)
  194. .filteredOn(ruleDto -> ruleDto.getUuid().equals(rule2.getUuid()))
  195. .extracting(RuleDto::getDefaultImpacts)
  196. .flatMap(Function.identity())
  197. .extracting(ImpactDto::getSeverity, ImpactDto::getSoftwareQuality)
  198. .containsExactlyInAnyOrder(
  199. tuple(org.sonar.api.issue.impact.Severity.HIGH, MAINTAINABILITY),
  200. tuple(org.sonar.api.issue.impact.Severity.MEDIUM, RELIABILITY));
  201. assertThat(ruleDtos)
  202. .filteredOn(ruleDto -> ruleDto.getUuid().equals(rule3.getUuid()))
  203. .extracting(RuleDto::getDefaultImpacts)
  204. .flatMap(Function.identity())
  205. .extracting(ImpactDto::getSeverity, ImpactDto::getSoftwareQuality)
  206. .containsExactlyInAnyOrder(
  207. tuple(org.sonar.api.issue.impact.Severity.HIGH, MAINTAINABILITY));
  208. }
  209. private void assertEquals(RuleDto actual, RuleDto expected) {
  210. assertThat(actual.getUuid()).isEqualTo(expected.getUuid());
  211. assertThat(actual.getRepositoryKey()).isEqualTo(expected.getRepositoryKey());
  212. assertThat(actual.getRuleKey()).isEqualTo(expected.getRuleKey());
  213. assertThat(actual.getKey()).isEqualTo(expected.getKey());
  214. assertThat(actual.getStatus()).isEqualTo(expected.getStatus());
  215. assertThat(actual.getName()).isEqualTo(expected.getName());
  216. assertThat(actual.getConfigKey()).isEqualTo(expected.getConfigKey());
  217. assertThat(actual.getSeverity()).isEqualTo(expected.getSeverity());
  218. assertThat(actual.getSeverityString()).isEqualTo(expected.getSeverityString());
  219. assertThat(actual.isExternal()).isEqualTo(expected.isExternal());
  220. assertThat(actual.isTemplate()).isEqualTo(expected.isTemplate());
  221. assertThat(actual.isCustomRule()).isEqualTo(expected.isCustomRule());
  222. assertThat(actual.getLanguage()).isEqualTo(expected.getLanguage());
  223. assertThat(actual.getTemplateUuid()).isEqualTo(expected.getTemplateUuid());
  224. assertThat(actual.getDefRemediationFunction()).isEqualTo(expected.getDefRemediationFunction());
  225. assertThat(actual.getDefRemediationGapMultiplier()).isEqualTo(expected.getDefRemediationGapMultiplier());
  226. assertThat(actual.getDefRemediationBaseEffort()).isEqualTo(expected.getDefRemediationBaseEffort());
  227. assertThat(actual.getGapDescription()).isEqualTo(expected.getGapDescription());
  228. assertThat(actual.getSystemTags()).isEqualTo(expected.getSystemTags());
  229. assertThat(actual.getSecurityStandards()).isEqualTo(expected.getSecurityStandards());
  230. assertThat(actual.getType()).isEqualTo(expected.getType());
  231. assertThat(actual.getDescriptionFormat()).isEqualTo(expected.getDescriptionFormat());
  232. assertThat(actual.getRemediationBaseEffort()).isEqualTo(expected.getRemediationBaseEffort());
  233. assertThat(actual.getRemediationFunction()).isEqualTo(expected.getRemediationFunction());
  234. assertThat(actual.getRemediationGapMultiplier()).isEqualTo(expected.getRemediationGapMultiplier());
  235. assertThat(actual.getTags()).isEqualTo(expected.getTags());
  236. assertThat(actual.getNoteData()).isEqualTo(expected.getNoteData());
  237. assertThat(actual.getNoteCreatedAt()).isEqualTo(expected.getNoteCreatedAt());
  238. assertThat(actual.getNoteUpdatedAt()).isEqualTo(expected.getNoteUpdatedAt());
  239. assertThat(actual.getAdHocName()).isEqualTo(expected.getAdHocName());
  240. assertThat(actual.getAdHocDescription()).isEqualTo(expected.getAdHocDescription());
  241. assertThat(actual.getAdHocSeverity()).isEqualTo(expected.getAdHocSeverity());
  242. assertThat(actual.getAdHocType()).isEqualTo(expected.getAdHocType());
  243. assertThat(actual.getRuleDescriptionSectionDtos()).usingRecursiveFieldByFieldElementComparator()
  244. .containsExactlyInAnyOrderElementsOf(expected.getRuleDescriptionSectionDtos());
  245. assertThat(actual.getEducationPrinciples()).isEqualTo(expected.getEducationPrinciples());
  246. assertThat(actual.getCleanCodeAttribute()).isEqualTo(expected.getCleanCodeAttribute());
  247. }
  248. @Test
  249. public void selectAllDefinitions() {
  250. RuleDto rule1 = db.rules().insert();
  251. RuleDto rule2 = db.rules().insert();
  252. RuleDto removedRule = db.rules().insert(r -> r.setStatus(REMOVED));
  253. List<RuleDto> ruleDtos = underTest.selectAll(db.getSession());
  254. assertThat(ruleDtos).extracting(RuleDto::getUuid).containsOnly(rule1.getUuid(), rule2.getUuid(), removedRule.getUuid());
  255. }
  256. @Test
  257. public void selectEnabled_with_ResultHandler() {
  258. RuleDto rule = db.rules().insert();
  259. db.rules().insert(r -> r.setStatus(REMOVED));
  260. List<RuleDto> rules = underTest.selectEnabled(db.getSession());
  261. assertThat(rules.size()).isOne();
  262. RuleDto ruleDto = rules.get(0);
  263. assertThat(ruleDto.getUuid()).isEqualTo(rule.getUuid());
  264. }
  265. @Test
  266. public void selectByTypeAndLanguages() {
  267. RuleDto rule1 = db.rules().insert(
  268. r -> r.setKey(RuleKey.of("java", "S001"))
  269. .setConfigKey("S1")
  270. .setType(RuleType.VULNERABILITY)
  271. .setLanguage("java"));
  272. RuleDto rule2 = db.rules().insert(
  273. r -> r.setKey(RuleKey.of("js", "S002"))
  274. .setType(RuleType.SECURITY_HOTSPOT)
  275. .setLanguage("js"));
  276. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.VULNERABILITY.getDbConstant()), singletonList("java")))
  277. .extracting(RuleDto::getUuid, RuleDto::getLanguage, RuleDto::getType)
  278. .containsExactly(tuple(rule1.getUuid(), "java", RuleType.VULNERABILITY.getDbConstant()));
  279. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.SECURITY_HOTSPOT.getDbConstant()), singletonList("js")))
  280. .extracting(RuleDto::getUuid, RuleDto::getLanguage, RuleDto::getType)
  281. .containsExactly(tuple(rule2.getUuid(), "js", RuleType.SECURITY_HOTSPOT.getDbConstant()));
  282. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.SECURITY_HOTSPOT.getDbConstant()), singletonList("java"))).isEmpty();
  283. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.VULNERABILITY.getDbConstant()), singletonList("js"))).isEmpty();
  284. }
  285. @Test
  286. public void selectByLanguage() {
  287. RuleDto rule1 = db.rules().insert(
  288. r -> r.setKey(RuleKey.of("java", "S001"))
  289. .setType(RuleType.VULNERABILITY)
  290. .setLanguage("java"));
  291. RuleDto rule2 = db.rules().insert(
  292. r -> r.setKey(RuleKey.of("js", "S002"))
  293. .setType(RuleType.SECURITY_HOTSPOT)
  294. .setLanguage("js"));
  295. RuleDto rule3 = db.rules().insert(
  296. r -> r.setKey(RuleKey.of("java", "S003"))
  297. .setType(RuleType.BUG)
  298. .setLanguage("java"));
  299. assertThat(underTest.selectByLanguage(db.getSession(), "java")).hasSize(2);
  300. assertThat(underTest.selectByLanguage(db.getSession(), "java"))
  301. .extracting(RuleDto::getUuid, RuleDto::getLanguage, RuleDto::getType)
  302. .containsExactlyInAnyOrder(
  303. tuple(rule1.getUuid(), "java", RuleType.VULNERABILITY.getDbConstant()),
  304. tuple(rule3.getUuid(), "java", RuleType.BUG.getDbConstant()));
  305. assertThat(underTest.selectByLanguage(db.getSession(), "js")).hasSize(1);
  306. assertThat(underTest.selectByLanguage(db.getSession(), "js"))
  307. .extracting(RuleDto::getUuid, RuleDto::getLanguage, RuleDto::getType)
  308. .containsExactly(tuple(rule2.getUuid(), "js", RuleType.SECURITY_HOTSPOT.getDbConstant()));
  309. }
  310. @Test
  311. public void selectByTypeAndLanguages_return_nothing_when_no_rule_on_languages() {
  312. db.rules().insert(
  313. r -> r.setKey(RuleKey.of("java", "S001"))
  314. .setConfigKey("S1")
  315. .setType(RuleType.VULNERABILITY)
  316. .setLanguage("java"));
  317. db.rules().insert(
  318. r -> r.setKey(RuleKey.of("js", "S002"))
  319. .setType(RuleType.VULNERABILITY)
  320. .setLanguage("js"));
  321. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.VULNERABILITY.getDbConstant()), singletonList("cpp")))
  322. .isEmpty();
  323. }
  324. @Test
  325. public void selectByTypeAndLanguages_return_nothing_when_no_rule_with_type() {
  326. db.rules().insert(
  327. r -> r.setKey(RuleKey.of("java", "S001"))
  328. .setConfigKey("S1")
  329. .setType(RuleType.VULNERABILITY)
  330. .setLanguage("java"));
  331. db.rules().insert(
  332. r -> r.setKey(RuleKey.of("java", "S002"))
  333. .setType(RuleType.SECURITY_HOTSPOT)
  334. .setLanguage("java"));
  335. db.rules().insert(
  336. r -> r.setKey(RuleKey.of("java", "S003"))
  337. .setType(RuleType.CODE_SMELL)
  338. .setLanguage("java"));
  339. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.BUG.getDbConstant()), singletonList("java")))
  340. .isEmpty();
  341. }
  342. @Test
  343. public void selectByTypeAndLanguages_ignores_external_rules() {
  344. db.rules().insert(
  345. r -> r.setKey(RuleKey.of("java", "S001"))
  346. .setConfigKey("S1")
  347. .setType(RuleType.VULNERABILITY)
  348. .setIsExternal(true)
  349. .setLanguage("java"));
  350. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.VULNERABILITY.getDbConstant()), singletonList("java")))
  351. .extracting(RuleDto::getUuid, RuleDto::getLanguage, RuleDto::getType)
  352. .isEmpty();
  353. }
  354. @Test
  355. public void selectByTypeAndLanguages_ignores_template_rules() {
  356. db.rules().insert(
  357. r -> r.setKey(RuleKey.of("java", "S001"))
  358. .setConfigKey("S1")
  359. .setType(RuleType.VULNERABILITY)
  360. .setIsTemplate(true)
  361. .setLanguage("java"));
  362. assertThat(underTest.selectByTypeAndLanguages(db.getSession(), singletonList(RuleType.VULNERABILITY.getDbConstant()), singletonList("java")))
  363. .extracting(RuleDto::getUuid, RuleDto::getLanguage, RuleDto::getType)
  364. .isEmpty();
  365. }
  366. @Test
  367. public void select_by_query() {
  368. db.rules().insert(r -> r.setKey(RuleKey.of("java", "S001")).setConfigKey("S1"));
  369. db.rules().insert(r -> r.setKey(RuleKey.of("java", "S002")));
  370. db.rules().insert(r -> r.setStatus(REMOVED));
  371. assertThat(underTest.selectByQuery(db.getSession(), RuleQuery.create())).hasSize(2);
  372. assertThat(underTest.selectByQuery(db.getSession(), RuleQuery.create().withKey("S001"))).hasSize(1);
  373. assertThat(underTest.selectByQuery(db.getSession(), RuleQuery.create().withConfigKey("S1"))).hasSize(1);
  374. assertThat(underTest.selectByQuery(db.getSession(), RuleQuery.create().withRepositoryKey("java"))).hasSize(2);
  375. assertThat(underTest.selectByQuery(db.getSession(),
  376. RuleQuery.create().withKey("S001").withConfigKey("S1").withRepositoryKey("java"))).hasSize(1);
  377. }
  378. @Test
  379. public void insert_rule_with_description_section_context() {
  380. RuleDto rule = db.rules().insert(r -> r
  381. .addRuleDescriptionSectionDto(createDescriptionSectionWithContext("how_to_fix", "spring", "Spring")));
  382. Optional<RuleDto> ruleDto = underTest.selectByUuid(rule.getUuid(), db.getSession());
  383. assertEquals(ruleDto.get(), rule);
  384. }
  385. @NotNull
  386. private static RuleDescriptionSectionDto createDescriptionSectionWithContext(String key, String contextKey, String contextDisplayName) {
  387. return RuleDescriptionSectionDto.builder()
  388. .uuid(UuidFactoryFast.getInstance().create())
  389. .content("content")
  390. .key(key)
  391. .context(RuleDescriptionSectionContextDto.of(contextKey, contextDisplayName))
  392. .build();
  393. }
  394. @Test
  395. public void insert_rule_with_different_section_context() {
  396. RuleDto rule = db.rules().insert(r -> r
  397. .addRuleDescriptionSectionDto(createDescriptionSectionWithContext("how_to_fix", "spring", "Spring"))
  398. .addRuleDescriptionSectionDto(createDescriptionSectionWithContext("how_to_fix", "myBatis", "My Batis")));
  399. Optional<RuleDto> ruleDto = underTest.selectByUuid(rule.getUuid(), db.getSession());
  400. assertEquals(ruleDto.get(), rule);
  401. }
  402. @Test
  403. public void insert() {
  404. RuleDescriptionSectionDto sectionDto = createDefaultRuleDescriptionSection();
  405. ImpactDto ruleDefaultImpactDto = newRuleDefaultImpact(SECURITY, org.sonar.api.issue.impact.Severity.HIGH);
  406. RuleDto newRule = new RuleDto()
  407. .setUuid("rule-uuid")
  408. .setRuleKey("NewRuleKey")
  409. .setRepositoryKey("plugin")
  410. .setName("new name")
  411. .setDescriptionFormat(RuleDto.Format.MARKDOWN)
  412. .addRuleDescriptionSectionDto(sectionDto)
  413. .addDefaultImpact(ruleDefaultImpactDto)
  414. .setStatus(DEPRECATED)
  415. .setConfigKey("NewConfigKey")
  416. .setSeverity(Severity.INFO)
  417. .setIsTemplate(true)
  418. .setIsExternal(true)
  419. .setIsAdHoc(true)
  420. .setLanguage("dart")
  421. .setTemplateUuid("uuid-3")
  422. .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.toString())
  423. .setDefRemediationGapMultiplier("5d")
  424. .setDefRemediationBaseEffort("10h")
  425. .setGapDescription("java.S115.effortToFix")
  426. .setSystemTags(newHashSet("systag1", "systag2"))
  427. .setTags(newHashSet("tag1", "tag2"))
  428. .setSecurityStandards(newHashSet("owaspTop10:a1", "cwe:123"))
  429. .setType(RuleType.BUG)
  430. .setCleanCodeAttribute(CleanCodeAttribute.CLEAR)
  431. .setScope(Scope.ALL)
  432. .setCreatedAt(1_500_000_000_000L)
  433. .setUpdatedAt(2_000_000_000_000L);
  434. underTest.insert(db.getSession(), newRule);
  435. db.getSession().commit();
  436. RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of("plugin", "NewRuleKey"));
  437. assertThat(ruleDto.getUuid()).isNotNull();
  438. assertThat(ruleDto.getName()).isEqualTo("new name");
  439. assertThat(ruleDto.getStatus()).isEqualTo(DEPRECATED);
  440. assertThat(ruleDto.getRuleKey()).isEqualTo("NewRuleKey");
  441. assertThat(ruleDto.getRepositoryKey()).isEqualTo("plugin");
  442. assertThat(ruleDto.getConfigKey()).isEqualTo("NewConfigKey");
  443. assertThat(ruleDto.getSeverity()).isZero();
  444. assertThat(ruleDto.getLanguage()).isEqualTo("dart");
  445. assertThat(ruleDto.isTemplate()).isTrue();
  446. assertThat(ruleDto.isExternal()).isTrue();
  447. assertThat(ruleDto.isAdHoc()).isTrue();
  448. assertThat(ruleDto.getTemplateUuid()).isEqualTo("uuid-3");
  449. assertThat(ruleDto.getDefRemediationFunction()).isEqualTo("LINEAR_OFFSET");
  450. assertThat(ruleDto.getDefRemediationGapMultiplier()).isEqualTo("5d");
  451. assertThat(ruleDto.getDefRemediationBaseEffort()).isEqualTo("10h");
  452. assertThat(ruleDto.getGapDescription()).isEqualTo("java.S115.effortToFix");
  453. assertThat(ruleDto.getSystemTags()).containsOnly("systag1", "systag2");
  454. assertThat(ruleDto.getSecurityStandards()).containsOnly("owaspTop10:a1", "cwe:123");
  455. assertThat(ruleDto.getScope()).isEqualTo(Scope.ALL);
  456. assertThat(ruleDto.getType()).isEqualTo(RuleType.BUG.getDbConstant());
  457. assertThat(ruleDto.getCreatedAt()).isEqualTo(1_500_000_000_000L);
  458. assertThat(ruleDto.getUpdatedAt()).isEqualTo(2_000_000_000_000L);
  459. assertThat(ruleDto.getDescriptionFormat()).isEqualTo(RuleDto.Format.MARKDOWN);
  460. assertThat(ruleDto.getRuleDescriptionSectionDtos()).usingRecursiveFieldByFieldElementComparator()
  461. .containsOnly(sectionDto);
  462. assertCleanCodeInformation(ruleDto, CleanCodeAttribute.CLEAR, ruleDefaultImpactDto);
  463. }
  464. private static void assertCleanCodeInformation(RuleDto ruleDto, CleanCodeAttribute attribute, ImpactDto ruleDefaultImpactDto) {
  465. assertThat(ruleDto.getCleanCodeAttribute()).isEqualTo(attribute);
  466. assertThat(ruleDto.getDefaultImpacts()).usingRecursiveFieldByFieldElementComparator()
  467. .containsOnly(ruleDefaultImpactDto);
  468. }
  469. @Test
  470. public void update_RuleDefinitionDto() {
  471. RuleDto rule = db.rules().insert();
  472. RuleDescriptionSectionDto sectionDto = createDefaultRuleDescriptionSection();
  473. RuleDto ruleToUpdate = new RuleDto()
  474. .setUuid(rule.getUuid())
  475. .setRuleKey("NewRuleKey")
  476. .setRepositoryKey("plugin")
  477. .setName("new name")
  478. .setDescriptionFormat(RuleDto.Format.MARKDOWN)
  479. .addRuleDescriptionSectionDto(sectionDto)
  480. .setStatus(DEPRECATED)
  481. .setConfigKey("NewConfigKey")
  482. .setSeverity(Severity.INFO)
  483. .setIsTemplate(true)
  484. .setIsExternal(true)
  485. .setIsAdHoc(true)
  486. .setLanguage("dart")
  487. .setTemplateUuid("uuid-3")
  488. .setDefRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.toString())
  489. .setDefRemediationGapMultiplier("5d")
  490. .setDefRemediationBaseEffort("10h")
  491. .setGapDescription("java.S115.effortToFix")
  492. .setSystemTags(newHashSet("systag1", "systag2"))
  493. .setSecurityStandards(newHashSet("owaspTop10:a1", "cwe:123"))
  494. .setScope(Scope.ALL)
  495. .setType(RuleType.BUG)
  496. .setCleanCodeAttribute(CleanCodeAttribute.TRUSTWORTHY)
  497. .setUpdatedAt(2_000_000_000_000L);
  498. underTest.update(db.getSession(), ruleToUpdate);
  499. db.getSession().commit();
  500. RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of("plugin", "NewRuleKey"));
  501. assertThat(ruleDto.getName()).isEqualTo("new name");
  502. assertThat(ruleDto.getStatus()).isEqualTo(DEPRECATED);
  503. assertThat(ruleDto.getRuleKey()).isEqualTo("NewRuleKey");
  504. assertThat(ruleDto.getRepositoryKey()).isEqualTo("plugin");
  505. assertThat(ruleDto.getConfigKey()).isEqualTo("NewConfigKey");
  506. assertThat(ruleDto.getSeverity()).isZero();
  507. assertThat(ruleDto.getLanguage()).isEqualTo("dart");
  508. assertThat(ruleDto.isTemplate()).isTrue();
  509. assertThat(ruleDto.isExternal()).isTrue();
  510. assertThat(ruleDto.isAdHoc()).isTrue();
  511. assertThat(ruleDto.getTemplateUuid()).isEqualTo("uuid-3");
  512. assertThat(ruleDto.getDefRemediationFunction()).isEqualTo("LINEAR_OFFSET");
  513. assertThat(ruleDto.getDefRemediationGapMultiplier()).isEqualTo("5d");
  514. assertThat(ruleDto.getDefRemediationBaseEffort()).isEqualTo("10h");
  515. assertThat(ruleDto.getGapDescription()).isEqualTo("java.S115.effortToFix");
  516. assertThat(ruleDto.getSystemTags()).containsOnly("systag1", "systag2");
  517. assertThat(ruleDto.getSecurityStandards()).containsOnly("owaspTop10:a1", "cwe:123");
  518. assertThat(ruleDto.getScope()).isEqualTo(Scope.ALL);
  519. assertThat(ruleDto.getType()).isEqualTo(RuleType.BUG.getDbConstant());
  520. assertThat(ruleDto.getCreatedAt()).isEqualTo(rule.getCreatedAt());
  521. assertThat(ruleDto.getUpdatedAt()).isEqualTo(2_000_000_000_000L);
  522. assertThat(ruleDto.getDescriptionFormat()).isEqualTo(RuleDto.Format.MARKDOWN);
  523. assertThat(ruleDto.getRuleDescriptionSectionDtos()).usingRecursiveFieldByFieldElementComparator()
  524. .containsOnly(sectionDto);
  525. }
  526. @Test
  527. public void update_rule_sections_add_new_section() {
  528. RuleDto rule = db.rules().insert();
  529. RuleDescriptionSectionDto existingSection = rule.getRuleDescriptionSectionDtos().iterator().next();
  530. RuleDescriptionSectionDto newSection = RuleDescriptionSectionDto.builder()
  531. .uuid(randomAlphanumeric(20))
  532. .key("new_key")
  533. .content(randomAlphanumeric(1000))
  534. .build();
  535. rule.addRuleDescriptionSectionDto(newSection);
  536. underTest.update(db.getSession(), rule);
  537. db.getSession().commit();
  538. RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
  539. assertThat(ruleDto.getRuleDescriptionSectionDtos())
  540. .usingRecursiveFieldByFieldElementComparator()
  541. .containsExactlyInAnyOrder(newSection, existingSection);
  542. }
  543. @Test
  544. public void update_rule_sections_replaces_section() {
  545. RuleDto rule = db.rules().insert();
  546. Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos();
  547. RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next();
  548. RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder()
  549. .uuid(randomAlphanumeric(20))
  550. .key(existingSection.getKey())
  551. .content(randomAlphanumeric(1000))
  552. .build();
  553. rule.replaceRuleDescriptionSectionDtos(List.of(replacingSection));
  554. underTest.update(db.getSession(), rule);
  555. db.getSession().commit();
  556. RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
  557. assertThat(ruleDto.getRuleDescriptionSectionDtos())
  558. .usingRecursiveFieldByFieldElementComparator()
  559. .containsOnly(replacingSection);
  560. }
  561. @Test
  562. public void update_rule_sections_replaces_section_with_context() {
  563. RuleDto rule = db.rules().insert();
  564. Set<RuleDescriptionSectionDto> ruleDescriptionSectionDtos = rule.getRuleDescriptionSectionDtos();
  565. RuleDescriptionSectionDto existingSection = ruleDescriptionSectionDtos.iterator().next();
  566. RuleDescriptionSectionContextDto contextDto = RuleDescriptionSectionContextDto.of(randomAlphanumeric(10), randomAlphanumeric(10));
  567. RuleDescriptionSectionDto replacingSection = RuleDescriptionSectionDto.builder()
  568. .uuid(randomAlphanumeric(20))
  569. .key(existingSection.getKey())
  570. .content(randomAlphanumeric(1000))
  571. .context(contextDto)
  572. .build();
  573. rule.replaceRuleDescriptionSectionDtos(List.of(replacingSection));
  574. underTest.update(db.getSession(), rule);
  575. db.getSession().commit();
  576. RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), RuleKey.of(rule.getRepositoryKey(), rule.getRuleKey()));
  577. assertThat(ruleDto.getRuleDescriptionSectionDtos())
  578. .usingRecursiveFieldByFieldElementComparator()
  579. .containsOnly(replacingSection);
  580. }
  581. @Test
  582. public void update_RuleMetadataDto_inserts_row_in_RULE_METADATA_if_not_exists_yet() {
  583. RuleDto rule = db.rules().insert();
  584. long createdAtBeforeUpdate = rule.getCreatedAt();
  585. rule.setNoteData("My note");
  586. rule.setNoteUserUuid("admin");
  587. rule.setNoteCreatedAt(DateUtils.parseDate("2013-12-19").getTime());
  588. rule.setNoteUpdatedAt(DateUtils.parseDate("2013-12-20").getTime());
  589. rule.setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString());
  590. rule.setRemediationGapMultiplier("1h");
  591. rule.setRemediationBaseEffort("5min");
  592. rule.setTags(newHashSet("tag1", "tag2"));
  593. rule.setAdHocName("ad hoc name");
  594. rule.setAdHocDescription("ad hoc desc");
  595. rule.setAdHocSeverity(Severity.BLOCKER);
  596. rule.setAdHocType(RuleType.CODE_SMELL);
  597. rule.setCreatedAt(3_500_000_000_000L);
  598. rule.setUpdatedAt(4_000_000_000_000L);
  599. underTest.update(db.getSession(), rule);
  600. db.getSession().commit();
  601. RuleDto ruleDto = underTest.selectOrFailByKey(db.getSession(), rule.getKey());
  602. assertThat(ruleDto.getNoteData()).isEqualTo("My note");
  603. assertThat(ruleDto.getNoteUserUuid()).isEqualTo("admin");
  604. assertThat(ruleDto.getNoteCreatedAt()).isNotNull();
  605. assertThat(ruleDto.getNoteUpdatedAt()).isNotNull();
  606. assertThat(ruleDto.getRemediationFunction()).isEqualTo("LINEAR");
  607. assertThat(ruleDto.getRemediationGapMultiplier()).isEqualTo("1h");
  608. assertThat(ruleDto.getRemediationBaseEffort()).isEqualTo("5min");
  609. assertThat(ruleDto.getTags()).containsOnly("tag1", "tag2");
  610. assertThat(ruleDto.getAdHocName()).isEqualTo("ad hoc name");
  611. assertThat(ruleDto.getAdHocDescription()).isEqualTo("ad hoc desc");
  612. assertThat(ruleDto.getAdHocSeverity()).isEqualTo(Severity.BLOCKER);
  613. assertThat(ruleDto.getAdHocType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
  614. assertThat(ruleDto.getSecurityStandards()).isEmpty();
  615. assertThat(ruleDto.getCreatedAt()).isEqualTo(createdAtBeforeUpdate);
  616. assertThat(ruleDto.getUpdatedAt()).isEqualTo(4_000_000_000_000L);
  617. // Info from rule definition
  618. assertThat(ruleDto.getDefRemediationFunction()).isEqualTo(rule.getDefRemediationFunction());
  619. assertThat(ruleDto.getDefRemediationGapMultiplier()).isEqualTo(rule.getDefRemediationGapMultiplier());
  620. assertThat(ruleDto.getDefRemediationBaseEffort()).isEqualTo(rule.getDefRemediationBaseEffort());
  621. assertThat(ruleDto.getGapDescription()).isEqualTo(rule.getGapDescription());
  622. assertThat(ruleDto.getSystemTags()).containsAll(rule.getSystemTags());
  623. assertThat(ruleDto.getType()).isEqualTo(rule.getType());
  624. }
  625. @Test
  626. public void update_RuleMetadataDto_updates_row_in_RULE_METADATA_if_already_exists() {
  627. RuleDto rule = db.rules().insert();
  628. rule.setAdHocDescription("ad-hoc-desc");
  629. rule.setCreatedAt(3_500_000_000_000L);
  630. rule.setUpdatedAt(4_000_000_000_000L);
  631. RuleDto ruleDtoBeforeUpdate = underTest.selectOrFailByKey(db.getSession(), rule.getKey());
  632. underTest.update(db.getSession(), rule);
  633. db.commit();
  634. RuleDto ruleDtoAfterUpdate = underTest.selectOrFailByKey(db.getSession(), rule.getKey());
  635. assertThat(ruleDtoAfterUpdate.getNoteData()).isEqualTo(rule.getNoteData());
  636. assertThat(ruleDtoAfterUpdate.getNoteUserUuid()).isEqualTo(rule.getNoteUserUuid());
  637. assertThat(ruleDtoAfterUpdate.getNoteCreatedAt()).isEqualTo(rule.getNoteCreatedAt());
  638. assertThat(ruleDtoAfterUpdate.getNoteUpdatedAt()).isEqualTo(rule.getNoteUpdatedAt());
  639. assertThat(ruleDtoAfterUpdate.getRemediationFunction()).isEqualTo(rule.getRemediationFunction());
  640. assertThat(ruleDtoAfterUpdate.getRemediationGapMultiplier()).isEqualTo(rule.getRemediationGapMultiplier());
  641. assertThat(ruleDtoAfterUpdate.getRemediationBaseEffort()).isEqualTo(rule.getRemediationBaseEffort());
  642. assertThat(ruleDtoAfterUpdate.getTags()).isEqualTo(rule.getTags());
  643. assertThat(ruleDtoAfterUpdate.getAdHocName()).isEqualTo(rule.getAdHocName());
  644. assertThat(ruleDtoAfterUpdate.getAdHocDescription()).isEqualTo("ad-hoc-desc");
  645. assertThat(ruleDtoAfterUpdate.getAdHocSeverity()).isEqualTo(rule.getAdHocSeverity());
  646. assertThat(ruleDtoAfterUpdate.getAdHocType()).isEqualTo(rule.getAdHocType());
  647. assertThat(ruleDtoAfterUpdate.getSecurityStandards()).isEqualTo(rule.getSecurityStandards());
  648. assertThat(ruleDtoAfterUpdate.getCreatedAt()).isEqualTo(ruleDtoBeforeUpdate.getCreatedAt());
  649. assertThat(ruleDtoAfterUpdate.getUpdatedAt()).isEqualTo(4_000_000_000_000L);
  650. rule.setNoteData("My note");
  651. rule.setNoteUserUuid("admin");
  652. rule.setNoteCreatedAt(DateUtils.parseDate("2013-12-19").getTime());
  653. rule.setNoteUpdatedAt(DateUtils.parseDate("2013-12-20").getTime());
  654. rule.setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString());
  655. rule.setRemediationGapMultiplier("1h");
  656. rule.setRemediationBaseEffort("5min");
  657. rule.setTags(newHashSet("tag1", "tag2"));
  658. rule.setAdHocName("ad hoc name");
  659. rule.setAdHocDescription("ad hoc desc");
  660. rule.setAdHocSeverity(Severity.BLOCKER);
  661. rule.setAdHocType(RuleType.CODE_SMELL);
  662. rule.setCreatedAt(6_500_000_000_000L);
  663. rule.setUpdatedAt(7_000_000_000_000L);
  664. underTest.update(db.getSession(), rule);
  665. db.commit();
  666. ruleDtoAfterUpdate = underTest.selectOrFailByKey(db.getSession(), rule.getKey());
  667. assertThat(ruleDtoAfterUpdate.getNoteData()).isEqualTo("My note");
  668. assertThat(ruleDtoAfterUpdate.getNoteUserUuid()).isEqualTo("admin");
  669. assertThat(ruleDtoAfterUpdate.getNoteCreatedAt()).isNotNull();
  670. assertThat(ruleDtoAfterUpdate.getNoteUpdatedAt()).isNotNull();
  671. assertThat(ruleDtoAfterUpdate.getRemediationFunction()).isEqualTo("LINEAR");
  672. assertThat(ruleDtoAfterUpdate.getRemediationGapMultiplier()).isEqualTo("1h");
  673. assertThat(ruleDtoAfterUpdate.getRemediationBaseEffort()).isEqualTo("5min");
  674. assertThat(ruleDtoAfterUpdate.getTags()).containsOnly("tag1", "tag2");
  675. assertThat(ruleDtoAfterUpdate.getAdHocName()).isEqualTo("ad hoc name");
  676. assertThat(ruleDtoAfterUpdate.getAdHocDescription()).isEqualTo("ad hoc desc");
  677. assertThat(ruleDtoAfterUpdate.getAdHocSeverity()).isEqualTo(Severity.BLOCKER);
  678. assertThat(ruleDtoAfterUpdate.getAdHocType()).isEqualTo(RuleType.CODE_SMELL.getDbConstant());
  679. assertThat(ruleDtoAfterUpdate.getSecurityStandards()).isEmpty();
  680. assertThat(ruleDtoAfterUpdate.getCreatedAt()).isEqualTo(ruleDtoBeforeUpdate.getCreatedAt());
  681. assertThat(ruleDtoAfterUpdate.getUpdatedAt()).isEqualTo(7_000_000_000_000L);
  682. }
  683. @Test
  684. public void select_all_rule_params() {
  685. RuleDto rule1 = db.rules().insert();
  686. RuleParamDto ruleParam1 = db.rules().insertRuleParam(rule1);
  687. RuleParamDto ruleParam12 = db.rules().insertRuleParam(rule1);
  688. RuleDto rule2 = db.rules().insert();
  689. RuleParamDto ruleParam2 = db.rules().insertRuleParam(rule2);
  690. RuleDto rule3 = db.rules().insert();
  691. RuleParamDto ruleParam3 = db.rules().insertRuleParam(rule3);
  692. List<RuleParamDto> ruleDtos = underTest.selectAllRuleParams(db.getSession());
  693. assertThat(ruleDtos).hasSize(4);
  694. assertThat(ruleDtos).extracting(RuleParamDto::getUuid)
  695. .containsExactlyInAnyOrder(ruleParam1.getUuid(), ruleParam12.getUuid(),
  696. ruleParam2.getUuid(), ruleParam3.getUuid());
  697. }
  698. @Test
  699. public void select_parameters_by_rule_key() {
  700. RuleDto rule = db.rules().insert();
  701. RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
  702. List<RuleParamDto> ruleDtos = underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey());
  703. assertThat(ruleDtos.size()).isOne();
  704. RuleParamDto ruleDto = ruleDtos.get(0);
  705. assertThat(ruleDto.getUuid()).isEqualTo(ruleParam.getUuid());
  706. assertThat(ruleDto.getName()).isEqualTo(ruleParam.getName());
  707. assertThat(ruleDto.getDescription()).isEqualTo(ruleParam.getDescription());
  708. assertThat(ruleDto.getType()).isEqualTo(ruleParam.getType());
  709. assertThat(ruleDto.getRuleUuid()).isEqualTo(rule.getUuid());
  710. }
  711. @Test
  712. public void select_parameters_by_rule_keys() {
  713. RuleDto rule1 = db.rules().insert();
  714. db.rules().insertRuleParam(rule1);
  715. RuleDto rule2 = db.rules().insert();
  716. db.rules().insertRuleParam(rule2);
  717. assertThat(underTest.selectRuleParamsByRuleKeys(db.getSession(),
  718. Arrays.asList(rule1.getKey(), rule2.getKey()))).hasSize(2);
  719. assertThat(underTest.selectRuleParamsByRuleKeys(db.getSession(),
  720. singletonList(RuleKey.of("unknown", "Unknown")))).isEmpty();
  721. }
  722. @Test
  723. public void insert_parameter() {
  724. RuleDto ruleDefinitionDto = db.rules().insert();
  725. RuleParamDto orig = RuleParamDto.createFor(ruleDefinitionDto)
  726. .setName("max")
  727. .setType("INTEGER")
  728. .setDefaultValue("30")
  729. .setDescription("My Parameter");
  730. underTest.insertRuleParam(db.getSession(), ruleDefinitionDto, orig);
  731. List<RuleParamDto> ruleParamDtos = underTest.selectRuleParamsByRuleKey(db.getSession(), ruleDefinitionDto.getKey());
  732. assertThat(ruleParamDtos).hasSize(1);
  733. RuleParamDto loaded = ruleParamDtos.get(0);
  734. assertThat(loaded.getRuleUuid()).isEqualTo(orig.getRuleUuid());
  735. assertThat(loaded.getName()).isEqualTo(orig.getName());
  736. assertThat(loaded.getType()).isEqualTo(orig.getType());
  737. assertThat(loaded.getDefaultValue()).isEqualTo(orig.getDefaultValue());
  738. assertThat(loaded.getDescription()).isEqualTo(orig.getDescription());
  739. }
  740. @Test
  741. public void should_fail_to_insert_duplicate_parameter() {
  742. RuleDto ruleDefinitionDto = db.rules().insert();
  743. RuleParamDto param = RuleParamDto.createFor(ruleDefinitionDto)
  744. .setName("max")
  745. .setType("INTEGER")
  746. .setDefaultValue("30")
  747. .setDescription("My Parameter");
  748. DbSession session = db.getSession();
  749. underTest.insertRuleParam(session, ruleDefinitionDto, param);
  750. assertThatThrownBy(() -> underTest.insertRuleParam(session, ruleDefinitionDto, param))
  751. .isInstanceOf(PersistenceException.class);
  752. }
  753. @Test
  754. public void update_parameter() {
  755. RuleDto rule = db.rules().insert();
  756. RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
  757. List<RuleParamDto> params = underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey());
  758. assertThat(params).hasSize(1);
  759. RuleParamDto param = new RuleParamDto()
  760. .setUuid(ruleParam.getUuid())
  761. .setRuleUuid(rule.getUuid())
  762. // Name will not be updated
  763. .setName("format")
  764. .setType("STRING")
  765. .setDefaultValue("^[a-z]+(\\.[a-z][a-z0-9]*)*$")
  766. .setDescription("Regular expression used to check the package names against.");
  767. underTest.updateRuleParam(db.getSession(), rule, param);
  768. assertThat(underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey()))
  769. .extracting(RuleParamDto::getName, RuleParamDto::getType, RuleParamDto::getDefaultValue, RuleParamDto::getDescription)
  770. .containsExactlyInAnyOrder(tuple(ruleParam.getName(), "STRING", "^[a-z]+(\\.[a-z][a-z0-9]*)*$", "Regular expression used to check the package names against."));
  771. }
  772. @Test
  773. public void delete_parameter() {
  774. RuleDto rule = db.rules().insert();
  775. RuleParamDto ruleParam = db.rules().insertRuleParam(rule);
  776. assertThat(underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey())).hasSize(1);
  777. underTest.deleteRuleParam(db.getSession(), ruleParam.getUuid());
  778. assertThat(underTest.selectRuleParamsByRuleKey(db.getSession(), rule.getKey())).isEmpty();
  779. }
  780. @Test
  781. public void scrollIndexingRules_on_empty_table() {
  782. Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
  783. underTest.selectIndexingRules(db.getSession(), accumulator);
  784. assertThat(accumulator.list).isEmpty();
  785. }
  786. @Test
  787. public void scrollIndexingRules() {
  788. Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
  789. RuleDescriptionSectionDto ruleDescriptionSectionDto = RuleDescriptionSectionDto.builder()
  790. .key("DESC")
  791. .uuid("uuid")
  792. .content("my description")
  793. .context(RuleDescriptionSectionContextDto.of("context key", "context display name"))
  794. .build();
  795. RuleDto r1 = db.rules().insert(r -> {
  796. r.addRuleDescriptionSectionDto(ruleDescriptionSectionDto);
  797. });
  798. RuleDto r2 = db.rules().insert(r -> r.setIsExternal(true));
  799. underTest.selectIndexingRules(db.getSession(), accumulator);
  800. RuleForIndexingDto firstRule = findRuleForIndexingWithUuid(accumulator, r1.getUuid());
  801. RuleForIndexingDto secondRule = findRuleForIndexingWithUuid(accumulator, r2.getUuid());
  802. assertThat(Arrays.asList(firstRule, secondRule))
  803. .extracting(RuleForIndexingDto::getUuid, RuleForIndexingDto::getRuleKey)
  804. .containsExactlyInAnyOrder(tuple(r1.getUuid(), r1.getKey()), tuple(r2.getUuid(), r2.getKey()));
  805. Iterator<RuleForIndexingDto> it = accumulator.list.iterator();
  806. assertThat(firstRule.getRepository()).isEqualTo(r1.getRepositoryKey());
  807. assertThat(firstRule.getPluginRuleKey()).isEqualTo(r1.getRuleKey());
  808. assertThat(firstRule.getName()).isEqualTo(r1.getName());
  809. assertThat(firstRule.getRuleDescriptionSectionsDtos().stream()
  810. .filter(s -> s.getKey().equals(ruleDescriptionSectionDto.getKey()))
  811. .collect(MoreCollectors.onlyElement()))
  812. .usingRecursiveComparison()
  813. .isEqualTo(ruleDescriptionSectionDto);
  814. assertThat(firstRule.getDescriptionFormat()).isEqualTo(r1.getDescriptionFormat());
  815. assertThat(firstRule.getSeverity()).isEqualTo(r1.getSeverity());
  816. assertThat(firstRule.getStatus()).isEqualTo(r1.getStatus());
  817. assertThat(firstRule.isExternal()).isFalse();
  818. assertThat(firstRule.isTemplate()).isEqualTo(r1.isTemplate());
  819. assertThat(firstRule.getSystemTags()).isEqualTo(r1.getSystemTags());
  820. assertThat(firstRule.getSecurityStandards()).isEqualTo(r1.getSecurityStandards());
  821. assertThat(firstRule.getTemplateRuleKey()).isNull();
  822. assertThat(firstRule.getTemplateRepository()).isNull();
  823. assertThat(firstRule.getInternalKey()).isEqualTo(r1.getConfigKey());
  824. assertThat(firstRule.getLanguage()).isEqualTo(r1.getLanguage());
  825. assertThat(firstRule.getType()).isEqualTo(r1.getType());
  826. assertThat(firstRule.getCreatedAt()).isEqualTo(r1.getCreatedAt());
  827. assertThat(firstRule.getUpdatedAt()).isEqualTo(r1.getUpdatedAt());
  828. assertThat(secondRule.isExternal()).isTrue();
  829. }
  830. @Test
  831. public void scrollIndexingRules_maps_rule_definition_fields_for_regular_rule_and_template_rule() {
  832. Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
  833. RuleDto r1 = db.rules().insert();
  834. r1.setTags(Set.of("t1", "t2"));
  835. r1 = db.rules().update(r1);
  836. String r1Uuid = r1.getUuid();
  837. RuleDto r2 = db.rules().insert(rule -> rule.setTemplateUuid(r1Uuid));
  838. underTest.selectIndexingRules(db.getSession(), accumulator);
  839. assertThat(accumulator.list).hasSize(2);
  840. RuleForIndexingDto firstRule = findRuleForIndexingWithUuid(accumulator, r1.getUuid());
  841. RuleForIndexingDto secondRule = findRuleForIndexingWithUuid(accumulator, r2.getUuid());
  842. assertRuleDefinitionFieldsAreEquals(r1, firstRule);
  843. assertThat(r1.getTags()).isEqualTo(firstRule.getTags());
  844. assertThat(firstRule.getTemplateRuleKey()).isNull();
  845. assertThat(firstRule.getTemplateRepository()).isNull();
  846. assertRuleDefinitionFieldsAreEquals(r2, secondRule);
  847. assertThat(secondRule.getTemplateRuleKey()).isEqualTo(r1.getRuleKey());
  848. assertThat(secondRule.getTemplateRepository()).isEqualTo(r1.getRepositoryKey());
  849. }
  850. @NotNull
  851. private static RuleForIndexingDto findRuleForIndexingWithUuid(Accumulator<RuleForIndexingDto> accumulator, String uuid) {
  852. return accumulator.list.stream()
  853. .filter(rule -> rule.getUuid().equals(uuid))
  854. .findFirst().orElseThrow();
  855. }
  856. @Test
  857. public void scrollIndexingRulesByKeys() {
  858. Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
  859. RuleDto r1 = db.rules().insert();
  860. db.rules().insert();
  861. underTest.selectIndexingRulesByKeys(db.getSession(), singletonList(r1.getUuid()), accumulator);
  862. assertThat(accumulator.list)
  863. .extracting(RuleForIndexingDto::getUuid, RuleForIndexingDto::getRuleKey)
  864. .containsExactlyInAnyOrder(tuple(r1.getUuid(), r1.getKey()));
  865. }
  866. @Test
  867. public void scrollIndexingRulesByKeys_maps_rule_definition_fields_for_regular_rule_and_template_rule() {
  868. Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
  869. RuleDto r1 = db.rules().insert();
  870. RuleDto r2 = db.rules().insert(rule -> rule.setTemplateUuid(r1.getUuid()));
  871. underTest.selectIndexingRulesByKeys(db.getSession(), Arrays.asList(r1.getUuid(), r2.getUuid()), accumulator);
  872. assertThat(accumulator.list).hasSize(2);
  873. RuleForIndexingDto firstRule = accumulator.list.stream().filter(t -> t.getUuid().equals(r1.getUuid())).findFirst().get();
  874. RuleForIndexingDto secondRule = accumulator.list.stream().filter(t -> t.getUuid().equals(r2.getUuid())).findFirst().get();
  875. assertRuleDefinitionFieldsAreEquals(r1, firstRule);
  876. assertThat(firstRule.getTemplateRuleKey()).isNull();
  877. assertThat(firstRule.getTemplateRepository()).isNull();
  878. assertRuleDefinitionFieldsAreEquals(r2, secondRule);
  879. assertThat(secondRule.getTemplateRuleKey()).isEqualTo(r1.getRuleKey());
  880. assertThat(secondRule.getTemplateRepository()).isEqualTo(r1.getRepositoryKey());
  881. }
  882. private void assertRuleDefinitionFieldsAreEquals(RuleDto r1, RuleForIndexingDto ruleForIndexing) {
  883. assertThat(ruleForIndexing.getUuid()).isEqualTo(r1.getUuid());
  884. assertThat(ruleForIndexing.getRuleKey()).isEqualTo(r1.getKey());
  885. assertThat(ruleForIndexing.getRepository()).isEqualTo(r1.getRepositoryKey());
  886. assertThat(ruleForIndexing.getPluginRuleKey()).isEqualTo(r1.getRuleKey());
  887. assertThat(ruleForIndexing.getName()).isEqualTo(r1.getName());
  888. assertThat(ruleForIndexing.getRuleDescriptionSectionsDtos())
  889. .usingRecursiveComparison()
  890. .isEqualTo(r1.getRuleDescriptionSectionDtos());
  891. assertThat(ruleForIndexing.getDescriptionFormat()).isEqualTo(r1.getDescriptionFormat());
  892. assertThat(ruleForIndexing.getSeverity()).isEqualTo(r1.getSeverity());
  893. assertThat(ruleForIndexing.getSeverityAsString()).isEqualTo(SeverityUtil.getSeverityFromOrdinal(r1.getSeverity()));
  894. assertThat(ruleForIndexing.getStatus()).isEqualTo(r1.getStatus());
  895. assertThat(ruleForIndexing.isTemplate()).isEqualTo(r1.isTemplate());
  896. assertThat(ruleForIndexing.getSystemTags()).isEqualTo(r1.getSystemTags());
  897. assertThat(ruleForIndexing.getSecurityStandards()).isEqualTo(r1.getSecurityStandards());
  898. assertThat(ruleForIndexing.getInternalKey()).isEqualTo(r1.getConfigKey());
  899. assertThat(ruleForIndexing.getLanguage()).isEqualTo(r1.getLanguage());
  900. assertThat(ruleForIndexing.getType()).isEqualTo(r1.getType());
  901. assertThat(ruleForIndexing.getTypeAsRuleType()).isEqualTo(RuleType.valueOf(r1.getType()));
  902. assertThat(ruleForIndexing.getCreatedAt()).isEqualTo(r1.getCreatedAt());
  903. assertThat(ruleForIndexing.getUpdatedAt()).isEqualTo(r1.getUpdatedAt());
  904. }
  905. @Test
  906. public void scrollIndexingRulesByKeys_scrolls_nothing_if_key_does_not_exist() {
  907. Accumulator<RuleForIndexingDto> accumulator = new Accumulator<>();
  908. db.rules().insert();
  909. String nonExistingRuleUuid = "non-existing-uuid";
  910. underTest.selectIndexingRulesByKeys(db.getSession(), singletonList(nonExistingRuleUuid), accumulator);
  911. assertThat(accumulator.list).isEmpty();
  912. }
  913. @Test
  914. public void selectAllDeprecatedRuleKeys() {
  915. RuleDto r1 = db.rules().insert();
  916. RuleDto r2 = db.rules().insert();
  917. db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r1.getUuid()));
  918. db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r2.getUuid()));
  919. db.getSession().commit();
  920. Set<DeprecatedRuleKeyDto> deprecatedRuleKeyDtos = underTest.selectAllDeprecatedRuleKeys(db.getSession());
  921. assertThat(deprecatedRuleKeyDtos).hasSize(2);
  922. }
  923. @Test
  924. public void selectDeprecatedRuleKeysByRuleUuids() {
  925. RuleDto r1 = db.rules().insert();
  926. RuleDto r2 = db.rules().insert();
  927. RuleDto r3 = db.rules().insert();
  928. RuleDto r4 = db.rules().insert();
  929. DeprecatedRuleKeyDto drk1 = db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r1.getUuid()));
  930. DeprecatedRuleKeyDto drk2 = db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r1.getUuid()));
  931. DeprecatedRuleKeyDto drk3 = db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r2.getUuid()));
  932. db.rules().insertDeprecatedKey(r -> r.setRuleUuid(r4.getUuid()));
  933. db.getSession().commit();
  934. Set<DeprecatedRuleKeyDto> deprecatedRuleKeyDtos = underTest.selectDeprecatedRuleKeysByRuleUuids(
  935. db.getSession(), ImmutableSet.of(r1.getUuid(), r2.getUuid(), r3.getUuid()));
  936. assertThat(deprecatedRuleKeyDtos)
  937. .extracting(DeprecatedRuleKeyDto::getUuid)
  938. .containsExactlyInAnyOrder(drk1.getUuid(), drk2.getUuid(), drk3.getUuid());
  939. }
  940. @Test
  941. public void selectAllDeprecatedRuleKeys_return_values_even_if_there_is_no_rule() {
  942. db.rules().insertDeprecatedKey();
  943. db.rules().insertDeprecatedKey();
  944. Set<DeprecatedRuleKeyDto> deprecatedRuleKeyDtos = underTest.selectAllDeprecatedRuleKeys(db.getSession());
  945. assertThat(deprecatedRuleKeyDtos).hasSize(2);
  946. assertThat(deprecatedRuleKeyDtos)
  947. .extracting(DeprecatedRuleKeyDto::getNewRepositoryKey, DeprecatedRuleKeyDto::getNewRuleKey)
  948. .containsExactly(
  949. tuple(null, null),
  950. tuple(null, null));
  951. }
  952. @Test
  953. public void deleteDeprecatedRuleKeys_with_empty_list_has_no_effect() {
  954. db.rules().insertDeprecatedKey();
  955. db.rules().insertDeprecatedKey();
  956. assertThat(underTest.selectAllDeprecatedRuleKeys(db.getSession())).hasSize(2);
  957. underTest.deleteDeprecatedRuleKeys(db.getSession(), emptyList());
  958. assertThat(underTest.selectAllDeprecatedRuleKeys(db.getSession())).hasSize(2);
  959. }
  960. @Test
  961. public void deleteDeprecatedRuleKeys_with_non_existing_uuid_has_no_effect() {
  962. db.rules().insertDeprecatedKey(d -> d.setUuid("A1"));
  963. db.rules().insertDeprecatedKey(d -> d.setUuid("A2"));
  964. assertThat(underTest.selectAllDeprecatedRuleKeys(db.getSession())).hasSize(2);
  965. underTest.deleteDeprecatedRuleKeys(db.getSession(), asList("B1", "B2"));
  966. assertThat(underTest.selectAllDeprecatedRuleKeys(db.getSession())).hasSize(2);
  967. }
  968. @Test
  969. public void selectTags_shouldReturnSortedAndDistinct() {
  970. db.rules().insert(ruleDto -> ruleDto.setSystemTags(newHashSet("s1", "s2")).setTags(newHashSet("t1", "t2", "t3")));
  971. db.rules().insert(ruleDto -> ruleDto.setSystemTags(newHashSet("s3", "s4", "s5")).setTags(newHashSet("t3", "t4")));
  972. db.getSession().commit();
  973. assertThat(underTest.selectTags(db.getSession(), null, forPage(1).andSize(10)))
  974. .containsExactly("s1", "s2", "s3", "s4", "s5", "t1", "t2", "t3", "t4");
  975. }
  976. @Test
  977. public void selectTags_whenQueryPresent_shouldReturnFilteredList() {
  978. db.rules().insert(ruleDto -> ruleDto.setSystemTags(newHashSet("foo_1", "bar_2")).setTags(newHashSet("foo_3", "bar_4")));
  979. db.rules().insert(ruleDto -> ruleDto.setSystemTags(newHashSet("ping_5", "pong_6")).setTags(newHashSet("ping_7", "pong_8")));
  980. db.getSession().commit();
  981. assertThat(underTest.selectTags(db.getSession(), "foo", forPage(1).andSize(10))).containsExactly("foo_1", "foo_3");
  982. }
  983. @Test
  984. public void deleteDeprecatedRuleKeys() {
  985. DeprecatedRuleKeyDto deprecatedRuleKeyDto1 = db.rules().insertDeprecatedKey();
  986. db.rules().insertDeprecatedKey();
  987. assertThat(underTest.selectAllDeprecatedRuleKeys(db.getSession())).hasSize(2);
  988. underTest.deleteDeprecatedRuleKeys(db.getSession(), singletonList(deprecatedRuleKeyDto1.getUuid()));
  989. assertThat(underTest.selectAllDeprecatedRuleKeys(db.getSession())).hasSize(1);
  990. }
  991. @Test
  992. public void insertDeprecatedRuleKey() {
  993. RuleDto r1 = db.rules().insert();
  994. DeprecatedRuleKeyDto deprecatedRuleKeyDto = db.rules().insertDeprecatedKey(d -> d.setRuleUuid(r1.getUuid()));
  995. db.getSession().commit();
  996. Set<DeprecatedRuleKeyDto> deprecatedRuleKeyDtos = underTest.selectAllDeprecatedRuleKeys(db.getSession());
  997. assertThat(deprecatedRuleKeyDtos).hasSize(1);
  998. DeprecatedRuleKeyDto deprecatedRuleKeyDto1 = deprecatedRuleKeyDtos.iterator().next();
  999. assertThat(deprecatedRuleKeyDto1.getOldRepositoryKey()).isEqualTo(deprecatedRuleKeyDto.getOldRepositoryKey());
  1000. assertThat(deprecatedRuleKeyDto1.getOldRuleKey()).isEqualTo(deprecatedRuleKeyDto.getOldRuleKey());
  1001. assertThat(deprecatedRuleKeyDto1.getNewRepositoryKey()).isEqualTo(r1.getRepositoryKey());
  1002. assertThat(deprecatedRuleKeyDto1.getNewRuleKey()).isEqualTo(r1.getRuleKey());
  1003. assertThat(deprecatedRuleKeyDto1.getUuid()).isEqualTo(deprecatedRuleKeyDto.getUuid());
  1004. assertThat(deprecatedRuleKeyDto1.getCreatedAt()).isEqualTo(deprecatedRuleKeyDto.getCreatedAt());
  1005. assertThat(deprecatedRuleKeyDto1.getRuleUuid()).isEqualTo(r1.getUuid());
  1006. }
  1007. @Test
  1008. public void countByLanguage_shouldReturnExpectedNumberOfRules() {
  1009. insertMultipleRules(10, "js", false, READY);
  1010. insertMultipleRules(5, "js", true, READY);
  1011. insertMultipleRules(3, "kotlin", false, DEPRECATED);
  1012. insertMultipleRules(3, "java", false, REMOVED);
  1013. db.getSession().commit();
  1014. assertThat(underTest.countByLanguage(db.getSession(), "js")).isEqualTo(10);
  1015. assertThat(underTest.countByLanguage(db.getSession(), "kotlin")).isEqualTo(3);
  1016. assertThat(underTest.countByLanguage(db.getSession(), "java")).isZero();
  1017. }
  1018. private void insertMultipleRules(int rulesCount, String language, boolean isExternal, RuleStatus ruleStatus) {
  1019. for (int i = 0; i < rulesCount; i++) {
  1020. db.rules().insert(rule -> rule.setLanguage(language).setIsExternal(isExternal).setStatus(ruleStatus));
  1021. }
  1022. }
  1023. @Test
  1024. public void insertDeprecatedRuleKey_with_same_RuleKey_should_fail() {
  1025. String repositoryKey = randomAlphanumeric(50);
  1026. String ruleKey = randomAlphanumeric(50);
  1027. RuleDbTester ruleTester = db.rules();
  1028. ruleTester.insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey)
  1029. .setOldRuleKey(ruleKey));
  1030. assertThatThrownBy(() -> {
  1031. ruleTester.insertDeprecatedKey(d -> d.setOldRepositoryKey(repositoryKey)
  1032. .setOldRuleKey(ruleKey));
  1033. })
  1034. .isInstanceOf(PersistenceException.class);
  1035. }
  1036. @Test
  1037. public void selectRules_whenPagination_shouldReturnSpecificPage() {
  1038. db.rules().insert(rule -> rule.setUuid("uuid_1"));
  1039. db.rules().insert(rule -> rule.setUuid("uuid_2"));
  1040. db.rules().insert(rule -> rule.setUuid("uuid_3"));
  1041. db.rules().insert(rule -> rule.setUuid("uuid_4"));
  1042. Pagination pagination = Pagination.forPage(1).andSize(2);
  1043. RuleListResult ruleListResult = underTest.selectRules(db.getSession(), newRuleListQueryBuilder().build(), pagination);
  1044. assertThat(ruleListResult.getTotal()).isEqualTo(4);
  1045. assertThat(ruleListResult.getUuids()).containsExactly("uuid_1", "uuid_2");
  1046. }
  1047. @Test
  1048. public void selectRules_whenQueriedWithCreatedAt_shouldReturnRulesCreatedAfterCorrectlySorted() {
  1049. long baseTime = 1696028921248L;
  1050. db.rules().insert(rule -> rule.setUuid("uuid_1").setCreatedAt(baseTime));
  1051. db.rules().insert(rule -> rule.setUuid("uuid_2").setCreatedAt(baseTime + 1000));
  1052. db.rules().insert(rule -> rule.setUuid("uuid_3").setCreatedAt(baseTime - 2000));
  1053. db.rules().insert(rule -> rule.setUuid("uuid_4").setCreatedAt(baseTime - 1));
  1054. db.rules().insert(rule -> rule.setUuid("uuid_5").setCreatedAt(baseTime + 1));
  1055. RuleListQuery ruleListQuery = newRuleListQueryBuilder().createdAt(baseTime).sortField("createdAt").sortDirection("desc").build();
  1056. RuleListResult ruleListResult = underTest.selectRules(db.getSession(), ruleListQuery, Pagination.all());
  1057. assertThat(ruleListResult.getUuids()).containsExactly("uuid_2", "uuid_5", "uuid_1");
  1058. assertThat(ruleListResult.getTotal()).isEqualTo(3);
  1059. }
  1060. @Test
  1061. public void selectRules_whenQueriedWithLanguage_shouldReturnOnlyRulesWithLanguage() {
  1062. String queriedLang = "java";
  1063. db.rules().insert(rule -> rule.setUuid("uuid_1").setLanguage(queriedLang));
  1064. db.rules().insert(rule -> rule.setUuid("uuid_2").setLanguage("cpp"));
  1065. db.rules().insert(rule -> rule.setUuid("uuid_3").setLanguage("js"));
  1066. db.rules().insert(rule -> rule.setUuid("uuid_4").setLanguage(queriedLang));
  1067. RuleListQuery ruleListQuery = newRuleListQueryBuilder().language(queriedLang).build();
  1068. RuleListResult ruleListResult = underTest.selectRules(db.getSession(), ruleListQuery, Pagination.all());
  1069. assertThat(ruleListResult.getUuids()).containsExactly("uuid_1", "uuid_4");
  1070. assertThat(ruleListResult.getTotal()).isEqualTo(2);
  1071. }
  1072. @Test
  1073. public void selectRules_whenQueriedWithQualityProfile_shouldReturnOnlyRulesActiveForThisQualityProfile() {
  1074. QProfileDto profile = db.qualityProfiles().insert();
  1075. RuleDto rule1 = db.rules().insert(rule -> rule.setUuid("uuid_1"));
  1076. db.rules().insert(rule -> rule.setUuid("uuid_2"));
  1077. RuleDto rule3 = db.rules().insert(rule -> rule.setUuid("uuid_3"));
  1078. db.rules().insert(rule -> rule.setUuid("uuid_4"));
  1079. db.qualityProfiles().activateRule(profile, rule1);
  1080. db.qualityProfiles().activateRule(profile, rule3);
  1081. RuleListQuery ruleListQuery = newRuleListQueryBuilder().profileUuid(profile.getRulesProfileUuid()).build();
  1082. RuleListResult ruleListResult = underTest.selectRules(db.getSession(), ruleListQuery, Pagination.all());
  1083. assertThat(ruleListResult.getUuids()).containsExactly("uuid_1", "uuid_3");
  1084. assertThat(ruleListResult.getTotal()).isEqualTo(2);
  1085. }
  1086. private static ImpactDto newRuleDefaultImpact(SoftwareQuality softwareQuality, org.sonar.api.issue.impact.Severity severity) {
  1087. return new ImpactDto()
  1088. .setUuid(UuidFactoryFast.getInstance().create())
  1089. .setSoftwareQuality(softwareQuality)
  1090. .setSeverity(severity);
  1091. }
  1092. private static RuleDescriptionSectionDto createDefaultRuleDescriptionSection() {
  1093. return RuleDescriptionSectionDto.createDefaultRuleDescriptionSection(UuidFactoryFast.getInstance().create(), RandomStringUtils.randomAlphanumeric(1000));
  1094. }
  1095. private static class Accumulator<T> implements Consumer<T> {
  1096. private final List<T> list = new ArrayList<>();
  1097. @Override
  1098. public void accept(T dto) {
  1099. list.add(dto);
  1100. }
  1101. }
  1102. }