private static ActiveRules load(ActiveRulesLoader loader, QualityProfiles qProfiles) { Collection<String> qProfileKeys = getKeys(qProfiles); Set<RuleKey> loadedRulesKey = new HashSet<>(); ActiveRulesBuilder builder = new ActiveRulesBuilder(); for (String qProfileKey : qProfileKeys) { Collection<LoadedActiveRule> qProfileRules = load(loader, qProfileKey); for (LoadedActiveRule r : qProfileRules) { if (!loadedRulesKey.contains(r.getRuleKey())) { loadedRulesKey.add(r.getRuleKey()); builder.addRule(transform(r, qProfileKey)); } } } return builder.build(); }
private SensorContextTester(Path moduleBaseDir) { this.settings = new MapSettings(); this.fs = new DefaultFileSystem(moduleBaseDir).setEncoding(Charset.defaultCharset()); this.activeRules = new ActiveRulesBuilder().build(); this.sensorStorage = new InMemorySensorStorage(); this.project = new DefaultInputProject(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile())); this.module = new DefaultInputModule(ProjectDefinition.create().setKey("projectKey").setBaseDir(moduleBaseDir.toFile()).setWorkDir(moduleBaseDir.resolve(".sonar").toFile())); this.runtime = SonarRuntimeImpl.forSonarQube(ApiVersion.load(System2.INSTANCE), SonarQubeSide.SCANNER); }
@Test public void fail_to_add_twice_the_same_rule() { ActiveRulesBuilder builder = new ActiveRulesBuilder(); NewActiveRule rule = new NewActiveRule.Builder() .setRuleKey(RuleKey.of("squid", "S0001")) .build(); builder.addRule(rule); thrown.expect(IllegalStateException.class); thrown.expectMessage("Rule 'squid:S0001' is already activated"); builder.addRule(rule); } }
@Before public void setActiveRules() { context.setActiveRules( new ActiveRulesBuilder() .create(RuleKey.of("PerlCritic", "TestingAndDebugging::RequireUseStrict")).activate() .build() ); }
@Test public void class_name_as_check_key() { RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithoutProperties"); NewActiveRule rule = new NewActiveRule.Builder() .setRuleKey(ruleKey) .build(); builder.addRule(rule); CheckFactory checkFactory = new CheckFactory(builder.build()); Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithoutProperties.class); Object check = checks.of(ruleKey); assertThat(check).isInstanceOf(CheckWithoutProperties.class); assertThat(checks.all()).containsOnly(check); assertThat(checks.ruleKey(check)).isEqualTo(ruleKey); }
/** * Every rules and active rules has to be added in builders before creating IssuePublisher */ private void initModuleIssues() { moduleIssues = new IssuePublisher(activeRulesBuilder.build(), filters, reportPublisher); }
@Test public void add_issue_to_cache() { ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME); activeRulesBuilder.addRule(new NewActiveRule.Builder() .setRuleKey(SQUID_RULE_KEY) .setSeverity(Severity.INFO) .setQProfileKey("qp-1") .build()); initModuleIssues(); DefaultIssue issue = new DefaultIssue(project) .at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo")) .forRule(SQUID_RULE_KEY) .overrideSeverity(org.sonar.api.batch.rule.Severity.CRITICAL); when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true); boolean added = moduleIssues.initAndAddIssue(issue); assertThat(added).isTrue(); ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class); verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture()); assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.CRITICAL); }
@Test public void no_rules() { ActiveRulesBuilder builder = new ActiveRulesBuilder(); ActiveRules rules = builder.build(); assertThat(rules.findAll()).isEmpty(); }
private static ActiveRules transform(Collection<LoadedActiveRule> loadedRules) { ActiveRulesBuilder builder = new ActiveRulesBuilder(); for (LoadedActiveRule activeRule : loadedRules) { NewActiveRule newActiveRule = builder.create(activeRule.getRuleKey()); newActiveRule.setName(activeRule.getName()); newActiveRule.setSeverity(activeRule.getSeverity()); newActiveRule.setLanguage(activeRule.getLanguage()); newActiveRule.setInternalKey(activeRule.getInternalKey()); newActiveRule.setTemplateRuleKey(activeRule.getTemplateRuleKey()); // load parameters if (activeRule.getParams() != null) { for (Map.Entry<String, String> params : activeRule.getParams().entrySet()) { newActiveRule.setParam(params.getKey(), params.getValue()); } } newActiveRule.activate(); } return builder.build(); }
@Test public void param_as_string_field() { RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithStringProperty"); NewActiveRule rule = new NewActiveRule.Builder() .setRuleKey(ruleKey) .setParam("pattern", "foo") .build(); builder.addRule(rule); CheckFactory checkFactory = new CheckFactory(builder.build()); Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithStringProperty.class); Object check = checks.of(ruleKey); assertThat(check).isInstanceOf(CheckWithStringProperty.class); assertThat(((CheckWithStringProperty) check).getPattern()).isEqualTo("foo"); }
@Test public void no_checks_are_enabled() { CheckFactory checkFactory = new CheckFactory(builder.build()); Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithoutProperties.class); assertThat(checks.all()).isEmpty(); }
@Test public void use_severity_from_active_rule_if_no_severity_on_issue() { ruleBuilder.add(SQUID_RULE_KEY).setName(SQUID_RULE_NAME); activeRulesBuilder.addRule(new NewActiveRule.Builder() .setRuleKey(SQUID_RULE_KEY) .setSeverity(Severity.INFO) .setQProfileKey("qp-1") .build()); initModuleIssues(); DefaultIssue issue = new DefaultIssue(project) .at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("Foo")) .forRule(SQUID_RULE_KEY); when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true); moduleIssues.initAndAddIssue(issue); ArgumentCaptor<ScannerReport.Issue> argument = ArgumentCaptor.forClass(ScannerReport.Issue.class); verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), argument.capture()); assertThat(argument.getValue().getSeverity()).isEqualTo(org.sonar.scanner.protocol.Constants.Severity.INFO); }
@Test public void testActiveRules() { NewActiveRule activeRule = new NewActiveRule.Builder() .setRuleKey(RuleKey.of("foo", "bar")) .build(); ActiveRules activeRules = new ActiveRulesBuilder().addRule(activeRule).build(); tester.setActiveRules(activeRules); assertThat(tester.activeRules().findAll()).hasSize(1); }
@Before public void prepare() throws Exception { fs = new DefaultFileSystem(temp.newFolder().toPath()); settings = new MapSettings(); optimizer = new ModuleSensorOptimizer(fs, new ActiveRulesBuilder().build(), settings.asConfig()); }
private ActiveRules load(ProjectRepositories ref) { ActiveRulesBuilder builder = new ActiveRulesBuilder(); for (ActiveRule activeRule : ref.activeRules()) { NewActiveRule newActiveRule = builder.create(RuleKey.of(activeRule.repositoryKey(), activeRule.ruleKey())); newActiveRule.setName(activeRule.name()); newActiveRule.setSeverity(activeRule.severity()); newActiveRule.setLanguage(activeRule.language()); newActiveRule.setInternalKey(activeRule.internalKey()); newActiveRule.setTemplateRuleKey(activeRule.templateRuleKey()); // load parameters for (Entry<String, String> param : activeRule.params().entrySet()) { newActiveRule.setParam(param.getKey(), param.getValue()); } newActiveRule.activate(); } return builder.build(); } }
@Test public void override_field_key() { RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithOverriddenPropertyKey"); NewActiveRule rule = new NewActiveRule.Builder() .setRuleKey(ruleKey) .setParam("maximum", "300") .build(); builder.addRule(rule); CheckFactory checkFactory = new CheckFactory(builder.build()); Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithOverriddenPropertyKey.class); Object check = checks.of(ruleKey); assertThat(check).isInstanceOf(CheckWithOverriddenPropertyKey.class); assertThat(((CheckWithOverriddenPropertyKey) check).getMax()).isEqualTo(300); }
@Test public void should_accept_issues_on_no_sonar_rules() { // The "No Sonar" rule logs violations on the lines that are flagged with "NOSONAR" !! ruleBuilder.add(NOSONAR_RULE_KEY).setName("No Sonar"); activeRulesBuilder.addRule(new NewActiveRule.Builder() .setRuleKey(NOSONAR_RULE_KEY) .setSeverity(Severity.INFO) .setQProfileKey("qp-1") .build()); initModuleIssues(); file.noSonarAt(new HashSet<>(Collections.singletonList(3))); DefaultIssue issue = new DefaultIssue(project) .at(new DefaultIssueLocation().on(file).at(file.selectLine(3)).message("")) .forRule(NOSONAR_RULE_KEY); when(filters.accept(any(InputComponent.class), any(ScannerReport.Issue.class))).thenReturn(true); boolean added = moduleIssues.initAndAddIssue(issue); assertThat(added).isTrue(); verify(reportPublisher.getWriter()).appendComponentIssue(eq(file.scannerId()), any()); }
@Test public void should_optimize_on_repository() { DefaultSensorDescriptor descriptor = new DefaultSensorDescriptor() .createIssuesForRuleRepositories("squid"); assertThat(optimizer.shouldExecute(descriptor)).isFalse(); ActiveRules activeRules = new ActiveRulesBuilder() .addRule(new NewActiveRule.Builder().setRuleKey(RuleKey.of("repo1", "foo")).build()) .build(); optimizer = new ModuleSensorOptimizer(fs, activeRules, settings.asConfig()); assertThat(optimizer.shouldExecute(descriptor)).isFalse(); activeRules = new ActiveRulesBuilder() .addRule(new NewActiveRule.Builder().setRuleKey(RuleKey.of("repo1", "foo")).build()) .addRule(new NewActiveRule.Builder().setRuleKey(RuleKey.of("squid", "rule")).build()) .build(); optimizer = new ModuleSensorOptimizer(fs, activeRules, settings.asConfig()); assertThat(optimizer.shouldExecute(descriptor)).isTrue(); }
@Before public void prepare() throws Exception { activeRules = new ActiveRulesBuilder().build(); fs = new DefaultFileSystem(temp.newFolder().toPath()); MetricFinder metricFinder = mock(MetricFinder.class); when(metricFinder.<Integer>findByKey(CoreMetrics.NCLOC_KEY)).thenReturn(CoreMetrics.NCLOC); when(metricFinder.<String>findByKey(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION_KEY)).thenReturn(CoreMetrics.FUNCTION_COMPLEXITY_DISTRIBUTION); settings = new MapSettings(); sensorStorage = mock(SensorStorage.class); analysisMode = mock(AnalysisMode.class); runtime = SonarRuntimeImpl.forSonarQube(Version.parse("5.5"), SonarQubeSide.SCANNER); hierarchy = new DefaultInputModuleHierarchy(new DefaultInputModule(ProjectDefinition.create() .setWorkDir(temp.newFolder()) .setBaseDir(temp.newFolder()).setKey("foo"))); adaptor = new ModuleSensorContext(mock(DefaultInputProject.class), mock(InputModule.class), settings.asConfig(), settings, fs, activeRules, analysisMode, sensorStorage, runtime); }
private GoSensor getSensor(String... activeRuleArray) { Set<String> activeRuleSet = new HashSet<>(Arrays.asList(activeRuleArray)); List<Class> ruleClasses = GoChecks.getChecks(); List<String> allKeys = ruleClasses.stream().map(ruleClass -> ((org.sonar.check.Rule) ruleClass.getAnnotations()[0]).key()).collect(Collectors.toList()); ActiveRulesBuilder rulesBuilder = new ActiveRulesBuilder(); allKeys.forEach(key -> { NewActiveRule newActiveRule = rulesBuilder.create(RuleKey.of(GoRulesDefinition.REPOSITORY_KEY, key)); if (activeRuleSet.contains(key)) { newActiveRule.activate(); if (key.equals("S1451")) { newActiveRule.setParam("headerFormat", "some header format"); } } }); ActiveRules activeRules = rulesBuilder.build(); CheckFactory checkFactory = new CheckFactory(activeRules); Checks<Check> checks = checkFactory.create(GoRulesDefinition.REPOSITORY_KEY); checks.addAnnotatedChecks((Iterable) ruleClasses); return new GoSensor(checkFactory, fileLinesContextFactory); }