Example #1
0
  void compareWithPastMeasures(DecoratorContext context, int index, List<Object[]> pastMeasures) {
    Map<MeasureKey, Object[]> pastMeasuresByKey = Maps.newHashMap();
    for (Object[] pastMeasure : pastMeasures) {
      pastMeasuresByKey.put(new MeasureKey(pastMeasure), pastMeasure);
    }

    // for each measure, search equivalent past measure
    for (Measure measure : context.getMeasures(MeasuresFilters.all())) {
      // compare with past measure
      Integer metricId =
          (measure.getMetric().getId() != null
              ? measure.getMetric().getId()
              : metricFinder.findByKey(measure.getMetric().getKey()).getId());
      Integer characteristicId =
          (measure.getCharacteristic() != null ? measure.getCharacteristic().getId() : null);
      Integer ruleId =
          (measure instanceof RuleMeasure ? ((RuleMeasure) measure).getRule().getId() : null);

      Object[] pastMeasure =
          pastMeasuresByKey.get(new MeasureKey(metricId, characteristicId, ruleId));
      if (updateVariation(measure, pastMeasure, index)) {
        context.saveMeasure(measure);
      }
    }
  }
  @Test
  public void includeCurrentMeasures() throws ParseException {
    TendencyAnalyser analyser = mock(TendencyAnalyser.class);
    TimeMachineQuery query =
        new TimeMachineQuery(null).setMetrics(CoreMetrics.LINES, CoreMetrics.COVERAGE);
    TimeMachine timeMachine = mock(TimeMachine.class);

    when(timeMachine.getMeasuresFields(query))
        .thenReturn(
            Arrays.<Object[]>asList(
                new Object[] {date("2009-12-01"), CoreMetrics.LINES, 1200.0},
                new Object[] {date("2009-12-01"), CoreMetrics.COVERAGE, 80.5},
                new Object[] {date("2009-12-02"), CoreMetrics.LINES, 1300.0},
                new Object[] {date("2009-12-02"), CoreMetrics.COVERAGE, 79.6},
                new Object[] {date("2009-12-15"), CoreMetrics.LINES, 1150.0}));

    DecoratorContext context = mock(DecoratorContext.class);
    when(context.getMeasure(CoreMetrics.LINES)).thenReturn(new Measure(CoreMetrics.LINES, 1400.0));
    when(context.getMeasure(CoreMetrics.COVERAGE)).thenReturn(new Measure(CoreMetrics.LINES, 90.0));

    TendencyDecorator decorator = new TendencyDecorator(timeMachine, query, analyser, newConf());
    decorator.decorate(new JavaPackage("org.foo"), context);

    verify(analyser).analyseLevel(Arrays.asList(1200.0, 1300.0, 1150.0, 1400.0));
    verify(analyser).analyseLevel(Arrays.asList(80.5, 79.6, 90.0));
  }
  private void decorateResource(DecoratorContext context) {
    Metric.Level globalLevel = Metric.Level.OK;
    List<String> labels = Lists.newArrayList();

    for (final Alert alert : profile.getAlerts()) {
      Measure measure = context.getMeasure(alert.getMetric());
      if (measure != null) {
        Metric.Level level = AlertUtils.getLevel(alert, measure);

        measure.setAlertStatus(level);
        String text = getText(alert, level);
        if (!StringUtils.isBlank(text)) {
          measure.setAlertText(text);
          labels.add(text);
        }

        context.saveMeasure(measure);

        if (Metric.Level.WARN == level && globalLevel != Metric.Level.ERROR) {
          globalLevel = Metric.Level.WARN;

        } else if (Metric.Level.ERROR == level) {
          globalLevel = Metric.Level.ERROR;
        }
      }
    }

    Measure globalMeasure = new Measure(CoreMetrics.ALERT_STATUS, globalLevel);
    globalMeasure.setAlertStatus(globalLevel);
    globalMeasure.setAlertText(StringUtils.join(labels, ", "));
    context.saveMeasure(globalMeasure);
  }
 private void computeTotalViolations(DecoratorContext context) {
   if (context.getMeasure(CoreMetrics.VIOLATIONS) == null) {
     Collection<Measure> childrenViolations = context.getChildrenMeasures(CoreMetrics.VIOLATIONS);
     Double sum = MeasureUtils.sum(true, childrenViolations);
     context.saveMeasure(CoreMetrics.VIOLATIONS, sum + context.getViolations().size());
   }
 }
  private void computeViolationsPerRules(DecoratorContext context) {
    Map<RulePriority, Multiset<Rule>> rulesPerSeverity = Maps.newHashMap();
    for (Violation violation : context.getViolations()) {
      Multiset<Rule> rulesBag = initRules(rulesPerSeverity, violation.getSeverity());
      rulesBag.add(violation.getRule());
    }

    for (RulePriority severity : RulePriority.values()) {
      Metric metric = SeverityUtils.severityToViolationMetric(severity);

      Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
      for (Measure child : children) {
        RuleMeasure childRuleMeasure = (RuleMeasure) child;
        Rule rule = childRuleMeasure.getRule();
        if (rule != null && MeasureUtils.hasValue(childRuleMeasure)) {
          Multiset<Rule> rulesBag = initRules(rulesPerSeverity, severity);
          rulesBag.add(rule, childRuleMeasure.getIntValue());
        }
      }

      Multiset<Rule> rulesBag = rulesPerSeverity.get(severity);
      if (rulesBag != null) {
        for (Multiset.Entry<Rule> entry : rulesBag.entrySet()) {
          RuleMeasure measure =
              RuleMeasure.createForRule(metric, entry.getElement(), (double) entry.getCount());
          measure.setSeverity(severity);
          context.saveMeasure(measure);
        }
      }
    }
  }
 private static DecoratorContext mockContext(int conditions, int uncoveredConditions) {
   DecoratorContext context = mock(DecoratorContext.class);
   when(context.getMeasure(CoreMetrics.IT_CONDITIONS_TO_COVER))
       .thenReturn(new Measure(CoreMetrics.IT_CONDITIONS_TO_COVER, (double) conditions));
   when(context.getMeasure(CoreMetrics.IT_UNCOVERED_CONDITIONS))
       .thenReturn(new Measure(CoreMetrics.IT_UNCOVERED_CONDITIONS, (double) uncoveredConditions));
   return context;
 }
 @Override
 protected Double countCoveredElements(DecoratorContext context) {
   double uncoveredLines =
       MeasureUtils.getValue(context.getMeasure(JaCoCoItMetrics.IT_UNCOVERED_LINES), 0.0);
   double lines =
       MeasureUtils.getValue(context.getMeasure(JaCoCoItMetrics.IT_LINES_TO_COVER), 0.0);
   return lines - uncoveredLines;
 }
  /**
   * @param context the context
   * @return the valid lines of the component, i.e. the real number of lines
   */
  protected double getValidLines(DecoratorContext context) {
    double duplicatedLines =
        MeasureUtils.getValue(context.getMeasure(CoreMetrics.DUPLICATED_LINES), 0.0);
    double totalLines = MeasureUtils.getValue(context.getMeasure(CoreMetrics.NCLOC), 0.0);
    double validLines = totalLines - duplicatedLines;

    return validLines > 0 ? validLines : 1.0;
  }
  @Test
  public void noDensityIfNoDuplicationMeasure() {
    DecoratorContext context = mock(DecoratorContext.class);
    when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 45.0));

    DuplicationDensityDecorator decorator = new DuplicationDensityDecorator();
    decorator.decorate(null, context);

    verify(context, never()).saveMeasure(eq(CoreMetrics.DUPLICATED_LINES_DENSITY), anyDouble());
  }
Example #10
0
 public void decorate(Resource resource, DecoratorContext context) {
   if (Scopes.isFile(resource) && !Qualifiers.UNIT_TEST_FILE.equals(resource.getQualifier())) {
     int classes = 0;
     for (DecoratorContext child : context.getChildren()) {
       if (Scopes.isProgramUnit(child.getResource())) {
         classes++;
       }
     }
     context.saveMeasure(new Measure(CoreMetrics.CLASSES, (double) classes));
   }
 }
  @Test
  public void shouldSaveZeroOnProjects() {
    when(resource.getScope()).thenReturn(Scopes.PROJECT);
    when(context.getViolations()).thenReturn(Collections.<Violation>emptyList());
    when(context.getChildrenMeasures((MeasuresFilter) anyObject()))
        .thenReturn(Collections.<Measure>emptyList());

    decorator.decorate(resource, context);

    verify(context).saveMeasure(CoreMetrics.VIOLATIONS, 0.0);
  }
  @Test
  public void shouldNotSaveDataWhenNoMeasures() {
    NewCoverageAggregator aggregator = new NewCoverageAggregator();
    DecoratorContext context = mock(DecoratorContext.class);
    when(context.getChildrenMeasures(CoreMetrics.NEW_LINES_TO_COVER))
        .thenReturn(Collections.<Measure>emptyList());

    aggregator.aggregate(context, CoreMetrics.NEW_LINES_TO_COVER, 3);

    verify(context, never()).saveMeasure(Matchers.<Measure>anyObject());
  }
Example #13
0
 private int saveValue(DecoratorContext context, Metric metric, String ruleKey) {
   int result;
   result = MeasureUtils.sum(true, context.getChildrenMeasures(metric)).intValue();
   for (Violation violation : context.getViolations()) {
     if (violation.getRule().getKey().equals(ruleKey)) {
       result++;
     }
   }
   context.saveMeasure(metric, (double) result);
   return result;
 }
  @Test
  public void checkShouldGenerateViolationOnFileIfTestFailures() {
    when(resource.getQualifier()).thenReturn(Qualifiers.UNIT_TEST_FILE);
    when(context.getMeasure(CoreMetrics.TEST_ERRORS))
        .thenReturn(new Measure(CoreMetrics.TEST_ERRORS, 2.0));
    when(context.getMeasure(CoreMetrics.TEST_FAILURES))
        .thenReturn(new Measure(CoreMetrics.TEST_FAILURES, 3.0));

    check.checkResource(resource, context, null, perspectives);

    verify(perspectives, times(1)).as(Issuable.class, resource);
  }
  @Test
  public void densityEvenIfNoComments() {
    DecoratorContext context = mock(DecoratorContext.class);
    when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 40.0));
    when(context.getMeasure(CoreMetrics.DUPLICATED_LINES))
        .thenReturn(new Measure(CoreMetrics.DUPLICATED_LINES, 10.0));

    DuplicationDensityDecorator decorator = new DuplicationDensityDecorator();
    decorator.decorate(null, context);

    verify(context).saveMeasure(CoreMetrics.DUPLICATED_LINES_DENSITY, 25.0);
  }
 private long getDevelopmentCost(DecoratorContext context) {
   InputFile file = fs.inputFile(fs.predicates().hasRelativePath(context.getResource().getKey()));
   if (file != null) {
     String language = file.language();
     return getMeasureValue(context, sqaleRatingSettings.getSizeMetric(language, metrics))
         * sqaleRatingSettings.getDevCost(language);
   } else {
     Collection<Measure> childrenMeasures =
         context.getChildrenMeasures(CoreMetrics.DEVELOPMENT_COST);
     Double sum = sum(childrenMeasures);
     return sum.longValue();
   }
 }
  @Test
  public void densityIsBalancedByNclocAndCommentLines() {
    DecoratorContext context = mock(DecoratorContext.class);
    when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 40.0));
    when(context.getMeasure(CoreMetrics.COMMENT_LINES))
        .thenReturn(new Measure(CoreMetrics.COMMENT_LINES, 10.0));
    when(context.getMeasure(CoreMetrics.DUPLICATED_LINES))
        .thenReturn(new Measure(CoreMetrics.DUPLICATED_LINES, 10.0));

    DuplicationDensityDecorator decorator = new DuplicationDensityDecorator();
    decorator.decorate(null, context);

    verify(context).saveMeasure(CoreMetrics.DUPLICATED_LINES_DENSITY, 20.0);
  }
  @Test
  public void noDensityWhenZeroNclocAndComments() {
    DecoratorContext context = mock(DecoratorContext.class);
    when(context.getMeasure(CoreMetrics.NCLOC)).thenReturn(new Measure(CoreMetrics.NCLOC, 0.0));
    when(context.getMeasure(CoreMetrics.DUPLICATED_LINES))
        .thenReturn(new Measure(CoreMetrics.COMMENT_LINES, 0.0));
    when(context.getMeasure(CoreMetrics.DUPLICATED_LINES))
        .thenReturn(new Measure(CoreMetrics.DUPLICATED_LINES, 10.0));

    DuplicationDensityDecorator decorator = new DuplicationDensityDecorator();
    decorator.decorate(null, context);

    verify(context, never()).saveMeasure(eq(CoreMetrics.DUPLICATED_LINES_DENSITY), anyDouble());
  }
 public Collection<Measure> getChildrenMeasures(MeasuresFilter filter) {
   List<Measure> result = Lists.newArrayList();
   for (DecoratorContext childContext : childrenContexts) {
     Object childResult = childContext.getMeasures(filter);
     if (childResult != null) {
       if (childResult instanceof Collection) {
         result.addAll((Collection) childResult);
       } else {
         result.add((Measure) childResult);
       }
     }
   }
   return result;
 }
  private void computeViolationsPerSeverities(DecoratorContext context) {
    Multiset<RulePriority> severitiesBag = HashMultiset.create();
    for (Violation violation : context.getViolations()) {
      severitiesBag.add(violation.getSeverity());
    }

    for (RulePriority severity : RulePriority.values()) {
      Metric metric = SeverityUtils.severityToViolationMetric(severity);
      if (context.getMeasure(metric) == null) {
        Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.metric(metric));
        int sum = MeasureUtils.sum(true, children).intValue() + severitiesBag.count(severity);
        context.saveMeasure(metric, (double) sum);
      }
    }
  }
  @Override
  public void decorate(Resource resource, DecoratorContext context) {
    if (ResourceUtils.isPersistable(resource) && !ResourceUtils.isUnitTestFile(resource)) {
      Long developmentCost = getDevelopmentCost(context);
      context.saveMeasure(
          new Measure(CoreMetrics.DEVELOPMENT_COST, Long.toString(developmentCost)));

      long debt = getMeasureValue(context, CoreMetrics.TECHNICAL_DEBT);
      double density = computeDensity(debt, developmentCost);
      context.saveMeasure(CoreMetrics.SQALE_DEBT_RATIO, 100.0 * density);

      SqaleRatingGrid ratingGrid = new SqaleRatingGrid(sqaleRatingSettings.getRatingGrid());
      context.saveMeasure(createRatingMeasure(ratingGrid.getRatingForDensity(density)));
    }
  }
  @Test
  public void shouldCountViolationsBySeverity() {
    when(resource.getScope()).thenReturn(Scopes.PROJECT);
    when(context.getViolations()).thenReturn(createViolations());
    when(context.getChildrenMeasures((MeasuresFilter) anyObject()))
        .thenReturn(Collections.<Measure>emptyList());

    decorator.decorate(resource, context);

    verify(context).saveMeasure(CoreMetrics.BLOCKER_VIOLATIONS, 0.0);
    verify(context).saveMeasure(CoreMetrics.CRITICAL_VIOLATIONS, 2.0);
    verify(context).saveMeasure(CoreMetrics.MAJOR_VIOLATIONS, 1.0);
    verify(context).saveMeasure(CoreMetrics.MINOR_VIOLATIONS, 1.0);
    verify(context).saveMeasure(CoreMetrics.INFO_VIOLATIONS, 0.0);
  }
 private long getMeasureValue(DecoratorContext context, Metric metric) {
   Measure measure = context.getMeasure(metric);
   if (measure != null) {
     return measure.getValue().longValue();
   }
   return 0L;
 }
Example #24
0
  public void decorate(Resource resource, DecoratorContext context) {
    int apiBreaks = 0;
    boolean active = false;
    if (configuration.isApiBreakActive()) {
      apiBreaks = saveValue(context, ClirrMetrics.API_BREAKS, ClirrConstants.RULE_API_BREAK);
      active = true;
    }

    int apiBehaviorChanges = 0;
    if (configuration.isApiBehaviorChangeActive()) {
      apiBehaviorChanges =
          saveValue(
              context, ClirrMetrics.API_BEHAVIOR_CHANGES, ClirrConstants.RULE_API_BEHAVIOR_CHANGE);
      active = true;
    }

    int newApi = 0;
    if (configuration.isNewApiActive()) {
      newApi = saveValue(context, ClirrMetrics.NEW_API, ClirrConstants.RULE_NEW_API);
      active = true;
    }

    if (active) {
      context.saveMeasure(
          ClirrMetrics.TOTAL_API_CHANGES, (double) (apiBreaks + apiBehaviorChanges + newApi));
    }
  }
  @Before
  public void setUp() {
    rightNow = new Date();
    tenDaysAgo = DateUtils.addDays(rightNow, -10);
    fiveDaysAgo = DateUtils.addDays(rightNow, -5);

    PastSnapshot pastSnapshot = mock(PastSnapshot.class);
    when(pastSnapshot.getIndex()).thenReturn(1);
    when(pastSnapshot.getTargetDate()).thenReturn(fiveDaysAgo);

    PastSnapshot pastSnapshot2 = mock(PastSnapshot.class);
    when(pastSnapshot2.getIndex()).thenReturn(2);
    when(pastSnapshot2.getTargetDate()).thenReturn(tenDaysAgo);

    timeMachineConfiguration = mock(TimeMachineConfiguration.class);
    when(timeMachineConfiguration.getProjectPastSnapshots())
        .thenReturn(Arrays.asList(pastSnapshot, pastSnapshot2));

    context = mock(DecoratorContext.class);
    resource = new File("com/foo/bar");
    when(context.getResource()).thenReturn(resource);

    notificationManager = mock(NotificationManager.class);
    decorator = new NewViolationsDecorator(timeMachineConfiguration, notificationManager);

    rule1 = Rule.create().setRepositoryKey("rule1").setKey("rule1").setName("name1");
    rule2 = Rule.create().setRepositoryKey("rule2").setKey("rule2").setName("name2");
    rule3 = Rule.create().setRepositoryKey("rule3").setKey("rule3").setName("name3");
  }
  @Test
  public void checkShouldNotGenerateViolationIfNoFailedTests() {
    when(resource.getQualifier()).thenReturn(Qualifiers.UNIT_TEST_FILE);

    // this test has no "test_errors" or "test_failures" measure
    check.checkResource(resource, context, null, perspectives);
    verify(perspectives, times(0)).as(Issuable.class, resource);

    // this is the case of a test file that has only successful tests
    when(context.getMeasure(CoreMetrics.TEST_ERRORS))
        .thenReturn(new Measure(CoreMetrics.TEST_ERRORS, 0.0));
    when(context.getMeasure(CoreMetrics.TEST_FAILURES))
        .thenReturn(new Measure(CoreMetrics.TEST_FAILURES, 0.0));
    check.checkResource(resource, context, null, perspectives);
    verify(perspectives, times(0)).as(Issuable.class, resource);
  }
  @Test
  public void testProjectOverThreshold() {
    // add enough violations to be over threshold
    int threshold = settings.getInt(ProfileProgressionPlugin.QUALITY_PROFILE_CHANGE_THRESHOLD_KEY);
    List<ActiveRule> rules = testProjectModel.getRulesProfile().getActiveRules();
    int numberOfRules = rules.size();
    List<Violation> violations = decoratorContext.getViolations();
    int initialNumberOfViolations = violations.size();

    int numberOfExtraViolations =
        ((threshold + 1) * (numberOfRules / 100)) - initialNumberOfViolations;

    for (int i = 0; i < numberOfExtraViolations; i++) {
      violations.add(Violation.create(rules.get(initialNumberOfViolations + i), testProject));
    }

    // test profile isn't progressed
    String profileBefore = testProjectModel.getRulesProfile().getName();
    runAnalysis();
    String profileAfter = testProjectModel.getRulesProfile().getName();

    testOutcome(
        "Projects profile has been changed despite the violation threshold not met.",
        profileBefore,
        profileAfter,
        false);
  }
  private void saveLineCoverage(DecoratorContext context) {
    Double elements = countElements(context);
    Double coveredElements = countCoveredElements(context);

    if (elements != null && elements > 0.0 && coveredElements != null) {
      context.saveMeasure(getTargetMetric(), calculateCoverage(coveredElements, elements));
    }
  }
Example #29
0
 private void saveOnRequirement(
     DecoratorContext context, Map<TechnicalDebtRequirement, Double> requirementCosts) {
   for (Map.Entry<TechnicalDebtRequirement, Double> entry : requirementCosts.entrySet()) {
     saveCost(
         context,
         entry.getKey().toCharacteristic(),
         entry.getValue(),
         ResourceUtils.isEntity(context.getResource()));
   }
 }
  /** See http://jira.codehaus.org/browse/SONAR-1729 */
  @Test
  public void shouldNotCountViolationsIfMeasureAlreadyExists() {
    when(resource.getScope()).thenReturn(Scopes.PROJECT);
    when(context.getViolations()).thenReturn(createViolations());
    when(context.getChildrenMeasures((MeasuresFilter) anyObject()))
        .thenReturn(Collections.<Measure>emptyList());
    when(context.getMeasure(CoreMetrics.VIOLATIONS))
        .thenReturn(new Measure(CoreMetrics.VIOLATIONS, 3000.0));
    when(context.getMeasure(CoreMetrics.MAJOR_VIOLATIONS))
        .thenReturn(new Measure(CoreMetrics.MAJOR_VIOLATIONS, 500.0));

    decorator.decorate(resource, context);

    verify(context, never()).saveMeasure(eq(CoreMetrics.VIOLATIONS), anyDouble()); // not changed
    verify(context, never())
        .saveMeasure(eq(CoreMetrics.MAJOR_VIOLATIONS), anyDouble()); // not changed
    verify(context, times(1))
        .saveMeasure(eq(CoreMetrics.CRITICAL_VIOLATIONS), anyDouble()); // did not exist
  }