@Test
  public void search_by_template_key() throws InterruptedException {
    RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
    dao.insert(dbSession, templateRule);
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM"))
            .setTemplateId(templateRule.getId()));
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(2);

    // Only custom rule
    query = new RuleQuery().setTemplateKey("java:S001");
    results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule())
        .isEqualTo("S001_MY_CUSTOM");
    assertThat(Iterables.getFirst(results.getHits(), null).templateKey())
        .isEqualTo(RuleKey.of("java", "S001"));

    // null => no filter
    query = new RuleQuery().setTemplateKey(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  @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 search_by_any_of_severities() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setSeverity(Severity.BLOCKER));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setSeverity(Severity.INFO));
    dbSession.commit();

    RuleQuery query = new RuleQuery().setSeverities(Arrays.asList(Severity.INFO, Severity.MINOR));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setSeverities(Arrays.asList(Severity.MINOR));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setSeverities(Collections.<String>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setSeverities(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  @Test
  public void fail_to_update_custom_rule_when_empty_description() {
    // Create template rule
    RuleDto templateRule = RuleTesting.newTemplateRule(RuleKey.of("java", "S001"));
    ruleDao.insert(dbSession, templateRule);

    // Create custom rule
    RuleDto customRule = RuleTesting.newCustomRule(templateRule);
    ruleDao.insert(dbSession, customRule);

    dbSession.commit();

    // Update custom rule
    RuleUpdate update =
        RuleUpdate.createForCustomRule(customRule.getKey())
            .setName("New name")
            .setMarkdownDescription("");
    try {
      updater.update(update, userSessionRule);
      fail();
    } catch (Exception e) {
      assertThat(e)
          .isInstanceOf(IllegalArgumentException.class)
          .hasMessage("The description is missing");
    }
  }
  @Test
  public void search_by_is_template() throws InterruptedException {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(false));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setIsTemplate(true));
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(2);

    // Only template
    query = new RuleQuery().setIsTemplate(true);
    results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");
    assertThat(Iterables.getFirst(results.getHits(), null).isTemplate()).isTrue();

    // Only not template
    query = new RuleQuery().setIsTemplate(false);
    results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).isTemplate()).isFalse();
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S001");

    // null => no filter
    query = new RuleQuery().setIsTemplate(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  @Test
  public void search_by_any_of_statuses() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setStatus(RuleStatus.BETA));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setStatus(RuleStatus.READY));
    dbSession.commit();

    RuleQuery query =
        new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED, RuleStatus.READY));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setStatuses(Arrays.asList(RuleStatus.DEPRECATED));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setStatuses(Collections.<RuleStatus>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setStatuses(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  @Test
  public void paging() {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S003")));
    dbSession.commit();

    // from 0 to 1 included
    QueryContext options = new QueryContext();
    options.setOffset(0).setLimit(2);
    Result results = index.search(new RuleQuery(), options);
    assertThat(results.getTotal()).isEqualTo(3);
    assertThat(results.getHits()).hasSize(2);

    // from 0 to 9 included
    options.setOffset(0).setLimit(10);
    results = index.search(new RuleQuery(), options);
    assertThat(results.getTotal()).isEqualTo(3);
    assertThat(results.getHits()).hasSize(3);

    // from 2 to 11 included
    options.setOffset(2).setLimit(10);
    results = index.search(new RuleQuery(), options);
    assertThat(results.getTotal()).isEqualTo(3);
    assertThat(results.getHits()).hasSize(1);
  }
  @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 search_by_template_key_with_params() throws InterruptedException {
    RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
    RuleParamDto ruleParamDto =
        RuleParamDto.createFor(templateRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex")
            .setDefaultValue(".*");
    dao.insert(dbSession, templateRule);
    dao.addRuleParam(dbSession, templateRule, ruleParamDto);

    RuleDto customRule =
        RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM"))
            .setTemplateId(templateRule.getId());
    RuleParamDto customRuleParam =
        RuleParamDto.createFor(customRule)
            .setName("regex")
            .setType("STRING")
            .setDescription("Reg ex")
            .setDefaultValue("a.*");
    dao.insert(dbSession, customRule);
    dao.addRuleParam(dbSession, customRule, customRuleParam);
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(2);

    // get params
    assertThat(index.getByKey(templateRule.getKey()).params()).hasSize(1);
    assertThat(index.getByKey(customRule.getKey()).params()).hasSize(1);
  }
  @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 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 QueryContext());
    assertThat(results.getHits()).hasSize(2);

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

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

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

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

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

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

    // match by SubChar & Char
    query = new RuleQuery().setQueryText(char11.getKey() + " " + char1.getKey());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(1);
  }
  @Test
  public void search_all_rules() throws InterruptedException {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "S001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")));
    dbSession.commit();

    Result results = index.search(new RuleQuery(), new QueryContext());

    assertThat(results.getTotal()).isEqualTo(2);
    assertThat(results.getHits()).hasSize(2);
  }
  @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);
  }
  @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();
  }
  @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 filter_by_key() {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "X001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("cobol", "X001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("php", "S002")));
    dbSession.commit();

    // key
    RuleQuery query = new RuleQuery().setKey(RuleKey.of("javascript", "X001").toString());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(1);

    // partial key does not match
    query = new RuleQuery().setKey("X001");
    // TODO fix non-partial match for Key search
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();
  }
  @Test
  public void search_by_any_of_languages() throws InterruptedException {
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("java", "S001")).setLanguage("java"),
        RuleTesting.newDto(RuleKey.of("javascript", "S002")).setLanguage("js"));
    dbSession.commit();

    RuleQuery query = new RuleQuery().setLanguages(Arrays.asList("cobol", "js"));
    Result<Rule> results = index.search(query, new QueryOptions());

    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setLanguages(Arrays.asList("cpp"));
    assertThat(index.search(query, new QueryOptions()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setLanguages(Collections.<String>emptyList());
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setLanguages(null);
    assertThat(index.search(query, new QueryOptions()).getHits()).hasSize(2);
  }
  @Test
  public void backup_with_disabled_rules() {
    when(dao.selectEnabledCharacteristics(session))
        .thenReturn(
            newArrayList(
                new CharacteristicDto()
                    .setId(1)
                    .setKey("PORTABILITY")
                    .setName("Portability updated")
                    .setOrder(2),
                new CharacteristicDto()
                    .setId(2)
                    .setKey("COMPILER")
                    .setName("Compiler updated")
                    .setParentId(1)));

    when(ruleDao.selectEnabledAndNonManual(session))
        .thenReturn(
            newArrayList(
                // Debt disabled
                new RuleDto()
                    .setRepositoryKey("squid")
                    .setRuleKey("UselessImportCheck")
                    .setSubCharacteristicId(RuleDto.DISABLED_CHARACTERISTIC_ID),

                // Not debt
                new RuleDto().setRepositoryKey("squid").setRuleKey("AvoidNPE")));

    debtModelBackup.backup();

    verify(debtModelXMLExporter).export(any(DebtModel.class), ruleDebtListCaptor.capture());

    assertThat(ruleDebtListCaptor.getValue()).isEmpty();
  }
Beispiel #19
0
  @Test
  public void fail_to_recreate_built_in_profile_when_rule_not_found() throws Exception {
    String name = "Default";
    String language = "java";

    RulesProfile profile = RulesProfile.create(name, language);
    Rule rule = Rule.create("pmd", "rule");
    profile.activateRule(rule, null);

    ProfileDefinition profileDefinition = mock(ProfileDefinition.class);
    when(profileDefinition.createProfile(any(ValidationMessages.class))).thenReturn(profile);
    definitions.add(profileDefinition);

    when(ruleDao.getNullableByKey(session, RuleKey.of("pmd", "rule"))).thenReturn(null);

    when(qProfileOperations.newProfile(
            eq(name), eq(language), eq(true), any(UserSession.class), eq(session)))
        .thenReturn(new QProfile().setId(1));

    try {
      backup.recreateBuiltInProfilesByLanguage(language);
      fail();
    } catch (Exception e) {
      assertThat(e).isInstanceOf(NotFoundException.class);
    }
    verifyZeroInteractions(qProfileActiveRuleOperations);
  }
  @Test
  public void
      restore_from_xml_disable_rule_debt_when_not_in_xml_and_rule_have_default_debt_values() {
    when(characteristicsXMLImporter.importXML(anyString()))
        .thenReturn(
            new DebtModel()
                .addRootCharacteristic(
                    new DefaultDebtCharacteristic()
                        .setKey("PORTABILITY")
                        .setName("Portability")
                        .setOrder(1))
                .addSubCharacteristic(
                    new DefaultDebtCharacteristic().setKey("COMPILER").setName("Compiler"),
                    "PORTABILITY"));

    when(dao.selectEnabledCharacteristics(session))
        .thenReturn(
            newArrayList(
                new CharacteristicDto()
                    .setId(1)
                    .setKey("PORTABILITY")
                    .setName("Portability")
                    .setOrder(1)
                    .setCreatedAt(oldDate),
                new CharacteristicDto()
                    .setId(2)
                    .setKey("COMPILER")
                    .setName("Compiler")
                    .setParentId(1)
                    .setCreatedAt(oldDate)));

    when(ruleDao.selectEnabledAndNonManual(session))
        .thenReturn(
            newArrayList(
                new RuleDto()
                    .setId(1)
                    .setRepositoryKey("squid")
                    .setRuleKey("UselessImportCheck")
                    .setDefaultSubCharacteristicId(2)
                    .setDefaultRemediationFunction("LINEAR_OFFSET")
                    .setDefaultRemediationCoefficient("2h")
                    .setDefaultRemediationOffset("15min")
                //        .setCreatedAt(oldDate).setUpdatedAt(oldDate)
                ));

    debtModelBackup.restoreFromXml("<xml/>");

    verify(ruleOperations)
        .updateRule(
            ruleCaptor.capture(),
            isNull(CharacteristicDto.class),
            isNull(String.class),
            isNull(String.class),
            isNull(String.class),
            eq(session));

    verify(ruleDao).selectEnabledAndNonManual(session);
    verify(session).commit();
  }
  @Test
  public void search_by_tag() throws InterruptedException {
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S001")).setTags(ImmutableSet.of("tag1")));
    dao.insert(
        dbSession, RuleTesting.newDto(RuleKey.of("java", "S002")).setTags(ImmutableSet.of("tag2")));
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // tag1 in query
    query = new RuleQuery().setQueryText("tag1");
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(1);
    assertThat(Iterables.getFirst(index.search(query, new QueryContext()).getHits(), null).tags())
        .containsExactly("tag1");

    // tag1 and tag2 in query
    query = new RuleQuery().setQueryText("tag1 tag2");
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // tag2 in filter
    query = new RuleQuery().setTags(ImmutableSet.of("tag2"));
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(1);
    assertThat(Iterables.getFirst(index.search(query, new QueryContext()).getHits(), null).tags())
        .containsExactly("tag2");

    // tag2 in filter and tag1 tag2 in query
    query = new RuleQuery().setTags(ImmutableSet.of("tag2")).setQueryText("tag1");
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(0);

    // tag2 in filter and tag1 in query
    query = new RuleQuery().setTags(ImmutableSet.of("tag2")).setQueryText("tag1 tag2");
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(1);
    assertThat(Iterables.getFirst(index.search(query, new QueryContext()).getHits(), null).tags())
        .containsExactly("tag2");

    // null list => no filter
    query = new RuleQuery().setTags(Collections.<String>emptySet());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // null list => no filter
    query = new RuleQuery().setTags(null);
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  @Test
  public void search_by_has_debt_characteristic() throws InterruptedException {
    CharacteristicDto char1 =
        DebtTesting.newCharacteristicDto("c1").setEnabled(true).setName("char1");
    db.debtCharacteristicDao().insert(char1, dbSession);
    dbSession.commit();

    CharacteristicDto char11 =
        DebtTesting.newCharacteristicDto("c11")
            .setEnabled(true)
            .setName("char11")
            .setParentId(char1.getId());
    db.debtCharacteristicDao().insert(char11, dbSession);

    // Rule with default characteristic
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("findbugs", "S001"))
            .setSubCharacteristicId(null)
            .setRemediationFunction(null)
            .setDefaultSubCharacteristicId(char11.getId())
            .setDefaultRemediationFunction("LINEAR")
            .setDefaultRemediationCoefficient("2h"));
    // Rule with overridden characteristic
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("pmd", "S002"))
            .setSubCharacteristicId(char11.getId())
            .setRemediationFunction("LINEAR")
            .setRemediationCoefficient("2h")
            .setDefaultSubCharacteristicId(null)
            .setDefaultRemediationFunction(null));
    dbSession.commit();

    // 0. assert base case
    assertThat(index.search(new RuleQuery(), new QueryContext()).getTotal()).isEqualTo(2);
    assertThat(db.debtCharacteristicDao().selectCharacteristics()).hasSize(2);

    // 1. assert hasSubChar filter
    assertThat(
            index
                .search(new RuleQuery().setHasDebtCharacteristic(true), new QueryContext())
                .getTotal())
        .isEqualTo(2);
  }
Beispiel #23
0
  @Test
  public void
      recreate_built_in_profiles_from_language_with_multiple_profiles_with_same_name_and_same_language()
          throws Exception {
    RulesProfile profile1 = RulesProfile.create("Default", "java");
    profile1.activateRule(Rule.create("pmd", "rule").setSeverity(RulePriority.BLOCKER), null);
    ProfileDefinition profileDefinition1 = mock(ProfileDefinition.class);
    when(profileDefinition1.createProfile(any(ValidationMessages.class))).thenReturn(profile1);
    definitions.add(profileDefinition1);

    RulesProfile profile2 = RulesProfile.create("Default", "java");
    profile2.activateRule(Rule.create("checkstyle", "rule").setSeverity(RulePriority.MAJOR), null);
    ProfileDefinition profileDefinition2 = mock(ProfileDefinition.class);
    when(profileDefinition2.createProfile(any(ValidationMessages.class))).thenReturn(profile2);
    definitions.add(profileDefinition2);

    when(ruleDao.getNullableByKey(session, RuleKey.of("pmd", "rule")))
        .thenReturn(new RuleDto().setId(10).setSeverity("INFO"));
    when(ruleDao.getNullableByKey(session, RuleKey.of("checkstyle", "rule")))
        .thenReturn(new RuleDto().setId(11).setSeverity("INFO"));

    when(qProfileOperations.newProfile(
            eq("Default"), eq("java"), eq(true), any(UserSession.class), eq(session)))
        .thenReturn(new QProfile().setId(1));

    backup.recreateBuiltInProfilesByLanguage("java");

    verify(qProfileActiveRuleOperations)
        .createActiveRule(
            eq(QualityProfileKey.of("Default", "java")),
            eq(RuleKey.of("pmd", "rule")),
            eq("BLOCKER"),
            eq(session));
    verify(qProfileActiveRuleOperations)
        .createActiveRule(
            eq(QualityProfileKey.of("Default", "java")),
            eq(RuleKey.of("checkstyle", "rule")),
            eq("MAJOR"),
            eq(session));
    verifyNoMoreInteractions(qProfileActiveRuleOperations);

    verify(dryRunCache).reportGlobalModification(session);
    verify(session).commit();
  }
  @Test
  public void search_by_any_of_repositories() {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("findbugs", "S001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("pmd", "S002")));
    dbSession.commit();

    RuleQuery query = new RuleQuery().setRepositories(Arrays.asList("checkstyle", "pmd"));
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(1);
    assertThat(Iterables.getFirst(results.getHits(), null).key().rule()).isEqualTo("S002");

    // no results
    query = new RuleQuery().setRepositories(Arrays.asList("checkstyle"));
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // empty list => no filter
    query = new RuleQuery().setRepositories(Collections.<String>emptyList());
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);
  }
  @Test
  public void show_custom_rule() throws InterruptedException {
    RuleDto templateRule = RuleTesting.newDto(RuleKey.of("java", "S001")).setIsTemplate(true);
    dao.insert(dbSession, templateRule);
    dao.insert(
        dbSession,
        RuleTesting.newDto(RuleKey.of("java", "S001_MY_CUSTOM"))
            .setTemplateId(templateRule.getId()));
    dbSession.commit();

    // find all
    RuleQuery query = new RuleQuery();
    Result<Rule> results = index.search(query, new QueryContext());
    assertThat(results.getHits()).hasSize(2);

    // find custom rule
    assertThat(index.getByKey(RuleKey.of("java", "S001_MY_CUSTOM")).templateKey())
        .isEqualTo(RuleKey.of("java", "S001"));
  }
  @Test
  public void global_facet_on_repositories_and_tags() {
    dao.insert(
            dbSession,
            RuleTesting.newDto(RuleKey.of("php", "S001")).setSystemTags(ImmutableSet.of("sysTag")))
        .setTags(ImmutableSet.<String>of());
    dao.insert(
            dbSession,
            RuleTesting.newDto(RuleKey.of("php", "S002")).setSystemTags(ImmutableSet.<String>of()))
        .setTags(ImmutableSet.of("tag1"));
    dao.insert(
            dbSession,
            RuleTesting.newDto(RuleKey.of("javascript", "S002"))
                .setTags(ImmutableSet.of("tag1", "tag2")))
        .setSystemTags(ImmutableSet.<String>of());
    dbSession.commit();
    index.refresh();

    // should not have any facet!
    RuleQuery query = new RuleQuery();
    Result result = index.search(query, new QueryOptions().setFacet(false));
    assertThat(result.getFacets()).isEmpty();

    // Repositories Facet is preset
    result = index.search(query, new QueryOptions().setFacet(true));
    assertThat(result.getFacets()).isNotNull();
    assertThat(result.getFacets()).hasSize(3);

    // Verify the value of a given facet
    Collection<FacetValue> repoFacets = result.getFacetValues("repositories");
    assertThat(repoFacets).hasSize(2);
    assertThat(Iterables.get(repoFacets, 0).getKey()).isEqualTo("php");
    assertThat(Iterables.get(repoFacets, 0).getValue()).isEqualTo(2);
    assertThat(Iterables.get(repoFacets, 1).getKey()).isEqualTo("javascript");
    assertThat(Iterables.get(repoFacets, 1).getValue()).isEqualTo(1);

    // Check that tag facet has both Tags and SystemTags values
    Collection<FacetValue> tagFacet = result.getFacetValues("tags");
    assertThat(tagFacet).hasSize(3);
    assertThat(Iterables.get(tagFacet, 0).getKey()).isEqualTo("tag1");
    assertThat(Iterables.get(tagFacet, 0).getValue()).isEqualTo(2);
  }
  @Test
  public void search_key_by_query() {
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("javascript", "X001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("cobol", "X001")));
    dao.insert(dbSession, RuleTesting.newDto(RuleKey.of("php", "S002")));
    dbSession.commit();

    // key
    RuleQuery query = new RuleQuery().setQueryText("X001");
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(2);

    // partial key does not match
    query = new RuleQuery().setQueryText("X00");
    // TODO fix non-partial match for Key search
    assertThat(index.search(query, new QueryContext()).getHits()).isEmpty();

    // repo:key -> nice-to-have !
    query = new RuleQuery().setQueryText("javascript:X001");
    assertThat(index.search(query, new QueryContext()).getHits()).hasSize(1);
  }
  @Test
  public void complex_param_value() throws InterruptedException {
    String value =
        "//expression[primary/qualifiedIdentifier[count(IDENTIFIER) = 2]/IDENTIFIER[2]/@tokenValue = 'firstOf' and primary/identifierSuffix/arguments/expression[not(primary) or primary[not(qualifiedIdentifier) or identifierSuffix]]]";

    QualityProfileDto profile = QProfileTesting.newXooP1();
    db.qualityProfileDao().insert(dbSession, profile);

    RuleDto rule = RuleTesting.newXooX1();
    dao.insert(dbSession, rule);

    RuleParamDto param =
        RuleParamDto.createFor(rule).setName("testing").setType("STRING").setDefaultValue(value);
    dao.addRuleParam(dbSession, rule, param);

    dbSession.commit();

    assertThat(index.getByKey(rule.getKey()).params()).hasSize(1);
    assertThat(index.getByKey(rule.getKey()).params().get(0).defaultValue()).isEqualTo(value);
  }
  @Test
  public void backup_from_language() {
    when(dao.selectEnabledCharacteristics(session))
        .thenReturn(
            newArrayList(
                new CharacteristicDto()
                    .setId(1)
                    .setKey("PORTABILITY")
                    .setName("Portability updated")
                    .setOrder(2),
                new CharacteristicDto()
                    .setId(2)
                    .setKey("COMPILER")
                    .setName("Compiler updated")
                    .setParentId(1)));

    when(ruleDao.selectEnabledAndNonManual(session))
        .thenReturn(
            newArrayList(
                new RuleDto()
                    .setId(1)
                    .setRepositoryKey("squid")
                    .setRuleKey("UselessImportCheck")
                    .setLanguage("java")
                    .setSubCharacteristicId(2)
                    .setRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE.toString())
                    .setRemediationOffset("15min"),
                //        .setCreatedAt(oldDate).setUpdatedAt(oldDate),
                // Should be ignored
                new RuleDto()
                    .setId(2)
                    .setRepositoryKey("checkstyle")
                    .setLanguage("java2")
                    .setSubCharacteristicId(3)
                    .setRemediationFunction(DebtRemediationFunction.Type.LINEAR.toString())
                    .setRemediationCoefficient("2h")
                //        .setCreatedAt(oldDate).setUpdatedAt(oldDate)
                ));

    debtModelBackup.backup("java");

    verify(debtModelXMLExporter).export(any(DebtModel.class), ruleDebtListCaptor.capture());

    List<RuleDebt> rules = ruleDebtListCaptor.getValue();
    assertThat(rules).hasSize(1);

    RuleDebt rule = rules.get(0);
    assertThat(rule.ruleKey().repository()).isEqualTo("squid");
    assertThat(rule.ruleKey().rule()).isEqualTo("UselessImportCheck");
    assertThat(rule.subCharacteristicKey()).isEqualTo("COMPILER");
    assertThat(rule.function()).isEqualTo("CONSTANT_ISSUE");
    assertThat(rule.coefficient()).isNull();
    assertThat(rule.offset()).isEqualTo("15min");
  }
 @Test
 public void scroll_byIds() throws Exception {
   Set<Integer> ids = new HashSet<Integer>();
   for (int i = 0; i < 150; i++) {
     RuleDto rule = RuleTesting.newDto(RuleKey.of("scroll", "r_" + i));
     dao.insert(dbSession, rule);
     dbSession.commit();
     ids.add(rule.getId());
   }
   List<Rule> rules = index.getByIds(ids);
   assertThat(rules).hasSize(ids.size());
 }