@Test public void constructor_reads_parameters_from_DB() { DbClient dbClient = mock(DbClient.class); DbSession dbSession = mock(DbSession.class); RuleDao ruleDao = mock(RuleDao.class); when(dbClient.openSession(anyBoolean())).thenReturn(dbSession); when(dbClient.ruleDao()).thenReturn(ruleDao); List<RuleKey> ruleKeys = Arrays.asList(RuleKey.of("A", "B"), RuleKey.of("C", "D"), RuleKey.of("E", "F")); when(ruleDao.selectAllDefinitions(dbSession)).thenReturn(ruleKeys.stream().map(RuleTesting::newRule).collect(toList())); new CachingRuleFinder(dbClient); verify(ruleDao).selectRuleParamsByRuleKeys(dbSession, ImmutableSet.copyOf(ruleKeys)); }
@Test public void key_can_contain_colons() { RuleKey key = RuleKey.of("squid", "Key:With:Some::Colons"); assertThat(key.repository()).isEqualTo("squid"); assertThat(key.rule()).isEqualTo("Key:With:Some::Colons"); }
@Test public void encode_and_decode_string() { RuleKey key = RuleKey.of("squid", "NullDeref"); String serialized = key.toString(); assertThat(serialized).isEqualTo("squid:NullDeref"); RuleKey parsed = RuleKey.parse(serialized); assertThat(parsed.repository()).isEqualTo("squid"); assertThat(parsed.rule()).isEqualTo("NullDeref"); assertThat(parsed.toString()).isEqualTo("squid:NullDeref"); }
RuleDefinitionDto setKey(RuleKey key) { this.key = key; setRepositoryKey(key.repository()); setRuleKey(key.rule()); return this; }
@Test public void shouldPassToChainIfRuleDoesNotMatch() { String rule = "rule"; RuleKey ruleKey = mock(RuleKey.class); when(ruleKey.toString()).thenReturn(rule); when(issue.ruleKey()).thenReturn(ruleKey); IssuePattern matching = mock(IssuePattern.class); when(matching.matchRule(ruleKey)).thenReturn(false); when(exclusionPatternInitializer.getMulticriteriaPatterns()).thenReturn(ImmutableList.of(matching)); ignoreFilter = new EnforceIssuesFilter(exclusionPatternInitializer, mock(AnalysisWarnings.class)); assertThat(ignoreFilter.accept(issue, chain)).isTrue(); verify(chain).accept(issue); }
@Test public void move_directory_issue_to_project_root() { SensorStorage storage = mock(SensorStorage.class); DefaultIssue issue = new DefaultIssue(project, storage) .at(new DefaultIssueLocation() .on(new DefaultInputDir("foo", "src/main").setModuleBaseDir(project.getBaseDir())) .message("Wrong way!")) .forRule(RuleKey.of("repo", "rule")) .overrideSeverity(Severity.BLOCKER); assertThat(issue.primaryLocation().inputComponent()).isEqualTo(project); assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("repo", "rule")); assertThat(issue.primaryLocation().textRange()).isNull(); assertThat(issue.primaryLocation().message()).isEqualTo("[src/main] Wrong way!"); assertThat(issue.overriddenSeverity()).isEqualTo(Severity.BLOCKER); issue.save(); verify(storage).store(issue); }
@Test public void define_rule_debt() { RulesDefinition.Context context = new RulesDefinition.Context(); List<DebtModelXMLExporter.RuleDebt> ruleDebts = newArrayList( new DebtModelXMLExporter.RuleDebt() .setRuleKey(RuleKey.of("checkstyle", "ConstantName")) .setFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name()) .setCoefficient("1d") .setOffset("10min")); Reader javaModelReader = mock(Reader.class); when(debtModelRepository.createReaderForXMLFile("java")).thenReturn(javaModelReader); when(debtModelRepository.getContributingPluginList()).thenReturn(newArrayList("java")); when(importer.importXML(eq(javaModelReader), any(ValidationMessages.class))).thenReturn(ruleDebts); new DeprecatedRulesDefinitionLoader(i18n, debtModelRepository, importer, pluginRepository, new RuleRepository[] {new CheckstyleRules()}).complete(context); assertThat(context.repositories()).hasSize(1); RulesDefinition.Repository checkstyle = context.repository("checkstyle"); assertThat(checkstyle.rules()).hasSize(1); RulesDefinition.Rule rule = checkstyle.rule("ConstantName"); assertThat(rule).isNotNull(); assertThat(rule.key()).isEqualTo("ConstantName"); assertThat(rule.debtRemediationFunction().type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET); assertThat(rule.debtRemediationFunction().gapMultiplier()).isEqualTo("1d"); assertThat(rule.debtRemediationFunction().baseEffort()).isEqualTo("10min"); }
@Test public void process_new_issue() { when(analysisMetadataHolder.isLongLivingBranch()).thenReturn(true); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setMsg("the message") .setRuleRepository("xoo") .setRuleKey("S001") .setSeverity(Constants.Severity.BLOCKER) .build(); reportReader.putIssues(FILE_REF, asList(reportIssue)); fileSourceRepository.addLine(FILE_REF, "line1"); underTest.visitAny(FILE); verify(issueLifecycle).initNewOpenIssue(defaultIssueCaptor.capture()); DefaultIssue capturedIssue = defaultIssueCaptor.getValue(); assertThat(capturedIssue.ruleKey().rule()).isEqualTo("S001"); verify(issueStatusCopier).tryMerge(FILE, Collections.singletonList(capturedIssue)); verify(issueLifecycle).doAutomaticTransition(capturedIssue); assertThat(newArrayList(issueCache.traverse())).hasSize(1); }
@Test public void testParamsAreTransformed() { LoadedActiveRule r1 = mockRule("rule1"); LoadedActiveRule r2 = mockRule("rule2"); r2.setParams(ImmutableMap.of("foo1", "bar1", "foo2", "bar2")); List<LoadedActiveRule> qpRules = ImmutableList.of(r1, r2); when(loader.load(eq("qp"))).thenReturn(qpRules); QualityProfiles profiles = mockProfiles("qp"); ActiveRules activeRules = provider.provide(loader, profiles); assertThat(activeRules.findAll()).hasSize(2); assertThat(activeRules.findAll()).extracting("ruleKey", "params").containsOnly( Tuple.tuple(RuleKey.of("rule1", "rule1"), ImmutableMap.of()), Tuple.tuple(RuleKey.of("rule2", "rule2"), ImmutableMap.of("foo1", "bar1", "foo2", "bar2"))); verify(loader).load(eq("qp")); verifyNoMoreInteractions(loader); }
@Test public void import_linear() throws Exception { String xml = getFileContent("import_linear.xml"); List<RuleDebt> results = underTest.importXML(xml, validationMessages); assertThat(results).hasSize(1); RuleDebt ruleDebt = results.get(0); assertThat(ruleDebt.ruleKey()).isEqualTo(RuleKey.of("checkstyle", "Regexp")); assertThat(ruleDebt.function()).isEqualTo(DebtRemediationFunction.Type.LINEAR.name()); assertThat(ruleDebt.coefficient()).isEqualTo("3h"); assertThat(ruleDebt.offset()).isNull(); }
@Test public void filter_exclude_issues_on_common_rule() { RuleKey ruleKey = RuleKey.of(CommonRuleKeys.commonRepositoryForLang("java"), "InsufficientCoverage"); markRuleAsActive(ruleKey); when(issueFilter.accept(any(), eq(FILE))).thenReturn(false); when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line")); DefaultIssue ceIssue = new DefaultIssue() .setRuleKey(ruleKey) .setMessage("not enough coverage") .setGap(10.0); when(commonRuleEngine.process(FILE)).thenReturn(singletonList(ceIssue)); Input<DefaultIssue> input = underTest.create(FILE); assertThat(input.getIssues()).isEmpty(); }
@Test public void set_rule() { IssueDto dto = new IssueDto() .setKee("100") .setRule(new RuleDefinitionDto().setId(1).setRuleKey("AvoidCycle").setRepositoryKey("squid").setIsExternal(true)) .setLanguage("xoo"); assertThat(dto.getRuleId()).isEqualTo(1); assertThat(dto.getRuleRepo()).isEqualTo("squid"); assertThat(dto.getRule()).isEqualTo("AvoidCycle"); assertThat(dto.getRuleKey().toString()).isEqualTo("squid:AvoidCycle"); assertThat(dto.getLanguage()).isEqualTo("xoo"); assertThat(dto.isExternal()).isEqualTo(true); }
@Test public void disable_then_enable_rule() { // Install rule when(system.now()).thenReturn(DATE1.getTime()); execute(new FakeRepositoryV1()); // Uninstall rule when(system.now()).thenReturn(DATE2.getTime()); execute(); RuleDto rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), defaultOrganization, RULE_KEY1); assertThat(rule.getStatus()).isEqualTo(REMOVED); assertThat(ruleIndex.search(new RuleQuery().setKey(RULE_KEY1.toString()), new SearchOptions()).getTotal()).isEqualTo(0); // Re-install rule when(system.now()).thenReturn(DATE3.getTime()); execute(new FakeRepositoryV1()); rule = dbClient.ruleDao().selectOrFailByKey(db.getSession(), defaultOrganization, RULE_KEY1); assertThat(rule.getStatus()).isEqualTo(RuleStatus.BETA); assertThat(ruleIndex.search(new RuleQuery().setKey(RULE_KEY1.toString()), new SearchOptions()).getTotal()).isEqualTo(1); }
private void setIssueBelongToNonExistingRule() { when(issue.getRuleKey()) .thenReturn(RuleKey.of("repo", "disabled")); }
@Test public void exclude_issues_on_common_rules() { RuleKey ruleKey = RuleKey.of(CommonRuleKeys.commonRepositoryForLang("java"), "S001"); markRuleAsActive(ruleKey); when(sourceLinesHash.getLineHashesMatchingDBVersion(FILE)).thenReturn(Collections.singletonList("line")); ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setMsg("the message") .setRuleRepository(ruleKey.repository()) .setRuleKey(ruleKey.rule()) .setSeverity(Constants.Severity.BLOCKER) .build(); reportReader.putIssues(FILE.getReportAttributes().getRef(), singletonList(reportIssue)); Input<DefaultIssue> input = underTest.create(FILE); assertThat(input.getIssues()).isEmpty(); }
private void assertThatRuleIsUpdated(QProfileDto profile, RuleDefinitionDto rule, String expectedSeverity, @Nullable ActiveRuleInheritance expectedInheritance, Map<String, String> expectedParams) { OrgActiveRuleDto activeRule = db.getDbClient().activeRuleDao().selectByProfile(db.getSession(), profile) .stream() .filter(ar -> ar.getRuleKey().equals(rule.getKey())) .findFirst() .orElseThrow(IllegalStateException::new); assertThat(activeRule.getSeverityString()).isEqualTo(expectedSeverity); assertThat(activeRule.getInheritance()).isEqualTo(expectedInheritance != null ? expectedInheritance.name() : null); assertThat(activeRule.getCreatedAt()).isNotNull(); assertThat(activeRule.getUpdatedAt()).isNotNull(); List<ActiveRuleParamDto> params = db.getDbClient().activeRuleDao().selectParamsByActiveRuleId(db.getSession(), activeRule.getId()); assertThat(params).hasSize(expectedParams.size()); }
@Test public void selectDefinitionByKeys() { RuleDefinitionDto rule = db.rules().insert(); assertThat(underTest.selectDefinitionByKeys(db.getSession(), Collections.emptyList())).isEmpty(); assertThat(underTest.selectDefinitionByKeys(db.getSession(), asList(RuleKey.of("NOT", "FOUND")))).isEmpty(); List<RuleDefinitionDto> rules = underTest.selectDefinitionByKeys(db.getSession(), asList(rule.getKey(), RuleKey.of("java", "OTHER"))); assertThat(rules).hasSize(1); assertThat(rules.get(0).getId()).isEqualTo(rule.getId()); }
@Test public void execute_issue_visitors() { ScannerReport.Issue reportIssue = ScannerReport.Issue.newBuilder() .setMsg("the message") .setRuleRepository("xoo") .setRuleKey("S001") .setSeverity(Constants.Severity.BLOCKER) .build(); reportReader.putIssues(FILE_REF, asList(reportIssue)); fileSourceRepository.addLine(FILE_REF, "line1"); underTest.visitAny(FILE); verify(issueVisitor).beforeComponent(FILE); verify(issueVisitor).afterComponent(FILE); verify(issueVisitor).onIssue(eq(FILE), defaultIssueCaptor.capture()); assertThat(defaultIssueCaptor.getValue().ruleKey().rule()).isEqualTo("S001"); }
@Test public void persist_new_externally_defined_Rules() { underTest = new RuleRepositoryImpl(adHocRuleCreator, db.getDbClient(), analysisMetadataHolder); RuleKey ruleKey = RuleKey.of("external_eslint", "no-cond-assign"); underTest.addOrUpdateAddHocRuleIfNeeded(ruleKey, () -> new NewAdHocRule(ScannerReport.ExternalIssue.newBuilder().setEngineId("eslint").setRuleId("no-cond-assign").build())); underTest.saveOrUpdateAddHocRules(db.getSession()); db.commit(); Optional<RuleDefinitionDto> ruleDefinitionDto = db.getDbClient().ruleDao().selectDefinitionByKey(db.getSession(), ruleKey); assertThat(ruleDefinitionDto).isPresent(); Rule rule = underTest.getByKey(ruleKey); assertThat(rule).isNotNull(); assertThat(underTest.getById(ruleDefinitionDto.get().getId())).isNotNull(); verify(ruleIndexer).commitAndIndex(db.getSession(), ruleDefinitionDto.get().getId()); }