org.sonar.api.rule.Severity Java Examples

The following examples show how to use org.sonar.api.rule.Severity. 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: 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 #2
Source File: LicenseCheckRulesDefinition.java    From sonarqube-licensecheck with Apache License 2.0 6 votes vote down vote up
@Override
public void define(Context context)
{
    NewRepository repository = context.createRepository(LicenseCheckMetrics.LICENSE_CHECK_KEY, "java");
    repository.setName("License Check");

    repository
        .createRule(LicenseCheckMetrics.LICENSE_CHECK_UNLISTED_KEY)
        .setName("Dependency has unknown license [license-check]")
        .setHtmlDescription("The dependencies license could not be determined!")
        .setSeverity(Severity.BLOCKER);

    repository
        .createRule(LicenseCheckMetrics.LICENSE_CHECK_NOT_ALLOWED_LICENSE_KEY)
        .setName("License is not allowed [license-check]")
        .setHtmlDescription("Violation because the license of the dependency is not allowed.")
        .setSeverity(Severity.BLOCKER);

    repository.done();
}
 
Example #3
Source File: TsLintRuleTest.java    From SonarTsPlugin with MIT License 6 votes vote down vote up
@Test
public void ruleWithoutDebtRemediation() {
    TsLintRule rule = new TsLintRule(
        "key",
        Severity.MAJOR,
        "name",
        "<html></html>"
    );

    assertEquals("key", rule.key);
    assertEquals(Severity.MAJOR, rule.severity);
    assertEquals("name", rule.name);
    assertEquals("<html></html>", rule.htmlDescription);
    assertEquals(false, rule.hasDebtRemediation);
    assertEquals(DebtRemediationFunction.Type.CONSTANT_ISSUE, rule.debtRemediationFunction);
    assertEquals("0min", rule.debtRemediationScalar);
    assertEquals("0min", rule.debtRemediationOffset);
    assertEquals(null, rule.debtType);
}
 
Example #4
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 #5
Source File: GraphqlCheckRunProvider.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private static CheckAnnotationLevel mapToGithubAnnotationLevel(String sonarqubeSeverity) {
    switch (sonarqubeSeverity) {
        case Severity.INFO:
            return CheckAnnotationLevel.NOTICE;
        case Severity.MINOR:
        case Severity.MAJOR:
            return CheckAnnotationLevel.WARNING;
        case Severity.CRITICAL:
        case Severity.BLOCKER:
            return CheckAnnotationLevel.FAILURE;
        default:
            throw new IllegalArgumentException("Unknown severity value: " + sonarqubeSeverity);
    }
}
 
Example #6
Source File: BitbucketServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private void updateAnnotations(String project, String repo, AnalysisDetails analysisDetails, AlmSettingDto almSettingDto) throws IOException {
    final AtomicInteger chunkCounter = new AtomicInteger(0);

    client.deleteAnnotations(project, repo, analysisDetails.getCommitSha(), almSettingDto);

    Map<Object, Set<Annotation>> annotationChunks = analysisDetails.getPostAnalysisIssueVisitor().getIssues().stream()
            .filter(i -> i.getComponent().getReportAttributes().getScmPath().isPresent())
            .filter(i -> i.getComponent().getType() == Component.Type.FILE)
            .filter(i -> OPEN_ISSUE_STATUSES.contains(i.getIssue().status()))
            .sorted(Comparator.comparing(a -> Severity.ALL.indexOf(a.getIssue().severity())))
            .map(componentIssue -> {
                String path = componentIssue.getComponent().getReportAttributes().getScmPath().get();
                return new Annotation(componentIssue.getIssue().key(),
                        Optional.ofNullable(componentIssue.getIssue().getLine()).orElse(0),
                        analysisDetails.getIssueUrl(componentIssue.getIssue().key()),
                        componentIssue.getIssue().getMessage(),
                        path,
                        toBitbucketSeverity(componentIssue.getIssue().severity()),
                        toBitbucketType(componentIssue.getIssue().type()));
            }).collect(Collectors.groupingBy(s -> chunkCounter.getAndIncrement() / DEFAULT_MAX_ANNOTATIONS, toSet()));

    for (Set<Annotation> annotations : annotationChunks.values()) {
        try {
            client.createAnnotations(project, repo, analysisDetails.getCommitSha(), new CreateAnnotationsRequest(annotations), almSettingDto);
        } catch (BitbucketException e) {
            if (e.isError(BitbucketException.PAYLOAD_TOO_LARGE)) {
                LOGGER.warn("The annotations will be truncated since the maximum number of annotations for this report has been reached.");
            } else {
                throw e;
            }

        }
    }
}
 
Example #7
Source File: BitbucketServerPullRequestDecorator.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 5 votes vote down vote up
private String toBitbucketSeverity(String severity) {
    if (severity == null) {
        return "LOW";
    }
    switch (severity) {
        case Severity.BLOCKER:
        case Severity.CRITICAL:
            return "HIGH";
        case Severity.MAJOR:
            return "MEDIUM";
        default:
            return "LOW";
    }
}
 
Example #8
Source File: GraphqlCheckRunProviderTest.java    From sonarqube-community-branch-plugin with GNU General Public License v3.0 4 votes vote down vote up
@Test
public void checkExcessIssuesCorrectlyReported() throws IOException, GeneralSecurityException {
    ReportAttributes reportAttributes = mock(ReportAttributes.class);
    when(reportAttributes.getScmPath()).thenReturn(Optional.of("abc"));
    Component component = mock(Component.class);
    when(component.getType()).thenReturn(Component.Type.FILE);
    when(component.getReportAttributes()).thenReturn(reportAttributes);
    List<PostAnalysisIssueVisitor.ComponentIssue> issues = IntStream.range(0, 120)
            .mapToObj(i -> {
                DefaultIssue defaultIssue = mock(DefaultIssue.class);
                when(defaultIssue.severity()).thenReturn(Severity.INFO);
                when(defaultIssue.getMessage()).thenReturn("message");
                when(defaultIssue.status()).thenReturn(Issue.STATUS_OPEN);
                when(defaultIssue.resolution()).thenReturn(null);
                return defaultIssue;
            })
            .map(i -> {
                PostAnalysisIssueVisitor.ComponentIssue componentIssue = mock(
                        PostAnalysisIssueVisitor.ComponentIssue.class);
                when(componentIssue.getComponent()).thenReturn(component);
                when(componentIssue.getIssue()).thenReturn(i);
                return componentIssue;
            }).collect(Collectors.toList());

    PostAnalysisIssueVisitor postAnalysisIssuesVisitor = mock(PostAnalysisIssueVisitor.class);
    when(postAnalysisIssuesVisitor.getIssues()).thenReturn(issues);

    AnalysisDetails analysisDetails = mock(AnalysisDetails.class);
    when(analysisDetails.getPostAnalysisIssueVisitor()).thenReturn(postAnalysisIssuesVisitor);
    when(analysisDetails.getBranchName()).thenReturn("branchName");
    when(analysisDetails.getAnalysisProjectKey()).thenReturn("projectKey");
    when(analysisDetails.getAnalysisDate()).thenReturn(new Date());

    List<InputObject.Builder> builders = new ArrayList<>();

    GraphqlProvider graphqlProvider = mock(GraphqlProvider.class);
    when(graphqlProvider.createInputObject()).thenAnswer(i -> {
        InputObject.Builder builder = spy(new InputObject.Builder<>());
        builders.add(builder);
        return builder;
    });

    GraphQLRequestEntity.RequestBuilder requestBuilder = GraphQLRequestEntity.Builder();
    ObjectMapper objectMapper = new ObjectMapper();

    when(graphqlProvider.createRequestBuilder()).thenReturn(requestBuilder);

    GraphQLTemplate graphQLTemplate = mock(GraphQLTemplate.class);
    GraphQLResponseEntity<CreateCheckRun> graphQLResponseEntity =
            new ObjectMapper().readValue("{\"response\": {\"checkRun\": {\"id\": \"ABC\"}}}", objectMapper.getTypeFactory().constructParametricType(GraphQLResponseEntity.class, CreateCheckRun.class));
    when(graphQLTemplate.mutate(any(), eq(CreateCheckRun.class))).thenReturn(graphQLResponseEntity);
    GraphQLResponseEntity<UpdateCheckRun> graphQLResponseEntity2 =
            new ObjectMapper().readValue("{\"response\": {\"checkRun\": {\"id\": \"ABC\"}}}", objectMapper.getTypeFactory().constructParametricType(GraphQLResponseEntity.class, UpdateCheckRun.class));
    when(graphQLTemplate.mutate(any(), eq(UpdateCheckRun.class))).thenReturn(graphQLResponseEntity2);
    when(graphqlProvider.createGraphQLTemplate()).thenReturn(graphQLTemplate);

    Clock clock = mock(Clock.class);
    when(clock.instant()).thenReturn(Instant.now());

    RepositoryAuthenticationToken repositoryAuthenticationToken = mock(RepositoryAuthenticationToken.class);
    when(repositoryAuthenticationToken.getAuthenticationToken()).thenReturn("dummy");
    GithubApplicationAuthenticationProvider githubApplicationAuthenticationProvider = mock(GithubApplicationAuthenticationProvider.class);
    when(githubApplicationAuthenticationProvider.getInstallationToken(any(), any(), any(), any())).thenReturn(repositoryAuthenticationToken);

    Server server = mock(Server.class);

    ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class);
    when(projectAlmSettingDto.getAlmRepo()).thenReturn("dummy/repo");
    AlmSettingDto almSettingDto = mock(AlmSettingDto.class);
    when(almSettingDto.getUrl()).thenReturn("http://host.name");
    when(almSettingDto.getAppId()).thenReturn("app id");
    when(almSettingDto.getPrivateKey()).thenReturn("private key");

    GraphqlCheckRunProvider testCase = new GraphqlCheckRunProvider(graphqlProvider, clock, githubApplicationAuthenticationProvider, server);
    testCase.createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto);

    ArgumentCaptor<Class<?>> classArgumentCaptor = ArgumentCaptor.forClass(Class.class);
    verify(graphQLTemplate, times(3)).mutate(any(GraphQLRequestEntity.class), classArgumentCaptor.capture());

    assertThat(classArgumentCaptor.getAllValues()).containsExactly(CreateCheckRun.class, UpdateCheckRun.class, UpdateCheckRun.class);

    ArgumentCaptor<List<InputObject>> annotationsArgumentCaptor = ArgumentCaptor.forClass(List.class);
    verify(builders.get(100), times(3)).put(eq("annotations"), annotationsArgumentCaptor.capture());
    assertThat(annotationsArgumentCaptor.getAllValues().get(0)).hasSize(50);
    assertThat(annotationsArgumentCaptor.getAllValues().get(1)).hasSize(50);
    assertThat(annotationsArgumentCaptor.getAllValues().get(2)).hasSize(20);
}
 
Example #9
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 #10
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());
}