@Test
  public void get_profile_by_project_and_language() {
    ComponentDto project =
        new ComponentDto()
            .setId(1L)
            .setUuid("ABCD")
            .setKey("org.codehaus.sonar:sonar")
            .setName("SonarQube")
            .setLongName("SonarQube")
            .setQualifier("TRK")
            .setScope("TRK")
            .setEnabled(true);
    db.componentDao().insert(dbSession, project);

    QualityProfileDto profileDto = QProfileTesting.newXooP1();
    db.qualityProfileDao().insert(dbSession, profileDto);
    dbSession.commit();
    dbSession.clearCache();
    assertThat(factory.getByProjectAndLanguage("org.codehaus.sonar:sonar", "xoo")).isNull();

    tester
        .get(QProfileProjectOperations.class)
        .addProject(
            profileDto.getKey(),
            project.uuid(),
            new MockUserSession("me").setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN),
            dbSession);
    dbSession.commit();
    dbSession.clearCache();
    assertThat(factory.getByProjectAndLanguage("org.codehaus.sonar:sonar", "xoo").getKey())
        .isEqualTo(XOO_P1_KEY);
  }
예제 #2
0
  @Override
  public void handle(Request request, Response response) throws Exception {
    DbSession session = dbClient.openSession(false);
    try {
      String profileKey =
          QProfileIdentificationParamUtils.getProfileKeyFromParameters(
              request, profileFactory, session);
      if (dbClient.qualityProfileDao().getByKey(session, profileKey) == null) {
        throw new NotFoundException(
            String.format("Could not find a profile with key '%s'", profileKey));
      }

      QProfileActivityQuery query = new QProfileActivityQuery().setQprofileKey(profileKey);
      Date since = request.paramAsDateTime(PARAM_SINCE);
      if (since != null) {
        query.setSince(since);
      }
      Date to = request.paramAsDateTime(PARAM_TO);
      if (to != null) {
        query.setTo(to);
      }
      SearchOptions options = new SearchOptions();

      int page = request.mandatoryParamAsInt(Param.PAGE);
      options.setPage(page, request.mandatoryParamAsInt(Param.PAGE_SIZE));

      Result<QProfileActivity> result = searchActivities(query, options);
      writeResponse(
          response.newJsonWriter(),
          result,
          Paging.create(options.getLimit(), page, (int) result.getTotal()));
    } finally {
      session.close();
    }
  }
예제 #3
0
  @Test
  public void insert_new_rules() {
    execute(new FakeRepositoryV1());

    // verify db
    assertThat(dbClient.ruleDao().selectAll(dbTester.getSession())).hasSize(2);
    RuleKey ruleKey1 = RuleKey.of("fake", "rule1");
    RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbTester.getSession(), ruleKey1);
    assertThat(rule1.getName()).isEqualTo("One");
    assertThat(rule1.getDescription()).isEqualTo("Description of One");
    assertThat(rule1.getSeverityString()).isEqualTo(Severity.BLOCKER);
    assertThat(rule1.getTags()).isEmpty();
    assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag2", "tag3");
    assertThat(rule1.getConfigKey()).isEqualTo("config1");
    assertThat(rule1.getStatus()).isEqualTo(RuleStatus.BETA);
    assertThat(rule1.getCreatedAt()).isEqualTo(DATE1);
    assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1);
    // TODO check characteristic and remediation function

    List<RuleParamDto> params =
        dbClient.ruleDao().selectRuleParamsByRuleKey(dbTester.getSession(), ruleKey1);
    assertThat(params).hasSize(2);
    RuleParamDto param = getParam(params, "param1");
    assertThat(param.getDescription()).isEqualTo("parameter one");
    assertThat(param.getDefaultValue()).isEqualTo("default1");
  }
예제 #4
0
  private String backupFromLanguage(@Nullable String languageKey) {
    checkPermission();

    DbSession session = dbClient.openSession(false);
    try {
      DebtModel debtModel = new DebtModel();
      List<CharacteristicDto> characteristicDtos =
          dbClient.debtCharacteristicDao().selectEnabledCharacteristics(session);
      for (CharacteristicDto characteristicDto : characteristicDtos) {
        if (characteristicDto.getParentId() == null) {
          debtModel.addRootCharacteristic(toDebtCharacteristic(characteristicDto));
          for (CharacteristicDto sub :
              subCharacteristics(characteristicDto.getId(), characteristicDtos)) {
            debtModel.addSubCharacteristic(toDebtCharacteristic(sub), characteristicDto.getKey());
          }
        }
      }

      List<RuleDebt> rules = newArrayList();
      for (RuleDto rule : dbClient.ruleDao().selectEnabledAndNonManual(session)) {
        if (languageKey == null || languageKey.equals(rule.getLanguage())) {
          RuleDebt ruleDebt = toRuleDebt(rule, debtModel);
          if (ruleDebt != null) {
            rules.add(ruleDebt);
          }
        }
      }
      return debtModelXMLExporter.export(debtModel, rules);
    } finally {
      MyBatis.closeQuietly(session);
    }
  }
예제 #5
0
 private void doDelete(DbSession session, QualityProfileDto profile) {
   db.activeRuleDao().deleteByProfileKey(session, profile.getKey());
   db.qualityProfileDao().delete(session, profile);
   db.propertiesDao()
       .deleteProjectProperties(
           PROFILE_PROPERTY_PREFIX + profile.getLanguage(), profile.getName(), session);
 }
예제 #6
0
  void setParent(
      DbSession dbSession, QualityProfileKey key, @Nullable QualityProfileKey parentKey) {
    QualityProfileDto profile = db.qualityProfileDao().getNonNullByKey(dbSession, key);
    if (parentKey == null) {
      // unset if parent is defined, else nothing to do
      removeParent(dbSession, profile);

    } else if (profile.getParentKey() == null || !profile.getParentKey().equals(parentKey)) {
      QualityProfileDto parentProfile =
          db.qualityProfileDao().getNonNullByKey(dbSession, parentKey);
      if (isDescendant(dbSession, profile, parentProfile)) {
        throw new BadRequestException(
            String.format(
                "Descendant profile '%s' can not be selected as parent of '%s'", parentKey, key));
      }
      removeParent(dbSession, profile);

      // set new parent
      profile.setParent(parentKey.name());
      db.qualityProfileDao().update(dbSession, profile);
      for (ActiveRuleDto parentActiveRule :
          db.activeRuleDao().findByProfileKey(dbSession, parentKey)) {
        RuleActivation activation =
            new RuleActivation(ActiveRuleKey.of(key, parentActiveRule.getKey().ruleKey()));
        activate(dbSession, activation);
      }
    }
  }
예제 #7
0
  private RuleKey createCustomRule(
      RuleKey ruleKey, NewRule newRule, RuleDto templateRuleDto, DbSession dbSession) {
    RuleDto ruleDto =
        RuleDto.createFor(ruleKey)
            .setTemplateId(templateRuleDto.getId())
            .setConfigKey(templateRuleDto.getConfigKey())
            .setName(newRule.name())
            .setDescription(newRule.markdownDescription())
            .setDescriptionFormat(Format.MARKDOWN)
            .setSeverity(newRule.severity())
            .setStatus(newRule.status())
            .setLanguage(templateRuleDto.getLanguage())
            .setDefaultSubCharacteristicId(templateRuleDto.getDefaultSubCharacteristicId())
            .setDefaultRemediationFunction(templateRuleDto.getDefaultRemediationFunction())
            .setDefaultRemediationCoefficient(templateRuleDto.getDefaultRemediationCoefficient())
            .setDefaultRemediationOffset(templateRuleDto.getDefaultRemediationOffset())
            .setEffortToFixDescription(templateRuleDto.getEffortToFixDescription())
            .setTags(templateRuleDto.getTags())
            .setSystemTags(templateRuleDto.getSystemTags());
    dbClient.ruleDao().insert(dbSession, ruleDto);

    for (RuleParamDto templateRuleParamDto :
        dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, templateRuleDto.getKey())) {
      String customRuleParamValue =
          Strings.emptyToNull(newRule.parameter(templateRuleParamDto.getName()));
      createCustomRuleParams(customRuleParamValue, ruleDto, templateRuleParamDto, dbSession);
    }
    return ruleKey;
  }
  @Test
  public void delete_descendants() {
    initRules();

    // create parent and child profiles
    db.qualityProfileDao()
        .insert(
            dbSession,
            QProfileTesting.newXooP1(),
            QProfileTesting.newXooP2(),
            QProfileTesting.newXooP3());
    tester.get(RuleActivator.class).setParent(dbSession, XOO_P2_KEY, XOO_P1_KEY);
    tester.get(RuleActivator.class).setParent(dbSession, XOO_P3_KEY, XOO_P1_KEY);
    tester
        .get(RuleActivator.class)
        .activate(dbSession, new RuleActivation(RuleTesting.XOO_X1), XOO_P1_KEY);
    dbSession.commit();
    dbSession.clearCache();
    assertThat(db.qualityProfileDao().selectAll(dbSession)).hasSize(3);
    assertThat(db.activeRuleDao().selectAll(dbSession)).hasSize(3);

    factory.delete(XOO_P1_KEY);

    dbSession.clearCache();
    assertThat(db.qualityProfileDao().selectAll(dbSession)).isEmpty();
    assertThat(db.activeRuleDao().selectAll(dbSession)).isEmpty();
    assertThat(db.activeRuleDao().selectAllParams(dbSession)).isEmpty();
    assertThat(index.get(ActiveRuleIndex.class).findByProfile(XOO_P1_KEY)).isEmpty();
    assertThat(index.get(ActiveRuleIndex.class).findByProfile(XOO_P2_KEY)).isEmpty();
    assertThat(index.get(ActiveRuleIndex.class).findByProfile(XOO_P3_KEY)).isEmpty();
  }
  @Test
  public void create_target_profile_with_same_parent_than_source() {
    // two profiles : parent and its child
    db.qualityProfileDao()
        .insert(dbSession, QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY));

    // parent and child with x1 activated
    RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
    activation.setSeverity(Severity.BLOCKER);
    activation.setParameter("max", "7");
    ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P1_KEY);
    dbSession.commit();
    dbSession.clearCache();

    // copy child -> profile2 is created with parent P1
    copier.copyToName(QProfileTesting.XOO_P1_KEY, QProfileTesting.XOO_P2_NAME.getName());

    verifyOneActiveRule(
        QProfileTesting.XOO_P2_KEY,
        Severity.BLOCKER,
        ActiveRuleDto.INHERITED,
        ImmutableMap.of("max", "7"));
    QualityProfileDto profile2Dto =
        db.qualityProfileDao().selectByKey(dbSession, QProfileTesting.XOO_P2_KEY);
    assertThat(profile2Dto.getParentKee()).isEqualTo(QProfileTesting.XOO_P1_KEY);
  }
예제 #10
0
 private CharacteristicDto restoreCharacteristic(
     DebtCharacteristic targetCharacteristic,
     @Nullable Integer parentId,
     List<CharacteristicDto> sourceCharacteristics,
     Date updateDate,
     DbSession session) {
   CharacteristicDto sourceCharacteristic =
       characteristicByKey(targetCharacteristic.key(), sourceCharacteristics, false);
   if (sourceCharacteristic == null) {
     CharacteristicDto newCharacteristic =
         toDto(targetCharacteristic, parentId).setCreatedAt(updateDate);
     dbClient.debtCharacteristicDao().insert(newCharacteristic, session);
     return newCharacteristic;
   } else {
     // Update only if modifications
     if (ObjectUtils.notEqual(sourceCharacteristic.getName(), targetCharacteristic.name())
         || ObjectUtils.notEqual(sourceCharacteristic.getOrder(), targetCharacteristic.order())
         || ObjectUtils.notEqual(sourceCharacteristic.getParentId(), parentId)) {
       sourceCharacteristic.setName(targetCharacteristic.name());
       sourceCharacteristic.setOrder(targetCharacteristic.order());
       sourceCharacteristic.setParentId(parentId);
       sourceCharacteristic.setUpdatedAt(updateDate);
       dbClient.debtCharacteristicDao().update(sourceCharacteristic, session);
     }
     return sourceCharacteristic;
   }
 }
  @Test
  public void update_debt_rule() throws Exception {
    verifyRulesInDb();

    // Update x1 rule
    RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1);
    db.ruleDao()
        .update(
            dbSession,
            ruleDto
                .setDefaultSubCharacteristicId(123456)
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("2h")
                .setDefaultRemediationOffset("35min"));
    dbSession.commit();
    dbSession.clearCache();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify default debt has been reset to plugin definition
    Rule ruleReloaded = index.getByKey(RuleTesting.XOO_X1);
    assertThat(ruleReloaded.debtSubCharacteristicKey())
        .isEqualTo(RulesDefinition.SubCharacteristics.INTEGRATION_TESTABILITY);
    assertThat(ruleReloaded.debtRemediationFunction().type())
        .isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET);
    assertThat(ruleReloaded.debtRemediationFunction().coefficient()).isEqualTo("1h");
    assertThat(ruleReloaded.debtRemediationFunction().offset()).isEqualTo("30min");
  }
  @Test
  public void remove_debt_rule() throws Exception {
    verifyRulesInDb();

    // Set some default debt on x2 rule, which has no debt provided by th plugin
    RuleDto ruleDto = db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X2);
    db.ruleDao()
        .update(
            dbSession,
            ruleDto
                .setDefaultSubCharacteristicId(
                    db.debtCharacteristicDao()
                        .selectByKey(
                            RulesDefinition.SubCharacteristics.INTEGRATION_TESTABILITY, dbSession)
                        .getId())
                .setDefaultRemediationFunction("LINEAR_OFFSET")
                .setDefaultRemediationCoefficient("2h")
                .setDefaultRemediationOffset("35min"));
    dbSession.commit();
    dbSession.clearCache();

    // Re-execute startup tasks
    tester.get(Platform.class).executeStartupTasks();

    // Verify default debt has been removed
    Rule ruleReloaded = index.getByKey(RuleTesting.XOO_X2);
    assertThat(ruleReloaded.debtSubCharacteristicKey()).isNull();
    assertThat(ruleReloaded.debtRemediationFunction()).isNull();
  }
  @Test
  public void do_not_deactivate_removed_rules_if_repository_accidentaly_uninstalled()
      throws Exception {
    MockUserSession.set()
        .setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
        .setLogin("me");

    // create a profile and activate rule
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    dbSession.commit();
    dbSession.clearCache();
    RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
    tester.get(QProfileService.class).activate(QProfileTesting.XOO_P1_KEY, activation);
    dbSession.clearCache();

    // restart without x1, x2, template1 -> keep active rule of x1
    rulesDefinition.includeX1 = false;
    rulesDefinition.includeX2 = false;
    rulesDefinition.includeTemplate1 = false;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();
    assertThat(db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X1).getStatus())
        .isEqualTo(RuleStatus.REMOVED);
    assertThat(db.ruleDao().getByKey(dbSession, RuleTesting.XOO_X2).getStatus())
        .isEqualTo(RuleStatus.REMOVED);
    assertThat(db.activeRuleDao().findByProfileKey(dbSession, QProfileTesting.XOO_P1_KEY))
        .hasSize(1);
  }
  @Test
  public void deactivate_removed_rules_only_if_repository_still_exists() throws Exception {
    MockUserSession.set()
        .setGlobalPermissions(GlobalPermissions.QUALITY_PROFILE_ADMIN)
        .setLogin("me");

    // create a profile and activate rule
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    dbSession.commit();
    dbSession.clearCache();
    RuleActivation activation = new RuleActivation(RuleTesting.XOO_X1);
    tester.get(QProfileService.class).activate(QProfileTesting.XOO_P1_KEY, activation);
    dbSession.clearCache();

    // restart, x2 still exists -> deactivate x1
    rulesDefinition.includeX1 = false;
    rulesDefinition.includeX2 = true;
    tester.get(Platform.class).executeStartupTasks();
    dbSession.clearCache();
    assertThat(db.ruleDao().getByKey(dbSession, RuleKey.of("xoo", "x1")).getStatus())
        .isEqualTo(RuleStatus.REMOVED);
    assertThat(db.ruleDao().getByKey(dbSession, RuleKey.of("xoo", "x2")).getStatus())
        .isEqualTo(RuleStatus.READY);
    assertThat(db.activeRuleDao().findByProfileKey(dbSession, QProfileTesting.XOO_P1_KEY))
        .hasSize(0);
  }
예제 #15
0
 public boolean rename(String key, String newName) {
   Verifications.check(StringUtils.isNotBlank(newName), "Name must be set");
   Verifications.check(
       newName.length() < 100, String.format("Name is too long (>%d characters)", 100));
   DbSession dbSession = db.openSession(false);
   try {
     QualityProfileDto profile = db.qualityProfileDao().getNonNullByKey(dbSession, key);
     if (!StringUtils.equals(newName, profile.getName())) {
       if (db.qualityProfileDao().getByNameAndLanguage(newName, profile.getLanguage(), dbSession)
           != null) {
         throw new BadRequestException("Quality profile already exists: " + newName);
       }
       String previousName = profile.getName();
       profile.setName(newName);
       db.qualityProfileDao().update(dbSession, profile);
       db.propertiesDao()
           .updateProperties(
               PROFILE_PROPERTY_PREFIX + profile.getLanguage(), previousName, newName, dbSession);
       dbSession.commit();
       return true;
     }
     return false;
   } finally {
     dbSession.close();
   }
 }
예제 #16
0
  /** Reset from provided model */
  public void reset() {
    checkPermission();

    Date updateDate = new Date(system2.now());
    DbSession session = dbClient.openSession(false);
    try {
      // Restore characteristics
      List<CharacteristicDto> allCharacteristicDtos =
          restoreCharacteristics(
              loadModelFromPlugin(DebtModelPluginRepository.DEFAULT_MODEL), updateDate, session);

      // Restore rules
      List<RuleDto> ruleDtos = dbClient.ruleDao().selectEnabledAndNonManual(session);
      if (!ruleDtos.isEmpty()) {

        // Load default rule definitions
        RulesDefinition.Context context = defLoader.load();
        List<RulesDefinition.Rule> rules = newArrayList();
        for (RulesDefinition.Repository repoDef : context.repositories()) {
          rules.addAll(repoDef.rules());
        }

        resetRules(ruleDtos, rules, allCharacteristicDtos, updateDate, session);
      }

      session.commit();
    } finally {
      MyBatis.closeQuietly(session);
    }
  }
  @Before
  public void before() {
    tester.clearDbAndIndexes();
    db = tester.get(DbClient.class);
    dbSession = db.openSession(false);
    ruleActivator = tester.get(RuleActivator.class);
    index = tester.get(ActiveRuleIndex.class);
    copier = tester.get(QProfileCopier.class);

    // create pre-defined rules
    RuleDto xooRule1 = RuleTesting.newXooX1().setSeverity("MINOR");
    RuleDto xooRule2 = RuleTesting.newXooX2().setSeverity("MAJOR");
    db.deprecatedRuleDao().insert(dbSession, xooRule1, xooRule2);
    db.deprecatedRuleDao()
        .insertRuleParam(
            dbSession,
            xooRule1,
            RuleParamDto.createFor(xooRule1)
                .setName("max")
                .setDefaultValue("10")
                .setType(RuleParamType.INTEGER.type()));

    // create pre-defined profile
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    dbSession.commit();
    dbSession.clearCache();
  }
  @Before
  public void setUp() {
    when(system2.now()).thenReturn(now.getTime());

    userSessionRule.setGlobalPermissions(GlobalPermissions.SYSTEM_ADMIN);

    currentId = 10;
    // Associate an id when inserting an object to simulate the db id generator
    doAnswer(
            new Answer() {
              public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                CharacteristicDto dto = (CharacteristicDto) args[0];
                dto.setId(++currentId);
                return null;
              }
            })
        .when(dao)
        .insert(any(CharacteristicDto.class), any(SqlSession.class));

    when(dbClient.openSession(false)).thenReturn(session);
    when(dbClient.ruleDao()).thenReturn(ruleDao);
    when(dbClient.debtCharacteristicDao()).thenReturn(dao);
    service = new DebtModelOperations(dbClient, system2, userSessionRule);
  }
예제 #19
0
 public void executeDeprecated() {
   DbSession session = db.openSession(false);
   try {
     synchronize(session, db.deprecatedRuleDao(), index.get(RuleIndex.class));
     synchronize(session, db.activeRuleDao(), index.get(ActiveRuleIndex.class));
     session.commit();
   } finally {
     session.close();
   }
 }
예제 #20
0
  @Test
  public void search_by_characteristics() throws InterruptedException {
    CharacteristicDto char1 = DebtTesting.newCharacteristicDto("RELIABILITY");
    db.debtCharacteristicDao().insert(char1, dbSession);

    CharacteristicDto char11 =
        DebtTesting.newCharacteristicDto("SOFT_RELIABILITY").setParentId(char1.getId());
    db.debtCharacteristicDao().insert(char11, dbSession);
    dbSession.commit();

    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("java", "S001")).setSubCharacteristicId(char11.getId()));

    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "S002")));

    dbSession.commit();
    dbSession.clearCache();

    RuleQuery query;
    Result<Rule> results;

    // 0. we have 2 rules in index
    results = index.search(new RuleQuery(), new QueryOptions());
    assertThat(results.getHits()).hasSize(2);

    // filter by non-subChar
    query = new RuleQuery().setDebtCharacteristics(ImmutableSet.of("toto"));
    assertThat(index.search(query, new QueryOptions()).getHits()).isEmpty();

    // filter by subChar
    query = new RuleQuery().setDebtCharacteristics(ImmutableSet.of(char11.getKey()));
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // filter by Char
    query = new RuleQuery().setDebtCharacteristics(ImmutableSet.of(char1.getKey()));
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // filter by Char and SubChar
    query =
        new RuleQuery().setDebtCharacteristics(ImmutableSet.of(char11.getKey(), char1.getKey()));
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // match by Char
    query = new RuleQuery().setQueryText(char1.getKey());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // match by SubChar
    query = new RuleQuery().setQueryText(char11.getKey());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);

    // match by SubChar & Char
    query = new RuleQuery().setQueryText(char11.getKey() + " " + char1.getKey());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(1);
  }
  @Test
  public void set_default_profile() {
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    dbSession.commit();
    dbSession.clearCache();

    assertThat(db.qualityProfileDao().selectByKey(dbSession, XOO_P1_KEY).isDefault()).isFalse();

    factory.setDefault(XOO_P1_KEY);
    dbSession.clearCache();

    assertThat(db.qualityProfileDao().selectByKey(dbSession, XOO_P1_KEY).isDefault()).isTrue();
  }
예제 #22
0
  @Test
  public void do_not_update_rules_when_no_changes() {
    execute(new FakeRepositoryV1());
    assertThat(dbClient.ruleDao().selectAll(dbTester.getSession())).hasSize(2);

    when(system.now()).thenReturn(DATE2.getTime());
    execute(new FakeRepositoryV1());

    RuleKey ruleKey1 = RuleKey.of("fake", "rule1");
    RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbTester.getSession(), ruleKey1);
    assertThat(rule1.getCreatedAt()).isEqualTo(DATE1);
    assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1);
  }
예제 #23
0
 @CheckForNull
 private String findDataFromComponent(String fileKey, String metricKey) {
   DbSession session = dbClient.openSession(false);
   try {
     MeasureDto data =
         dbClient.measureDao().getNullableByKey(session, MeasureKey.of(fileKey, metricKey));
     if (data != null) {
       return data.getData();
     }
     return null;
   } finally {
     MyBatis.closeQuietly(session);
   }
 }
예제 #24
0
  private void insertDebtCharacteristics(DbSession dbSession) {
    CharacteristicDto reliability = DebtTesting.newCharacteristicDto("RELIABILITY");
    db.debtCharacteristicDao().insert(dbSession, reliability);

    CharacteristicDto softReliability =
        DebtTesting.newCharacteristicDto("SOFT_RELIABILITY").setParentId(reliability.getId());
    db.debtCharacteristicDao().insert(dbSession, softReliability);
    softReliabilityId = softReliability.getId();

    CharacteristicDto hardReliability =
        DebtTesting.newCharacteristicDto("HARD_RELIABILITY").setParentId(reliability.getId());
    db.debtCharacteristicDao().insert(dbSession, hardReliability);
    hardReliabilityId = hardReliability.getId();
  }
  @Test
  public void do_not_delete_default_profile() {
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    factory.setDefault(dbSession, XOO_P1_KEY);
    dbSession.commit();
    dbSession.clearCache();

    try {
      factory.delete(XOO_P1_KEY);
      fail();
    } catch (BadRequestException e) {
      assertThat(e).hasMessage("The profile marked as default can not be deleted: XOO_P1");
      assertThat(db.qualityProfileDao().selectAll(dbSession)).hasSize(1);
    }
  }
예제 #26
0
 /** Does not commit */
 private void removeParent(DbSession dbSession, QualityProfileDto profileDto) {
   if (profileDto.getParent() != null) {
     profileDto.setParent(null);
     db.qualityProfileDao().update(dbSession, profileDto);
     for (ActiveRuleDto activeRule :
         db.activeRuleDao().findByProfileKey(dbSession, profileDto.getKey())) {
       if (ActiveRuleDto.INHERITED.equals(activeRule.getInheritance())) {
         deactivate(dbSession, activeRule.getKey(), true);
       } else if (ActiveRuleDto.OVERRIDES.equals(activeRule.getInheritance())) {
         activeRule.setInheritance(null);
         db.activeRuleDao().update(dbSession, activeRule);
       }
     }
   }
 }
  @Test
  public void delete_characteristic() {
    DbSession batchSession = mock(DbSession.class);
    when(dbClient.openSession(true)).thenReturn(batchSession);

    when(ruleDao.findRulesByDebtSubCharacteristicId(batchSession, subCharacteristicDto.getId()))
        .thenReturn(
            newArrayList(
                new RuleDto()
                    .setSubCharacteristicId(subCharacteristicDto.getId())
                    .setRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.toString())
                    .setRemediationCoefficient("2h")
                    .setRemediationOffset("5min")));
    when(dao.selectCharacteristicsByParentId(1, batchSession))
        .thenReturn(newArrayList(subCharacteristicDto));
    when(dao.selectById(1, batchSession)).thenReturn(characteristicDto);

    service.delete(1);

    verify(ruleDao).update(eq(batchSession), ruleCaptor.capture());

    verify(dao, times(2)).update(characteristicCaptor.capture(), eq(batchSession));
    CharacteristicDto subCharacteristicDto = characteristicCaptor.getAllValues().get(0);
    CharacteristicDto characteristicDto = characteristicCaptor.getAllValues().get(1);

    // Sub characteristic is disable
    assertThat(subCharacteristicDto.getId()).isEqualTo(2);
    assertThat(subCharacteristicDto.isEnabled()).isFalse();
    assertThat(subCharacteristicDto.getUpdatedAt()).isEqualTo(now);

    // Characteristic is disable
    assertThat(characteristicDto.getId()).isEqualTo(1);
    assertThat(characteristicDto.isEnabled()).isFalse();
    assertThat(characteristicDto.getUpdatedAt()).isEqualTo(now);
  }
예제 #28
0
 private void updateMetricInDb(
     DbSession dbSession, MetricDto metricInDb, MetricDto metricTemplate) {
   String key = metricTemplate.getKey();
   String name = metricTemplate.getShortName();
   String type = metricTemplate.getValueType();
   String domain = metricTemplate.getDomain();
   String description = metricTemplate.getDescription();
   if (key != null) {
     metricInDb.setKey(key);
   }
   if (name != null) {
     metricInDb.setShortName(name);
   }
   if (type != null) {
     metricInDb.setValueType(type);
   }
   if (domain != null) {
     metricInDb.setDomain(domain);
   }
   if (description != null) {
     metricInDb.setDescription(description);
   }
   dbClient.metricDao().update(dbSession, metricInDb);
   dbSession.commit();
 }
예제 #29
0
  @VisibleForTesting
  List<CharacteristicDto> restoreCharacteristics(
      DebtModel targetModel, Date updateDate, DbSession session) {
    List<CharacteristicDto> sourceCharacteristics =
        dbClient.debtCharacteristicDao().selectEnabledCharacteristics(session);

    List<CharacteristicDto> result = newArrayList();

    // Create new characteristics
    for (DebtCharacteristic characteristic : targetModel.rootCharacteristics()) {
      CharacteristicDto rootCharacteristicDto =
          restoreCharacteristic(characteristic, null, sourceCharacteristics, updateDate, session);
      result.add(rootCharacteristicDto);
      for (DebtCharacteristic subCharacteristic :
          targetModel.subCharacteristics(characteristic.key())) {
        result.add(
            restoreCharacteristic(
                subCharacteristic,
                rootCharacteristicDto.getId(),
                sourceCharacteristics,
                updateDate,
                session));
      }
    }
    // Disable no more existing characteristics
    for (CharacteristicDto sourceCharacteristic : sourceCharacteristics) {
      if (targetModel.characteristicByKey(sourceCharacteristic.getKey()) == null) {
        debtModelOperations.delete(sourceCharacteristic, updateDate, session);
      }
    }
    return result;
  }
예제 #30
0
 @Test
 public void mass_insert() {
   execute(new BigRepository());
   assertThat(dbClient.ruleDao().selectAll(dbTester.getSession())).hasSize(BigRepository.SIZE);
   assertThat(dbClient.ruleDao().selectAllRuleParams(dbTester.getSession()))
       .hasSize(BigRepository.SIZE * 20);
 }