org.sonar.api.issue.Issue Java Examples

The following examples show how to use org.sonar.api.issue.Issue. 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: PmdViolationRecorderTest.java    From sonar-p3c-pmd with MIT License 6 votes vote down vote up
@Test
public void should_convert_pmd_violation_to_sonar_violation() {
  org.sonar.api.rules.Rule sonarRule = createRuleInRuleFinder("RULE");
  File file1 = new File("src/source.java");
  DefaultInputFile inputFile1 = addToFileSystem(file1);
  Issuable issuable = createIssuable(inputFile1);
  RuleViolation pmdViolation = createPmdViolation(file1, 42, "Description", "RULE");

  Issue issue = mock(Issue.class);
  IssueBuilder issueBuilder = mock(IssueBuilder.class);
  when(issuable.newIssueBuilder()).thenReturn(issueBuilder);
  when(issueBuilder.ruleKey(sonarRule.ruleKey())).thenReturn(issueBuilder);
  when(issueBuilder.message("Description")).thenReturn(issueBuilder);
  when(issueBuilder.line(42)).thenReturn(issueBuilder);
  when(issueBuilder.build()).thenReturn(issue);

  pmdViolationRecorder.saveViolation(pmdViolation);
  verify(issuable).addIssue(issue);
  verify(issueBuilder).ruleKey(sonarRule.ruleKey());
  verify(issueBuilder).message("Description");
  verify(issueBuilder).line(42);
  verify(sonarRule, atLeastOnce()).ruleKey();
}
 
Example #2
Source File: ApexSquidSensor.java    From enforce-sonarqube-plugin with MIT License 6 votes vote down vote up
/**
 * Saves issues form input file and source file.
 *
 * @param sonarFile input file.
 * @param squidFile source file.
 */
private void saveIssues(InputFile sonarFile, SourceFile squidFile) {
    Collection<CheckMessage> messages = squidFile.getCheckMessages();
    messages.forEach(message -> {
        RuleKey ruleKey = checks.ruleKey((SquidAstVisitor<Grammar>) message.getCheck());
        Issuable issuable = resourcePerspectives.as(Issuable.class, sonarFile);

        if (issuable != null) {
            Issue issue = issuable.newIssueBuilder()
                    .ruleKey(ruleKey)
                    .line(message.getLine())
                    .message(message.getText(Locale.ENGLISH))
                    .build();
            issuable.addIssue(issue);
        }
    });
}
 
Example #3
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 createCheckRunExceptionOnInvalidIssueSeverity() throws IOException, GeneralSecurityException {
    when(githubApplicationAuthenticationProvider.getInstallationToken(any(), any(), any(), any()))
            .thenReturn(mock(RepositoryAuthenticationToken.class));
    when(server.getPublicRootUrl()).thenReturn("http://sonar.server/root");

    ReportAttributes reportAttributes = mock(ReportAttributes.class);
    when(reportAttributes.getScmPath()).thenReturn(Optional.of("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.severity()).thenReturn("dummy");
    when(defaultIssue.status()).thenReturn(Issue.STATUS_OPEN);
    when(defaultIssue.resolution()).thenReturn(null);

    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.getQualityGateStatus()).thenReturn(QualityGate.Status.OK);
    when(analysisDetails.createAnalysisSummary(any())).thenReturn("dummy summary");
    when(analysisDetails.getCommitSha()).thenReturn("commit SHA");
    when(analysisDetails.getAnalysisProjectKey()).thenReturn("projectKey");
    when(analysisDetails.getBranchName()).thenReturn("branchName");
    when(analysisDetails.getAnalysisDate()).thenReturn(new Date(1234567890));
    when(analysisDetails.getAnalysisId()).thenReturn("analysis ID");
    when(analysisDetails.getPostAnalysisIssueVisitor()).thenReturn(postAnalysisIssueVisitor);

    ProjectAlmSettingDto projectAlmSettingDto = mock(ProjectAlmSettingDto.class);
    AlmSettingDto almSettingDto = mock(AlmSettingDto.class);
    when(almSettingDto.getUrl()).thenReturn("url");
    when(almSettingDto.getAppId()).thenReturn("app ID");
    when(almSettingDto.getPrivateKey()).thenReturn("key");
    when(projectAlmSettingDto.getAlmRepo()).thenReturn("group/repo");

    GraphqlCheckRunProvider testCase =
            new GraphqlCheckRunProvider(graphqlProvider, clock, githubApplicationAuthenticationProvider, server);
    assertThatThrownBy(() -> testCase.createCheckRun(analysisDetails, almSettingDto, projectAlmSettingDto))
            .hasMessage("Unknown severity value: dummy")
            .isExactlyInstanceOf(IllegalArgumentException.class);
}
 
Example #4
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 #5
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);
}