org.sonar.api.rules.RuleType Java Examples

The following examples show how to use org.sonar.api.rules.RuleType. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TsLintRuleTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void ruleWithDebtRemediation() {
    TsLintRule rule = new TsLintRule(
        "key",
        Severity.MAJOR,
        "name",
        "<html></html>",
        DebtRemediationFunction.Type.LINEAR_OFFSET,
        "1min",
        "2min",
        RuleType.CODE_SMELL.name()
    );

    assertEquals("key", rule.key);
    assertEquals(Severity.MAJOR, rule.severity);
    assertEquals("name", rule.name);
    assertEquals("<html></html>", rule.htmlDescription);
    assertEquals(true, rule.hasDebtRemediation);
    assertEquals(DebtRemediationFunction.Type.LINEAR_OFFSET, rule.debtRemediationFunction);
    assertEquals("1min", rule.debtRemediationScalar);
    assertEquals("2min", rule.debtRemediationOffset);
    assertEquals(RuleType.CODE_SMELL.name(), rule.debtType);
}
 
Example #2
Source File: BitbucketServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 6 votes vote down vote up
private CreateReportRequest toReport(AnalysisDetails analysisDetails) {
    Map<RuleType, Long> rules = analysisDetails.countRuleByType();

    List<ReportData> reportData = new ArrayList<>();
    reportData.add(reliabilityReport(rules.get(RuleType.BUG)));
    reportData.add(new ReportData("Code coverage", new DataValue.Percentage(newCoverage(analysisDetails))));
    reportData.add(securityReport(rules.get(RuleType.VULNERABILITY), rules.get(RuleType.SECURITY_HOTSPOT)));
    reportData.add(new ReportData("Duplication", new DataValue.Percentage(newDuplication(analysisDetails))));
    reportData.add(maintainabilityReport(rules.get(RuleType.CODE_SMELL)));
    reportData.add(new ReportData("Analysis details", new DataValue.Link("Go to SonarQube", analysisDetails.getDashboardUrl())));

    return new CreateReportRequest(reportData,
            reportDescription(analysisDetails),
            "SonarQube",
            "SonarQube",
            analysisDetails.getAnalysisDate().toInstant(),
            analysisDetails.getDashboardUrl(),
            format("%s/common/icon.png", analysisDetails.getBaseImageUrl()),
            asInsightStatus(analysisDetails.getQualityGateStatus()));
}
 
Example #3
Source File: SmellRulesDefinition.java    From qualinsight-plugins-sonarqube-smell with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void addMetadata(final NewRule rule, final String metadataKey) {
    final String json = readRuleDefinitionResource(metadataKey + ".json");
    if (json != null) {
        final RuleMetadata metadata = this.gson.fromJson(json, RuleMetadata.class);
        rule.setSeverity(metadata.defaultSeverity.toUpperCase(Locale.US));
        rule.setName(metadata.title);
        rule.setTags(metadata.tags);
        rule.setStatus(RuleStatus.valueOf(metadata.status.toUpperCase(Locale.US)));
        rule.setType(RuleType.valueOf(metadata.type));

        if (metadata.remediation != null) {
            // metadata.remediation is null for template rules
            rule.setDebtRemediationFunction(metadata.remediation.remediationFunction(rule.debtRemediationFunctions()));
            rule.setGapDescription(metadata.remediation.linearDesc);
        }
    }
}
 
Example #4
Source File: RubyRulesDefinitionTest.java    From sonar-ruby-plugin with MIT License 6 votes vote down vote up
@Test
public void testGetCoreRules() {
    List<RubocopRule> coreRules = rules.getCoreRules();

    assertThat(coreRules.size()).isEqualTo(340);

    assertSeverityCount(Severity.BLOCKER, coreRules, 0);
    assertSeverityCount(Severity.CRITICAL, coreRules, 4);
    assertSeverityCount(Severity.MAJOR, coreRules, 0);
    assertSeverityCount(Severity.MINOR, coreRules, 324);
    assertSeverityCount(Severity.INFO, coreRules, 12);

    assertTypeCount(RuleType.CODE_SMELL, coreRules, 311);
    assertTypeCount(RuleType.VULNERABILITY, coreRules, 4);
    assertTypeCount(RuleType.BUG, coreRules, 25);
}
 
Example #5
Source File: AnalysisDetails.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
public Map<RuleType, Long> countRuleByType() {
    return Arrays.stream(RuleType.values()).collect(Collectors.toMap(k -> k,
                                                                     k -> postAnalysisIssueVisitor.getIssues()
                                                                             .stream()
                                                                             .map(PostAnalysisIssueVisitor.ComponentIssue::getIssue)
                                                                             .filter(i -> !CLOSED_ISSUE_STATUS
                                                                                     .contains(i.status()))
                                                                             .filter(i -> k == i.type()).count()));
}
 
Example #6
Source File: EsqlRulesDefinitionTest.java    From sonar-esql-plugin with Apache License 2.0 5 votes vote down vote up
private void assertRuleProperties(Repository repository) {
  Rule rule = repository.rule("UnusedRoutine");
  assertThat(rule).isNotNull();
  assertThat(rule.name()).isEqualTo("Unused routines should be removed");
  assertThat(rule.debtRemediationFunction().type()).isEqualTo(Type.CONSTANT_ISSUE);
  assertThat(rule.type()).isEqualTo(RuleType.CODE_SMELL);
  assertThat(repository.rule("CommentRegularExpression").template()).isTrue();
}
 
Example #7
Source File: CustomAllChecksProvider.java    From sonar-tsql-plugin with GNU General Public License v3.0 5 votes vote down vote up
public CandidateRule[] getChecks(final SensorContext context) {
	final Configuration config = context.config();
	final boolean skipCustomRules = config.getBoolean(Constants.PLUGIN_SKIP_CUSTOM_RULES).orElse(false);
	final String baseDir = context.fileSystem().baseDir().getAbsolutePath();

	final String[] paths = config.getStringArray(Constants.PLUGIN_CUSTOM_RULES_PATH);
	final String rulesPrefix = config.get(Constants.PLUGIN_CUSTOM_RULES_PREFIX).orElse(".customRules");

	final List<SqlRules> rules = new ArrayList<>();

	rules.addAll(provider.getRules(baseDir, rulesPrefix, paths).values());

	if (!skipCustomRules) {
		final SqlRules customRules = pluginChecksProvider.getRules();
		rules.add(customRules);
	}

	for (final SqlRules sqlRules : rules) {
		if (sqlRules.isIsAdhoc()) {
			for (final Rule r : sqlRules.getRule()) {
				context.newAdHocRule().description(r.getDescription()).engineId(sqlRules.getRepoKey())
						.ruleId(r.getKey()).type(RuleType.valueOf(r.getRuleType())).name(r.getName())
						.severity(Severity.valueOf(r.getSeverity())).save();
			}
		}
	}

	final SqlRules[] finalRules = rules.toArray(new SqlRules[0]);

	final CandidateRule[] candidateRules = convert(finalRules);
	LOGGER.info(String.format("Total %s custom rules repositories with total %s checks", rules.size(),
			candidateRules.length));
	return candidateRules;

}
 
Example #8
Source File: FlowRulesDefinition.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Converts the check to a rule by reading the params
 * @param check
 * @param repository
 */
@VisibleForTesting
protected void newRule(Class<? extends FlowCheck> check, NewRepository repository) {
  // Read the rule annotation of the check
  org.sonar.check.Rule ruleAnnotation = AnnotationUtils.getAnnotation(check,
      org.sonar.check.Rule.class);
  if (ruleAnnotation == null) {
    throw new IllegalArgumentException("No Rule annotation was found on " + check.getName());
  }
  // Read the ruleType annotation of the check
  FlowCheckRuleType ruleTypeAnnotation = AnnotationUtils.getAnnotation(check,
      FlowCheckRuleType.class);
  RuleType rt;
  if (ruleTypeAnnotation == null) {
    rt = RuleType.CODE_SMELL;
  }else {
    rt = ruleTypeAnnotation.ruletype();
  }
  // Add to repo
  String ruleKey = ruleAnnotation.key();
  if (StringUtils.isEmpty(ruleKey)) {
    throw new IllegalArgumentException("No key is defined in Rule annotation of " + check.getName());
  }
  NewRule rule = repository.rule(ruleKey);
  if (rule == null) {
    throw new IllegalStateException(
        "No rule was created for " + check + " in " + repository.key());
  }
  ruleKeys.add(rule.key());
  // Set html template
  addHtmlDescription(rule, ruleKey);
  rule.setTemplate(AnnotationUtils.getAnnotation(check, RuleTemplate.class) != null);
  // Set the type of the rule, instead of working with tags
  rule.setType(rt);
}
 
Example #9
Source File: RubyRulesDefinitionTest.java    From sonar-ruby-plugin with MIT License 5 votes vote down vote up
private void assertTypeCount(RuleType type, List<RubocopRule> rules, int expectedCount) {
    List<RubocopRule> filteredRules = rules.stream()
        .filter(rule -> type.equals(rule.debtType))
        .collect(Collectors.toList());

    assertThat(filteredRules.size()).isEqualTo(expectedCount);
}
 
Example #10
Source File: RubocopRule.java    From sonar-ruby-plugin with MIT License 5 votes vote down vote up
public RubocopRule(String key,String severity, String name, RuleType debtType, String htmlDescription) {
    this.key = key;
    this.severity = severity;
    this.name = name;
    this.debtType = debtType;
    this.htmlDescription = htmlDescription;
}
 
Example #11
Source File: RubyRulesDefinition.java    From sonar-ruby-plugin with MIT License 5 votes vote down vote up
private static RuleType findType(String rule) {
    RuleType type = CODE_SMELL;

    if (startsWith(rule, "Performance")) {
        type = BUG;
    } else if (startsWith(rule, "Security")) {
        type = VULNERABILITY;
    }

    return type;
}
 
Example #12
Source File: SonarDefinition.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void addMetadata(NewRule rule, String metadataKey) {
    URL resource = SonarDefinition.class.getResource(RESOURCE_BASE_PATH + "/" + metadataKey + "_java.json");
    if (resource != null) {
        RuleMetatada metatada = gson.fromJson(readResource(resource), RuleMetatada.class);
        rule.setSeverity(metatada.defaultSeverity.toUpperCase(Locale.US));
        rule.setName(metatada.title);
        rule.addTags(metatada.tags);
        rule.setType(RuleType.valueOf(metatada.type));
        rule.setStatus(RuleStatus.valueOf(metatada.status.toUpperCase(Locale.US)));
        if (metatada.remediation != null) {
            rule.setDebtRemediationFunction(metatada.remediation.remediationFunction(rule.debtRemediationFunctions()));
            rule.setGapDescription(metatada.remediation.linearDesc);
        }
    }
}
 
Example #13
Source File: SonarDefinition.java    From vjtools with Apache License 2.0 5 votes vote down vote up
private void addMetadata(NewRule rule, String metadataKey) {
    URL resource = SonarDefinition.class.getResource(RESOURCE_BASE_PATH + "/" + metadataKey + "_java.json");
    if (resource != null) {
        RuleMetatada metatada = gson.fromJson(readResource(resource), RuleMetatada.class);
        rule.setSeverity(metatada.defaultSeverity.toUpperCase(Locale.US));
        rule.setName(metatada.title);
        rule.addTags(metatada.tags);
        rule.setType(RuleType.valueOf(metatada.type));
        rule.setStatus(RuleStatus.valueOf(metatada.status.toUpperCase(Locale.US)));
        if (metatada.remediation != null) {
            rule.setDebtRemediationFunction(metatada.remediation.remediationFunction(rule.debtRemediationFunctions()));
            rule.setGapDescription(metatada.remediation.linearDesc);
        }
    }
}
 
Example #14
Source File: WebDriverRulesDefinition.java    From sonar-webdriver-plugin with MIT License 5 votes vote down vote up
private void addMetadata(NewRule rule, String metadataKey) {
  URL resource = WebDriverRulesDefinition.class.getResource(RESOURCE_BASE_PATH + "/" + metadataKey + "_java.json");
  if (resource != null) {
    RuleMetadata metadata = gson.fromJson(readResource(resource), RuleMetadata.class);
    rule.setSeverity(metadata.defaultSeverity.toUpperCase(Locale.US));
    rule.setName(metadata.title);
    rule.addTags(metadata.tags);
    rule.setType(RuleType.valueOf(metadata.type));
    rule.setStatus(RuleStatus.valueOf(metadata.status.toUpperCase(Locale.US)));
    if (metadata.remediation != null) {
      rule.setDebtRemediationFunction(metadata.remediation.remediationFunction(rule.debtRemediationFunctions()));
      rule.setGapDescription(metadata.remediation.linearDesc);
    }
  }
}
 
Example #15
Source File: BitbucketServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private String toBitbucketType(RuleType sonarqubeType) {
    switch (sonarqubeType) {
        case SECURITY_HOTSPOT:
        case VULNERABILITY:
            return "VULNERABILITY";
        case CODE_SMELL:
            return "CODE_SMELL";
        case BUG:
            return "BUG";
        default:
            throw new IllegalStateException(format("%s is not a valid ruleType.", sonarqubeType));
    }
}
 
Example #16
Source File: ExitCheck.java    From sonar-flow-plugin with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static RuleType getRuleType() {
  return RuleType.BUG;
}
 
Example #17
Source File: BitbucketPullRequestDecoratorTest.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 4 votes vote down vote up
private void mockValidAnalysis() {
    when(analysisDetails.getCommitSha()).thenReturn(COMMIT);
    when(analysisDetails.getQualityGateStatus()).thenReturn(QualityGate.Status.OK);

    Map<RuleType, Long> ruleCount = new HashMap<>();
    ruleCount.put(RuleType.CODE_SMELL, 1L);
    ruleCount.put(RuleType.VULNERABILITY, 2L);
    ruleCount.put(RuleType.SECURITY_HOTSPOT, 3L);
    ruleCount.put(RuleType.BUG, 4L);

    when(analysisDetails.countRuleByType()).thenReturn(ruleCount);
    when(analysisDetails.findQualityGateCondition(CoreMetrics.NEW_COVERAGE_KEY)).thenReturn(Optional.empty());
    when(analysisDetails.findQualityGateCondition(CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY)).thenReturn(Optional.empty());
    when(analysisDetails.getAnalysisDate()).thenReturn(Date.from(Instant.now()));
    when(analysisDetails.getDashboardUrl()).thenReturn(DASHBOARD_URL);

    ReportAttributes reportAttributes = mock(ReportAttributes.class);
    when(reportAttributes.getScmPath()).thenReturn(Optional.of(ISSUE_PATH));

    Component component = mock(Component.class);
    when(component.getType()).thenReturn(Component.Type.FILE);
    when(component.getReportAttributes()).thenReturn(reportAttributes);

    DefaultIssue defaultIssue = mock(DefaultIssue.class);
    when(defaultIssue.status()).thenReturn(Issue.STATUS_OPEN);
    when(defaultIssue.severity()).thenReturn(Severity.CRITICAL);
    when(defaultIssue.getLine()).thenReturn(ISSUE_LINE);
    when(defaultIssue.key()).thenReturn(ISSUE_KEY);
    when(defaultIssue.type()).thenReturn(RuleType.BUG);
    when(defaultIssue.getMessage()).thenReturn(ISSUE_MESSAGE);
    when(analysisDetails.getIssueUrl(ISSUE_KEY)).thenReturn(ISSUE_LINK);
    when(analysisDetails.getBaseImageUrl()).thenReturn(IMAGE_URL);

    PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(PostAnalysisIssueVisitor.ComponentIssue.class);
    when(componentIssue.getIssue()).thenReturn(defaultIssue);
    when(componentIssue.getComponent()).thenReturn(component);

    PostAnalysisIssueVisitor postAnalysisIssueVisitor = mock(PostAnalysisIssueVisitor.class);
    when(postAnalysisIssueVisitor.getIssues()).thenReturn(Collections.singletonList(componentIssue));

    when(analysisDetails.getPostAnalysisIssueVisitor()).thenReturn(postAnalysisIssueVisitor);
}
 
Example #18
Source File: TsRulesDefinition.java    From SonarTsPlugin with MIT License 4 votes vote down vote up
private void createRule(NewRepository repository, TsLintRule tsRule) {
    NewRule sonarRule =
                repository
                .createRule(tsRule.key)
                .setName(tsRule.name)
                .setSeverity(tsRule.severity)
                .setHtmlDescription(tsRule.htmlDescription)
                .setStatus(RuleStatus.READY);

    if (tsRule.hasDebtRemediation) {
        DebtRemediationFunction debtRemediationFn = null;
        DebtRemediationFunctions funcs = sonarRule.debtRemediationFunctions();

        switch (tsRule.debtRemediationFunction)
        {
            case LINEAR:
                debtRemediationFn = funcs.linear(tsRule.debtRemediationScalar);
                break;

            case LINEAR_OFFSET:
                debtRemediationFn = funcs.linearWithOffset(tsRule.debtRemediationScalar, tsRule.debtRemediationOffset);
                break;

            case CONSTANT_ISSUE:
                debtRemediationFn = funcs.constantPerIssue(tsRule.debtRemediationScalar);
                break;
        }

        sonarRule.setDebtRemediationFunction(debtRemediationFn);
    }

    RuleType type = null;

    if (tsRule.debtType != null && RuleType.names().contains(tsRule.debtType)) {
        // Try and parse it as a new-style rule type (since 5.5 SQALE's been replaced
        // with something simpler, and there's really only three buckets)
        type = RuleType.valueOf(tsRule.debtType);
    }

    if (type == null) {
        type = RuleType.CODE_SMELL;
    }

    sonarRule.setType(type);
}
 
Example #19
Source File: AnalysisDetails.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 4 votes vote down vote up
public String createAnalysisSummary(FormatterFactory formatterFactory) {

        BigDecimal newCoverage = getNewCoverage().orElse(null);


        double coverage = findMeasure(CoreMetrics.COVERAGE_KEY).map(Measure::getDoubleValue).orElse(0D);

        BigDecimal newDuplications = findQualityGateCondition(CoreMetrics.NEW_DUPLICATED_LINES_DENSITY_KEY)
                .filter(condition -> condition.getStatus() != EvaluationStatus.NO_VALUE)
                .map(QualityGate.Condition::getValue)
                .map(BigDecimal::new)
                .orElse(null);

        double duplications =
                findMeasure(CoreMetrics.DUPLICATED_LINES_DENSITY_KEY).map(Measure::getDoubleValue).orElse(0D);

        NumberFormat decimalFormat = new DecimalFormat("#0.00", DecimalFormatSymbols.getInstance(Locale.ENGLISH));

        Map<RuleType, Long> issueCounts = countRuleByType();
        long issueTotal = issueCounts.values().stream().mapToLong(l -> l).sum();

        List<QualityGate.Condition> failedConditions = findFailedConditions();

        String baseImageUrl = getBaseImageUrl();

        Document document = new Document(new Paragraph((QualityGate.Status.OK == getQualityGateStatus() ?
                                                        new Image("Passed", baseImageUrl +
                                                                            "/checks/QualityGateBadge/passed.svg?sanitize=true") :
                                                        new Image("Failed", baseImageUrl +
                                                                            "/checks/QualityGateBadge/failed.svg?sanitize=true"))),
                                         failedConditions.isEmpty() ? new Text("") :
                                         new com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.List(
                                                 com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.List.Style.BULLET,
                                                 failedConditions.stream().map(c -> new ListItem(new Text(format(c))))
                                                         .toArray(ListItem[]::new)),
                                         new Heading(1, new Text("Analysis Details")), new Heading(2, new Text(
                issueTotal + " Issue" + (issueCounts.values().stream().mapToLong(l -> l).sum() == 1 ? "" : "s"))),
                                         new com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.List(
                                                 com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.List.Style.BULLET,
                                                 new ListItem(new Image("Bug",
                                                                        baseImageUrl + "/common/bug.svg?sanitize=true"),
                                                              new Text(" "), new Text(
                                                         pluralOf(issueCounts.get(RuleType.BUG), "Bug", "Bugs"))),
                                                 new ListItem(new Image("Vulnerability", baseImageUrl +
                                                                                         "/common/vulnerability.svg?sanitize=true"),
                                                              new Text(" "), new Text(pluralOf(
                                                         issueCounts.get(RuleType.VULNERABILITY) +
                                                         issueCounts.get(RuleType.SECURITY_HOTSPOT), "Vulnerability",
                                                         "Vulnerabilities"))), new ListItem(new Image("Code Smell",
                                                                                                      baseImageUrl +
                                                                                                      "/common/vulnerability.svg?sanitize=true"),
                                                                                            new Text(" "), new Text(
                                                 pluralOf(issueCounts.get(RuleType.CODE_SMELL), "Code Smell",
                                                          "Code Smells")))),
                                         new Heading(2, new Text("Coverage and Duplications")),
                                         new com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.List(
                                                 com.github.mc1arke.sonarqube.plugin.ce.pullrequest.markup.List.Style.BULLET,
                                                 new ListItem(createCoverageImage(newCoverage, baseImageUrl),
                                                              new Text(" "), new Text(
                                                         Optional.ofNullable(newCoverage).map(decimalFormat::format)
                                                                 .map(i -> i + "% Coverage")
                                                                 .orElse("No coverage information") + " (" +
                                                         decimalFormat.format(coverage) + "% Estimated after merge)")),
                                                 new ListItem(createDuplicateImage(newDuplications, baseImageUrl),
                                                              new Text(" "), new Text(
                                                         Optional.ofNullable(newDuplications).map(decimalFormat::format)
                                                                 .map(i -> i + "% Duplicated Code")
                                                                 .orElse("No duplication information") + " (" +
                                                         decimalFormat.format(duplications) +
                                                         "% Estimated after merge)"))),
                                         new Link(getDashboardUrl(), new Text("View in SonarQube")));

        return formatterFactory.documentFormatter().format(document, formatterFactory);
    }
 
Example #20
Source File: TsRulesDefinitionTest.java    From SonarTsPlugin with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {

    this.settings = mock(Settings.class);

    when(this.settings.getKeysStartingWith(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS))
        .thenReturn(new ArrayList<String>() {{
            add(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg1.name");
            add(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg1.config");
            add(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg2.name");
            add(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg2.config");
            add(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg3.name");
            add(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg3.config");
        }});

    // config with one disabled rule
    when(this.settings.getString(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg1.config"))
        .thenReturn(
            "custom-rule-1=false\n" +
            "custom-rule-1.name=test rule #1\n" +
            "custom-rule-1.severity=MAJOR\n" +
            "custom-rule-1.description=#1 description\n" +
            "\n"
        );

    // config with a basic rule (no debt settings)
    when(this.settings.getString(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg2.config"))
        .thenReturn(
            "custom-rule-2=true\n" +
            "custom-rule-2.name=test rule #2\n" +
            "custom-rule-2.severity=MINOR\n" +
            "custom-rule-2.description=#2 description\n" +
            "\n"
        );

    // config with a advanced rules (including debt settings)
    when(this.settings.getString(TypeScriptPlugin.SETTING_TS_RULE_CONFIGS + ".cfg3.config"))
        .thenReturn(
            "custom-rule-3=true\n" +
            "custom-rule-3.name=test rule #3\n" +
            "custom-rule-3.severity=INFO\n" +
            "custom-rule-3.description=#3 description\n" +
            "custom-rule-3.debtFunc=" + DebtRemediationFunction.Type.CONSTANT_ISSUE + "\n" +
            "custom-rule-3.debtScalar=15min\n" +
            "custom-rule-3.debtOffset=1min\n" +
            "custom-rule-3.debtType=INVALID_TYPE_GOES_HERE\n" +
            "\n" +
            "custom-rule-4=true\n" +
            "custom-rule-4.name=test rule #4\n" +
            "custom-rule-4.severity=MINOR\n" +
            "custom-rule-4.description=#4 description\n" +
            "custom-rule-4.debtFunc=" + DebtRemediationFunction.Type.LINEAR + "\n" +
            "custom-rule-4.debtScalar=5min\n" +
            "custom-rule-4.debtOffset=2h\n" +
            "custom-rule-4.debtType=" + RuleType.BUG.name() + "\n" +
            "\n" +
            "custom-rule-5=true\n" +
            "custom-rule-5.name=test rule #5\n" +
            "custom-rule-5.severity=MAJOR\n" +
            "custom-rule-5.description=#5 description\n" +
            "custom-rule-5.debtFunc=" + DebtRemediationFunction.Type.LINEAR_OFFSET + "\n" +
            "custom-rule-5.debtScalar=30min\n" +
            "custom-rule-5.debtOffset=15min\n" +
            "custom-rule-5.debtType=" + RuleType.VULNERABILITY.name() + "\n" +
            "\n"
        );

    this.definition = new TsRulesDefinition(this.settings);
    this.context = new Context();
    this.definition.define(context);
}
 
Example #21
Source File: TsRulesDefinitionTest.java    From SonarTsPlugin with MIT License 4 votes vote down vote up
@Test
public void ConfiguresAdditionalRules() {
    // cfg1
    Rule rule1 = getRule("custom-rule-1");
    assertNull(rule1);

    // cfg2
    Rule rule2 = getRule("custom-rule-2");
    assertNotNull(rule2);
    assertEquals("test rule #2", rule2.name());
    assertEquals(Severity.MINOR, rule2.severity());
    assertEquals("#2 description", rule2.htmlDescription());
    assertEquals(null, rule2.debtRemediationFunction());
    assertEquals(RuleType.CODE_SMELL, rule2.type());

    // cfg3
    Rule rule3 = getRule("custom-rule-3");
    assertNotNull(rule3);
    assertEquals("test rule #3", rule3.name());
    assertEquals(Severity.INFO, rule3.severity());
    assertEquals("#3 description", rule3.htmlDescription());
    assertEquals(
        DebtRemediationFunction.Type.CONSTANT_ISSUE,
        rule3.debtRemediationFunction().type()
    );
    assertEquals(null, rule3.debtRemediationFunction().gapMultiplier());
    assertEquals("15min", rule3.debtRemediationFunction().baseEffort());
    assertEquals(RuleType.CODE_SMELL, rule3.type());

    // cfg4
    Rule rule4 = getRule("custom-rule-4");
    assertNotNull(rule4);
    assertEquals("test rule #4", rule4.name());
    assertEquals(Severity.MINOR, rule4.severity());
    assertEquals("#4 description", rule4.htmlDescription());
    assertEquals(
        DebtRemediationFunction.Type.LINEAR,
        rule4.debtRemediationFunction().type()
    );
    assertEquals("5min", rule4.debtRemediationFunction().gapMultiplier());
    assertEquals(null, rule4.debtRemediationFunction().baseEffort());
    assertEquals(RuleType.BUG, rule4.type());

    // cfg5
    Rule rule5 = getRule("custom-rule-5");
    assertNotNull(rule5);
    assertEquals("test rule #5", rule5.name());
    assertEquals(Severity.MAJOR, rule5.severity());
    assertEquals("#5 description", rule5.htmlDescription());
    assertEquals(RuleType.VULNERABILITY, rule5.type());

    assertEquals("30min", rule5.debtRemediationFunction().gapMultiplier());
    assertEquals("15min", rule5.debtRemediationFunction().baseEffort());
}