Search in sources :

Example 6 with EvaluatedQualityGate

use of org.sonar.server.qualitygate.EvaluatedQualityGate in project sonarqube by SonarSource.

the class WebhookPostTaskTest method callWebHooks.

private void callWebHooks(@Nullable String analysisUUid, @Nullable QualityGate qualityGate) {
    Project project = newProjectBuilder().setUuid(randomAlphanumeric(3)).setKey(randomAlphanumeric(4)).setName(randomAlphanumeric(5)).build();
    CeTask ceTask = newCeTaskBuilder().setStatus(CeTask.Status.values()[random.nextInt(CeTask.Status.values().length)]).setId(randomAlphanumeric(6)).build();
    Date date = new Date();
    Map<String, String> properties = ImmutableMap.of(randomAlphanumeric(17), randomAlphanumeric(18));
    Branch branch = newBranchBuilder().setIsMain(random.nextBoolean()).setType(Branch.Type.values()[random.nextInt(Branch.Type.values().length)]).setName(randomAlphanumeric(29)).build();
    PostProjectAnalysisTaskTester.of(underTest).at(date).withCeTask(ceTask).withProject(project).withBranch(branch).withQualityGate(qualityGate).withScannerContext(newScannerContextBuilder().addProperties(properties).build()).withAnalysisUuid(analysisUUid).withQualityGate(qualityGate).execute();
    ArgumentCaptor<Supplier> supplierCaptor = ArgumentCaptor.forClass(Supplier.class);
    verify(webHooks).sendProjectAnalysisUpdate(eq(new WebHooks.Analysis(project.getUuid(), analysisUUid, ceTask.getId())), supplierCaptor.capture(), any(LogStatistics.class));
    assertThat(supplierCaptor.getValue().get()).isSameAs(webhookPayload);
    EvaluatedQualityGate webQualityGate = null;
    if (qualityGate != null) {
        QualityGate.Condition condition = qualityGate.getConditions().iterator().next();
        Condition qgCondition = new Condition(condition.getMetricKey(), Condition.Operator.valueOf(condition.getOperator().name()), condition.getErrorThreshold());
        webQualityGate = EvaluatedQualityGate.newBuilder().setQualityGate(new org.sonar.server.qualitygate.QualityGate(qualityGate.getId(), qualityGate.getName(), Collections.singleton(qgCondition))).setStatus(Metric.Level.valueOf(qualityGate.getStatus().name())).addEvaluatedCondition(qgCondition, EvaluatedCondition.EvaluationStatus.valueOf(condition.getStatus().name()), condition.getValue()).build();
    }
    verify(payloadFactory).create(new ProjectAnalysis(new org.sonar.server.webhook.Project(project.getUuid(), project.getKey(), project.getName()), new org.sonar.server.webhook.CeTask(ceTask.getId(), org.sonar.server.webhook.CeTask.Status.valueOf(ceTask.getStatus().name())), analysisUUid == null ? null : new Analysis(analysisUUid, date.getTime(), null), new org.sonar.server.webhook.Branch(branch.isMain(), branch.getName().get(), org.sonar.server.webhook.Branch.Type.valueOf(branch.getType().name())), webQualityGate, analysisUUid == null ? null : date.getTime(), properties));
}
Also used : EvaluatedCondition(org.sonar.server.qualitygate.EvaluatedCondition) Condition(org.sonar.server.qualitygate.Condition) CeTask(org.sonar.api.ce.posttask.CeTask) Date(java.util.Date) QualityGate(org.sonar.api.ce.posttask.QualityGate) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) Project(org.sonar.api.ce.posttask.Project) ProjectAnalysis(org.sonar.server.webhook.ProjectAnalysis) Branch(org.sonar.api.ce.posttask.Branch) Analysis(org.sonar.server.webhook.Analysis) ProjectAnalysis(org.sonar.server.webhook.ProjectAnalysis) LogStatistics(org.sonar.api.ce.posttask.PostProjectAnalysisTask.LogStatistics) Supplier(java.util.function.Supplier) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate)

Example 7 with EvaluatedQualityGate

use of org.sonar.server.qualitygate.EvaluatedQualityGate in project sonarqube by SonarSource.

the class LiveQualityGateComputerImplTest method refreshGateStatus_generates_gate_related_measures.

@Test
public void refreshGateStatus_generates_gate_related_measures() {
    ComponentDto project = ComponentTesting.newPublicProjectDto();
    MetricDto conditionMetric = newMetricDto();
    MetricDto statusMetric = newMetricDto().setKey(CoreMetrics.ALERT_STATUS_KEY);
    MetricDto detailsMetric = newMetricDto().setKey(CoreMetrics.QUALITY_GATE_DETAILS_KEY);
    Condition condition = new Condition(conditionMetric.getKey(), Condition.Operator.GREATER_THAN, "10");
    QualityGate gate = new QualityGate("1", "foo", ImmutableSet.of(condition));
    MeasureMatrix matrix = new MeasureMatrix(singleton(project), asList(conditionMetric, statusMetric, detailsMetric), emptyList());
    EvaluatedQualityGate result = underTest.refreshGateStatus(project, gate, matrix, configuration);
    QualityGateEvaluator.Measures measures = qualityGateEvaluator.getCalledMeasures();
    assertThat(measures.get(conditionMetric.getKey())).isEmpty();
    assertThat(result.getStatus()).isEqualTo(Metric.Level.OK);
    assertThat(result.getEvaluatedConditions()).extracting(EvaluatedCondition::getStatus).containsExactly(EvaluatedCondition.EvaluationStatus.OK);
    assertThat(matrix.getMeasure(project, CoreMetrics.ALERT_STATUS_KEY).get().getDataAsString()).isEqualTo(Metric.Level.OK.name());
    assertThat(matrix.getMeasure(project, CoreMetrics.QUALITY_GATE_DETAILS_KEY).get().getDataAsString()).isNotEmpty().startsWith("{").endsWith("}");
}
Also used : EvaluatedCondition(org.sonar.server.qualitygate.EvaluatedCondition) Condition(org.sonar.server.qualitygate.Condition) MetricTesting.newMetricDto(org.sonar.db.metric.MetricTesting.newMetricDto) MetricDto(org.sonar.db.metric.MetricDto) ComponentDto(org.sonar.db.component.ComponentDto) QualityGateEvaluator(org.sonar.server.qualitygate.QualityGateEvaluator) QualityGate(org.sonar.server.qualitygate.QualityGate) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) Test(org.junit.Test)

Example 8 with EvaluatedQualityGate

use of org.sonar.server.qualitygate.EvaluatedQualityGate in project sonarqube by SonarSource.

the class ProjectAnalysisTest method defines_hashcode_based_on_all_fields.

@Test
public void defines_hashcode_based_on_all_fields() {
    assertThat(underTest).hasSameHashCodeAs(underTest).hasSameHashCodeAs(new ProjectAnalysis(project, ceTask, analysis, branch, qualityGate, 1L, properties));
    assertThat(underTest.hashCode()).isNotEqualTo(new Object().hashCode()).isNotEqualTo(new ProjectAnalysis(project, new CeTask("2", CeTask.Status.SUCCESS), analysis, branch, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(new Project("A", "B", "C"), ceTask, analysis, branch, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(new Project("A", "B", "C"), ceTask, analysis, branch, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, null, null, null, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, null, null, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, new Analysis("foo", 1_500L, "sha1"), null, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, null, qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, new Branch(false, "B", Branch.Type.BRANCH), qualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, null, 1L, properties).hashCode());
    EvaluatedQualityGate otherQualityGate = EvaluatedQualityGate.newBuilder().setQualityGate(new QualityGate("A", "B", emptySet())).setStatus(Metric.Level.ERROR).build();
    assertThat(underTest.hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, otherQualityGate, 1L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, null, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, 2L, properties).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, 1L, emptyMap()).hashCode()).isNotEqualTo(new ProjectAnalysis(project, ceTask, analysis, branch, this.qualityGate, 1L, ImmutableMap.of("B", "C")).hashCode());
}
Also used : EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) QualityGate(org.sonar.server.qualitygate.QualityGate) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) Test(org.junit.Test)

Example 9 with EvaluatedQualityGate

use of org.sonar.server.qualitygate.EvaluatedQualityGate in project sonarqube by SonarSource.

the class LiveMeasureComputerImpl method refreshComponentsOnSameProject.

private Optional<QGChangeEvent> refreshComponentsOnSameProject(DbSession dbSession, List<ComponentDto> touchedComponents) {
    // load all the components to be refreshed, including their ancestors
    List<ComponentDto> components = loadTreeOfComponents(dbSession, touchedComponents);
    ComponentDto branchComponent = findBranchComponent(components);
    BranchDto branch = loadBranch(dbSession, branchComponent);
    ProjectDto project = loadProject(dbSession, branch.getProjectUuid());
    Optional<SnapshotDto> lastAnalysis = dbClient.snapshotDao().selectLastAnalysisByRootComponentUuid(dbSession, branchComponent.uuid());
    if (!lastAnalysis.isPresent()) {
        return Optional.empty();
    }
    QualityGate qualityGate = qGateComputer.loadQualityGate(dbSession, project, branch);
    Collection<String> metricKeys = getKeysOfAllInvolvedMetrics(qualityGate);
    List<MetricDto> metrics = dbClient.metricDao().selectByKeys(dbSession, metricKeys);
    Map<String, MetricDto> metricsPerId = metrics.stream().collect(uniqueIndex(MetricDto::getUuid));
    List<String> componentUuids = components.stream().map(ComponentDto::uuid).collect(toArrayList(components.size()));
    List<LiveMeasureDto> dbMeasures = dbClient.liveMeasureDao().selectByComponentUuidsAndMetricUuids(dbSession, componentUuids, metricsPerId.keySet());
    // previous status must be load now as MeasureMatrix mutate the LiveMeasureDto which are passed to it
    Metric.Level previousStatus = loadPreviousStatus(metrics, dbMeasures);
    Configuration config = projectConfigurationLoader.loadProjectConfiguration(dbSession, branchComponent);
    DebtRatingGrid debtRatingGrid = new DebtRatingGrid(config);
    MeasureMatrix matrix = new MeasureMatrix(components, metricsPerId.values(), dbMeasures);
    FormulaContextImpl context = new FormulaContextImpl(matrix, debtRatingGrid);
    long beginningOfLeak = getBeginningOfLeakPeriod(lastAnalysis, branch);
    components.forEach(c -> {
        IssueCounter issueCounter = new IssueCounter(dbClient.issueDao().selectIssueGroupsByBaseComponent(dbSession, c, beginningOfLeak));
        for (IssueMetricFormula formula : formulaFactory.getFormulas()) {
            // use formulas when the leak period is defined, it's a PR, or the formula is not about the leak period
            if (shouldUseLeakFormulas(lastAnalysis.get(), branch) || !formula.isOnLeak()) {
                context.change(c, formula);
                try {
                    formula.compute(context, issueCounter);
                } catch (RuntimeException e) {
                    throw new IllegalStateException("Fail to compute " + formula.getMetric().getKey() + " on " + context.getComponent().getDbKey(), e);
                }
            }
        }
    });
    EvaluatedQualityGate evaluatedQualityGate = qGateComputer.refreshGateStatus(branchComponent, qualityGate, matrix, config);
    // persist the measures that have been created or updated
    matrix.getChanged().sorted(LiveMeasureComparator.INSTANCE).forEach(m -> dbClient.liveMeasureDao().insertOrUpdate(dbSession, m));
    projectIndexer.commitAndIndexComponents(dbSession, singleton(branchComponent), ProjectIndexer.Cause.MEASURE_CHANGE);
    return Optional.of(new QGChangeEvent(project, branch, lastAnalysis.get(), config, previousStatus, () -> Optional.of(evaluatedQualityGate)));
}
Also used : ProjectDto(org.sonar.db.project.ProjectDto) BranchDto(org.sonar.db.component.BranchDto) Configuration(org.sonar.api.config.Configuration) SnapshotDto(org.sonar.db.component.SnapshotDto) ComponentDto(org.sonar.db.component.ComponentDto) QGChangeEvent(org.sonar.server.qualitygate.changeevent.QGChangeEvent) QualityGate(org.sonar.server.qualitygate.QualityGate) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) MetricDto(org.sonar.db.metric.MetricDto) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) Metric(org.sonar.api.measures.Metric) DebtRatingGrid(org.sonar.server.measure.DebtRatingGrid)

Example 10 with EvaluatedQualityGate

use of org.sonar.server.qualitygate.EvaluatedQualityGate in project sonarqube by SonarSource.

the class LiveQualityGateComputerImpl method refreshGateStatus.

@Override
public EvaluatedQualityGate refreshGateStatus(ComponentDto project, QualityGate gate, MeasureMatrix measureMatrix, Configuration configuration) {
    QualityGateEvaluator.Measures measures = metricKey -> {
        Optional<LiveMeasureDto> liveMeasureDto = measureMatrix.getMeasure(project, metricKey);
        if (!liveMeasureDto.isPresent()) {
            return Optional.empty();
        }
        MetricDto metric = measureMatrix.getMetricByUuid(liveMeasureDto.get().getMetricUuid());
        return Optional.of(new LiveMeasure(liveMeasureDto.get(), metric));
    };
    EvaluatedQualityGate evaluatedGate = evaluator.evaluate(gate, measures, configuration);
    measureMatrix.setValue(project, CoreMetrics.ALERT_STATUS_KEY, evaluatedGate.getStatus().name());
    measureMatrix.setValue(project, CoreMetrics.QUALITY_GATE_DETAILS_KEY, QualityGateConverter.toJson(evaluatedGate));
    return evaluatedGate;
}
Also used : BranchDto(org.sonar.db.component.BranchDto) QualityGateConverter(org.sonar.server.qualitygate.QualityGateConverter) QualityGateEvaluator(org.sonar.server.qualitygate.QualityGateEvaluator) OptionalDouble(java.util.OptionalDouble) DbSession(org.sonar.db.DbSession) QualityGateFinder(org.sonar.server.qualitygate.QualityGateFinder) Condition(org.sonar.server.qualitygate.Condition) HashSet(java.util.HashSet) QualityGateConditionDto(org.sonar.db.qualitygate.QualityGateConditionDto) Map(java.util.Map) Configuration(org.sonar.api.config.Configuration) QualityGate(org.sonar.server.qualitygate.QualityGate) BranchType(org.sonar.db.component.BranchType) Collection(java.util.Collection) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate) Set(java.util.Set) QualityGateDto(org.sonar.db.qualitygate.QualityGateDto) MoreCollectors.toHashSet(org.sonar.core.util.stream.MoreCollectors.toHashSet) CoreMetrics(org.sonar.api.measures.CoreMetrics) DbClient(org.sonar.db.DbClient) ComponentDto(org.sonar.db.component.ComponentDto) Stream(java.util.stream.Stream) MetricDto(org.sonar.db.metric.MetricDto) LiveMeasureDto(org.sonar.db.measure.LiveMeasureDto) ProjectDto(org.sonar.db.project.ProjectDto) MoreCollectors.uniqueIndex(org.sonar.core.util.stream.MoreCollectors.uniqueIndex) Optional(java.util.Optional) Metric(org.sonar.api.measures.Metric) MetricDto(org.sonar.db.metric.MetricDto) Optional(java.util.Optional) QualityGateEvaluator(org.sonar.server.qualitygate.QualityGateEvaluator) EvaluatedQualityGate(org.sonar.server.qualitygate.EvaluatedQualityGate)

Aggregations

EvaluatedQualityGate (org.sonar.server.qualitygate.EvaluatedQualityGate)12 QualityGate (org.sonar.server.qualitygate.QualityGate)8 Test (org.junit.Test)7 Condition (org.sonar.server.qualitygate.Condition)6 EvaluatedCondition (org.sonar.server.qualitygate.EvaluatedCondition)5 Metric (org.sonar.api.measures.Metric)3 ComponentDto (org.sonar.db.component.ComponentDto)3 MetricDto (org.sonar.db.metric.MetricDto)3 Map (java.util.Map)2 Optional (java.util.Optional)2 Set (java.util.Set)2 Supplier (java.util.function.Supplier)2 QualityGate (org.sonar.api.ce.posttask.QualityGate)2 Configuration (org.sonar.api.config.Configuration)2 BranchDto (org.sonar.db.component.BranchDto)2 LiveMeasureDto (org.sonar.db.measure.LiveMeasureDto)2 ProjectDto (org.sonar.db.project.ProjectDto)2 QualityGateEvaluator (org.sonar.server.qualitygate.QualityGateEvaluator)2 Analysis (org.sonar.server.webhook.Analysis)2 Collection (java.util.Collection)1