@Test
  public void update_target_profile() {
    // source 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();

    // create target with both x1 and x2 activated
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP2());
    activation = new RuleActivation(RuleTesting.XOO_X1);
    activation.setSeverity(Severity.CRITICAL);
    activation.setParameter("max", "20");
    ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P2_KEY);
    activation = new RuleActivation(RuleTesting.XOO_X2);
    activation.setSeverity(Severity.CRITICAL);
    ruleActivator.activate(dbSession, activation, QProfileTesting.XOO_P2_KEY);
    dbSession.commit();
    dbSession.clearCache();

    // copy -> reset x1 and deactivate x2
    copier.copyToName(QProfileTesting.XOO_P1_KEY, QProfileTesting.XOO_P2_NAME.getName());

    verifyOneActiveRule(
        QProfileTesting.XOO_P2_KEY, Severity.BLOCKER, null, ImmutableMap.of("max", "7"));
  }
  @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);
  }
  @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 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();
  }
  @Test
  public void ignore_renaming_if_same_name() {
    QualityProfileDto dto = factory.create(dbSession, new QProfileName("xoo", "P1"));
    dbSession.commit();
    dbSession.clearCache();
    String key = dto.getKey();

    assertThat(factory.rename(key, "P1")).isFalse();
    dbSession.clearCache();

    QualityProfileDto reloaded = db.qualityProfileDao().selectByKey(dbSession, dto.getKee());
    assertThat(reloaded.getKey()).isEqualTo(key);
    assertThat(reloaded.getName()).isEqualTo("P1");
  }
  @Test
  public void no_changes() {
    ruleDao.insert(
        dbSession,
        RuleTesting.newDto(RULE_KEY)
            // the following fields are not supposed to be updated
            .setNoteData("my *note*")
            .setNoteUserLogin("me")
            .setTags(ImmutableSet.of("tag1"))
            .setSubCharacteristicId(33)
            .setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.name())
            .setRemediationCoefficient("1d")
            .setRemediationOffset("5min"));
    dbSession.commit();

    RuleUpdate update = RuleUpdate.createForPluginRule(RULE_KEY);
    assertThat(update.isEmpty()).isTrue();
    updater.update(update, userSessionRule);

    dbSession.clearCache();
    RuleDto rule = ruleDao.getNullableByKey(dbSession, RULE_KEY);
    assertThat(rule.getNoteData()).isEqualTo("my *note*");
    assertThat(rule.getNoteUserLogin()).isEqualTo("me");
    assertThat(rule.getTags()).containsOnly("tag1");
    assertThat(rule.getSubCharacteristicId()).isEqualTo(33);
    assertThat(rule.getRemediationFunction())
        .isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE.name());
    assertThat(rule.getRemediationCoefficient()).isEqualTo("1d");
    assertThat(rule.getRemediationOffset()).isEqualTo("5min");
  }
  @Test
  public void update_manual_rule() {
    // Create manual rule
    RuleDto manualRule =
        RuleTesting.newManualRule("My manual")
            .setName("Old name")
            .setDescription("Old description")
            .setSeverity(Severity.INFO);
    ruleDao.insert(dbSession, manualRule);

    dbSession.commit();

    // Update manual rule
    RuleUpdate update =
        RuleUpdate.createForManualRule(manualRule.getKey())
            .setName("New name")
            .setMarkdownDescription("New description")
            .setSeverity(Severity.CRITICAL);
    updater.update(update, userSessionRule);

    dbSession.clearCache();

    // Verify manual rule is updated
    Rule manualRuleReloaded = ruleIndex.getByKey(manualRule.getKey());
    assertThat(manualRuleReloaded).isNotNull();
    assertThat(manualRuleReloaded.name()).isEqualTo("New name");
    assertThat(manualRuleReloaded.htmlDescription()).isEqualTo("New description");
    assertThat(manualRuleReloaded.severity()).isEqualTo(Severity.CRITICAL);
  }
  @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);
  }
  @Test
  public void bulk_deactivate_rule_by_profile() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule0 = createRule(profile.getLanguage(), "hello");
    RuleDto rule1 = createRule(profile.getLanguage(), "world");
    createActiveRule(rule0, profile);
    createActiveRule(rule1, profile);
    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(2);

    // 1. Deactivate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_DEACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(WebService.Param.TEXT_QUERY, "hello");
    WsTester.Result result = request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).hasSize(1);
  }
  @Test
  public void reset() throws Exception {
    QualityProfileDto profile = QProfileTesting.newXooP1();
    QualityProfileDto subProfile =
        QProfileTesting.newXooP2().setParentKee(QProfileTesting.XOO_P1_KEY);
    db.qualityProfileDao().insert(session, profile, subProfile);

    RuleDto rule = createRule(profile.getLanguage(), "rule");
    ActiveRuleDto active1 =
        ActiveRuleDto.createFor(profile, rule).setSeverity(rule.getSeverityString());
    ActiveRuleDto active2 = ActiveRuleDto.createFor(subProfile, rule).setSeverity("MINOR");
    db.activeRuleDao().insert(session, active1);
    db.activeRuleDao().insert(session, active2);

    session.commit();
    ruIndexer.index();
    activeRuIndexer.index();

    // 0. assert rule child rule is minor
    assertThat(db.activeRuleDao().selectOrFailByKey(session, active2.getKey()).getSeverityString())
        .isEqualTo("MINOR");

    // 1. reset child rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.ACTIVATE_ACTION);
    request.setParam("profile_key", subProfile.getKey());
    request.setParam("rule_key", rule.getKey().toString());
    request.setParam("reset", "true");
    request.execute();
    session.clearCache();

    // 2. assert rule child rule is NOT minor
    assertThat(db.activeRuleDao().selectOrFailByKey(session, active2.getKey()).getSeverityString())
        .isNotEqualTo("MINOR");
  }
  @Test
  public void
      does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile()
          throws Exception {
    QualityProfileDto javaProfile = createProfile("java");
    createRule(javaProfile.getLanguage(), "toto");
    createRule(javaProfile.getLanguage(), "tata");
    QualityProfileDto phpProfile = createProfile("php");
    createRule(phpProfile.getLanguage(), "hello");
    createRule(phpProfile.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, javaProfile.getKey());
    request.setParam(PARAM_QPROFILE, javaProfile.getKey());
    request.setParam("activation", "false");
    request
        .execute()
        .assertJson(
            getClass(),
            "does_not_return_warnings_when_bulk_activate_on_profile_and_rules_exist_on_another_language_than_profile.json");
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, javaProfile.getKey())).hasSize(2);
  }
  @Test
  public void fail_to_update_custom_when_description_is_empty() {
    // Template rule
    RuleDto templateRule =
        ruleDao.insert(session, RuleTesting.newTemplateRule(RuleKey.of("java", "S001")));

    // Custom rule
    RuleDto customRule = RuleTesting.newCustomRule(templateRule);
    ruleDao.insert(session, customRule);
    session.commit();
    session.clearCache();

    WsTester.TestRequest request =
        wsTester
            .newPostRequest("api/rules", "update")
            .setParam("key", customRule.getKey().toString())
            .setParam("name", "My custom rule")
            .setParam("markdown_description", "");

    try {
      request.execute();
      fail();
    } catch (Exception e) {
      assertThat(e)
          .isInstanceOf(IllegalArgumentException.class)
          .hasMessage("The description is missing");
    }
  }
  @Test
  public void bulk_activate_rule_not_all() throws Exception {
    QualityProfileDto java = createProfile("java");
    QualityProfileDto php = createProfile("php");
    createRule(java.getLanguage(), "toto");
    createRule(java.getLanguage(), "tata");
    createRule(php.getLanguage(), "hello");
    createRule(php.getLanguage(), "world");
    session.commit();
    ruIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, php.getKey())).isEmpty();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(
            QProfilesWs.API_ENDPOINT, BulkRuleActivationActions.BULK_ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, php.getKey());
    request.setParam(PARAM_LANGUAGES, "php");
    request.execute().assertJson(getClass(), "bulk_activate_rule_not_all.json");
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    assertThat(db.activeRuleDao().selectByProfileKey(session, php.getKey())).hasSize(2);
  }
  @Test
  public void activate_rule_override_severity() throws Exception {
    QualityProfileDto profile = createProfile("java");
    RuleDto rule = createRule(profile.getLanguage(), "toto");
    session.commit();
    ruIndexer.index();

    // 0. Assert No Active Rule for profile
    assertThat(db.activeRuleDao().selectByProfileKey(session, profile.getKey())).isEmpty();

    // 1. Activate Rule
    WsTester.TestRequest request =
        wsTester.newPostRequest(QProfilesWs.API_ENDPOINT, RuleActivationActions.ACTIVATE_ACTION);
    request.setParam(RuleActivationActions.PROFILE_KEY, profile.getKey());
    request.setParam(RuleActivationActions.RULE_KEY, rule.getKey().toString());
    request.setParam(RuleActivationActions.SEVERITY, "MINOR");
    WsTester.Result result = request.execute();
    session.clearCache();

    // 2. Assert ActiveRule in DAO
    ActiveRuleKey activeRuleKey = ActiveRuleKey.of(profile.getKey(), rule.getKey());

    assertThat(db.activeRuleDao().selectOrFailByKey(session, activeRuleKey).getSeverityString())
        .isEqualTo("MINOR");
  }
  @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();
  }
  @Test
  public void delete() {
    initRules();
    db.qualityProfileDao().insert(dbSession, QProfileTesting.newXooP1());
    tester
        .get(RuleActivator.class)
        .activate(dbSession, new RuleActivation(RuleTesting.XOO_X1), XOO_P1_KEY);
    dbSession.commit();
    dbSession.clearCache();

    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();
  }
  @Test
  public void update_custom_rule() {
    // Create template rule
    RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
    ruleDao.insert(dbSession, templateRule);
    RuleParamDto templateRuleParam1 =
        RuleParamDto.createFor(templateRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex")
            .setDefaultValue(".*");
    RuleParamDto templateRuleParam2 =
        RuleParamDto.createFor(templateRule)
            .setName("format")
            .setType("STRING")
            .setDescription("Format");
    ruleDao.insertRuleParam(dbSession, templateRule, templateRuleParam1);
    ruleDao.insertRuleParam(dbSession, templateRule, templateRuleParam2);

    // Create custom rule
    RuleDto customRule =
        RuleTesting.newCustomRule(templateRule)
            .setName("Old name")
            .setDescription("Old description")
            .setSeverity(Severity.MINOR)
            .setStatus(RuleStatus.BETA);
    ruleDao.insert(dbSession, customRule);
    ruleDao.insertRuleParam(dbSession, customRule, templateRuleParam1.setDefaultValue("a.*"));
    ruleDao.insertRuleParam(dbSession, customRule, templateRuleParam2.setDefaultValue(null));

    dbSession.commit();

    // Update custom rule
    RuleUpdate update =
        RuleUpdate.createForCustomRule(customRule.getKey())
            .setName("New name")
            .setMarkdownDescription("New description")
            .setSeverity("MAJOR")
            .setStatus(RuleStatus.READY)
            .setParameters(ImmutableMap.of("regex", "b.*"));
    updater.update(update, userSessionRule);

    dbSession.clearCache();

    // Verify custom rule is updated
    Rule customRuleReloaded = ruleIndex.getByKey(customRule.getKey());
    assertThat(customRuleReloaded).isNotNull();
    assertThat(customRuleReloaded.name()).isEqualTo("New name");
    assertThat(customRuleReloaded.htmlDescription()).isEqualTo("New description");
    assertThat(customRuleReloaded.severity()).isEqualTo("MAJOR");
    assertThat(customRuleReloaded.status()).isEqualTo(RuleStatus.READY);
    assertThat(customRuleReloaded.params()).hasSize(2);

    assertThat(customRuleReloaded.params().get(0).defaultValue()).isEqualTo("b.*");
    assertThat(customRuleReloaded.params().get(1).defaultValue()).isNull();
  }
  @Test
  public void get_profile_by_name_and_language() {
    QualityProfileDto profileDto =
        QProfileTesting.newQProfileDto(new QProfileName("xoo", "SonarQube way"), "abcd");
    db.qualityProfileDao().insert(dbSession, profileDto);
    dbSession.commit();
    dbSession.clearCache();

    assertThat(factory.getByNameAndLanguage("SonarQube way", "xoo").getKey()).isEqualTo("abcd");
    assertThat(factory.getByNameAndLanguage("SonarQube way", "java")).isNull();
    assertThat(factory.getByNameAndLanguage("Unfound", "xoo")).isNull();
  }
  @Test
  public void fail_renaming_if_name_already_exists() {
    QualityProfileDto p1 = factory.create(dbSession, new QProfileName("xoo", "P1"));
    QualityProfileDto p2 = factory.create(dbSession, new QProfileName("xoo", "P2"));
    dbSession.commit();
    dbSession.clearCache();

    try {
      factory.rename(p1.getKey(), "P2");
      fail();
    } catch (BadRequestException e) {
      assertThat(e).hasMessage("Quality profile already exists: P2");
    }
  }
  @Test
  public void fail_if_blank_renaming() {
    QualityProfileDto dto = factory.create(dbSession, new QProfileName("xoo", "P1"));
    dbSession.commit();
    dbSession.clearCache();
    String key = dto.getKey();

    try {
      factory.rename(key, " ");
      fail();
    } catch (BadRequestException e) {
      assertThat(e).hasMessage("Name must be set");
    }
  }
  @Test
  public void fail_to_create_if_already_exists() {
    QProfileName name = new QProfileName("xoo", "P1");
    factory.create(dbSession, name);
    dbSession.commit();
    dbSession.clearCache();

    try {
      factory.create(dbSession, name);
      fail();
    } catch (BadRequestException e) {
      assertThat(e).hasMessage("Quality profile already exists: {lang=xoo, name=P1}");
    }
  }
  @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);
    }
  }
  @Test
  public void create_target_profile() {
    // source
    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();

    // target does not exist
    copier.copyToName(QProfileTesting.XOO_P1_KEY, QProfileTesting.XOO_P2_NAME.getName());

    verifyOneActiveRule(
        QProfileTesting.XOO_P2_NAME, Severity.BLOCKER, null, ImmutableMap.of("max", "7"));
  }
  @Test
  public void fail_to_copy_on_self() {
    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();

    try {
      copier.copyToName(QProfileTesting.XOO_P1_KEY, QProfileTesting.XOO_P1_NAME.getName());
      fail();
    } catch (IllegalArgumentException e) {
      assertThat(e).hasMessage("Source and target profiles are equal: P1");
    }
  }
  @Test
  public void remove_markdown_note() {
    ruleDao.insert(
        dbSession, RuleTesting.newDto(RULE_KEY).setNoteData("my *note*").setNoteUserLogin("me"));
    dbSession.commit();

    RuleUpdate update = RuleUpdate.createForPluginRule(RULE_KEY).setMarkdownNote(null);
    updater.update(update, userSessionRule);

    dbSession.clearCache();
    RuleDto rule = ruleDao.getNullableByKey(dbSession, RULE_KEY);
    assertThat(rule.getNoteData()).isNull();
    assertThat(rule.getNoteUserLogin()).isNull();
    assertThat(rule.getNoteCreatedAt()).isNull();
    assertThat(rule.getNoteUpdatedAt()).isNull();
  }
 private void initRules() {
   // create pre-defined rules
   RuleDto xooRule1 = RuleTesting.newXooX1();
   RuleDto xooRule2 = RuleTesting.newXooX2();
   db.deprecatedRuleDao().insert(dbSession, xooRule1, xooRule2);
   db.deprecatedRuleDao()
       .insertRuleParam(
           dbSession,
           xooRule1,
           RuleParamDto.createFor(xooRule1)
               .setName("max")
               .setDefaultValue("10")
               .setType(RuleParamType.INTEGER.type()));
   dbSession.commit();
   dbSession.clearCache();
 }
  @Test
  public void override_debt() {
    insertDebtCharacteristics(dbSession);
    ruleDao.insert(
        dbSession,
        RuleTesting.newDto(RULE_KEY)
            .setDefaultSubCharacteristicId(hardReliabilityId)
            .setDefaultRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET.name())
            .setDefaultRemediationCoefficient("1d")
            .setDefaultRemediationOffset("5min")
            .setSubCharacteristicId(null)
            .setRemediationFunction(null)
            .setRemediationCoefficient(null)
            .setRemediationOffset(null));
    dbSession.commit();

    DefaultDebtRemediationFunction fn =
        new DefaultDebtRemediationFunction(
            DebtRemediationFunction.Type.CONSTANT_ISSUE, null, "1min");
    RuleUpdate update =
        RuleUpdate.createForPluginRule(RULE_KEY)
            .setDebtSubCharacteristic("SOFT_RELIABILITY")
            .setDebtRemediationFunction(fn);
    updater.update(update, userSessionRule);
    dbSession.clearCache();

    // verify debt is overridden
    Rule indexedRule = tester.get(RuleIndex.class).getByKey(RULE_KEY);
    assertThat(indexedRule.debtCharacteristicKey()).isEqualTo("RELIABILITY");
    assertThat(indexedRule.debtSubCharacteristicKey()).isEqualTo("SOFT_RELIABILITY");
    assertThat(indexedRule.debtRemediationFunction().type())
        .isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE);
    assertThat(indexedRule.debtRemediationFunction().coefficient()).isNull();
    assertThat(indexedRule.debtRemediationFunction().offset()).isEqualTo("1min");

    assertThat(indexedRule.debtOverloaded()).isTrue();
    assertThat(indexedRule.defaultDebtCharacteristicKey()).isEqualTo("RELIABILITY");
    assertThat(indexedRule.defaultDebtSubCharacteristicKey()).isEqualTo("HARD_RELIABILITY");
    assertThat(indexedRule.defaultDebtRemediationFunction().type())
        .isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET);
    assertThat(indexedRule.defaultDebtRemediationFunction().coefficient()).isEqualTo("1d");
    assertThat(indexedRule.defaultDebtRemediationFunction().offset()).isEqualTo("5min");
  }
  @Test
  public void create() {
    QualityProfileDto dto = factory.create(dbSession, new QProfileName("xoo", "P1"));
    dbSession.commit();
    dbSession.clearCache();
    assertThat(dto.getKey()).startsWith("xoo-p1-");
    assertThat(dto.getName()).isEqualTo("P1");
    assertThat(dto.getLanguage()).isEqualTo("xoo");
    assertThat(dto.getId()).isNotNull();

    // reload the dto
    dto = db.qualityProfileDao().selectByNameAndLanguage("P1", "xoo", dbSession);
    assertThat(dto.getLanguage()).isEqualTo("xoo");
    assertThat(dto.getName()).isEqualTo("P1");
    assertThat(dto.getKey()).startsWith("xoo-p1");
    assertThat(dto.getId()).isNotNull();
    assertThat(dto.getParentKee()).isNull();

    assertThat(db.qualityProfileDao().selectAll(dbSession)).hasSize(1);
  }
  @Test
  public void remove_tags() {
    ruleDao.insert(
        dbSession,
        RuleTesting.newDto(RULE_KEY)
            .setTags(Sets.newHashSet("security"))
            .setSystemTags(Sets.newHashSet("java8", "javadoc")));
    dbSession.commit();

    RuleUpdate update = RuleUpdate.createForPluginRule(RULE_KEY).setTags(null);
    updater.update(update, userSessionRule);

    dbSession.clearCache();
    RuleDto rule = ruleDao.getNullableByKey(dbSession, RULE_KEY);
    assertThat(rule.getTags()).isEmpty();
    assertThat(rule.getSystemTags()).containsOnly("java8", "javadoc");

    // verify that tags are indexed in index
    Set<String> tags = tester.get(RuleService.class).listTags();
    assertThat(tags).containsOnly("java8", "javadoc");
  }
  @Test
  public void update_custom_rule_with_empty_parameter() {
    // Create template rule
    RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
    ruleDao.insert(dbSession, templateRule);
    RuleParamDto templateRuleParam =
        RuleParamDto.createFor(templateRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex");
    ruleDao.insertRuleParam(dbSession, templateRule, templateRuleParam);

    // Create custom rule
    RuleDto customRule =
        RuleTesting.newCustomRule(templateRule)
            .setName("Old name")
            .setDescription("Old description")
            .setSeverity(Severity.MINOR)
            .setStatus(RuleStatus.BETA);
    ruleDao.insert(dbSession, customRule);
    ruleDao.insertRuleParam(dbSession, customRule, templateRuleParam);

    dbSession.commit();

    // Update custom rule without setting a value for the parameter
    RuleUpdate update =
        RuleUpdate.createForCustomRule(customRule.getKey())
            .setName("New name")
            .setMarkdownDescription("New description")
            .setSeverity("MAJOR")
            .setStatus(RuleStatus.READY);
    updater.update(update, userSessionRule);

    dbSession.clearCache();

    // Verify custom rule is updated
    Rule customRuleReloaded = ruleIndex.getByKey(customRule.getKey());
    RuleParam param = customRuleReloaded.params().get(0);
    assertThat(param.defaultValue()).isNull();
  }