diff options
author | Duarte Meneses <duarte.meneses@sonarsource.com> | 2022-04-08 13:41:49 -0400 |
---|---|---|
committer | sonartech <sonartech@sonarsource.com> | 2022-04-21 20:02:50 +0000 |
commit | 3b7e8d87a77c1d116cfb7ad09d2ece9d8c3d76f5 (patch) | |
tree | a924db854caeee06ae3a6530da5cd86904aeed6a /sonar-plugin-api/src/test | |
parent | d6678b8eeae881a5e2a4e2c188735c3886cbdd76 (diff) | |
download | sonarqube-3b7e8d87a77c1d116cfb7ad09d2ece9d8c3d76f5.tar.gz sonarqube-3b7e8d87a77c1d116cfb7ad09d2ece9d8c3d76f5.zip |
SONAR-16232 Delete sonar-plugin-api module
Diffstat (limited to 'sonar-plugin-api/src/test')
184 files changed, 0 insertions, 15317 deletions
diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/PluginTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/PluginTest.java deleted file mode 100644 index 997d5823a12..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/PluginTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api; - -import java.util.Arrays; -import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.internal.PluginContextImpl; -import org.sonar.api.internal.SonarRuntimeImpl; -import org.sonar.api.utils.Version; - -import static org.assertj.core.api.Assertions.assertThat; - -public class PluginTest { - - private static final Version VERSION_5_6 = Version.create(5, 6); - - @Test - public void test_context() { - SonarRuntime runtime = SonarRuntimeImpl.forSonarQube(VERSION_5_6, SonarQubeSide.SERVER, SonarEdition.COMMUNITY); - MapSettings settings = new MapSettings().setProperty("foo", "bar"); - Plugin.Context context = new PluginContextImpl.Builder() - .setSonarRuntime(runtime) - .setBootConfiguration(settings.asConfig()) - .build(); - - assertThat(context.getSonarQubeVersion()).isEqualTo(VERSION_5_6); - assertThat(context.getExtensions()).isEmpty(); - - context.addExtension("foo"); - assertThat(context.getExtensions()).containsOnly("foo"); - - context.addExtensions(Arrays.asList("bar", "baz")); - assertThat(context.getExtensions()).containsOnly("foo", "bar", "baz"); - - context.addExtensions("one", "two", "three", "four"); - assertThat(context.getExtensions()).containsOnly("foo", "bar", "baz", "one", "two", "three", "four"); - - assertThat(context.getBootConfiguration().get("foo")).hasValue("bar"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/SonarQubeVersionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/SonarQubeVersionTest.java deleted file mode 100644 index 9b344891c96..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/SonarQubeVersionTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api; - -import org.junit.Test; -import org.sonar.api.utils.Version; - -import static org.assertj.core.api.Assertions.assertThat; - -public class SonarQubeVersionTest { - - @Test - public void isGte() { - Version version = Version.parse("1.2.3"); - SonarQubeVersion qubeVersion = new SonarQubeVersion(version); - assertThat(qubeVersion.get()).isEqualTo(version); - assertThat(qubeVersion.isGreaterThanOrEqual(version)).isTrue(); - assertThat(qubeVersion.isGreaterThanOrEqual(Version.parse("1.1"))).isTrue(); - assertThat(qubeVersion.isGreaterThanOrEqual(Version.parse("1.3"))).isFalse(); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectBuilderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectBuilderTest.java deleted file mode 100644 index 18095976be1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectBuilderTest.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.bootstrap; - -import java.io.File; -import org.junit.Test; -import org.sonar.api.batch.bootstrap.internal.ProjectBuilderContext; -import org.sonar.api.config.Configuration; -import org.sonar.api.config.internal.MapSettings; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class ProjectBuilderTest { - - @Test - public void shouldChangeProject() { - // this reactor is created and provided by Sonar - final ProjectReactor projectReactor = new ProjectReactor(ProjectDefinition.create()); - - ProjectBuilder builder = new ProjectBuilderSample(); - final MapSettings settings = new MapSettings(); - settings.setProperty("foo", "bar"); - final Configuration configuration = settings.asConfig(); - builder.build(new ProjectBuilderContext(projectReactor, configuration)); - - assertThat(projectReactor.getProjects().size(), is(2)); - ProjectDefinition root = projectReactor.getRoot(); - assertThat(root.getName(), is("Name changed by plugin")); - assertThat(root.getSubProjects().size(), is(1)); - assertThat(root.getSubProjects().get(0).sources()).contains("src"); - } - - final static class ProjectBuilderSample extends ProjectBuilder { - - @Override - public void build(Context context) { - assertThat(context.config().get("foo")).contains("bar"); - // change name of root project - ProjectDefinition root = context.projectReactor().getRoot(); - root.setName("Name changed by plugin"); - - // add sub-project - File baseDir = new File(root.getBaseDir(), "path/to/subproject"); - ProjectDefinition subProject = ProjectDefinition.create(); - subProject.setBaseDir(baseDir); - subProject.setWorkDir(new File(baseDir, "target/.sonar")); - subProject.setKey("groupId:parentProjectId"); - subProject.setProjectVersion(root.getOriginalVersion()); - subProject.setName("Sub Project"); - subProject.setSources("src"); - root.addSubProject(subProject); - } - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectDefinitionTest.java deleted file mode 100644 index 5570546a420..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectDefinitionTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.bootstrap; - -import java.util.HashMap; -import java.util.Map; -import org.junit.Test; -import org.sonar.api.CoreProperties; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ProjectDefinitionTest { - - @Test - public void shouldSetKey() { - ProjectDefinition def = ProjectDefinition.create(); - def.setKey("mykey"); - assertThat(def.getKey()).isEqualTo("mykey"); - } - - @Test - public void shouldSetVersion() { - ProjectDefinition def = ProjectDefinition.create(); - def.setProjectVersion("2.0-SNAPSHOT"); - assertThat(def.getVersion()).isEqualTo("2.0-SNAPSHOT"); - } - - @Test - public void shouldSupportNoVersion() { - ProjectDefinition def = ProjectDefinition.create(); - def.setProjectVersion(null); - assertThat(def.getVersion()).isEqualTo("not provided"); - assertThat(def.getOriginalVersion()).isEmpty(); - } - - @Test - public void shouldSetOptionalFields() { - ProjectDefinition def = ProjectDefinition.create(); - def.setName("myname"); - def.setDescription("desc"); - assertThat(def.getName()).isEqualTo("myname"); - assertThat(def.getDescription()).isEqualTo("desc"); - } - - @Test - public void shouldSupportDefaultName() { - ProjectDefinition def = ProjectDefinition.create(); - def.setKey("myKey"); - assertThat(def.getName()).isEqualTo("myKey"); - } - - @Test - public void shouldGetKeyFromProperties() { - Map<String, String> props = new HashMap<>(); - props.put(CoreProperties.PROJECT_KEY_PROPERTY, "foo"); - ProjectDefinition def = ProjectDefinition.create(); - def.setProperties(props); - assertThat(def.getKey()).isEqualTo("foo"); - } - - @Test - public void testDefaultValues() { - ProjectDefinition def = ProjectDefinition.create(); - assertThat(def.sources()).isEmpty(); - assertThat(def.tests()).isEmpty(); - } - - /** - * See SONAR-2879 - */ - @Test - public void shouldTrimPaths() { - ProjectDefinition def = ProjectDefinition.create(); - def.setSources("src1", " src2 ", " with whitespace"); - def.setTests("test1", " test2 ", " with whitespace"); - - assertThat(def.sources()).containsOnly("src1", "src2", "with whitespace"); - assertThat(def.tests()).containsOnly("test1", "test2", "with whitespace"); - } - - @Test - public void shouldManageRelationships() { - ProjectDefinition root = ProjectDefinition.create(); - ProjectDefinition child = ProjectDefinition.create(); - root.addSubProject(child); - - assertThat(root.getSubProjects()).hasSize(1); - assertThat(child.getSubProjects()).isEmpty(); - - assertThat(root.getParent()).isNull(); - assertThat(child.getParent()).isEqualTo(root); - } - - @Test - public void shouldResetSourceDirs() { - ProjectDefinition root = ProjectDefinition.create(); - root.addSources("src", "src2/main"); - assertThat(root.sources()).hasSize(2); - - root.resetSources(); - assertThat(root.sources()).isEmpty(); - } - - @Test - public void shouldResetTestDirs() { - ProjectDefinition root = ProjectDefinition.create(); - root.addTests("src", "src2/test"); - assertThat(root.tests()).hasSize(2); - - root.resetTests(); - assertThat(root.tests()).isEmpty(); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectReactorTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectReactorTest.java deleted file mode 100644 index ccf36a528c2..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/bootstrap/ProjectReactorTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.bootstrap; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ProjectReactorTest { - - @Test - public void shouldSupportMultipleProjects() { - ProjectDefinition root = ProjectDefinition.create(); - ProjectDefinition child = ProjectDefinition.create(); - root.addSubProject(child); - - ProjectReactor reactor = new ProjectReactor(root); - assertThat(reactor.getProjects()).hasSize(2); - assertThat(reactor.getRoot()).isSameAs(root); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldFailIfNotRoot() { - ProjectDefinition root = ProjectDefinition.create(); - ProjectDefinition child = ProjectDefinition.create(); - root.addSubProject(child); - - new ProjectReactor(child); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/AbstractCheck.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/AbstractCheck.java deleted file mode 100644 index b31ca35e0c4..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/AbstractCheck.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.RuleProperty; - -public abstract class AbstractCheck { - - @RuleProperty - private Integer max; - - public Integer getMax() { - return max; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckFactoryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckFactoryTest.java deleted file mode 100644 index cf2259a640a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckFactoryTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.junit.Test; -import org.sonar.api.batch.rule.internal.ActiveRulesBuilder; -import org.sonar.api.batch.rule.internal.NewActiveRule; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.utils.SonarException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class CheckFactoryTest { - - ActiveRulesBuilder builder = new ActiveRulesBuilder(); - - @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 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); - } - - @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 fail_if_missing_field() { - RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithStringProperty"); - NewActiveRule rule = new NewActiveRule.Builder() - .setRuleKey(ruleKey) - .setParam("unknown", "foo") - .build(); - builder.addRule(rule); - - CheckFactory checkFactory = new CheckFactory(builder.build()); - - assertThatThrownBy(() -> checkFactory.create("squid").addAnnotatedChecks(CheckWithStringProperty.class)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("The field 'unknown' does not exist or is not annotated with @RuleProperty in the class org.sonar.api.batch.rule.CheckWithStringProperty"); - } - - @Test - public void param_as_primitive_fields() { - RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithPrimitiveProperties"); - NewActiveRule rule = new NewActiveRule.Builder() - .setRuleKey(ruleKey) - .setParam("max", "300") - .setParam("ignore", "true") - .build(); - builder.addRule(rule); - - CheckFactory checkFactory = new CheckFactory(builder.build()); - Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithPrimitiveProperties.class); - - Object check = checks.of(ruleKey); - assertThat(check).isInstanceOf(CheckWithPrimitiveProperties.class); - assertThat(((CheckWithPrimitiveProperties) check).getMax()).isEqualTo(300); - assertThat(((CheckWithPrimitiveProperties) check).isIgnore()).isTrue(); - } - - /** - * SONAR-3164 - */ - @Test - public void param_as_inherited_field() { - RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithPrimitiveProperties"); - NewActiveRule rule = new NewActiveRule.Builder() - .setRuleKey(ruleKey) - .setParam("max", "300") - .build(); - builder.addRule(rule); - - CheckFactory checkFactory = new CheckFactory(builder.build()); - Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithPrimitiveProperties.class); - - Object check = checks.of(ruleKey); - assertThat(check).isInstanceOf(CheckWithPrimitiveProperties.class); - assertThat(((CheckWithPrimitiveProperties) check).getMax()).isEqualTo(300); - } - - @Test - public void use_template_rule_key() { - RuleKey ruleKey = RuleKey.of("squid", "S0001_123"); - NewActiveRule rule = new NewActiveRule.Builder() - .setRuleKey(ruleKey) - .setTemplateRuleKey("S0001") - .build(); - builder.addRule(rule); - - CheckFactory checkFactory = new CheckFactory(builder.build()); - Checks checks = checkFactory.create("squid").addAnnotatedChecks(CheckWithKey.class); - - Object check = checks.of(ruleKey); - assertThat(check).isInstanceOf(CheckWithKey.class); - assertThat(checks.of(ruleKey)).isSameAs(check); - assertThat(checks.ruleKey(check)).isEqualTo(ruleKey); - assertThat(checks.all()).containsOnly(check); - } - - @Test - public void fail_if_field_type_is_not_supported() { - RuleKey ruleKey = RuleKey.of("squid", "org.sonar.api.batch.rule.CheckWithUnsupportedPropertyType"); - NewActiveRule rule = new NewActiveRule.Builder() - .setRuleKey(ruleKey) - .setParam("max", "300") - .build(); - builder.addRule(rule); - - CheckFactory checkFactory = new CheckFactory(builder.build()); - - assertThatThrownBy(() -> checkFactory.create("squid").addAnnotatedChecks(CheckWithUnsupportedPropertyType.class)) - .isInstanceOf(SonarException.class); - } - - @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); - } - - /** - * SONAR-2900 - */ - @Test - public void checks_as_objects() { - 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()); - - CheckWithStringProperty check = new CheckWithStringProperty(); - Checks checks = checkFactory.create("squid").addAnnotatedChecks(check); - - Object createdCheck = checks.of(ruleKey); - assertThat(createdCheck).isSameAs(check); - assertThat(((CheckWithStringProperty) createdCheck).getPattern()).isEqualTo("foo"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithKey.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithKey.java deleted file mode 100644 index a9a62aef90e..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithKey.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; - -@Rule(key = "S0001", priority = Priority.CRITICAL) -public class CheckWithKey { - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithOverriddenPropertyKey.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithOverriddenPropertyKey.java deleted file mode 100644 index a582a6ab226..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithOverriddenPropertyKey.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.check.RuleProperty; - -@Rule(priority = Priority.CRITICAL) -public class CheckWithOverriddenPropertyKey{ - - @RuleProperty(key = "maximum") - private int max = 50; - - public int getMax() { - return max; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithPrimitiveProperties.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithPrimitiveProperties.java deleted file mode 100644 index fdc3f769180..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithPrimitiveProperties.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.check.RuleProperty; - -@Rule(priority = Priority.CRITICAL) -public class CheckWithPrimitiveProperties { - - @RuleProperty(description = "Maximum threshold") - private int max = 50; - - @RuleProperty - private boolean ignore; - - public int getMax() { - return max; - } - - public boolean isIgnore() { - return ignore; - } -} - diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithStringProperty.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithStringProperty.java deleted file mode 100644 index 292e343f325..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithStringProperty.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.check.RuleProperty; - -@Rule(priority = Priority.CRITICAL) -public class CheckWithStringProperty { - - @RuleProperty - private String pattern; - - public String getPattern() { - return pattern; - } -} - diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithUnsupportedPropertyType.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithUnsupportedPropertyType.java deleted file mode 100644 index a6742622620..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithUnsupportedPropertyType.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; -import org.sonar.check.RuleProperty; - -@Rule(priority = Priority.CRITICAL) -class CheckWithUnsupportedPropertyType { - - @RuleProperty - private StringBuilder max = null; - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithoutProperties.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithoutProperties.java deleted file mode 100644 index 7abf41b0a81..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/CheckWithoutProperties.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; - -@Rule(priority = Priority.CRITICAL) -public class CheckWithoutProperties { - -} - diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/ImplementedCheck.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/ImplementedCheck.java deleted file mode 100644 index cdc7e37c01f..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/rule/ImplementedCheck.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.rule; - -import org.sonar.check.Priority; -import org.sonar.check.Rule; - -@Rule(priority = Priority.CRITICAL) -public class ImplementedCheck extends AbstractCheck { - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/scm/BlameLineTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/scm/BlameLineTest.java deleted file mode 100644 index e79104f152d..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/scm/BlameLineTest.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.scm; - -import org.junit.Test; - -import java.util.Date; - -import static org.assertj.core.api.Assertions.assertThat; - -public class BlameLineTest { - - @Test - public void testBlameLine() { - Date date = new Date(); - BlameLine line1 = new BlameLine().date(date).revision("1").author("foo"); - - assertThat(line1.author()).isEqualTo("foo"); - assertThat(line1.date()).isEqualTo(date); - assertThat(line1.revision()).isEqualTo("1"); - assertThat(line1.toString()).isNotEqualTo("foo"); - assertThat(line1.toString()).contains("revision=1,author=foo"); - } - - @Test - public void test_equals_and_hashCode() { - Date date = new Date(); - BlameLine line1 = new BlameLine().date(date).revision("1").author("foo"); - BlameLine line2 = new BlameLine().date(date).revision("1").author("foo"); - BlameLine line3 = new BlameLine().date(null).revision("1").author("bar"); - BlameLine line4 = new BlameLine().date(date).revision("2").author("foo"); - BlameLine line5 = new BlameLine().date(date).revision("1").author("bar"); - - assertThat(line1) - .isEqualTo(line1) - .isNotNull() - .isEqualTo(line2) - .isNotEqualTo(line3) - .hasSameHashCodeAs(line2); - assertThat(line1.hashCode()).isNotEqualTo(line3.hashCode()); - assertThat(line1.hashCode()).isNotEqualTo(line4.hashCode()); - assertThat(line1.hashCode()).isNotEqualTo(line5.hashCode()); - } - - @Test - public void testTrimAuthor() { - BlameLine line1 = new BlameLine().date(null).revision("2").author("foo1"); - BlameLine line2 = new BlameLine().date(null).revision("2").author(" "); - BlameLine line3 = new BlameLine().date(null).revision("2").author(" foo3 "); - - assertThat(line1.author()).isEqualTo("foo1"); - assertThat(line2.author()).isNull(); - assertThat(line3.author()).isEqualTo("foo3"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/scm/ScmProviderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/scm/ScmProviderTest.java deleted file mode 100644 index cf904fe20c7..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/scm/ScmProviderTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.scm; - -import java.nio.file.Paths; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class ScmProviderTest { - - private final ScmProvider provider = new ScmProvider() { - - @Override - public String key() { - return "foo"; - } - }; - - @Test - public void default_implementation_does_not_support_blame() { - assertThat(provider.supports(null)).isFalse(); - - assertThatThrownBy(() -> provider.blameCommand()) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - public void default_implementation_does_not_support_relativePathFromScmRoot() { - assertThatThrownBy(() -> provider.relativePathFromScmRoot(Paths.get("foo"))) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - public void default_implementation_does_not_support_revisionId() { - assertThatThrownBy(() -> provider.revisionId(Paths.get("foo"))) - .isInstanceOf(UnsupportedOperationException.class); - } - - @Test - public void default_implementation_does_not_support_ignore() { - assertThatThrownBy(() -> provider.ignoreCommand()) - .isInstanceOf(UnsupportedOperationException.class); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/highlighting/TypeOfTextTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/highlighting/TypeOfTextTest.java deleted file mode 100644 index 214d5a1b142..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/batch/sensor/highlighting/TypeOfTextTest.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.batch.sensor.highlighting; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TypeOfTextTest { - - @Test - public void testForCss() { - assertThat(TypeOfText.forCssClass("k")).isEqualTo(TypeOfText.KEYWORD); - assertThat(TypeOfText.KEYWORD_LIGHT.cssClass()).isEqualTo("h"); - } - - @Test(expected = IllegalArgumentException.class) - public void throwIfUnknowCss() { - TypeOfText.forCssClass("w"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/RangeDistributionBuilderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/RangeDistributionBuilderTest.java deleted file mode 100644 index de392dce5bb..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/RangeDistributionBuilderTest.java +++ /dev/null @@ -1,172 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RangeDistributionBuilderTest { - - @Test - public void work_on_an_limits_array_copy() { - Integer[] limits = new Integer[] {4, 2, 0}; - RangeDistributionBuilder builder = new RangeDistributionBuilder(limits); - builder.add(3.2).add(2.0).add(6.2).build(); - - assertThat(limits[0]).isEqualTo(4); - assertThat(limits[1]).isEqualTo(2); - assertThat(limits[2]).isZero(); - } - - @Test - public void build_integer_distribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(new Integer[] {0, 2, 4}); - String data = builder - .add(3.2) - .add(2.0) - .add(6.2) - .build(); - - assertThat(data).isEqualTo("0=0;2=2;4=1"); - } - - @Test - public void build_double_distribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(new Double[] {0.0, 2.0, 4.0}); - String data = builder - .add(3.2) - .add(2.0) - .add(6.2) - .build(); - - assertThat(data).isEqualTo("0=0;2=2;4=1"); - } - - @Test - public void value_lesser_than_minimum_is_ignored() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(new Integer[] {0, 2, 4}); - String data = builder - .add(3.2) - .add(2.0) - .add(-3.0) - .build(); - - assertThat(data).isEqualTo("0=0;2=2;4=0"); - } - - @Test - public void add_existing_integer_distribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - String data = builder - .add("0=0;2=2;4=1") - .add("0=1;2=2;4=2") - .build(); - - assertThat(data).isEqualTo("0=1;2=4;4=3"); - } - - @Test - public void add_existing_double_distribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - String data = builder - .add("0.5=0;1.9=2;4.5=1") - .add("0.5=1;1.9=3;4.5=1") - .build(); - - assertThat(data).isEqualTo("0.5=1;1.9=5;4.5=2"); - } - - @Test - public void add_distribution_with_identical_limits() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - String data = builder - .add("0=1;2=0") - .add("0=3;2=5") - .build(); - - assertThat(data).isEqualTo("0=4;2=5"); - } - - @Test - public void add_distribution_with_different_int_limits() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - - assertThat(builder - .add("0=1") - .add("0=3;2=5") - .build()).isNull(); - } - - @Test - public void add_distribution_with_different_double_limits() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - - assertThat(builder - .add("0.0=3;3.0=5") - .add("0.0=3;3.0=5;6.0=9") - .build()).isNull(); - } - - @Test - public void init_limits_at_the_first_add() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - String data = builder - .add("0.5=3;3.5=5;6.5=9") - .add("0.5=0;3.5=2;6.5=1") - .build(); - - assertThat(data).isEqualTo("0.5=3;3.5=7;6.5=10"); - } - - @Test - public void keep_int_ranges_when_merging_distributions() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - String data = builder - .add("0=3;3=5;6=9") - .add("0=0;3=2;6=1") - .build(); - - assertThat(data).isEqualTo("0=3;3=7;6=10"); - } - - - @Test - public void is_empty_is_true_when_no_data() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - - assertThat(builder.isEmpty()).isTrue(); - } - - @Test - public void is_empty_is_true_when_no_data_on_distribution_with_limits() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(new Integer[] {4, 2, 0}); - - assertThat(builder.isEmpty()).isTrue(); - } - - @Test - public void aggregate_empty_distribution() { - RangeDistributionBuilder builder = new RangeDistributionBuilder(); - String distribution = builder.build(); - assertThat(distribution).isEmpty(); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestComponentTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestComponentTest.java deleted file mode 100644 index db4e86d050a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestComponentTest.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure.test; - -import org.junit.Test; -import org.sonar.api.ce.measure.Component; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TestComponentTest { - - @Test - public void create_project() { - TestComponent component = new TestComponent("Project", Component.Type.PROJECT, null); - - assertThat(component.getKey()).isEqualTo("Project"); - assertThat(component.getType()).isEqualTo(Component.Type.PROJECT); - } - - @Test - public void create_source_file() { - TestComponent component = new TestComponent("File", Component.Type.FILE, new TestComponent.FileAttributesImpl("xoo", false)); - - assertThat(component.getType()).isEqualTo(Component.Type.FILE); - assertThat(component.getFileAttributes().getLanguageKey()).isEqualTo("xoo"); - assertThat(component.getFileAttributes().isUnitTest()).isFalse(); - } - - @Test - public void create_test_file() { - TestComponent component = new TestComponent("File", Component.Type.FILE, new TestComponent.FileAttributesImpl(null, true)); - - assertThat(component.getType()).isEqualTo(Component.Type.FILE); - assertThat(component.getFileAttributes().isUnitTest()).isTrue(); - assertThat(component.getFileAttributes().getLanguageKey()).isNull(); - } - - @Test - public void fail_with_ISE_when_calling_get_file_attributes_on_not_file() { - TestComponent component = new TestComponent("Project", Component.Type.PROJECT, null); - - assertThatThrownBy(() -> component.getFileAttributes()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Only component of type FILE have a FileAttributes object"); - } - - @Test - public void fail_with_IAE_when_trying_to_create_a_file_without_file_attributes() { - assertThatThrownBy(() -> new TestComponent("File", Component.Type.FILE, null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Component of type FILE must have a FileAttributes object"); - } - - @Test - public void fail_with_IAE_when_trying_to_create_not_a_file_with_file_attributes() { - assertThatThrownBy(() -> new TestComponent("Project", Component.Type.PROJECT, new TestComponent.FileAttributesImpl(null, true))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Only component of type FILE have a FileAttributes object"); - } - - @Test - public void fail_with_NPE_when_creating_component_without_key() { - assertThatThrownBy(() -> new TestComponent(null, Component.Type.PROJECT, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Key cannot be null"); - } - - @Test - public void fail_with_NPE_when_creating_component_without_type() { - assertThatThrownBy(() -> new TestComponent("Project", null, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Type cannot be null"); - } - - @Test - public void test_equals_and_hashcode() { - TestComponent component = new TestComponent("Project1", Component.Type.PROJECT, null); - TestComponent sameComponent = new TestComponent("Project1", Component.Type.PROJECT, null); - TestComponent anotherComponent = new TestComponent("Project2", Component.Type.PROJECT, null); - - assertThat(component) - .isEqualTo(component) - .isEqualTo(sameComponent) - .isNotEqualTo(anotherComponent) - .isNotNull() - .hasSameHashCodeAs(component) - .hasSameHashCodeAs(sameComponent); - assertThat(component.hashCode()).isNotEqualTo(anotherComponent.hashCode()); - } - - @Test - public void test_to_string() { - assertThat(new TestComponent("File", Component.Type.FILE, new TestComponent.FileAttributesImpl("xoo", true)).toString()) - .isEqualTo("ComponentImpl{key=File, type='FILE', fileAttributes=FileAttributesImpl{languageKey='xoo', unitTest=true}}"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java deleted file mode 100644 index 4ceb693d714..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestIssueTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure.test; - -import org.junit.Test; -import org.sonar.api.ce.measure.Issue; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RuleType; -import org.sonar.api.utils.Duration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TestIssueTest { - - @Test - public void create_issue() { - Issue issue = new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setEffort(Duration.create(10L)) - .setType(RuleType.BUG) - .build(); - - assertThat(issue.key()).isEqualTo("ABCD"); - assertThat(issue.ruleKey()).isEqualTo(RuleKey.of("xoo", "S01")); - assertThat(issue.severity()).isEqualTo(Severity.BLOCKER); - assertThat(issue.status()).isEqualTo(org.sonar.api.issue.Issue.STATUS_RESOLVED); - assertThat(issue.resolution()).isEqualTo(org.sonar.api.issue.Issue.RESOLUTION_FIXED); - assertThat(issue.effort()).isEqualTo(Duration.create(10L)); - } - - @Test - public void create_issue_with_minimal_fields() { - Issue issue = new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setType(RuleType.BUG) - .build(); - - assertThat(issue.resolution()).isNull(); - assertThat(issue.effort()).isNull(); - } - - @Test - public void fail_with_NPE_when_building_issue_without_key() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setType(RuleType.BUG) - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("key cannot be null"); - } - - @Test - public void fail_with_NPE_when_creating_issue_with_null_key() { - assertThatThrownBy(() -> new TestIssue.Builder().setKey(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("key cannot be null"); - } - - @Test - public void fail_with_NPE_when_building_issue_without_rule_key() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setKey("ABCD") - .setSeverity(Severity.BLOCKER) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setType(RuleType.BUG) - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("ruleKey cannot be null"); - } - - @Test - public void fail_with_NPE_when_creating_issue_with_null_rule_key() { - assertThatThrownBy(() -> new TestIssue.Builder().setRuleKey(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("ruleKey cannot be null"); - } - - @Test - public void fail_with_IAE_when_building_issue_with_invalid_resolution() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution("unknown") - .setType(RuleType.BUG) - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("resolution 'unknown' is invalid"); - } - - @Test - public void fail_with_NPE_when_building_issue_without_severity() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setType(RuleType.BUG) - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("severity cannot be null"); - } - - @Test - public void fail_with_NPE_when_creating_issue_with_null_severity() { - assertThatThrownBy(() -> new TestIssue.Builder().setSeverity(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("severity cannot be null"); - } - - @Test - public void fail_with_IAE_when_building_issue_with_invalid_severity() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity("unknown") - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setType(RuleType.BUG) - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("severity 'unknown' is invalid"); - } - - @Test - public void fail_with_NPE_when_building_issue_without_status() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setType(RuleType.BUG) - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void fail_with_NPE_when_creating_issue_with_null_status() { - assertThatThrownBy(() -> new TestIssue.Builder().setStatus(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void fail_with_IAE_when_building_issue_with_invalid_status() { - assertThatThrownBy(() -> new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setStatus("unknown") - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setType(RuleType.BUG) - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("status 'unknown' is invalid"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java deleted file mode 100644 index 91c50617e3f..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerContextTest.java +++ /dev/null @@ -1,205 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure.test; - -import java.util.Arrays; -import org.junit.Test; -import org.sonar.api.ce.measure.Component; -import org.sonar.api.ce.measure.Issue; -import org.sonar.api.ce.measure.Settings; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RuleType; -import org.sonar.api.utils.Duration; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition; - -public class TestMeasureComputerContextTest { - - static final String INPUT_METRIC = "INPUT_METRIC"; - static final String OUTPUT_METRIC = "OUTPUT_METRIC"; - - final static Component PROJECT = new TestComponent("Project", Component.Type.PROJECT, null); - - final static MeasureComputerDefinition DEFINITION = new TestMeasureComputerDefinition.MeasureComputerDefinitionBuilderImpl() - .setInputMetrics(INPUT_METRIC) - .setOutputMetrics(OUTPUT_METRIC) - .build(); - - Settings settings = new TestSettings(); - - TestMeasureComputerContext underTest = new TestMeasureComputerContext(PROJECT, settings, DEFINITION); - - @Test - public void get_component() { - assertThat(underTest.getComponent()).isEqualTo(PROJECT); - } - - @Test - public void get_settings() { - assertThat(underTest.getSettings()).isEqualTo(settings); - } - - @Test - public void get_int_measure() { - underTest.addInputMeasure(INPUT_METRIC, 10); - - assertThat(underTest.getMeasure(INPUT_METRIC).getIntValue()).isEqualTo(10); - } - - @Test - public void get_double_measure() { - underTest.addInputMeasure(INPUT_METRIC, 10d); - - assertThat(underTest.getMeasure(INPUT_METRIC).getDoubleValue()).isEqualTo(10d); - } - - @Test - public void get_long_measure() { - underTest.addInputMeasure(INPUT_METRIC, 10L); - - assertThat(underTest.getMeasure(INPUT_METRIC).getLongValue()).isEqualTo(10L); - } - - @Test - public void get_string_measure() { - underTest.addInputMeasure(INPUT_METRIC, "text"); - - assertThat(underTest.getMeasure(INPUT_METRIC).getStringValue()).isEqualTo("text"); - } - - @Test - public void get_boolean_measure() { - underTest.addInputMeasure(INPUT_METRIC, true); - - assertThat(underTest.getMeasure(INPUT_METRIC).getBooleanValue()).isTrue(); - } - - @Test - public void fail_with_IAE_when_trying_to_get_measure_on_unknown_metric() { - assertThatThrownBy(() -> underTest.getMeasure("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Only metrics in [INPUT_METRIC] can be used to load measures"); - } - - @Test - public void get_int_children_measures() { - underTest.addChildrenMeasures(INPUT_METRIC, 10, 20); - - assertThat(underTest.getChildrenMeasures(INPUT_METRIC)).hasSize(2); - } - - @Test - public void get_doublet_children_measures() { - underTest.addChildrenMeasures(INPUT_METRIC, 10d, 20d); - - assertThat(underTest.getChildrenMeasures(INPUT_METRIC)).hasSize(2); - } - - @Test - public void get_long_children_measures() { - underTest.addChildrenMeasures(INPUT_METRIC, 10L, 20L); - - assertThat(underTest.getChildrenMeasures(INPUT_METRIC)).hasSize(2); - } - - @Test - public void get_string_children_measures() { - underTest.addChildrenMeasures(INPUT_METRIC, "value1", "value2"); - - assertThat(underTest.getChildrenMeasures(INPUT_METRIC)).hasSize(2); - } - - @Test - public void fail_with_IAE_when_trying_to_get_children_measures_on_unknown_metric() { - assertThatThrownBy(() -> underTest.getChildrenMeasures("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Only metrics in [INPUT_METRIC] can be used to load measures"); - } - - @Test - public void add_int_measure() { - underTest.addMeasure(OUTPUT_METRIC, 10); - - assertThat(underTest.getMeasure(OUTPUT_METRIC).getIntValue()).isEqualTo(10); - } - - @Test - public void add_double_measure() { - underTest.addMeasure(OUTPUT_METRIC, 10d); - - assertThat(underTest.getMeasure(OUTPUT_METRIC).getDoubleValue()).isEqualTo(10d); - } - - @Test - public void add_long_measure() { - underTest.addMeasure(OUTPUT_METRIC, 10L); - - assertThat(underTest.getMeasure(OUTPUT_METRIC).getLongValue()).isEqualTo(10L); - } - - @Test - public void add_string_measure() { - underTest.addMeasure(OUTPUT_METRIC, "text"); - - assertThat(underTest.getMeasure(OUTPUT_METRIC).getStringValue()).isEqualTo("text"); - } - - @Test - public void fail_with_IAE_when_trying_to_add_measure_on_unknown_metric() { - assertThatThrownBy(() -> underTest.addMeasure("unknown", 10)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Only metrics in [OUTPUT_METRIC] can be used to add measures. Metric 'unknown' is not allowed."); - } - - @Test - public void fail_with_IAE_when_trying_to_add_measure_on_input_metric() { - assertThatThrownBy(() -> underTest.addMeasure(INPUT_METRIC, 10)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Only metrics in [OUTPUT_METRIC] can be used to add measures. Metric 'INPUT_METRIC' is not allowed."); - } - - @Test - public void fail_with_UOE_when_trying_to_add_same_measures_twice() { - underTest.addMeasure(OUTPUT_METRIC, 10); - - assertThatThrownBy(() -> underTest.addMeasure(OUTPUT_METRIC, 20)) - .isInstanceOf(UnsupportedOperationException.class) - .hasMessage("A measure on metric 'OUTPUT_METRIC' already exists"); - } - - @Test - public void get_issues() { - Issue issue = new TestIssue.Builder() - .setKey("ABCD") - .setRuleKey(RuleKey.of("xoo", "S01")) - .setSeverity(Severity.BLOCKER) - .setStatus(org.sonar.api.issue.Issue.STATUS_RESOLVED) - .setResolution(org.sonar.api.issue.Issue.RESOLUTION_FIXED) - .setEffort(Duration.create(10L)) - .setType(RuleType.BUG) - .build(); - underTest.setIssues(Arrays.asList(issue)); - - assertThat(underTest.getIssues()).hasSize(1); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerDefinitionTest.java deleted file mode 100644 index 3df492461f1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureComputerDefinitionTest.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure.test; - -import org.junit.Test; -import org.sonar.api.ce.measure.MeasureComputer.MeasureComputerDefinition; -import org.sonar.api.ce.measure.test.TestMeasureComputerDefinition.MeasureComputerDefinitionBuilderImpl; -import org.sonar.api.measures.CoreMetrics; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TestMeasureComputerDefinitionTest { - - @Test - public void build_definition() { - MeasureComputerDefinition definition = new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", "INPUT_2") - .setOutputMetrics("OUTPUT_1", "OUTPUT_2") - .build(); - - assertThat(definition.getInputMetrics()).containsOnly("INPUT_1", "INPUT_2"); - assertThat(definition.getOutputMetrics()).containsOnly("OUTPUT_1", "OUTPUT_2"); - } - - @Test - public void build_definition_without_input_metric() { - MeasureComputerDefinition definition = new MeasureComputerDefinitionBuilderImpl() - .setOutputMetrics("OUTPUT_1", "OUTPUT_2") - .build(); - - assertThat(definition.getInputMetrics()).isEmpty(); - assertThat(definition.getOutputMetrics()).containsOnly("OUTPUT_1", "OUTPUT_2"); - } - - @Test - public void fail_with_NPE_when_building_definition_with_null_input_metrics() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics((String[]) null) - .setOutputMetrics("OUTPUT_1", "OUTPUT_2") - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("Input metrics cannot be null"); - } - - @Test - public void fail_with_NPE_when_building_definition_with_on_null_input_metric() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", null) - .setOutputMetrics("OUTPUT_1", "OUTPUT_2") - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("Null metric is not allowed"); - } - - @Test - public void fail_with_NPE_when_building_definition_with_null_output_metrics() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", "INPUT_2") - .setOutputMetrics((String[]) null) - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("Output metrics cannot be null"); - } - - @Test - public void fail_with_NPE_when_building_definition_without_output_metrics() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", "INPUT_2") - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("Output metrics cannot be null"); - } - - @Test - public void fail_with_NPE_when_building_definition_with_on_null_ouput_metric() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", "INPUT_2") - .setOutputMetrics("OUTPUT_1", null) - .build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("Null metric is not allowed"); - } - - @Test - public void fail_with_IAE_when_building_definition_with_empty_output_metrics() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", "INPUT_2") - .setOutputMetrics() - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("At least one output metric must be defined"); - } - - @Test - public void fail_with_IAE_when_building_definition_with_core_metrics_in_output_metrics() { - assertThatThrownBy(() -> new MeasureComputerDefinitionBuilderImpl() - .setInputMetrics("INPUT_1", "INPUT_2") - .setOutputMetrics(CoreMetrics.NCLOC_KEY) - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Core metrics are not allowed"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureTest.java deleted file mode 100644 index eecb98d3c94..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestMeasureTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure.test; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TestMeasureTest { - - @Test - public void create_double_measure() { - assertThat(TestMeasure.createMeasure(10d).getDoubleValue()).isEqualTo(10d); - } - - @Test - public void create_int_measure() { - assertThat(TestMeasure.createMeasure(10).getIntValue()).isEqualTo(10); - } - - @Test - public void create_long_measure() { - assertThat(TestMeasure.createMeasure(10L).getLongValue()).isEqualTo(10L); - } - - @Test - public void create_string_measure() { - assertThat(TestMeasure.createMeasure("value").getStringValue()).isEqualTo("value"); - } - - @Test - public void create_boolean_measure() { - assertThat(TestMeasure.createMeasure(true).getBooleanValue()).isTrue(); - } - - @Test - public void getDoubleValue_fails_with_ISE_when_not_a_double() { - assertThatThrownBy(() -> TestMeasure.createMeasure(10).getDoubleValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Not a double measure"); - } - - @Test - public void getIntValue_fails_with_ISE_when_not_an_int() { - assertThatThrownBy(() -> TestMeasure.createMeasure(10L).getIntValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Not an integer measure"); - } - - @Test - public void getLongValue_fails_with_ISE_when_not_a_long() { - assertThatThrownBy(() -> TestMeasure.createMeasure(10).getLongValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Not a long measure"); - } - - @Test - public void getStringValue_fails_with_ISE_when_not_a_string() { - assertThatThrownBy(() -> TestMeasure.createMeasure(10).getStringValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Not a string measure"); - } - - @Test - public void getBooleanValue_fails_with_ISE_when_not_a_boolean() { - assertThatThrownBy(() -> TestMeasure.createMeasure(10).getBooleanValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Not a boolean measure"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestSettingsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestSettingsTest.java deleted file mode 100644 index 8e3c67d9495..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/measure/test/TestSettingsTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.measure.test; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TestSettingsTest { - - TestSettings underTest = new TestSettings(); - - @Test - public void get_string_value() { - underTest.setValue("key", "value"); - - assertThat(underTest.getString("key")).isEqualTo("value"); - assertThat(underTest.getString("unknown")).isNull(); - } - - @Test - public void get_string_array_value() { - underTest.setValue("key", "value1,value2"); - - assertThat(underTest.getStringArray("key")).containsOnly("value1", "value2"); - assertThat(underTest.getStringArray("unknown")).isEmpty(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/CeTaskBuilder_PostProjectAnalysisTaskTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/CeTaskBuilder_PostProjectAnalysisTaskTesterTest.java deleted file mode 100644 index ef6f70cbddf..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/CeTaskBuilder_PostProjectAnalysisTaskTesterTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.posttask; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class CeTaskBuilder_PostProjectAnalysisTaskTesterTest { - private static final CeTask.Status SOME_STATUS = CeTask.Status.SUCCESS; - private static final String SOME_ID = "some id"; - - private PostProjectAnalysisTaskTester.CeTaskBuilder underTest = PostProjectAnalysisTaskTester.newCeTaskBuilder(); - - @Test - public void setId_throws_NPE_if_id_is_null() { - assertThatThrownBy(() -> underTest.setId(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("id cannot be null"); - } - - @Test - public void setStatus_throws_NPE_if_status_is_null() { - assertThatThrownBy(() -> underTest.setStatus(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void build_throws_NPE_if_id_is_null() { - underTest.setStatus(SOME_STATUS); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("id cannot be null"); - } - - @Test - public void build_throws_NPE_if_status_is_null() { - underTest.setId(SOME_ID); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void build_returns_new_instance_at_each_call() { - underTest.setId(SOME_ID).setStatus(SOME_STATUS); - - assertThat(underTest.build()).isNotSameAs(underTest.build()); - } - - @Test - public void verify_getters() { - CeTask ceTask = underTest.setId(SOME_ID).setStatus(SOME_STATUS).build(); - - assertThat(ceTask.getId()).isEqualTo(SOME_ID); - assertThat(ceTask.getStatus()).isEqualTo(SOME_STATUS); - } - - @Test - public void verify_toString() { - assertThat(underTest.setId(SOME_ID).setStatus(SOME_STATUS).build().toString()).isEqualTo("CeTask{id='some id', status=SUCCESS}"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/ConditionBuilder_PostProjectAnalysisTaskTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/ConditionBuilder_PostProjectAnalysisTaskTesterTest.java deleted file mode 100644 index c2fae1b18ed..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/ConditionBuilder_PostProjectAnalysisTaskTesterTest.java +++ /dev/null @@ -1,227 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.posttask; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class ConditionBuilder_PostProjectAnalysisTaskTesterTest { - private static final String SOME_METRIC_KEY = "some metric key"; - private static final QualityGate.Operator SOME_OPERATOR = QualityGate.Operator.GREATER_THAN; - private static final String SOME_ERROR_THRESHOLD = "some error threshold"; - private static final QualityGate.EvaluationStatus SOME_STATUS_BUT_NO_VALUE = QualityGate.EvaluationStatus.OK; - private static final String SOME_VALUE = "some value"; - - private PostProjectAnalysisTaskTester.ConditionBuilder underTest = PostProjectAnalysisTaskTester.newConditionBuilder(); - - @Test - public void setMetricKey_throws_NPE_if_operator_is_null() { - assertThatThrownBy(() -> underTest.setMetricKey(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("metricKey cannot be null"); - } - - @Test - public void setOperator_throws_NPE_if_operator_is_null() { - assertThatThrownBy(() -> underTest.setOperator(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("operator cannot be null"); - } - - @Test - public void buildNoValue_throws_NPE_if_metricKey_is_null() { - underTest.setOperator(SOME_OPERATOR).setErrorThreshold(SOME_ERROR_THRESHOLD); - - assertThatThrownBy(() -> underTest.buildNoValue()) - .isInstanceOf(NullPointerException.class) - .hasMessage("metricKey cannot be null"); - } - - @Test - public void buildNoValue_throws_NPE_if_operator_is_null() { - underTest.setMetricKey(SOME_METRIC_KEY).setErrorThreshold(SOME_ERROR_THRESHOLD); - - assertThatThrownBy(() -> underTest.buildNoValue()) - .isInstanceOf(NullPointerException.class) - .hasMessage("operator cannot be null"); - } - - @Test - public void buildNoValue_throws_NPE_if_errorThreshold_is_null() { - underTest.setMetricKey(SOME_METRIC_KEY).setOperator(SOME_OPERATOR); - - assertThatThrownBy(() -> underTest.buildNoValue()) - .isInstanceOf(NullPointerException.class) - .hasMessage("errorThreshold cannot be null"); - } - - @Test - public void buildNoValue_returns_Condition_which_getStatus_method_returns_NO_VALUE() { - initValidBuilder(); - - assertThat(underTest.buildNoValue().getStatus()).isEqualTo(QualityGate.EvaluationStatus.NO_VALUE); - } - - @Test - public void buildNoValue_returns_Condition_which_getValue_method_throws_ISE() { - initValidBuilder(); - QualityGate.Condition condition = underTest.buildNoValue(); - - assertThatThrownBy(() -> condition.getValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("There is no value when status is NO_VALUE"); - } - - @Test - public void buildNoValue_returns_new_instance_at_each_call() { - initValidBuilder(); - - assertThat(underTest.buildNoValue()).isNotSameAs(underTest.buildNoValue()); - } - - @Test - public void buildNoValue_has_no_value_in_toString_and_status_is_NO_VALUE() { - initValidBuilder(); - - assertThat(underTest.buildNoValue().toString()) - .isEqualTo( - "Condition{status=NO_VALUE, metricKey='some metric key', operator=GREATER_THAN, " + - "errorThreshold='some error threshold'}"); - } - - @Test - public void verify_getters_of_object_returned_by_buildNoValue() { - initValidBuilder().setOnLeakPeriod(true); - - QualityGate.Condition condition = underTest.buildNoValue(); - - assertThat(condition.getMetricKey()).isEqualTo(SOME_METRIC_KEY); - assertThat(condition.getOperator()).isEqualTo(SOME_OPERATOR); - assertThat(condition.getErrorThreshold()).isEqualTo(SOME_ERROR_THRESHOLD); - } - - @Test - public void build_throws_NPE_if_status_is_null() { - initValidBuilder(); - - assertThatThrownBy(() -> underTest.build(null, SOME_VALUE)) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void build_throws_IAE_if_status_is_NO_VALUE() { - initValidBuilder(); - - assertThatThrownBy(() -> underTest.build(QualityGate.EvaluationStatus.NO_VALUE, SOME_VALUE)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("status cannot be NO_VALUE, use method buildNoValue() instead"); - } - - @Test - public void build_throws_NPE_if_value_is_null() { - initValidBuilder(); - - assertThatThrownBy(() -> underTest.build(SOME_STATUS_BUT_NO_VALUE, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("value cannot be null, use method buildNoValue() instead"); - } - - @Test - public void build_throws_NPE_if_metricKey_is_null() { - underTest.setOperator(SOME_OPERATOR).setErrorThreshold(SOME_ERROR_THRESHOLD); - - assertThatThrownBy(() -> underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE)) - .isInstanceOf(NullPointerException.class) - .hasMessage("metricKey cannot be null"); - } - - @Test - public void build_throws_NPE_if_operator_is_null() { - underTest.setMetricKey(SOME_METRIC_KEY).setErrorThreshold(SOME_ERROR_THRESHOLD); - - assertThatThrownBy(() -> underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE)) - .isInstanceOf(NullPointerException.class) - .hasMessage("operator cannot be null"); - } - - @Test - public void build_throws_NPE_if_errorThreshold_is_null() { - underTest.setMetricKey(SOME_METRIC_KEY).setOperator(SOME_OPERATOR); - - assertThatThrownBy(() -> underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE)) - .isInstanceOf(NullPointerException.class) - .hasMessage("errorThreshold cannot be null"); - } - - @Test - public void build_returns_new_instance_at_each_call() { - initValidBuilder(); - - assertThat(underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE)).isNotSameAs(underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE)); - } - - @Test - public void build_has_value_in_toString_and_specified_status() { - initValidBuilder(); - - assertThat(underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE).toString()) - .isEqualTo( - "Condition{status=OK, metricKey='some metric key', operator=GREATER_THAN, " - + "errorThreshold='some error threshold', value='some value'}"); - } - - @Test - public void build_returns_Condition_which_getStatus_method_returns_NO_VALUE() { - initValidBuilder(); - - assertThat(underTest.buildNoValue().getStatus()).isEqualTo(QualityGate.EvaluationStatus.NO_VALUE); - } - - @Test - public void build_returns_Condition_which_getValue_method_throws_ISE() { - initValidBuilder(); - QualityGate.Condition condition = underTest.buildNoValue(); - - assertThatThrownBy(() -> condition.getValue()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("There is no value when status is NO_VALUE"); - } - - @Test - public void verify_getters_of_object_returned_by_build() { - initValidBuilder().setOnLeakPeriod(true); - - QualityGate.Condition condition = underTest.build(SOME_STATUS_BUT_NO_VALUE, SOME_VALUE); - - assertThat(condition.getStatus()).isEqualTo(SOME_STATUS_BUT_NO_VALUE); - assertThat(condition.getMetricKey()).isEqualTo(SOME_METRIC_KEY); - assertThat(condition.getOperator()).isEqualTo(SOME_OPERATOR); - assertThat(condition.getErrorThreshold()).isEqualTo(SOME_ERROR_THRESHOLD); - assertThat(condition.getValue()).isEqualTo(SOME_VALUE); - } - - private PostProjectAnalysisTaskTester.ConditionBuilder initValidBuilder() { - underTest.setMetricKey(SOME_METRIC_KEY).setOperator(SOME_OPERATOR).setErrorThreshold(SOME_ERROR_THRESHOLD); - return underTest; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/PostProjectAnalysisTaskTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/PostProjectAnalysisTaskTest.java deleted file mode 100644 index 1d5ad4a77d2..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/PostProjectAnalysisTaskTest.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.posttask; - -import org.junit.Test; -import org.mockito.Mockito; -import org.sonar.api.ce.posttask.PostProjectAnalysisTask.Context; -import org.sonar.api.ce.posttask.PostProjectAnalysisTask.ProjectAnalysis; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class PostProjectAnalysisTaskTest { - private final Context context = mock(Context.class); - private final ProjectAnalysis projectAnalysis = Mockito.mock(ProjectAnalysis.class); - - @Test - public void default_implementation_of_finished_ProjectAnalysis_returns_class_name() { - PostProjectAnalysisTask underTest = new PostTask(); - - assertThat(underTest.getDescription()).isEqualTo("PostTask"); - } - - private static class PostTask implements PostProjectAnalysisTask { - - } - - @Test - public void default_implementation_of_finished_Context_calls_finished_ProjectAnalysis() { - when(context.getProjectAnalysis()).thenReturn(projectAnalysis); - boolean[] called = {false}; - PostProjectAnalysisTask underTest = new PostProjectAnalysisTask() { - - // override default implementation which throws an exception - @Override - public void finished(ProjectAnalysis analysis) { - called[0] = true; - assertThat(analysis).isSameAs(projectAnalysis); - } - - @Override - public String getDescription() { - throw new UnsupportedOperationException("getDescription not implemented"); - } - }; - - underTest.finished(context); - - assertThat(called[0]).isTrue(); - verify(context).getProjectAnalysis(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/PostProjectAnalysisTaskTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/PostProjectAnalysisTaskTesterTest.java deleted file mode 100644 index b797189eafc..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/PostProjectAnalysisTaskTesterTest.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.posttask; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.Random; -import org.apache.commons.lang.RandomStringUtils; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; -import static org.sonar.api.ce.posttask.Branch.Type.BRANCH; - -public class PostProjectAnalysisTaskTesterTest { - - private CeTask ceTask = mock(CeTask.class); - private Project project = mock(Project.class); - private long someDateAsLong = 846351351684351L; - private Date someDate = new Date(someDateAsLong); - private String analysisUuid = RandomStringUtils.randomAlphanumeric(40); - private QualityGate qualityGate = mock(QualityGate.class); - private CaptorPostProjectAnalysisTask captorPostProjectAnalysisTask = new CaptorPostProjectAnalysisTask(); - private PostProjectAnalysisTaskTester underTest = PostProjectAnalysisTaskTester.of(captorPostProjectAnalysisTask); - - @Test - public void of_throws_NPE_if_PostProjectAnalysisTask_is_null() { - assertThatThrownBy(() -> PostProjectAnalysisTaskTester.of(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("PostProjectAnalysisTask instance cannot be null"); - } - - @Test - public void withCeTask_throws_NPE_if_ceTask_is_null() { - assertThatThrownBy(() -> underTest.withCeTask(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("ceTask cannot be null"); - } - - @Test - public void withProject_throws_NPE_if_project_is_null() { - assertThatThrownBy(() -> underTest.withProject(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("project cannot be null"); - } - - @Test - public void at_throws_NPE_if_date_is_null() { - assertThatThrownBy(() -> underTest.at(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("date cannot be null"); - } - - @Test - public void withQualityGate_does_not_throw_NPE_if_project_is_null() { - underTest.withQualityGate(null); - } - - @Test - public void execute_throws_NPE_if_ceTask_is_null() { - underTest.withProject(project).at(someDate); - - assertThatThrownBy(() -> underTest.execute()) - .isInstanceOf(NullPointerException.class) - .hasMessage("ceTask cannot be null"); - } - - @Test - public void execute_throws_NPE_if_project_is_null() { - underTest.withCeTask(ceTask).at(someDate); - - assertThatThrownBy(() -> underTest.execute()) - .isInstanceOf(NullPointerException.class) - .hasMessage("project cannot be null"); - } - - @Test - public void verify_getters_of_ProjectAnalysis_object_passed_to_PostProjectAnalysisTask() { - underTest.withCeTask(ceTask).withProject(project).withQualityGate(qualityGate).withAnalysisUuid(analysisUuid).at(someDate); - - underTest.execute(); - - PostProjectAnalysisTask.ProjectAnalysis projectAnalysis = captorPostProjectAnalysisTask.projectAnalysis; - assertThat(projectAnalysis).isNotNull(); - assertThat(projectAnalysis.getCeTask()).isSameAs(ceTask); - assertThat(projectAnalysis.getProject()).isSameAs(project); - assertThat(projectAnalysis.getQualityGate()).isSameAs(qualityGate); - assertThat(projectAnalysis.getAnalysis().get().getAnalysisUuid()).isSameAs(analysisUuid); - } - - @Test - public void verify_toString_of_ProjectAnalysis_object_passed_to_PostProjectAnalysisTask() { - when(ceTask.toString()).thenReturn("CeTask"); - when(project.toString()).thenReturn("Project"); - when(qualityGate.toString()).thenReturn("QualityGate"); - underTest.withCeTask(ceTask).withProject(project).withQualityGate(qualityGate).at(someDate); - - underTest.execute(); - - assertThat(captorPostProjectAnalysisTask.projectAnalysis) - .hasToString("ProjectAnalysis{ceTask=CeTask, project=Project, date=846351351684351, analysisDate=846351351684351, qualityGate=QualityGate}"); - - } - - @Test - public void execute_throws_NPE_if_date_is_null() { - underTest.withCeTask(ceTask).withProject(project); - - assertThatThrownBy(() -> underTest.execute()) - .isInstanceOf(NullPointerException.class) - .hasMessage("date cannot be null"); - } - - @Test - public void getLogStatistics_throws_ISE_if_called_before_execute() { - assertThatThrownBy(() -> underTest.getLogStatistics()) - .isInstanceOf(IllegalStateException.class) - .hasMessage("execute must be called first"); - } - - @Test - public void getLogStatistics_returns_empty_if_no_log_statistic_added_by_tested_Task() { - underTest.withCeTask(ceTask).withProject(project).withQualityGate(qualityGate).withAnalysisUuid(analysisUuid).at(someDate); - - underTest.execute(); - - assertThat(underTest.getLogStatistics()).isEmpty(); - } - - @Test - public void getLogStatistics_returns_log_statistics_added_by_tested_Task() { - Random random = new Random(); - Map<String, Object> expected = new HashMap<>(); - for (int i = 0; i < 1 + random.nextInt(10); i++) { - expected.put(String.valueOf(i), random.nextInt(100)); - } - PostProjectAnalysisTask projectAnalysisTask = mock(PostProjectAnalysisTask.class); - doAnswer(i -> { - PostProjectAnalysisTask.Context context = i.getArgument(0); - expected.forEach((k, v) -> context.getLogStatistics().add(k, v)); - return null; - }).when(projectAnalysisTask).finished(any(PostProjectAnalysisTask.Context.class)); - PostProjectAnalysisTaskTester underTest = PostProjectAnalysisTaskTester.of(projectAnalysisTask); - underTest.withCeTask(ceTask).withProject(project).withQualityGate(qualityGate).withAnalysisUuid(analysisUuid).at(someDate); - - underTest.execute(); - - assertThat(underTest.getLogStatistics()).isEqualTo(expected); - } - - @Test - public void branch_builder_builds_branch_of_type_branch_by_default() { - Branch branch = PostProjectAnalysisTaskTester.newBranchBuilder().build(); - - assertThat(branch.getType()).isEqualTo(BRANCH); - } - - private static class CaptorPostProjectAnalysisTask implements PostProjectAnalysisTask { - private ProjectAnalysis projectAnalysis; - - @Override - public String getDescription() { - return "captor"; - } - - @Override - public void finished(Context context) { - this.projectAnalysis = context.getProjectAnalysis(); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/ProjectBuilder_PostProjectAnalysisTaskTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/ProjectBuilder_PostProjectAnalysisTaskTesterTest.java deleted file mode 100644 index 9db590f3d83..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/ProjectBuilder_PostProjectAnalysisTaskTesterTest.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.posttask; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class ProjectBuilder_PostProjectAnalysisTaskTesterTest { - private static final String SOME_NAME = "some name"; - private static final String SOME_KEY = "some key"; - private static final String SOME_UUID = "some uuid"; - - private PostProjectAnalysisTaskTester.ProjectBuilder underTest = PostProjectAnalysisTaskTester.newProjectBuilder(); - - @Test - public void setKey_throws_NPE_if_key_is_null() { - assertThatThrownBy(() -> underTest.setKey(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("key cannot be null"); - } - - @Test - public void setName_throws_NPE_if_name_is_null() { - assertThatThrownBy(() -> underTest.setName(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("name cannot be null"); - } - - @Test - public void setUuid_throws_NPE_if_uuid_is_null() { - assertThatThrownBy(() -> underTest.setUuid(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("uuid cannot be null"); - } - - @Test - public void build_throws_NPE_if_key_is_null() { - underTest.setUuid(SOME_UUID).setName(SOME_NAME); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("key cannot be null"); - } - - @Test - public void build_throws_NPE_if_name_is_null() { - underTest.setUuid(SOME_UUID).setKey(SOME_KEY); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("name cannot be null"); - } - - @Test - public void build_throws_NPE_if_uuid_is_null() { - underTest.setKey(SOME_KEY).setName(SOME_NAME); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("uuid cannot be null"); - } - - @Test - public void build_returns_new_instance_at_each_call() { - underTest.setUuid(SOME_UUID).setKey(SOME_KEY).setName(SOME_NAME); - - assertThat(underTest.build()).isNotSameAs(underTest.build()); - } - - @Test - public void verify_getters() { - Project project = underTest.setUuid(SOME_UUID).setKey(SOME_KEY).setName(SOME_NAME).build(); - - assertThat(project.getUuid()).isEqualTo(SOME_UUID); - assertThat(project.getKey()).isEqualTo(SOME_KEY); - assertThat(project.getName()).isEqualTo(SOME_NAME); - } - - @Test - public void verify_toString() { - assertThat(underTest.setUuid(SOME_UUID).setKey(SOME_KEY).setName(SOME_NAME).build().toString()) - .isEqualTo("Project{uuid='some uuid', key='some key', name='some name'}"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/QualityGateBuilder_PostProjectAnalysisTaskTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/QualityGateBuilder_PostProjectAnalysisTaskTesterTest.java deleted file mode 100644 index d901b5831b8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/ce/posttask/QualityGateBuilder_PostProjectAnalysisTaskTesterTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.ce.posttask; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class QualityGateBuilder_PostProjectAnalysisTaskTesterTest { - private static final String SOME_NAME = "some name"; - private static final QualityGate.Status SOME_STATUS = QualityGate.Status.ERROR; - private static final String SOME_ID = "some id"; - - private QualityGate.Condition condition1 = mock(QualityGate.Condition.class); - private QualityGate.Condition condition2 = mock(QualityGate.Condition.class); - private PostProjectAnalysisTaskTester.QualityGateBuilder underTest = PostProjectAnalysisTaskTester.newQualityGateBuilder(); - - @Test - public void setId_throws_NPE_if_id_is_null() { - assertThatThrownBy(() -> underTest.setId(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("id cannot be null"); - } - - @Test - public void setStatus_throws_NPE_if_status_is_null() { - assertThatThrownBy(() -> underTest.setStatus(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void setName_throws_NPE_if_name_is_null() { - assertThatThrownBy(() -> underTest.setName(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("name cannot be null"); - } - - @Test - public void addCondition_throws_NPE_if_condition_is_null() { - assertThatThrownBy(() -> underTest.add(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("condition cannot be null"); - } - - @Test - public void clearConditions_does_not_raise_any_error_if_there_is_no_condition_in_builder() { - underTest.clearConditions(); - } - - @Test - public void clearConditions_removes_all_conditions_from_builder() { - underTest.setId(SOME_ID).setStatus(SOME_STATUS).setName(SOME_NAME).add(condition1).add(condition2); - - assertThat(underTest.build().getConditions()).containsOnly(condition1, condition2); - - underTest.clearConditions(); - - assertThat(underTest.build().getConditions()).isEmpty(); - } - - @Test - public void build_throws_NPE_if_id_is_null() { - underTest.setStatus(SOME_STATUS).setName(SOME_NAME); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("id cannot be null"); - } - - @Test - public void build_throws_NPE_if_status_is_null() { - underTest.setId(SOME_ID).setName(SOME_NAME); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("status cannot be null"); - } - - @Test - public void build_throws_NPE_if_name_is_null() { - underTest.setId(SOME_ID).setStatus(SOME_STATUS); - - assertThatThrownBy(() -> underTest.build()) - .isInstanceOf(NullPointerException.class) - .hasMessage("name cannot be null"); - } - - @Test - public void build_returns_new_instance_at_each_call() { - underTest.setId(SOME_ID).setStatus(SOME_STATUS).setName(SOME_NAME); - - assertThat(underTest.build()).isNotSameAs(underTest.build()); - } - - @Test - public void verify_getters() { - QualityGate qualityGate = underTest.setId(SOME_ID).setStatus(SOME_STATUS).setName(SOME_NAME).add(condition1).add(condition2).build(); - - assertThat(qualityGate.getId()).isEqualTo(SOME_ID); - assertThat(qualityGate.getStatus()).isEqualTo(SOME_STATUS); - assertThat(qualityGate.getName()).isEqualTo(SOME_NAME); - assertThat(qualityGate.getConditions()).containsOnly(condition1, condition2); - } - - @Test - public void verify_toString() { - when(condition1.toString()).thenReturn("condition1"); - when(condition2.toString()).thenReturn("condition2"); - - assertThat(underTest.setId(SOME_ID).setStatus(SOME_STATUS).setName(SOME_NAME).add(condition1).add(condition2).build().toString()) - .isEqualTo("QualityGate{id='some id', name='some name', status=ERROR, conditions=[condition1, condition2]}"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/CategoryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/CategoryTest.java deleted file mode 100644 index 5af98ca730c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/CategoryTest.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class CategoryTest { - - @Test - public void category_key_is_case_insentive() { - assertThat(new Category("Licenses")).isEqualTo(new Category("licenses")); - - // Just to raise coverage - assertThat(new Category("Licenses").key()).isNotEqualTo("Licenses"); - } - - @Test - public void should_preserve_original_key() { - assertThat(new Category("Licenses").originalKey()).isEqualTo("Licenses"); - } - - @Test - public void should_normalize_key() { - assertThat(new Category("Licenses").key()).isEqualTo("licenses"); - } - - @Test - public void should_use_original_key() { - assertThat(new Category("Licenses").toString()).isEqualTo("Licenses"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/ConfigurationTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/ConfigurationTest.java deleted file mode 100644 index 1ce65e519f9..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/ConfigurationTest.java +++ /dev/null @@ -1,135 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import java.util.Random; -import java.util.function.BiFunction; -import org.apache.commons.lang.RandomStringUtils; -import org.apache.commons.lang.StringUtils; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ConfigurationTest { - - private DumpMapConfiguration underTest = new DumpMapConfiguration(); - - @Test - public void getBoolean_supports_heading_and_or_trailing_whitespaces() { - boolean value = new Random().nextBoolean(); - - verifySupportHeadAndOrTrailingWhitespaces(value, Configuration::getBoolean); - } - - @Test - public void getBoolean_returns_false_if_value_is_not_true() { - verifyBooleanFalse("false"); - verifyBooleanFalse("False"); - verifyBooleanFalse("FALSE"); - verifyBooleanFalse(" false "); - verifyBooleanFalse("foo"); - verifyBooleanFalse("xxx"); - verifyBooleanFalse("___"); - verifyBooleanFalse("yes"); - verifyBooleanFalse("no"); - } - - @Test - public void getBoolean_returns_true_if_value_is_true_ignore_case() { - verifyBooleanTrue("true"); - verifyBooleanTrue("TRUE"); - verifyBooleanTrue("True"); - verifyBooleanTrue(" True "); - } - - private void verifyBooleanFalse(String value) { - underTest.put("foo", value); - assertThat(underTest.getBoolean("foo")).hasValue(false); - } - - private void verifyBooleanTrue(String value) { - underTest.put("foo", value); - assertThat(underTest.getBoolean("foo")).hasValue(true); - } - - @Test - public void getInt() { - int value = new Random().nextInt(); - - verifySupportHeadAndOrTrailingWhitespaces(value, Configuration::getInt); - } - - @Test - public void getLong() { - long value = new Random().nextLong(); - - verifySupportHeadAndOrTrailingWhitespaces(value, Configuration::getLong); - } - - @Test - public void getFloat() { - float value = new Random().nextFloat(); - - verifySupportHeadAndOrTrailingWhitespaces(value, Configuration::getFloat); - } - - @Test - public void getDouble() { - double value = new Random().nextDouble(); - - verifySupportHeadAndOrTrailingWhitespaces(value, Configuration::getDouble); - } - - private <T> void verifySupportHeadAndOrTrailingWhitespaces(T value, BiFunction<Configuration, String, Optional<T>> t) { - String randomKey = RandomStringUtils.randomAlphabetic(3); - String randomNumberOfWhitespaces = StringUtils.repeat(" ", 1 + new Random().nextInt(10)); - - assertThat(t.apply(underTest.put(randomKey, randomNumberOfWhitespaces + value), randomKey)).isEqualTo(Optional.of(value)); - assertThat(t.apply(underTest.put(randomKey, value + randomNumberOfWhitespaces), randomKey)).isEqualTo(Optional.of(value)); - assertThat(t.apply(underTest.put(randomKey, randomNumberOfWhitespaces + value + randomNumberOfWhitespaces), randomKey)).isEqualTo(Optional.of(value)); - } - - private static class DumpMapConfiguration implements Configuration { - private final Map<String, String> keyValues = new HashMap<>(); - - public Configuration put(String key, String value) { - keyValues.put(key, value.trim()); - return this; - } - - @Override - public Optional<String> get(String key) { - return Optional.ofNullable(keyValues.get(key)); - } - - @Override - public boolean hasKey(String key) { - throw new UnsupportedOperationException("hasKey not implemented"); - } - - @Override - public String[] getStringArray(String key) { - throw new UnsupportedOperationException("getStringArray not implemented"); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/EmailSettingsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/EmailSettingsTest.java deleted file mode 100644 index 371f69b04a6..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/EmailSettingsTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import org.apache.commons.lang.RandomStringUtils; -import org.junit.Test; -import org.sonar.api.config.internal.MapSettings; -import org.sonar.api.platform.Server; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class EmailSettingsTest { - - private MapSettings settings = new MapSettings(); - private Server server = mock(Server.class); - private EmailSettings underTest = new EmailSettings(settings.asConfig(), server); - - @Test - public void should_return_default_values() { - assertThat(underTest.getSmtpHost()).isEmpty(); - assertThat(underTest.getSmtpPort()).isEqualTo(25); - assertThat(underTest.getSmtpUsername()).isEmpty(); - assertThat(underTest.getSmtpPassword()).isEmpty(); - assertThat(underTest.getSecureConnection()).isEmpty(); - assertThat(underTest.getFrom()).isEqualTo("noreply@nowhere"); - assertThat(underTest.getFromName()).isEqualTo("SonarQube"); - assertThat(underTest.getPrefix()).isEqualTo("[SONARQUBE]"); - } - - @Test - public void getServerBaseUrl_returns_server_getPublicRootUrl() { - String expected = RandomStringUtils.randomAlphabetic(15); - when(server.getPublicRootUrl()).thenReturn(expected); - - assertThat(underTest.getServerBaseURL()).isEqualTo(expected); - } - - @Test - public void return_definitions() { - assertThat(EmailSettings.definitions()).hasSize(8); - } - - @Test - public void definitions_should_have_index() { - assertThat(EmailSettings.definitions()) - .extracting(PropertyDefinition::index) - .isNotEqualTo(999); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/GlobalPropertyChangeHandlerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/GlobalPropertyChangeHandlerTest.java deleted file mode 100644 index 95fed74fc5d..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/GlobalPropertyChangeHandlerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import org.junit.Test; - -import static org.hamcrest.core.Is.is; -import static org.hamcrest.core.IsNull.nullValue; -import static org.junit.Assert.assertThat; - -public class GlobalPropertyChangeHandlerTest { - @Test - public void propertyChangeToString() { - GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create("favourite.java.version", "1.5"); - assertThat(change.toString(), is("[key=favourite.java.version, newValue=1.5]")); - } - - @Test - public void propertyChangeGetters() { - GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create("favourite.java.version", "1.5"); - assertThat(change.getKey(), is("favourite.java.version")); - assertThat(change.getNewValue(), is("1.5")); - } - - @Test - public void nullNewValue() { - GlobalPropertyChangeHandler.PropertyChange change = GlobalPropertyChangeHandler.PropertyChange.create("favourite.java.version", null); - assertThat(change.getNewValue(), nullValue()); - assertThat(change.toString(), is("[key=favourite.java.version, newValue=null]")); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/PropertyDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/PropertyDefinitionTest.java deleted file mode 100644 index d7003bdfe3a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/PropertyDefinitionTest.java +++ /dev/null @@ -1,460 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import com.google.common.collect.ImmutableSet; -import java.util.Arrays; -import java.util.Collections; -import java.util.Set; -import java.util.function.BiConsumer; -import java.util.function.Consumer; -import org.junit.Test; -import org.sonar.api.Properties; -import org.sonar.api.Property; -import org.sonar.api.PropertyField; -import org.sonar.api.PropertyType; -import org.sonar.api.config.PropertyDefinition.Builder; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.utils.AnnotationUtils; - -import static org.apache.commons.lang.RandomStringUtils.randomAlphabetic; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatCode; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; - -public class PropertyDefinitionTest { - - @Test - public void should_override_toString() { - PropertyDefinition def = PropertyDefinition.builder("hello").build(); - assertThat(def.toString()).isEqualTo("hello"); - } - - @Test - public void should_create_property() { - PropertyDefinition def = PropertyDefinition.builder("hello") - .name("Hello") - .defaultValue("world") - .category("categ") - .options("de", "en") - .description("desc") - .type(PropertyType.FLOAT) - .onlyOnQualifiers(Qualifiers.MODULE) - .multiValues(true) - .build(); - - assertThat(def.key()).isEqualTo("hello"); - assertThat(def.name()).isEqualTo("Hello"); - assertThat(def.defaultValue()).isEqualTo("world"); - assertThat(def.category()).isEqualTo("categ"); - assertThat(def.options()).containsOnly("de", "en"); - assertThat(def.description()).isEqualTo("desc"); - assertThat(def.type()).isEqualTo(PropertyType.FLOAT); - assertThat(def.global()).isFalse(); - assertThat(def.qualifiers()).containsOnly(Qualifiers.MODULE); - assertThat(def.multiValues()).isTrue(); - assertThat(def.fields()).isEmpty(); - } - - @Test - public void should_create_from_annotation() { - Properties props = AnnotationUtils.getAnnotation(Init.class, Properties.class); - Property prop = props.value()[0]; - - PropertyDefinition def = PropertyDefinition.create(prop); - - assertThat(def.key()).isEqualTo("hello"); - assertThat(def.name()).isEqualTo("Hello"); - assertThat(def.defaultValue()).isEqualTo("world"); - assertThat(def.category()).isEqualTo("categ"); - assertThat(def.options()).containsOnly("de", "en"); - assertThat(def.description()).isEqualTo("desc"); - assertThat(def.type()).isEqualTo(PropertyType.FLOAT); - assertThat(def.global()).isFalse(); - assertThat(def.qualifiers()).containsOnly(Qualifiers.PROJECT, Qualifiers.MODULE); - assertThat(def.multiValues()).isTrue(); - assertThat(def.fields()).isEmpty(); - } - - @Test - public void should_create_hidden_property() { - PropertyDefinition def = PropertyDefinition.builder("hello") - .name("Hello") - .hidden() - .build(); - - assertThat(def.key()).isEqualTo("hello"); - assertThat(def.qualifiers()).isEmpty(); - assertThat(def.global()).isFalse(); - } - - @Test - public void should_create_property_with_default_values() { - PropertyDefinition def = PropertyDefinition.builder("hello") - .name("Hello") - .build(); - - assertThat(def.key()).isEqualTo("hello"); - assertThat(def.name()).isEqualTo("Hello"); - assertThat(def.defaultValue()).isEmpty(); - assertThat(def.category()).isEmpty(); - assertThat(def.options()).isEmpty(); - assertThat(def.description()).isEmpty(); - assertThat(def.type()).isEqualTo(PropertyType.STRING); - assertThat(def.global()).isTrue(); - assertThat(def.qualifiers()).isEmpty(); - assertThat(def.multiValues()).isFalse(); - assertThat(def.fields()).isEmpty(); - } - - @Test - public void should_create_from_annotation_default_values() { - Properties props = AnnotationUtils.getAnnotation(DefaultValues.class, Properties.class); - Property prop = props.value()[0]; - - PropertyDefinition def = PropertyDefinition.create(prop); - - assertThat(def.key()).isEqualTo("hello"); - assertThat(def.name()).isEqualTo("Hello"); - assertThat(def.defaultValue()).isEmpty(); - assertThat(def.category()).isEmpty(); - assertThat(def.options()).isEmpty(); - assertThat(def.description()).isEmpty(); - assertThat(def.type()).isEqualTo(PropertyType.STRING); - assertThat(def.global()).isTrue(); - assertThat(def.qualifiers()).isEmpty(); - assertThat(def.multiValues()).isFalse(); - assertThat(def.fields()).isEmpty(); - } - - @Test - public void should_support_property_sets() { - PropertyDefinition def = PropertyDefinition.builder("hello") - .name("Hello") - .fields( - PropertyFieldDefinition.build("first").name("First").description("Description").options("A", "B").build(), - PropertyFieldDefinition.build("second").name("Second").type(PropertyType.INTEGER).build()) - .build(); - - assertThat(def.type()).isEqualTo(PropertyType.PROPERTY_SET); - assertThat(def.fields()).hasSize(2); - assertThat(def.fields().get(0).key()).isEqualTo("first"); - assertThat(def.fields().get(0).name()).isEqualTo("First"); - assertThat(def.fields().get(0).description()).isEqualTo("Description"); - assertThat(def.fields().get(0).type()).isEqualTo(PropertyType.STRING); - assertThat(def.fields().get(0).options()).containsOnly("A", "B"); - assertThat(def.fields().get(1).key()).isEqualTo("second"); - assertThat(def.fields().get(1).name()).isEqualTo("Second"); - assertThat(def.fields().get(1).type()).isEqualTo(PropertyType.INTEGER); - assertThat(def.fields().get(1).options()).isEmpty(); - } - - @Test - public void should_support_property_sets_from_annotation() { - Properties props = AnnotationUtils.getAnnotation(WithPropertySet.class, Properties.class); - Property prop = props.value()[0]; - - PropertyDefinition def = PropertyDefinition.create(prop); - - assertThat(def.type()).isEqualTo(PropertyType.PROPERTY_SET); - assertThat(def.fields()).hasSize(2); - assertThat(def.fields().get(0).key()).isEqualTo("first"); - assertThat(def.fields().get(0).name()).isEqualTo("First"); - assertThat(def.fields().get(0).description()).isEqualTo("Description"); - assertThat(def.fields().get(0).type()).isEqualTo(PropertyType.STRING); - assertThat(def.fields().get(0).options()).containsOnly("A", "B"); - assertThat(def.fields().get(1).key()).isEqualTo("second"); - assertThat(def.fields().get(1).name()).isEqualTo("Second"); - assertThat(def.fields().get(1).type()).isEqualTo(PropertyType.INTEGER); - assertThat(def.fields().get(1).options()).isEmpty(); - } - - @Test - public void should_validate_string() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.STRING).build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("foo").isValid()).isTrue(); - } - - @Test - public void should_validate_boolean() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.BOOLEAN).build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("true").isValid()).isTrue(); - assertThat(def.validate("false").isValid()).isTrue(); - - assertThat(def.validate("foo").isValid()).isFalse(); - assertThat(def.validate("foo").getErrorKey()).isEqualTo("notBoolean"); - } - - @Test - public void should_validate_integer() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.INTEGER).build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("123456").isValid()).isTrue(); - - assertThat(def.validate("foo").isValid()).isFalse(); - assertThat(def.validate("foo").getErrorKey()).isEqualTo("notInteger"); - } - - @Test - public void validate_long() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.LONG).build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("123456").isValid()).isTrue(); - - assertThat(def.validate("foo").isValid()).isFalse(); - assertThat(def.validate("foo").getErrorKey()).isEqualTo("notInteger"); - } - - @Test - public void should_validate_float() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.FLOAT).build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("123456").isValid()).isTrue(); - assertThat(def.validate("3.14").isValid()).isTrue(); - - assertThat(def.validate("foo").isValid()).isFalse(); - assertThat(def.validate("foo").getErrorKey()).isEqualTo("notFloat"); - } - - @Test - public void validate_regular_expression() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.REGULAR_EXPRESSION).build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("[a-zA-Z]").isValid()).isTrue(); - - assertThat(def.validate("[a-zA-Z").isValid()).isFalse(); - assertThat(def.validate("[a-zA-Z").getErrorKey()).isEqualTo("notRegexp"); - } - - @Test - public void should_validate_single_select_list() { - PropertyDefinition def = PropertyDefinition.builder("foo").name("foo").type(PropertyType.SINGLE_SELECT_LIST).options("de", "en").build(); - - assertThat(def.validate(null).isValid()).isTrue(); - assertThat(def.validate("").isValid()).isTrue(); - assertThat(def.validate(" ").isValid()).isTrue(); - assertThat(def.validate("de").isValid()).isTrue(); - assertThat(def.validate("en").isValid()).isTrue(); - - assertThat(def.validate("fr").isValid()).isFalse(); - assertThat(def.validate("fr").getErrorKey()).isEqualTo("notInOptions"); - } - - @Test - public void should_auto_detect_password_type() { - PropertyDefinition def = PropertyDefinition.builder("scm.password.secured").name("SCM password").build(); - - assertThat(def.key()).isEqualTo("scm.password.secured"); - assertThat(def.type()).isEqualTo(PropertyType.PASSWORD); - } - - @Test - public void PropertyDef() { - PropertyDefinition def = PropertyDefinition.builder("views.license.secured").name("Views license").build(); - - assertThat(def.key()).isEqualTo("views.license.secured"); - assertThat(def.type()).isEqualTo(PropertyType.LICENSE); - } - - @Test - public void should_create_json_property_type() { - Builder builder = PropertyDefinition.builder("json-prop").type(PropertyType.JSON).multiValues(false); - assertThatCode(builder::build) - .doesNotThrowAnyException(); - } - - @Test - public void should_not_authorise_empty_key() { - Builder builder = PropertyDefinition.builder(null); - assertThatThrownBy(builder::build) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Key must be set"); - } - - @Test - public void should_not_create_json_multivalue() { - Builder builder = PropertyDefinition.builder("json-prop").type(PropertyType.JSON).multiValues(true); - assertThatThrownBy(builder::build) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Multivalues are not allowed to be defined for JSON-type property."); - } - - @Test - public void should_not_authorize_defining_on_qualifiers_and_hidden() { - Builder builder = PropertyDefinition.builder("foo").name("foo").onQualifiers(Qualifiers.PROJECT).hidden(); - assertThatThrownBy(builder::build) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Cannot be hidden and defining qualifiers on which to display"); - } - - @Test - public void should_not_authorize_defining_ony_on_qualifiers_and_hidden() { - Builder builder = PropertyDefinition.builder("foo").name("foo").onlyOnQualifiers(Qualifiers.PROJECT).hidden(); - assertThatThrownBy(builder::build) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Cannot be hidden and defining qualifiers on which to display"); - } - - @Test - public void should_not_authorize_defining_on_qualifiers_and_only_on_qualifiers() { - Builder builder = PropertyDefinition.builder("foo").name("foo").onQualifiers(Qualifiers.MODULE) - .onlyOnQualifiers(Qualifiers.PROJECT); - assertThatThrownBy(builder::build) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Cannot define both onQualifiers and onlyOnQualifiers"); - } - - private static final Set<String> ALLOWED_QUALIFIERS = ImmutableSet.of("TRK", "VW", "BRC", "SVW"); - private static final Set<String> NOT_ALLOWED_QUALIFIERS = ImmutableSet.of("FIL", "DIR", "UTS", "", randomAlphabetic(3)); - - @Test - public void onQualifiers_with_varargs_parameter_fails_with_IAE_when_qualifier_is_not_supported() { - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onQualifiers(qualifier)); - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onQualifiers("TRK", qualifier, "BRC")); - } - - @Test - public void onQualifiers_with_list_parameter_fails_with_IAE_when_qualifier_is_not_supported() { - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onQualifiers(Collections.singletonList(qualifier))); - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onQualifiers(Arrays.asList("TRK", qualifier, "BRC"))); - } - - @Test - public void onlyOnQualifiers_with_varargs_parameter_fails_with_IAE_when_qualifier_is_not_supported() { - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onlyOnQualifiers(qualifier)); - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onlyOnQualifiers("TRK", qualifier, "BRC")); - } - - @Test - public void onlyOnQualifiers_with_list_parameter_fails_with_IAE_when_qualifier_is_not_supported() { - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onlyOnQualifiers(Collections.singletonList(qualifier))); - failsWithIAEForUnsupportedQualifiers((builder, qualifier) -> builder.onlyOnQualifiers(Arrays.asList("TRK", qualifier, "BRC"))); - } - - @Test - public void onQualifiers_with_varargs_parameter_fails_with_NPE_when_qualifier_is_null() { - failsWithNPEForNullQualifiers(builder -> builder.onQualifiers((String) null)); - failsWithNPEForNullQualifiers(builder -> builder.onQualifiers("TRK", null, "BRC")); - } - - @Test - public void onQualifiers_with_list_parameter_fails_with_NPE_when_qualifier_is_null() { - failsWithNPEForNullQualifiers(builder -> builder.onQualifiers(Collections.singletonList(null))); - failsWithNPEForNullQualifiers(builder -> builder.onlyOnQualifiers("TRK", null, "BRC")); - } - - @Test - public void onlyOnQualifiers_with_varargs_parameter_fails_with_NPE_when_qualifier_is_null() { - failsWithNPEForNullQualifiers(builder -> builder.onlyOnQualifiers((String) null)); - failsWithNPEForNullQualifiers(builder -> builder.onlyOnQualifiers("TRK", null, "BRC")); - } - - @Test - public void onlyOnQualifiers_with_list_parameter_fails_with_NPE_when_qualifier_is_null() { - failsWithNPEForNullQualifiers(builder -> builder.onlyOnQualifiers(Collections.singletonList(null))); - failsWithNPEForNullQualifiers(builder -> builder.onlyOnQualifiers(Arrays.asList("TRK", null, "BRC"))); - } - - @Test - public void onQualifiers_with_varargs_parameter_accepts_supported_qualifiers() { - acceptsSupportedQualifiers((builder, qualifier) -> builder.onQualifiers(qualifier)); - } - - @Test - public void onQualifiers_with_list_parameter_accepts_supported_qualifiers() { - acceptsSupportedQualifiers((builder, qualifier) -> builder.onQualifiers(Collections.singletonList(qualifier))); - } - - @Test - public void onlyOnQualifiers_with_varargs_parameter_accepts_supported_qualifiers() { - acceptsSupportedQualifiers((builder, qualifier) -> builder.onlyOnQualifiers(qualifier)); - } - - @Test - public void onlyOnQualifiers_with_list_parameter_accepts_supported_qualifiers() { - acceptsSupportedQualifiers((builder, qualifier) -> builder.onlyOnQualifiers(Collections.singletonList(qualifier))); - } - - private static void failsWithIAEForUnsupportedQualifiers(BiConsumer<PropertyDefinition.Builder, String> biConsumer) { - PropertyDefinition.Builder builder = PropertyDefinition.builder(randomAlphabetic(3)); - NOT_ALLOWED_QUALIFIERS.forEach(qualifier -> { - try { - biConsumer.accept(builder, qualifier); - fail("A IllegalArgumentException should have been thrown for qualifier " + qualifier); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Qualifier must be one of [TRK, VW, BRC, SVW, APP]"); - } - }); - } - - private static void acceptsSupportedQualifiers(BiConsumer<PropertyDefinition.Builder, String> biConsumer) { - PropertyDefinition.Builder builder = PropertyDefinition.builder(randomAlphabetic(3)); - ALLOWED_QUALIFIERS.forEach(qualifier -> biConsumer.accept(builder, qualifier)); - } - - private static void failsWithNPEForNullQualifiers(Consumer<PropertyDefinition.Builder> consumer) { - PropertyDefinition.Builder builder = PropertyDefinition.builder(randomAlphabetic(3)); - NOT_ALLOWED_QUALIFIERS.forEach(qualifier -> { - try { - consumer.accept(builder); - fail("A NullPointerException should have been thrown for null qualifier"); - } catch (NullPointerException e) { - assertThat(e).hasMessage("Qualifier cannot be null"); - } - }); - } - - @Properties(@Property(key = "hello", name = "Hello", defaultValue = "world", description = "desc", - options = {"de", "en"}, category = "categ", type = PropertyType.FLOAT, global = false, project = true, module = true, multiValues = true, propertySetKey = "set")) - static class Init { - } - - @Properties(@Property(key = "hello", name = "Hello", fields = { - @PropertyField(key = "first", name = "First", description = "Description", options = {"A", "B"}), - @PropertyField(key = "second", name = "Second", type = PropertyType.INTEGER)})) - static class WithPropertySet { - } - - @Properties(@Property(key = "hello", name = "Hello")) - static class DefaultValues { - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/PropertyDefinitionsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/PropertyDefinitionsTest.java deleted file mode 100644 index f73fadd733a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/PropertyDefinitionsTest.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import com.google.common.collect.ImmutableMap; -import java.util.Arrays; -import java.util.List; -import java.util.Random; -import java.util.stream.IntStream; -import org.apache.commons.lang.RandomStringUtils; -import org.junit.Test; -import org.sonar.api.Properties; -import org.sonar.api.Property; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.utils.System2; - -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class PropertyDefinitionsTest { - - @Test - public void should_build_with_predefined_list_of_definitions() { - List<PropertyDefinition> list = Arrays.asList( - PropertyDefinition.builder("foo").name("Foo").build(), - PropertyDefinition.builder("one").name("One").build(), - PropertyDefinition.builder("two").name("Two").defaultValue("2").build()); - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, list); - - assertProperties(def); - } - - @Test - public void should_inspect_plugin_objects() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, - PropertyDefinition.builder("foo").name("Foo").build(), - PropertyDefinition.builder("one").name("One").build(), - PropertyDefinition.builder("two").name("Two").defaultValue("2").build()); - - assertProperties(def); - } - - @Test - public void should_inspect_annotation_plugin_objects() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, new PluginWithProperty(), new PluginWithProperties()); - - assertProperties(def); - } - - @Test - public void should_inspect_plugin_classes() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, PluginWithProperty.class, PluginWithProperties.class); - - assertProperties(def); - } - - @Test - public void test_categories() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, - PropertyDefinition.builder("inCateg").name("In Categ").category("categ").build(), - PropertyDefinition.builder("noCateg").name("No categ").build()); - - assertThat(def.getCategory("inCateg")).isEqualTo("categ"); - assertThat(def.getCategory("noCateg")).isEmpty(); - } - - @Test - public void test_categories_on_annotation_plugin() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, Categories.class); - - assertThat(def.getCategory("inCateg")).isEqualTo("categ"); - assertThat(def.getCategory("noCateg")).isEmpty(); - } - - @Test - public void test_default_category() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE); - def.addComponent(PropertyDefinition.builder("inCateg").name("In Categ").category("categ").build(), "default"); - def.addComponent(PropertyDefinition.builder("noCateg").name("No categ").build(), "default"); - - assertThat(def.getCategory("inCateg")).isEqualTo("categ"); - assertThat(def.getCategory("noCateg")).isEqualTo("default"); - } - - @Test - public void test_default_category_on_annotation_plugin() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE); - def.addComponent(Categories.class, "default"); - assertThat(def.getCategory("inCateg")).isEqualTo("categ"); - assertThat(def.getCategory("noCateg")).isEqualTo("default"); - } - - @Test - public void should_return_special_categories() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE); - - assertThat(def.propertiesByCategory(null).get(new Category("general"))).containsOnlyKeys(new SubCategory("email")); - assertThat(def.propertiesByCategory(null).get(new Category("general")).keySet().iterator().next().isSpecial()).isTrue(); - assertThat(def.propertiesByCategory(null).get(new Category("security"))).containsOnlyKeys(new SubCategory("encryption")); - assertThat(def.propertiesByCategory(null).get(new Category("security")).keySet().iterator().next().isSpecial()).isTrue(); - assertThat(def.propertiesByCategory(null).get(new Category("licenses"))).containsOnlyKeys(new SubCategory("server_id")); - assertThat(def.propertiesByCategory(null).get(new Category("licenses")).keySet().iterator().next().isSpecial()).isTrue(); - } - - @Test - public void should_group_by_category() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, - PropertyDefinition.builder("global1").name("Global1").category("catGlobal1").build(), - PropertyDefinition.builder("global2").name("Global2").category("catGlobal1").build(), - PropertyDefinition.builder("global3").name("Global3").category("catGlobal2").build(), - PropertyDefinition.builder("project").name("Project").category("catProject").onlyOnQualifiers(Qualifiers.PROJECT).build(), - PropertyDefinition.builder("module").name("Module").category("catModule").onlyOnQualifiers(Qualifiers.MODULE).build(), - PropertyDefinition.builder("view").name("View").category("catView").onlyOnQualifiers(Qualifiers.VIEW).build(), - PropertyDefinition.builder("app").name("Application").category("catApp").onlyOnQualifiers(Qualifiers.APP).build()); - - assertThat(def.propertiesByCategory(null).keySet()).contains(new Category("catGlobal1"), new Category("catGlobal2")); - assertThat(def.propertiesByCategory(Qualifiers.PROJECT)).containsOnlyKeys(new Category("catProject")); - assertThat(def.propertiesByCategory(Qualifiers.MODULE)).containsOnlyKeys(new Category("catModule")); - assertThat(def.propertiesByCategory(Qualifiers.VIEW)).containsOnlyKeys(new Category("catView")); - assertThat(def.propertiesByCategory(Qualifiers.APP)).containsOnlyKeys(new Category("catApp")); - assertThat(def.propertiesByCategory("Unkown").keySet()).isEmpty(); - } - - @Test - public void should_group_by_subcategory() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, - PropertyDefinition.builder("global1").name("Global1").category("catGlobal1").subCategory("sub1").build(), - PropertyDefinition.builder("global2").name("Global2").category("catGlobal1").subCategory("sub2").build(), - PropertyDefinition.builder("global3").name("Global3").category("catGlobal1").build(), - PropertyDefinition.builder("global4").name("Global4").category("catGlobal2").build()); - - assertThat(def.propertiesByCategory(null).get(new Category("catGlobal1"))).containsOnlyKeys(new SubCategory("catGlobal1"), new SubCategory("sub1"), - new SubCategory("sub2")); - assertThat(def.propertiesByCategory(null).get(new Category("catGlobal2"))).containsOnlyKeys(new SubCategory("catGlobal2")); - } - - @Test - public void should_group_by_category_on_annotation_plugin() { - PropertyDefinitions def = new PropertyDefinitions(System2.INSTANCE, ByCategory.class); - - assertThat(def.propertiesByCategory(null).keySet()).contains(new Category("catglobal1"), new Category("catglobal2")); - assertThat(def.propertiesByCategory(Qualifiers.PROJECT)).containsOnlyKeys(new Category("catproject")); - assertThat(def.propertiesByCategory(Qualifiers.MODULE)).containsOnlyKeys(new Category("catmodule")); - } - - private void assertProperties(PropertyDefinitions definitions) { - assertThat(definitions.get("foo").name()).isEqualTo("Foo"); - assertThat(definitions.get("one").name()).isEqualTo("One"); - assertThat(definitions.get("two").name()).isEqualTo("Two"); - assertThat(definitions.get("unknown")).isNull(); - - assertThat(definitions.getDefaultValue("foo")).isNull(); - assertThat(definitions.getDefaultValue("two")).isEqualTo("2"); - - assertThat(definitions.getAll()).hasSize(3); - } - - @Test - public void validKey_throws_NPE_if_key_is_null() { - PropertyDefinitions underTest = new PropertyDefinitions(System2.INSTANCE); - - assertThatThrownBy(() -> underTest.validKey(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("key can't be null"); - } - - @Test - public void get_throws_NPE_if_key_is_null() { - PropertyDefinitions underTest = new PropertyDefinitions(System2.INSTANCE); - - assertThatThrownBy(() -> underTest.get(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("key can't be null"); - } - - @Test - public void get_trims_key_before_looking_for_replacement() { - Random random = new Random(); - String key = RandomStringUtils.randomAlphanumeric(4); - String deprecatedKey = RandomStringUtils.randomAlphanumeric(4); - PropertyDefinitions underTest = new PropertyDefinitions(System2.INSTANCE, singletonList( - PropertyDefinition.builder(key) - .deprecatedKey(deprecatedKey) - .build())); - - String untrimmedKey = blank(random) + deprecatedKey + blank(random); - assertThat(underTest.get(untrimmedKey).key()) - .describedAs("expecting key %s being returned for get(%s)", key, untrimmedKey) - .isEqualTo(key); - } - - private static String blank(Random random) { - StringBuilder b = new StringBuilder(); - IntStream.range(0, random.nextInt(3)).mapToObj(s -> " ").forEach(b::append); - return b.toString(); - } - - @Test - public void get_value_from_env() { - System2 system = mock(System2.class); - when(system.envVariable("FOO")).thenReturn("777"); - when(system.envVariable("ONE")).thenReturn("888"); - when(system.envVariable("SOME_COMPLETELY_RANDOM_ENV_VAR")).thenReturn("999"); - - PropertyDefinitions underTest = new PropertyDefinitions(system, new PluginWithProperty(), new PluginWithProperties()); - - assertThat(underTest.getValueFromEnv("foo")).hasValue("777"); - assertThat(underTest.getValueFromEnv("one")).hasValue("888"); - assertThat(underTest.getValueFromEnv("two")).isEmpty(); - assertThat(underTest.getValueFromEnv("some.unrecognizable.prop")).isEmpty(); - } - - @Test - public void get_all_properties_set_in_env() { - System2 system = mock(System2.class); - when(system.envVariable("FOO")).thenReturn("777"); - when(system.envVariable("ONE")).thenReturn("888"); - when(system.envVariable("SOME_COMPLETELY_RANDOM_ENV_VAR")).thenReturn("999"); - - PropertyDefinitions underTest = new PropertyDefinitions(system, new PluginWithProperty(), new PluginWithProperties()); - - assertThat(underTest.getAllPropertiesSetInEnv()).containsExactlyInAnyOrderEntriesOf(ImmutableMap.of("foo", "777", "one", "888")); - } - - @Property(key = "foo", name = "Foo") - static final class PluginWithProperty { - } - - @Properties({ - @Property(key = "one", name = "One"), - @Property(key = "two", name = "Two", defaultValue = "2") - }) - static final class PluginWithProperties { - } - - @Properties({ - @Property(key = "inCateg", name = "In Categ", category = "categ"), - @Property(key = "noCateg", name = "No categ") - }) - static final class Categories { - } - - @Properties({ - @Property(key = "global1", name = "Global1", category = "catGlobal1", global = true, project = false, module = false), - @Property(key = "global2", name = "Global2", category = "catGlobal1", global = true, project = false, module = false), - @Property(key = "global3", name = "Global3", category = "catGlobal2", global = true, project = false, module = false), - @Property(key = "project", name = "Project", category = "catProject", global = false, project = true, module = false), - @Property(key = "module", name = "Module", category = "catModule", global = false, project = false, module = true) - }) - static final class ByCategory { - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/config/SubCategoryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/config/SubCategoryTest.java deleted file mode 100644 index 28598f61769..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/config/SubCategoryTest.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.config; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class SubCategoryTest { - - // see processProperties in application_controller.rb - @Test - public void defaultSubCategoryShouldEqualParentCategory() { - assertThat(new Category("general")).isEqualTo(new SubCategory("general")); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/database/model/UserTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/database/model/UserTest.java deleted file mode 100644 index 947609319fd..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/database/model/UserTest.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.database.model; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class UserTest { - - @Test - public void testToString() { - User user = new User() - .setEmail("super@m.an") - .setLogin("superman") - .setName("Superman"); - assertThat(user.toString()).contains("super@m.an"); - assertThat(user.toString()).contains("superman"); - assertThat(user.toString()).contains("Superman"); - } - - @Test - public void testEquals() { - User one = new User() - .setLogin("one") - .setName("One"); - - User two = new User() - .setLogin("two") - .setName("Two"); - - assertThat(one.equals(one)).isTrue(); - assertThat(one.equals(new User().setLogin("one"))).isTrue(); - assertThat(one.equals(two)).isFalse(); - - assertThat(one).hasSameHashCodeAs(new User().setLogin("one")); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/issue/NoSonarFilterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/issue/NoSonarFilterTest.java deleted file mode 100644 index f70acedfa9f..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/issue/NoSonarFilterTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.issue; - -import java.util.Arrays; -import java.util.HashSet; -import org.junit.Test; -import org.sonar.api.batch.fs.internal.DefaultInputFile; -import org.sonar.api.batch.fs.internal.TestInputFileBuilder; -import org.sonar.api.batch.sensor.issue.internal.DefaultNoSonarFilter; - -import static org.assertj.core.api.Assertions.assertThat; - -public class NoSonarFilterTest { - - @Test - public void should_store_nosonar_lines_on_inputfile() { - DefaultInputFile f = TestInputFileBuilder.create("module1", "myfile.java").setLines(8).build(); - new DefaultNoSonarFilter().noSonarInFile(f, new HashSet<>(Arrays.asList(1, 4))); - - assertThat(f.hasNoSonarAt(1)).isTrue(); - assertThat(f.hasNoSonarAt(2)).isFalse(); - assertThat(f.hasNoSonarAt(4)).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java deleted file mode 100644 index 2f9f06e8048..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/measures/MetricTest.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.measures; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class MetricTest { - - @Test - public void shouldCreateMetric() { - Metric metric = new Metric.Builder("foo", "Foo", Metric.ValueType.INT) - .setDomain("my domain") - .create(); - - assertThat(metric.getKey()).isEqualTo("foo"); - assertThat(metric.getName()).isEqualTo("Foo"); - assertThat(metric.getDomain()).isEqualTo("my domain"); - } - - @Test - public void shouldCreateMetricWithDefaultValues() { - Metric metric = new Metric.Builder("foo", "Foo", Metric.ValueType.INT) - .create(); - - assertThat(metric.getBestValue()).isNull(); - assertThat(metric.getDescription()).isNull(); - assertThat(metric.getWorstValue()).isNull(); - assertThat(metric.getDirection()).isEqualTo(Metric.DIRECTION_NONE); - assertThat(metric.getEnabled()).isTrue(); - assertThat(metric.getUuid()).isNull(); - assertThat(metric.getUserManaged()).isFalse(); - assertThat(metric.isHidden()).isFalse(); - assertThat(metric.isOptimizedBestValue()).isFalse(); - } - - @Test - public void shouldCreatePercentMetricWithDefaultValues() { - Metric better = new Metric.Builder("foo", "Foo", Metric.ValueType.PERCENT) - .setDirection(Metric.DIRECTION_BETTER) - .create(); - Metric worst = new Metric.Builder("foo", "Foo", Metric.ValueType.PERCENT) - .setDirection(Metric.DIRECTION_WORST) - .create(); - - assertThat(better.getBestValue()).isEqualTo(100.0); - assertThat(better.getWorstValue()).isEqualTo(0.0); - assertThat(worst.getBestValue()).isEqualTo(0.0); - assertThat(worst.getWorstValue()).isEqualTo(100.0); - } - - @Test - public void override_decimal_scale_of_float_metric() { - Metric metric = new Metric.Builder("foo", "Foo", Metric.ValueType.FLOAT) - .setDecimalScale(3) - .create(); - assertThat(metric.getDecimalScale()).isEqualTo(3); - } - - @Test - public void fail_if_decimal_scale_is_greater_than_max_supported_value() { - assertThatThrownBy(() -> new Metric.Builder("foo", "Foo", Metric.ValueType.FLOAT) - .setDecimalScale(6) - .create()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Scale of decimal metric [foo] must be less than or equal 5: 6"); - } - - @Test - public void override_decimal_scale_of_percent_metric() { - Metric metric = new Metric.Builder("foo", "Foo", Metric.ValueType.PERCENT) - .setDecimalScale(3) - .create(); - assertThat(metric.getDecimalScale()).isEqualTo(3); - } - - @Test - public void default_decimal_scale_is_1() { - Metric metric = new Metric.Builder("foo", "Foo", Metric.ValueType.FLOAT) - .create(); - assertThat(metric.getDecimalScale()).isOne(); - } - - @Test - public void non_decimal_metric_has_no_scale() { - Metric metric = new Metric.Builder("foo", "Foo", Metric.ValueType.INT) - .create(); - assertThat(metric.getDecimalScale()).isNull(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/platform/NewUserHandlerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/platform/NewUserHandlerTest.java deleted file mode 100644 index 1bde5dcd8b7..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/platform/NewUserHandlerTest.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.platform; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class NewUserHandlerTest { - - @Test - public void build_context() { - NewUserHandler.Context context = NewUserHandler.Context.builder().setLogin("marius").setName("Marius").setEmail("marius@lesbronzes.fr").build(); - - assertThat(context.getLogin()).isEqualTo("marius"); - assertThat(context.getName()).isEqualTo("Marius"); - assertThat(context.getEmail()).isEqualTo("marius@lesbronzes.fr"); - } - - @Test - public void login_is_mandatory() { - assertThatThrownBy(() -> NewUserHandler.Context.builder().setName("Marius").build()) - .isInstanceOf(NullPointerException.class); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/ProfileExporterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/profiles/ProfileExporterTest.java deleted file mode 100644 index 9fafd1dca02..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/ProfileExporterTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.profiles; - -import org.junit.Test; - -import java.io.Writer; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class ProfileExporterTest { - - @Test - public void testSupportedRepositories() { - ProfileExporter exporter = new ProfileExporter("all", "All") { - @Override - public void exportProfile(RulesProfile profile, Writer writer) { - } - }; - exporter.setSupportedLanguages("java", "php"); - - assertThat(exporter.getSupportedLanguages().length, is(2)); - assertThat(exporter.getSupportedLanguages()[0], is("java")); - assertThat(exporter.getSupportedLanguages()[1], is("php")); - } - - @Test - public void supportAllRepositories() { - ProfileExporter exporter = new ProfileExporter("all", "All") { - @Override - public void exportProfile(RulesProfile profile, Writer writer) { - } - }; - - assertThat(exporter.getSupportedLanguages().length, is(0)); - - exporter.setSupportedLanguages(); - assertThat(exporter.getSupportedLanguages().length, is(0)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/ProfileImporterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/profiles/ProfileImporterTest.java deleted file mode 100644 index 1a02bfd491c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/ProfileImporterTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.profiles; - -import org.junit.Test; -import org.sonar.api.utils.ValidationMessages; - -import java.io.Reader; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class ProfileImporterTest { - - @Test - public void testSupportedLanguages() { - ProfileImporter inmporter = new ProfileImporter("all", "All") { - @Override - public RulesProfile importProfile(Reader reader, ValidationMessages messages) { - return null; - } - }; - inmporter.setSupportedLanguages("java", "php"); - - assertThat(inmporter.getSupportedLanguages().length, is(2)); - assertThat(inmporter.getSupportedLanguages()[0], is("java")); - assertThat(inmporter.getSupportedLanguages()[1], is("php")); - } - - @Test - public void supportAllLanguages() { - ProfileImporter importer = new ProfileImporter("all", "All") { - @Override - public RulesProfile importProfile(Reader reader, ValidationMessages messages) { - return null; - } - }; - - assertThat(importer.getSupportedLanguages().length, is(0)); - - importer.setSupportedLanguages(); - assertThat(importer.getSupportedLanguages().length, is(0)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/RulesProfileTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/profiles/RulesProfileTest.java deleted file mode 100644 index 33331cddfb6..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/RulesProfileTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.profiles; - -import org.junit.Test; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; -import org.sonar.api.utils.MessageException; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - - -public class RulesProfileTest { - - @Test - public void searchRulesByConfigKey() { - RulesProfile profile = RulesProfile.create(); - profile.activateRule(Rule.create("repo", "key1", "name1"), null); - profile.activateRule(Rule.create("repo", "key2", "name2").setConfigKey("config2"), null); - - assertThat(profile.getActiveRuleByConfigKey("repo", "unknown")).isNull(); - assertThat(profile.getActiveRuleByConfigKey("repo", "config2").getRuleKey()).isEqualTo("key2"); - } - - @Test - public void activateRuleWithDefaultPriority() { - RulesProfile profile = RulesProfile.create(); - Rule rule = Rule.create("repo", "key1", "name1").setSeverity(RulePriority.CRITICAL); - profile.activateRule(rule, null); - assertThat(profile.getActiveRule("repo", "key1").getSeverity()).isEqualTo(RulePriority.CRITICAL); - } - - @Test - public void activateRuleWithSpecificPriority() { - RulesProfile profile = RulesProfile.create(); - Rule rule = Rule.create("repo", "key1", "name1").setSeverity(RulePriority.CRITICAL); - profile.activateRule(rule, RulePriority.MINOR); - assertThat(profile.getActiveRule("repo", "key1").getSeverity()).isEqualTo(RulePriority.MINOR); - } - - @Test - public void fail_to_activate_already_activated_rule() { - RulesProfile profile = RulesProfile.create("Default", "java"); - Rule rule = Rule.create("repo", "key1", "name1").setSeverity(RulePriority.CRITICAL); - profile.activateRule(rule, null); - - try { - profile.activateRule(rule, null); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(MessageException.class) - .hasMessage("The definition of the profile 'Default' (language 'java') contains multiple occurrences of the 'repo:key1' rule. The plugin which declares this profile should fix this."); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/XMLProfileParserTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/profiles/XMLProfileParserTest.java deleted file mode 100644 index b9d4b57cb88..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/XMLProfileParserTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.profiles; - -import org.junit.Test; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import org.sonar.api.rules.ActiveRule; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RuleFinder; -import org.sonar.api.rules.RulePriority; -import org.sonar.api.utils.ValidationMessages; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class XMLProfileParserTest { - - @Test - public void importProfile() { - ValidationMessages validation = ValidationMessages.create(); - RulesProfile profile = parse("importProfile.xml", validation); - - assertThat(profile.getLanguage()).isEqualTo("java"); - assertThat(profile.getName()).isEqualTo("sonar way"); - assertThat(validation.hasErrors()).isFalse(); - assertThat(profile).isNotNull(); - - assertThat(profile.getActiveRule("checkstyle", "IllegalRegexp").getSeverity()).isEqualTo(RulePriority.CRITICAL); - } - - @Test - public void nameAndLanguageShouldBeMandatory() { - ValidationMessages validation = ValidationMessages.create(); - parse("nameAndLanguageShouldBeMandatory.xml", validation); - - assertThat(validation.getErrors()).hasSize(2); - assertThat(validation.getErrors().get(0)).contains(""); - } - - @Test - public void importProfileWithRuleParameters() { - ValidationMessages validation = ValidationMessages.create(); - RulesProfile profile = parse("importProfileWithRuleParameters.xml", validation); - - assertThat(validation.hasErrors()).isFalse(); - assertThat(validation.hasWarnings()).isFalse(); - - ActiveRule rule = profile.getActiveRule("checkstyle", "IllegalRegexp"); - assertThat(rule.getParameter("format")).isEqualTo("foo"); - assertThat(rule.getParameter("message")).isEqualTo("with special characters < > &"); - } - - @Test - public void importProfileWithUnknownRuleParameter() { - ValidationMessages validation = ValidationMessages.create(); - RulesProfile profile = parse("importProfileWithUnknownRuleParameter.xml", validation); - - assertThat(validation.getWarnings()).hasSize(1); - ActiveRule rule = profile.getActiveRule("checkstyle", "IllegalRegexp"); - assertThat(rule.getParameter("unknown")).isNull(); - } - - private RulesProfile parse(String resource, ValidationMessages validation) { - return new XMLProfileParser(newRuleFinder()) - .parseResource(getClass().getClassLoader(), getResourcePath(resource), validation); - } - - private String getResourcePath(String resource) { - return "org/sonar/api/profiles/XMLProfileParserTest/" + resource; - } - - private RuleFinder newRuleFinder() { - RuleFinder ruleFinder = mock(RuleFinder.class); - when(ruleFinder.findByKey(anyString(), anyString())).thenAnswer(new Answer<Rule>() { - public Rule answer(InvocationOnMock iom) { - Rule rule = Rule.create((String) iom.getArguments()[0], (String) iom.getArguments()[1], (String) iom.getArguments()[1]); - rule.createParameter("format"); - rule.createParameter("message"); - return rule; - } - }); - return ruleFinder; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/XMLProfileSerializerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/profiles/XMLProfileSerializerTest.java deleted file mode 100644 index c39794020a8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/profiles/XMLProfileSerializerTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.profiles; - -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.sonar.api.rules.ActiveRule; -import org.sonar.api.rules.Rule; -import org.sonar.api.rules.RulePriority; -import org.xml.sax.SAXException; - -import static org.assertj.core.api.Assertions.assertThat; - -public class XMLProfileSerializerTest { - - @Test - public void exportEmptyProfile() throws IOException, SAXException { - Writer writer = new StringWriter(); - RulesProfile profile = RulesProfile.create("sonar way", "java"); - new XMLProfileSerializer().write(profile, writer); - - assertSimilarXml("exportEmptyProfile.xml", writer.toString()); - } - - @Test - public void exportProfile() throws IOException, SAXException { - Writer writer = new StringWriter(); - RulesProfile profile = RulesProfile.create("sonar way", "java"); - profile.activateRule(Rule.create("checkstyle", "IllegalRegexp", "illegal regexp"), RulePriority.BLOCKER); - new XMLProfileSerializer().write(profile, writer); - - assertSimilarXml("exportProfile.xml", writer.toString()); - } - - @Test - public void exportRuleParameters() throws IOException, SAXException { - Writer writer = new StringWriter(); - RulesProfile profile = RulesProfile.create("sonar way", "java"); - Rule rule = Rule.create("checkstyle", "IllegalRegexp", "illegal regexp"); - rule.createParameter("format"); - rule.createParameter("message"); - rule.createParameter("tokens"); - - ActiveRule activeRule = profile.activateRule(rule, RulePriority.BLOCKER); - activeRule.setParameter("format", "foo"); - activeRule.setParameter("message", "with special characters < > &"); - // the tokens parameter is not set - new XMLProfileSerializer().write(profile, writer); - - assertSimilarXml("exportRuleParameters.xml", writer.toString()); - } - - private void assertSimilarXml(String fileWithExpectedXml, String xml) throws IOException { - String pathToExpectedXml = "XMLProfileSerializerTest/" + fileWithExpectedXml; - assertThat(xml).isXmlEqualTo(IOUtils.toString(getClass().getResource(pathToExpectedXml))); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/AbstractLanguageTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/AbstractLanguageTest.java deleted file mode 100644 index 7da6cd731e6..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/AbstractLanguageTest.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.resources; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class AbstractLanguageTest { - - - @Test - public void test_equals_and_hashcode() { - final Language1 lang1 = new Language1(); - assertThat(lang1.equals(lang1)).isTrue(); - assertThat(lang1.equals(new Language2())).isFalse(); - assertThat(lang1.equals(new Language1Too())).isTrue(); - assertThat(lang1.equals("not a language")).isFalse(); - assertThat(lang1.equals(null)).isFalse(); - - // not an AbstractLanguage but a Language - assertThat(lang1.equals(new Language() { - @Override - public String getKey() { - return lang1.getKey(); - } - - @Override - public String getName() { - return lang1.getName(); - } - - @Override - public String[] getFileSuffixes() { - return lang1.getFileSuffixes(); - } - - @Override - public boolean publishAllFiles() { - return true; - } - })).isTrue(); - - assertThat(lang1) - .hasSameHashCodeAs(lang1) - .hasSameHashCodeAs(new Language1Too()); - } - - @Test - public void should_not_define_language_with_too_long_key() { - assertThatThrownBy(TooLongKeyLanguage::new) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The following language key exceeds 20 characters: 'aKeyWhichIsVeryVeryVeryVeryVeryLong'"); - } - - static class TooLongKeyLanguage extends AbstractLanguage { - public TooLongKeyLanguage() { - super("aKeyWhichIsVeryVeryVeryVeryVeryLong"); - } - - public String[] getFileSuffixes() { - // TODO Auto-generated method stub - return null; - } - } - - static class Language1 extends AbstractLanguage { - public Language1() { - super("lang1"); - } - - public String[] getFileSuffixes() { - return new String[0]; - } - } - - static class Language1Too extends AbstractLanguage { - public Language1Too() { - super("lang1"); - } - - public String[] getFileSuffixes() { - return new String[0]; - } - } - - static class Language2 extends AbstractLanguage { - public Language2() { - super("lang2"); - } - - public String[] getFileSuffixes() { - return new String[0]; - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java deleted file mode 100644 index 647cd3afad9..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/CoreMetricsTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.resources; - -import java.util.List; -import java.util.NoSuchElementException; -import org.junit.Test; -import org.sonar.api.measures.Metric; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.api.measures.CoreMetrics.DIRECTORIES; -import static org.sonar.api.measures.CoreMetrics.NCLOC; -import static org.sonar.api.measures.CoreMetrics.getMetric; -import static org.sonar.api.measures.CoreMetrics.getMetrics; - -public class CoreMetricsTest { - - @Test - public void read_metrics_from_class_reflection() { - List<Metric> metrics = getMetrics(); - assertThat(metrics.size()).isGreaterThan(100); - assertThat(metrics).contains(NCLOC, DIRECTORIES); - } - - @Test - public void get_metric_by_key() { - Metric metric = getMetric("ncloc"); - assertThat(metric.getKey()).isEqualTo("ncloc"); - } - - @Test - public void fail_get_unknown_metric_by_key() { - assertThatThrownBy(() -> getMetric("unknown")) - .isInstanceOf(NoSuchElementException.class); - } - - @Test - public void someMetricsAreMeantToBeHidden() { - Metric metric = getMetric("analysis_from_sonarqube_9_4"); - assertThat(metric.isHidden()).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/LanguagesTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/LanguagesTest.java deleted file mode 100644 index 5b8fb2a8f49..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/LanguagesTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.resources; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class LanguagesTest { - @Test - public void should_add_several_times_the_same_language() { - Languages languages = new Languages( - language("fake"), - language("fake")); - - assertThat(languages.get("fake").getKey()).isEqualTo("fake"); - } - - @Test - public void should_get_suffixes() { - Languages languages = new Languages( - language("java", "java"), - language("php", "php4", "php5")); - - assertThat(languages.getSuffixes()).containsOnly("java", "php4", "php5"); - assertThat(languages.getSuffixes("java")).containsOnly("java"); - assertThat(languages.getSuffixes("php")).containsOnly("php4", "php5"); - assertThat(languages.getSuffixes("xxx")).isEmpty(); - } - - @Test - public void test_no_languages() { - Languages languages = new Languages(); - assertThat(languages.get("foo")).isNull(); - assertThat(languages.getSuffixes("foo")).isEmpty(); - } - - static Language language(String key, String... suffixes) { - Language lang = mock(Language.class); - when(lang.getKey()).thenReturn(key); - when(lang.getFileSuffixes()).thenReturn(suffixes); - return lang; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypeTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypeTest.java deleted file mode 100644 index e43d90fa6c6..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypeTest.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.resources; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - - -public class ResourceTypeTest { - - @Test - public void shouldCreateWithDefaults() { - ResourceType def = ResourceType.builder("qualifier") - .build(); - assertThat(def.getQualifier()).isEqualTo("qualifier"); - assertThat(def.getIconPath()).isEqualTo("/images/q/qualifier.png"); - assertThat(def.hasSourceCode()).isFalse(); - } - - @Test - public void shouldCreate() { - ResourceType def = ResourceType.builder("qualifier") - .setIconPath("/custom-icon.png") - .hasSourceCode() - .setProperty("supportsMeasureFilters", "true") - .setProperty("anotherProperty", "foo") - .build(); - assertThat(def.getQualifier()).isEqualTo("qualifier"); - assertThat(def.getIconPath()).isEqualTo("/custom-icon.png"); - assertThat(def.hasSourceCode()).isTrue(); - assertThat(def.getStringProperty("anotherProperty")).isEqualTo("foo"); - } - - @Test(expected = IllegalArgumentException.class) - public void shouldCheckQualifierLength() { - ResourceType.builder("qualifier bigger than 10 characters"); - } - - @Test - public void testEqualsAndHashCode() { - ResourceType foo1 = ResourceType.builder("FOO").build(); - ResourceType foo2 = ResourceType.builder("FOO").build(); - ResourceType bar = ResourceType.builder("BAR").build(); - - assertThat(foo1.equals(foo1)).isTrue(); - assertThat(foo1.equals(foo2)).isTrue(); - assertThat(foo1.equals(bar)).isFalse(); - - assertThat(foo1).hasSameHashCodeAs(foo1); - } - - @Test - public void getBooleanProperty_is_set() { - // set with boolean parameter - ResourceType def = ResourceType.builder("qualifier").setProperty("test", true).build(); - assertThat(def.getBooleanProperty("test")).isTrue(); - - def = ResourceType.builder("qualifier").setProperty("test", false).build(); - assertThat(def.getBooleanProperty("test")).isFalse(); - - def = ResourceType.builder("qualifier").setProperty("test", "true").build(); - assertThat(def.getBooleanProperty("test")).isTrue(); - - def = ResourceType.builder("qualifier").setProperty("test", "false").build(); - assertThat(def.getBooleanProperty("test")).isFalse(); - } - - @Test - public void getBooleanProperty_is_not_set() { - ResourceType def = ResourceType.builder("qualifier").build(); - assertThat(def.getBooleanProperty("test")).isFalse(); - } - - @Test - public void hasProperty() { - ResourceType def = ResourceType.builder("qualifier").build(); - assertThat(def.hasProperty("foo")).isFalse(); - - def = ResourceType.builder("qualifier").setProperty("foo", "bar").build(); - assertThat(def.hasProperty("foo")).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypeTreeTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypeTreeTest.java deleted file mode 100644 index 494ef50fc6b..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypeTreeTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.resources; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.api.resources.ResourceTypesTest.qualifiers; - -public class ResourceTypeTreeTest { - private final ResourceTypeTree tree = ResourceTypeTree.builder() - .addType(ResourceType.builder("TRK").build()) - .addType(ResourceType.builder("DIR").build()) - .addType(ResourceType.builder("FIL").build()) - .addType(ResourceType.builder("UTS").build()) - .addRelations("TRK", "DIR") - .addRelations("DIR", "FIL") - .addRelations("DIR", "UTS") - .build(); - - @Test - public void getTypes() { - assertThat(tree.getTypes()).hasSize(4); - assertThat(qualifiers(tree.getTypes())).containsOnly("TRK", "DIR", "FIL", "UTS"); - } - - @Test - public void getChildren() { - assertThat(tree.getChildren("TRK")).containsOnly("DIR"); - - assertThat(tree.getChildren("DIR")).containsOnly("FIL", "UTS"); - - assertThat(tree.getChildren("FIL")).isEmpty(); - } - - @Test - public void getRoot() { - assertThat(tree.getRootType()).isEqualTo(ResourceType.builder("TRK").build()); - } - - @Test - public void getLeaves() { - assertThat(tree.getLeaves()).containsOnly("FIL", "UTS"); - } - - @Test(expected = IllegalArgumentException.class) - public void forbidNullRelation() { - ResourceTypeTree.builder() - .addType(ResourceType.builder("TRK").build()) - .addType(ResourceType.builder("DIR").build()) - .addRelations("DIR" /* missing child */) - .build(); - } - - @Test(expected = IllegalArgumentException.class) - public void forbidDuplicatedType() { - ResourceTypeTree.builder() - .addType(ResourceType.builder("TRK").build()) - .addType(ResourceType.builder("TRK").build()) - .build(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypesTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypesTest.java deleted file mode 100644 index 7e690e7a950..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/resources/ResourceTypesTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.resources; - -import com.google.common.collect.Collections2; -import java.util.Collection; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ResourceTypesTest { - - private ResourceTypeTree viewsTree = ResourceTypeTree.builder() - .addType(ResourceType.builder(Qualifiers.VIEW).setProperty("supportsMeasureFilters", "true").build()) - .addType(ResourceType.builder(Qualifiers.SUBVIEW).build()) - .addRelations(Qualifiers.VIEW, Qualifiers.SUBVIEW) - .addRelations(Qualifiers.SUBVIEW, Qualifiers.PROJECT) - .build(); - - private ResourceTypeTree applicationTree = ResourceTypeTree.builder() - .addType(ResourceType.builder(Qualifiers.APP).setProperty("supportsMeasureFilters", "true").build()) - .addRelations(Qualifiers.APP, Qualifiers.PROJECT) - .build(); - - private ResourceTypeTree defaultTree = ResourceTypeTree.builder() - .addType(ResourceType.builder(Qualifiers.PROJECT).setProperty("supportsMeasureFilters", "true").build()) - .addType(ResourceType.builder(Qualifiers.DIRECTORY).build()) - .addType(ResourceType.builder(Qualifiers.FILE).build()) - .addRelations(Qualifiers.PROJECT, Qualifiers.DIRECTORY) - .addRelations(Qualifiers.DIRECTORY, Qualifiers.FILE) - .build(); - - private ResourceTypes types = new ResourceTypes(new ResourceTypeTree[] {defaultTree, viewsTree, applicationTree}); - - @Test - public void get() { - assertThat(types.get(Qualifiers.PROJECT).getQualifier()).isEqualTo(Qualifiers.PROJECT); - - // does not return null - assertThat(types.get("xxx").getQualifier()).isEqualTo("xxx"); - } - - @Test - public void get_all() { - assertThat(qualifiers(types.getAll())).containsExactly(Qualifiers.PROJECT, Qualifiers.DIRECTORY, Qualifiers.FILE, Qualifiers.VIEW, Qualifiers.SUBVIEW, Qualifiers.APP); - } - - @Test - public void get_roots() { - assertThat(qualifiers(types.getRoots())).containsOnly(Qualifiers.PROJECT, Qualifiers.VIEW, Qualifiers.APP); - } - - @Test - public void get_leaves_qualifiers() { - assertThat(types.getLeavesQualifiers(Qualifiers.PROJECT)).containsExactly(Qualifiers.FILE); - assertThat(types.getLeavesQualifiers(Qualifiers.DIRECTORY)).containsExactly(Qualifiers.FILE); - assertThat(types.getLeavesQualifiers(Qualifiers.VIEW)).containsExactly(Qualifiers.PROJECT); - assertThat(types.getLeavesQualifiers(Qualifiers.APP)).containsExactly(Qualifiers.PROJECT); - assertThat(types.getLeavesQualifiers("xxx")).isEmpty(); - } - - @Test(expected = IllegalStateException.class) - public void fail_on_duplicated_qualifier() { - ResourceTypeTree tree1 = ResourceTypeTree.builder() - .addType(ResourceType.builder("foo").build()) - .build(); - ResourceTypeTree tree2 = ResourceTypeTree.builder() - .addType(ResourceType.builder("foo").build()) - .build(); - - new ResourceTypes(new ResourceTypeTree[] {tree1, tree2}); - } - - @Test - public void isQualifierPresent() { - assertThat(types.isQualifierPresent(Qualifiers.APP)).isTrue(); - assertThat(types.isQualifierPresent(Qualifiers.VIEW)).isTrue(); - assertThat(types.isQualifierPresent("XXXX")).isFalse(); - } - - static Collection<String> qualifiers(Collection<ResourceType> types) { - return Collections2.transform(types, ResourceType::getQualifier); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rule/RuleKeyTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rule/RuleKeyTest.java deleted file mode 100644 index c0c20d6bb71..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rule/RuleKeyTest.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rule; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class RuleKeyTest { - - @Test - public void testOf() throws Exception { - RuleKey key = RuleKey.of("squid", "NullDeref"); - assertThat(key.repository()).isEqualTo("squid"); - assertThat(key.rule()).isEqualTo("NullDeref"); - } - - @Test - public void key_can_contain_colons() { - RuleKey key = RuleKey.of("squid", "Key:With:Some::Colons"); - assertThat(key.repository()).isEqualTo("squid"); - assertThat(key.rule()).isEqualTo("Key:With:Some::Colons"); - } - - @Test - public void repository_must_not_be_null() { - try { - RuleKey.of(null, "NullDeref"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Repository must be set"); - } - } - - @Test - public void repository_must_not_be_empty() { - try { - RuleKey.of("", "NullDeref"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Repository must be set"); - } - } - - @Test - public void rule_must_not_be_null() { - try { - RuleKey.of("squid", null); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Rule must be set"); - } - } - - @Test - public void rule_must_not_be_empty() { - try { - RuleKey.of("squid", ""); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Rule must be set"); - } - } - - @Test - public void encode_and_decode_string() { - RuleKey key = RuleKey.of("squid", "NullDeref"); - String serialized = key.toString(); - assertThat(serialized).isEqualTo("squid:NullDeref"); - RuleKey parsed = RuleKey.parse(serialized); - assertThat(parsed.repository()).isEqualTo("squid"); - assertThat(parsed.rule()).isEqualTo("NullDeref"); - assertThat(parsed.toString()).isEqualTo("squid:NullDeref"); - } - - @Test - public void parse_key_with_colons() { - RuleKey key = RuleKey.parse("squid:Key:With:Some::Colons"); - assertThat(key.repository()).isEqualTo("squid"); - assertThat(key.rule()).isEqualTo("Key:With:Some::Colons"); - } - - @Test - public void not_accept_bad_format() { - try { - RuleKey.parse("foo"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Invalid rule key: foo"); - } - } - - @Test - public void test_equals_and_hashcode() throws Exception { - RuleKey key1 = RuleKey.of("squid", "NullDeref"); - RuleKey key2 = RuleKey.of("squid", "NullDeref"); - RuleKey key3 = RuleKey.of("squid", "Other"); - - assertThat(key1) - .isEqualTo(key1) - .isEqualTo(key2) - .isNotEqualTo(key3) - .isNotNull() - .hasSameHashCodeAs(key1) - .hasSameHashCodeAs(key2); - } - - @Test - public void test_compareTo() { - RuleKey aa = RuleKey.of("A", "A"); - RuleKey ab = RuleKey.of("A", "B"); - - assertThat(ab).isGreaterThan(aa); - assertThat(aa).isLessThan(ab); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rule/RuleStatusTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rule/RuleStatusTest.java deleted file mode 100644 index a03cbfe58f3..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rule/RuleStatusTest.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rule; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RuleStatusTest { - @Test - public void default_is_ready() { - assertThat(RuleStatus.defaultStatus()).isEqualTo(RuleStatus.READY); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rule/SeverityTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rule/SeverityTest.java deleted file mode 100644 index 387ad27506a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rule/SeverityTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rule; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class SeverityTest { - - @Test - public void test_ALL() { - assertThat(Severity.ALL).hasSize(5).containsSubsequence("INFO", "MINOR", "MAJOR", "CRITICAL", "BLOCKER"); - } - - @Test - public void default_is_major() { - assertThat(Severity.defaultSeverity()).isEqualTo(Severity.MAJOR); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotatedCheck.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotatedCheck.java deleted file mode 100644 index ca33ea5f30c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotatedCheck.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -@org.sonar.check.Rule(name ="Annotated Check", description = "Description") -public class AnnotatedCheck { -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotatedCheckWithParameters.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotatedCheckWithParameters.java deleted file mode 100644 index d84145a7653..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotatedCheckWithParameters.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -import org.sonar.check.RuleProperty; - -@org.sonar.check.Rule(key = "overridden_key", name = "Check with parameters", description = "Has parameters") -public class AnnotatedCheckWithParameters { - - @RuleProperty(description = "Maximum value") - private String max; - - @RuleProperty(key = "overridden_min", description = "Minimum value") - protected String min; - - private int nonConfigurableProperty; - - public String getMax() { - return max; - } - - public void setMax(String max) { - this.max = max; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotationRuleParserTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotationRuleParserTest.java deleted file mode 100644 index be73d6cf4a1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/AnnotationRuleParserTest.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -import java.util.Collections; -import java.util.List; -import org.junit.Test; -import org.sonar.api.PropertyType; -import org.sonar.api.utils.SonarException; -import org.sonar.check.Priority; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class AnnotationRuleParserTest { - - @Test - public void rule_with_property() { - List<Rule> rules = parseAnnotatedClass(RuleWithProperty.class); - assertThat(rules).hasSize(1); - Rule rule = rules.get(0); - assertThat(rule.getKey()).isEqualTo("foo"); - assertThat(rule.getName()).isEqualTo("bar"); - assertThat(rule.getDescription()).isEqualTo("Foo Bar"); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.BLOCKER); - assertThat(rule.getStatus()).isEqualTo(Rule.STATUS_READY); - assertThat(rule.getParams()).hasSize(1); - - RuleParam prop = rule.getParam("property"); - assertThat(prop.getKey()).isEqualTo("property"); - assertThat(prop.getDescription()).isEqualTo("Ignore ?"); - assertThat(prop.getDefaultValue()).isEqualTo("false"); - assertThat(prop.getType()).isEqualTo(PropertyType.STRING.name()); - } - - @Test - public void rule_with_integer_property() { - List<Rule> rules = parseAnnotatedClass(RuleWithIntegerProperty.class); - - RuleParam prop = rules.get(0).getParam("property"); - assertThat(prop.getDescription()).isEqualTo("Max"); - assertThat(prop.getDefaultValue()).isEqualTo("12"); - assertThat(prop.getType()).isEqualTo(PropertyType.INTEGER.name()); - } - - @Test - public void rule_with_text_property() { - List<Rule> rules = parseAnnotatedClass(RuleWithTextProperty.class); - - RuleParam prop = rules.get(0).getParam("property"); - assertThat(prop.getDescription()).isEqualTo("text"); - assertThat(prop.getDefaultValue()).isEqualTo("Long text"); - assertThat(prop.getType()).isEqualTo(PropertyType.TEXT.name()); - } - - @Test - public void should_reject_invalid_property_types() { - assertThatThrownBy(() -> parseAnnotatedClass(RuleWithInvalidPropertyType.class)) - .isInstanceOf(SonarException.class) - .hasMessage("Invalid property type [INVALID]"); - } - - @Test - public void should_recognize_type() { - assertThat(AnnotationRuleParser.guessType(Integer.class)).isEqualTo(PropertyType.INTEGER); - assertThat(AnnotationRuleParser.guessType(int.class)).isEqualTo(PropertyType.INTEGER); - assertThat(AnnotationRuleParser.guessType(Float.class)).isEqualTo(PropertyType.FLOAT); - assertThat(AnnotationRuleParser.guessType(float.class)).isEqualTo(PropertyType.FLOAT); - assertThat(AnnotationRuleParser.guessType(Boolean.class)).isEqualTo(PropertyType.BOOLEAN); - assertThat(AnnotationRuleParser.guessType(boolean.class)).isEqualTo(PropertyType.BOOLEAN); - assertThat(AnnotationRuleParser.guessType(String.class)).isEqualTo(PropertyType.STRING); - assertThat(AnnotationRuleParser.guessType(Object.class)).isEqualTo(PropertyType.STRING); - } - - @Test - public void rule_without_name_nor_description() { - List<Rule> rules = parseAnnotatedClass(RuleWithoutNameNorDescription.class); - assertThat(rules).hasSize(1); - Rule rule = rules.get(0); - assertThat(rule.getKey()).isEqualTo("foo"); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR); - assertThat(rule.getName()).isNull(); - assertThat(rule.getDescription()).isNull(); - } - - @Test - public void rule_without_key() { - List<Rule> rules = parseAnnotatedClass(RuleWithoutKey.class); - assertThat(rules).hasSize(1); - Rule rule = rules.get(0); - assertThat(rule.getKey()).isEqualTo(RuleWithoutKey.class.getCanonicalName()); - assertThat(rule.getName()).isEqualTo("foo"); - assertThat(rule.getDescription()).isNull(); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR); - } - - @Test - public void overridden_rule() { - List<Rule> rules = parseAnnotatedClass(OverridingRule.class); - assertThat(rules).hasSize(1); - Rule rule = rules.get(0); - assertThat(rule.getKey()).isEqualTo("overriding_foo"); - assertThat(rule.getName()).isEqualTo("Overriding Foo"); - assertThat(rule.getDescription()).isNull(); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR); - assertThat(rule.getParams()).hasSize(2); - } - - private List<Rule> parseAnnotatedClass(Class annotatedClass) { - return new AnnotationRuleParser().parse("repo", Collections.singleton(annotatedClass)); - } - - @org.sonar.check.Rule(name = "foo") - static class RuleWithoutKey { - } - - @org.sonar.check.Rule(key = "foo") - static class RuleWithoutNameNorDescription { - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", status = Rule.STATUS_READY, priority = Priority.BLOCKER) - static class RuleWithProperty { - @org.sonar.check.RuleProperty(description = "Ignore ?", defaultValue = "false") - private String property; - } - - @org.sonar.check.Rule(key = "overriding_foo", name = "Overriding Foo") - static class OverridingRule extends RuleWithProperty { - @org.sonar.check.RuleProperty - private String additionalProperty; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", status = Rule.STATUS_READY, priority = Priority.BLOCKER) - static class RuleWithIntegerProperty { - @org.sonar.check.RuleProperty(description = "Max", defaultValue = "12") - private Integer property; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", status = Rule.STATUS_READY, priority = Priority.BLOCKER) - static class RuleWithTextProperty { - @org.sonar.check.RuleProperty(description = "text", defaultValue = "Long text", type = "TEXT") - protected String property; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", status = Rule.STATUS_READY, priority = Priority.BLOCKER) - static class RuleWithInvalidPropertyType { - @org.sonar.check.RuleProperty(description = "text", defaultValue = "Long text", type = "INVALID") - public String property; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java deleted file mode 100644 index 2aa3bc13c26..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleAnnotationUtilsTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -import org.junit.Test; - -import static org.hamcrest.core.Is.is; -import static org.junit.Assert.assertThat; - -public class RuleAnnotationUtilsTest { - - @Test - public void defaultKeyShouldBeTheClassName() { - String key = RuleAnnotationUtils.getRuleKey(AnnotatedCheck.class); - assertThat(key, is(AnnotatedCheck.class.getName())); - } - - @Test - public void shouldGetKey() { - String key = RuleAnnotationUtils.getRuleKey(AnnotatedCheckWithParameters.class); - assertThat(key, is("overridden_key")); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RulePriorityTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/RulePriorityTest.java deleted file mode 100644 index 065328460b1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RulePriorityTest.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -import org.junit.Test; -import org.sonar.check.Priority; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RulePriorityTest { - - @Test - public void testValueOfString() { - assertThat(RulePriority.valueOfString("info")).isEqualTo(RulePriority.INFO); - assertThat(RulePriority.valueOfString("MAJOR")).isEqualTo(RulePriority.MAJOR); - assertThat(RulePriority.valueOfString("ERROR")).isEqualTo(RulePriority.MAJOR); - assertThat(RulePriority.valueOfString("WARNING")).isEqualTo(RulePriority.INFO); - assertThat(RulePriority.valueOfString("ErRor")).isEqualTo(RulePriority.MAJOR); - assertThat(RulePriority.valueOfString("WaRnInG")).isEqualTo(RulePriority.INFO); - } - - @Test(expected = IllegalArgumentException.class) - public void testUnknownValueOfString() { - RulePriority.valueOfString("make me crash"); - } - - @Test - public void test_toCheckPriority() { - assertThat(RulePriority.fromCheckPriority(Priority.BLOCKER)).isEqualTo(RulePriority.BLOCKER); - assertThat(RulePriority.fromCheckPriority(Priority.CRITICAL)).isEqualTo(RulePriority.CRITICAL); - assertThat(RulePriority.fromCheckPriority(Priority.MAJOR)).isEqualTo(RulePriority.MAJOR); - assertThat(RulePriority.fromCheckPriority(Priority.MINOR)).isEqualTo(RulePriority.MINOR); - assertThat(RulePriority.fromCheckPriority(Priority.INFO)).isEqualTo(RulePriority.INFO); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleTest.java deleted file mode 100644 index 59a86a29c2c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleTest.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -import java.util.Arrays; -import java.util.List; -import org.junit.Assert; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RuleTest { - - @Test - public void description_should_be_cleaned() { - Rule rule = Rule.create().setDescription(" my description "); - Assert.assertEquals("my description", rule.getDescription()); - - rule.setDescription(null); - assertThat(rule.getDescription()).isNull(); - } - - @Test - public void should_remove_new_line_characters_in_name_with_setter() { - Rule rule = Rule.create(); - for (String example : getExamplesContainingNewLineCharacter()) { - rule.setName(example); - assertThat(rule.getName()).isEqualTo("test"); - } - } - - @Test - public void should_remove_new_line_characters_in_name_with_first_constructor() { - Rule rule; - for (String example : getExamplesContainingNewLineCharacter()) { - rule = new Rule(null, null).setName(example); - assertThat(rule.getName()).isEqualTo("test"); - } - } - - @Test - public void should_remove_new_line_characters_in_name_with_second_constructor() { - Rule rule; - for (String example : getExamplesContainingNewLineCharacter()) { - rule = new Rule(null, null).setName(example); - assertThat(rule.getName()).isEqualTo("test"); - } - } - - @Test - public void default_priority_is_major() { - Rule rule = Rule.create(); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR); - - rule = new Rule("name", "key"); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR); - - rule.setSeverity(RulePriority.BLOCKER); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.BLOCKER); - - rule.setSeverity(null); - assertThat(rule.getSeverity()).isEqualTo(RulePriority.MAJOR); - } - - @Test(expected = IllegalStateException.class) - public void should_not_authorize_unkown_status() { - Rule.create().setStatus("Unknown"); - } - - @Test - public void should_set_valid_status() { - Rule rule = Rule.create().setStatus(Rule.STATUS_DEPRECATED); - assertThat(rule.getStatus()).isEqualTo(Rule.STATUS_DEPRECATED); - - rule = Rule.create().setStatus(Rule.STATUS_REMOVED); - assertThat(rule.getStatus()).isEqualTo(Rule.STATUS_REMOVED); - - rule = Rule.create().setStatus(Rule.STATUS_BETA); - assertThat(rule.getStatus()).isEqualTo(Rule.STATUS_BETA); - - rule = Rule.create().setStatus(Rule.STATUS_READY); - assertThat(rule.getStatus()).isEqualTo(Rule.STATUS_READY); - } - - @Test - public void testTags() { - Rule rule = Rule.create(); - assertThat(rule.getTags()).isEmpty(); - assertThat(rule.getSystemTags()).isEmpty(); - - rule.setTags(new String[] {"tag1", "tag2"}); - assertThat(rule.getTags()).containsOnly("tag1", "tag2"); - assertThat(rule.getSystemTags()).isEmpty(); - } - - private List<String> getExamplesContainingNewLineCharacter() { - return Arrays.asList("te\nst", "te\ns\nt", "te\rst", "te\n\rst", "te\r\nst"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleTypeTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleTypeTest.java deleted file mode 100644 index 19de1e83b52..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/rules/RuleTypeTest.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.rules; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class RuleTypeTest { - - - @Test - public void test_valueOf_db_constant() { - assertThat(RuleType.valueOf(1)).isEqualTo(RuleType.CODE_SMELL); - assertThat(RuleType.valueOf(2)).isEqualTo(RuleType.BUG); - } - - @Test - public void valueOf_throws_ISE_if_unsupported_db_constant() { - assertThatThrownBy(() -> RuleType.valueOf(5)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Unsupported type value : 5"); - } - - @Test - public void test_ALL_NAMES() { - assertThat(RuleType.names()).containsOnly("BUG", "VULNERABILITY", "CODE_SMELL", "SECURITY_HOTSPOT"); - } - - @Test - public void ALL_NAMES_is_immutable() { - assertThatThrownBy(() -> RuleType.names().add("foo")) - .isInstanceOf(UnsupportedOperationException.class); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/FileExclusionsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/FileExclusionsTest.java deleted file mode 100644 index 8f3c3d1478a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/FileExclusionsTest.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.scan.filesystem; - -import org.junit.Test; -import org.sonar.api.CoreProperties; -import org.sonar.api.config.internal.MapSettings; - -import static org.assertj.core.api.Assertions.assertThat; - -public class FileExclusionsTest { - @Test - public void ignore_inclusion_of_world() { - MapSettings settings = new MapSettings(); - settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*"); - settings.setProperty(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*"); - assertThat(new FileExclusions(settings.asConfig()).sourceInclusions()).isEmpty(); - assertThat(new FileExclusions(settings.asConfig()).testInclusions()).isEmpty(); - } - - @Test - public void load_inclusions() { - MapSettings settings = new MapSettings(); - settings.setProperty(CoreProperties.PROJECT_INCLUSIONS_PROPERTY, "**/*Foo.java"); - settings.setProperty(CoreProperties.PROJECT_TEST_INCLUSIONS_PROPERTY, "**/*FooTest.java"); - FileExclusions moduleExclusions = new FileExclusions(settings.asConfig()); - - assertThat(moduleExclusions.sourceInclusions()).containsOnly("**/*Foo.java"); - assertThat(moduleExclusions.testInclusions()).containsOnly("**/*FooTest.java"); - } - - @Test - public void load_exclusions() { - MapSettings settings = new MapSettings(); - settings.setProperty(CoreProperties.PROJECT_EXCLUSIONS_PROPERTY, "**/*Foo.java"); - settings.setProperty(CoreProperties.PROJECT_TEST_EXCLUSIONS_PROPERTY, "**/*FooTest.java"); - FileExclusions moduleExclusions = new FileExclusions(settings.asConfig()); - - assertThat(moduleExclusions.sourceInclusions()).isEmpty(); - assertThat(moduleExclusions.sourceExclusions()).containsOnly("**/*Foo.java"); - assertThat(moduleExclusions.testInclusions()).isEmpty(); - assertThat(moduleExclusions.testExclusions()).containsOnly("**/*FooTest.java"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/PathResolverTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/PathResolverTest.java deleted file mode 100644 index c50a79edcdf..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/scan/filesystem/PathResolverTest.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.scan.filesystem; - -import java.io.File; -import java.io.IOException; -import java.util.Arrays; -import java.util.List; -import org.apache.commons.io.FilenameUtils; -import org.apache.commons.lang.SystemUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import static org.assertj.core.api.Assertions.assertThat; - -public class PathResolverTest { - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void get_file_by_relative_path() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - File file = resolver.relativeFile(rootDir, "org/foo/Bar.java"); - assertThat(file.getName()).isEqualTo("Bar.java"); - assertThat(FilenameUtils.separatorsToUnix(file.getCanonicalPath())).endsWith("org/foo/Bar.java"); - assertThat(file.getParentFile().getParentFile().getParentFile().getCanonicalPath()).isEqualTo(rootDir.getCanonicalPath()); - } - - @Test - public void get_file_by_absolute_path() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - File file = resolver.relativeFile(rootDir, new File(rootDir, "org/foo/Bar.java").getAbsolutePath()); - assertThat(file.getName()).isEqualTo("Bar.java"); - assertThat(FilenameUtils.separatorsToUnix(file.getCanonicalPath())).endsWith("org/foo/Bar.java"); - assertThat(file.getParentFile().getParentFile().getParentFile().getCanonicalPath()).isEqualTo(rootDir.getCanonicalPath()); - } - - @Test - public void get_files_by_relative_paths() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - List<File> files = resolver.relativeFiles(rootDir, Arrays.asList("org/foo/Bar.java", "org/hello/World.java")); - assertThat(files).hasSize(2); - for (File file : files) { - assertThat(file.getName()).endsWith(".java"); - assertThat(file.getParentFile().getParentFile().getParentFile().getCanonicalPath()).isEqualTo(rootDir.getCanonicalPath()); - } - } - - @Test - public void relative_path_from_dir() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - File org = new File(rootDir, "org"); - File hello = new File(org, "hello"); - File world = new File(hello, "World.java"); - - assertThat(resolver.relativePath(rootDir, world)).isEqualTo("org/hello/World.java"); - assertThat(resolver.relativePath(new File(rootDir, "."), world)).isEqualTo("org/hello/World.java"); - } - - @Test - public void relative_path_from_not_normalized_dir() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = new File(temp.newFolder(), "foo/.."); - File org = new File(rootDir, "org"); - File hello = new File(org, "hello"); - File world = new File(hello, "World.java"); - - assertThat(resolver.relativePath(rootDir, world)).isEqualTo("org/hello/World.java"); - } - - @Test - public void relative_path_for_not_normalized_dir() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - File file = new File(rootDir, "level1/../dir/file.c"); - - assertThat(resolver.relativePath(rootDir, file)).isEqualTo("dir/file.c"); - } - - @Test - public void relative_path_for_not_normalized_dir_sub_level() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - File file = new File(rootDir, "level1/level2/../dir/file.c"); - - assertThat(resolver.relativePath(rootDir, file)).isEqualTo("level1/dir/file.c"); - } - - @Test - public void relative_path_for_case_insensitive_fs() throws IOException { - // To please the quality gate, don't use assumeTrue, or the test will be reported as skipped - if (SystemUtils.IS_OS_WINDOWS) { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - File baseDir = new File(rootDir, "level1"); - File file = new File(baseDir, "../Level1/dir/file.c"); - - assertThat(resolver.relativePath(baseDir, file)).isEqualTo("dir/file.c"); - } - } - - @Test - public void relative_path_from_multiple_dirs() throws IOException { - PathResolver resolver = new PathResolver(); - File dir1 = temp.newFolder("D1"); - File dir2 = temp.newFolder("D2"); - - File org = new File(dir2, "org"); - File hello = new File(org, "hello"); - File world = new File(hello, "World.java"); - - PathResolver.RelativePath relativePath = resolver.relativePath(Arrays.asList(dir1, dir2), world); - assertThat(relativePath.dir().getCanonicalPath()).isEqualTo(dir2.getCanonicalPath()); - assertThat(relativePath.path()).isEqualTo("org/hello/World.java"); - } - - @Test - public void relative_path_from_not_normalized_dirs() throws IOException { - PathResolver resolver = new PathResolver(); - - File rootDir = new File(temp.newFolder(), "foo/.."); - File org = new File(rootDir, "org"); - File hello = new File(org, "hello"); - File world = new File(hello, "World.java"); - - PathResolver.RelativePath relativePath = resolver.relativePath(Arrays.asList(rootDir), world); - assertThat(relativePath).isNotNull(); - assertThat(relativePath.dir()).isEqualTo(rootDir); - assertThat(relativePath.path()).isEqualTo("org/hello/World.java"); - } - - @Test - public void cant_find_relative_path_from_multiple_dirs() throws IOException { - PathResolver resolver = new PathResolver(); - File dir1 = temp.newFolder("D1"); - File dir2 = temp.newFolder("D2"); - - File org = new File(dir2, "org"); - File hello = new File(org, "hello"); - File world = new File(hello, "World.java"); - - PathResolver.RelativePath relativePath = resolver.relativePath(Arrays.asList(dir1), world); - assertThat(relativePath).isNull(); - } - - @Test - public void null_relative_path_when_file_is_not_in_dir() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - - assertThat(resolver.relativePath(rootDir, new File("Elsewhere.java"))).isNull(); - } - - @Test - public void null_relative_path_when_file_is_not_in_dir2() throws IOException { - PathResolver resolver = new PathResolver(); - File rootDir = temp.newFolder(); - - assertThat(resolver.relativePath(rootDir, new File(rootDir, "../Elsewhere.java"))).isNull(); - } - - @Test - public void supportSymlink() { - PathResolver resolver = new PathResolver(); - File rootDir = new File("test-resources/org/sonar/api/scan/filesystem/sample-with-symlink"); - - assertThat(resolver.relativePath(rootDir, new File("test-resources/org/sonar/api/scan/filesystem/sample-with-symlink/testx/ClassOneTest.java"))).isEqualTo( - "testx/ClassOneTest.java"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/security/DefaultGroupsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/security/DefaultGroupsTest.java deleted file mode 100644 index a84ca8c270a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/security/DefaultGroupsTest.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.security; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DefaultGroupsTest { - @Test - public void isAnyone_is_not_case_sensitive() { - assertThat(DefaultGroups.isAnyone("ANYONE")).isTrue(); - assertThat(DefaultGroups.isAnyone("anyone")).isTrue(); - assertThat(DefaultGroups.isAnyone(DefaultGroups.ANYONE)).isTrue(); - - assertThat(DefaultGroups.isAnyone(DefaultGroups.ADMINISTRATORS)).isFalse(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/security/ExternalGroupsProviderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/security/ExternalGroupsProviderTest.java deleted file mode 100644 index 6b1d4e3e3c8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/security/ExternalGroupsProviderTest.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.security; - -import com.google.common.base.Preconditions; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import javax.annotation.Nullable; -import javax.servlet.http.HttpServletRequest; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class ExternalGroupsProviderTest { - @Test - public void doGetGroupsNoOverride() { - ExternalGroupsProvider groupsProvider = new ExternalGroupsProvider() { - }; - - String userName = "foo"; - assertThat(groupsProvider.doGetGroups(new ExternalGroupsProvider.Context(userName, - mock(HttpServletRequest.class)))).isNull(); - } - - @Test - public void doGetGroupsTests() { - final Map<String, Collection<String>> userGroupsMap = getTestUserGroupMapping(); - - ExternalGroupsProvider groupsProvider = new ExternalGroupsProvider() { - @Override - public Collection<String> doGetGroups(Context context) { - Preconditions.checkNotNull(context.getUsername()); - Preconditions.checkNotNull(context.getRequest()); - - return userGroupsMap.get(context.getUsername()); - } - }; - - runDoGetGroupsTests(groupsProvider, userGroupsMap); - } - - private static void runDoGetGroupsTests(ExternalGroupsProvider groupsProvider, Map<String, Collection<String>> userGroupsMap) { - for (Map.Entry<String, Collection<String>> userGroupMapEntry : userGroupsMap.entrySet()) { - Collection<String> groups = groupsProvider.doGetGroups(new ExternalGroupsProvider.Context( - userGroupMapEntry.getKey(), mock(HttpServletRequest.class))); - assertThat(groups).isEqualTo(userGroupMapEntry.getValue()); - } - } - - private static Map<String, Collection<String>> getTestUserGroupMapping() { - Map<String, Collection<String>> userGroupsMap = new HashMap<>(); - addUserGroupMapping(userGroupsMap, "userWithOneGroups", new String[] {"group1"}); - addUserGroupMapping(userGroupsMap, "userWithTwoGroups", new String[] {"group1", "group2"}); - addUserGroupMapping(userGroupsMap, "userWithNoGroup", new String[] {}); - addUserGroupMapping(userGroupsMap, "userWithNullGroup", null); - - return userGroupsMap; - } - - private static void addUserGroupMapping(Map<String, Collection<String>> userGroupsMap, String user, @Nullable String[] groups) { - Collection<String> groupsCollection = null; - if (groups != null) { - groupsCollection = Arrays.asList(groups); - } - - userGroupsMap.put(user, groupsCollection); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/security/ExternalUsersProviderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/security/ExternalUsersProviderTest.java deleted file mode 100644 index 3b3e310926d..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/security/ExternalUsersProviderTest.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.security; - -import com.google.common.base.Preconditions; -import org.junit.Test; - -import javax.servlet.http.HttpServletRequest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class ExternalUsersProviderTest { - - @Test - public void doGetUserDetails() { - ExternalUsersProvider provider = new ExternalUsersProvider() { - @Override - public UserDetails doGetUserDetails(Context context) { - Preconditions.checkNotNull(context.getUsername()); - Preconditions.checkNotNull(context.getRequest()); - UserDetails user = new UserDetails(); - user.setName(context.getUsername()); - user.setEmail("foo@bar.com"); - return user; - } - }; - UserDetails user = provider.doGetUserDetails(new ExternalUsersProvider.Context("foo", mock(HttpServletRequest.class))); - - assertThat(user.getName()).isEqualTo("foo"); - assertThat(user.getEmail()).isEqualTo("foo@bar.com"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/security/SecurityRealmTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/security/SecurityRealmTest.java deleted file mode 100644 index 4fd508646c8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/security/SecurityRealmTest.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.security; - -import org.junit.Test; - -import javax.servlet.http.HttpServletRequest; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class SecurityRealmTest { - - @Test - public void doGetAuthenticator() { - final Authenticator authenticator = mock(Authenticator.class); - SecurityRealm realm = new SecurityRealm() { - @Override - public Authenticator doGetAuthenticator() { - return authenticator; - } - }; - assertThat(realm.doGetAuthenticator()).isSameAs(authenticator); - assertThat(realm.getLoginPasswordAuthenticator()).isNull(); - } - - @Test - public void getLoginPasswordAuthenticator_deprecated_method_replaced_by_getAuthenticator() { - final LoginPasswordAuthenticator deprecatedAuthenticator = mock(LoginPasswordAuthenticator.class); - SecurityRealm realm = new SecurityRealm() { - @Override - public LoginPasswordAuthenticator getLoginPasswordAuthenticator() { - return deprecatedAuthenticator; - } - }; - Authenticator proxy = realm.doGetAuthenticator(); - Authenticator.Context context = new Authenticator.Context("foo", "bar", mock(HttpServletRequest.class)); - proxy.doAuthenticate(context); - - verify(deprecatedAuthenticator).authenticate("foo", "bar"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/security/UserDetailsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/security/UserDetailsTest.java deleted file mode 100644 index c8c414da0ab..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/security/UserDetailsTest.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.security; - -import org.junit.Before; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class UserDetailsTest { - private UserDetails userDetails; - - @Before - public void init() { - userDetails = new UserDetails(); - } - - @Test - public void getNameTest() { - userDetails.setName(null); - assertThat(userDetails.getName()).isNull(); - - userDetails.setName(""); - assertThat(userDetails.getName()).isEmpty(); - - userDetails.setName("foo"); - assertThat(userDetails.getName()).isEqualTo("foo"); - } - - @Test - public void getEmailTest() { - userDetails.setEmail(null); - assertThat(userDetails.getEmail()).isNull(); - - userDetails.setEmail(""); - assertThat(userDetails.getEmail()).isEmpty(); - - userDetails.setEmail("foo@example.com"); - assertThat(userDetails.getEmail()).isEqualTo("foo@example.com"); - } - - @Test - public void getUserIdTest() { - userDetails.setUserId(null); - assertThat(userDetails.getUserId()).isNull(); - - userDetails.setUserId(""); - assertThat(userDetails.getUserId()).isEmpty(); - - userDetails.setUserId("foo@example"); - assertThat(userDetails.getUserId()).isEqualTo("foo@example"); - } - - @Test - public void toStringTest() { - userDetails.setName("foo"); - userDetails.setEmail("foo@example.com"); - userDetails.setUserId("foo@example"); - - assertThat(userDetails.toString()).isEqualTo("UserDetails{name='foo', email='foo@example.com', userId='foo@example'}"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/authentication/DisplayTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/authentication/DisplayTest.java deleted file mode 100644 index 9b77233317d..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/authentication/DisplayTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.authentication; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class DisplayTest { - - @Test - public void create_display() { - Display display = Display.builder() - .setIconPath("/static/authgithub/github.svg") - .setBackgroundColor("#123456") - .build(); - - assertThat(display.getIconPath()).isEqualTo("/static/authgithub/github.svg"); - assertThat(display.getBackgroundColor()).isEqualTo("#123456"); - assertThat(display.getHelpMessage()).isNull(); - } - - @Test - public void create_display_with_default_background_color() { - Display display = Display.builder() - .setIconPath("/static/authgithub/github.svg") - .build(); - - assertThat(display.getBackgroundColor()).isEqualTo("#236a97"); - } - - - @Test - public void create_display_with_help_message() { - Display display = Display.builder() - .setIconPath("/static/authgithub/github.svg") - .setHelpMessage("Help message") - .build(); - - assertThat(display.getHelpMessage()).isEqualTo("Help message"); - } - - @Test - public void fail_when_icon_path_is_null() { - assertThatThrownBy(() -> Display.builder() - .setIconPath(null) - .setBackgroundColor("#123456") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Icon path must not be blank"); - } - - @Test - public void fail_when_icon_path_is_blank() { - assertThatThrownBy(() -> Display.builder() - .setIconPath("") - .setBackgroundColor("#123456") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Icon path must not be blank"); - } - - @Test - public void fail_when_background_color_is_null() { - assertThatThrownBy(() -> Display.builder() - .setIconPath("/static/authgithub/github.svg") - .setBackgroundColor(null) - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Background color must not be blank"); - } - - @Test - public void fail_when_background_color_is_blank() { - assertThatThrownBy(() -> Display.builder() - .setIconPath("/static/authgithub/github.svg") - .setBackgroundColor("") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Background color must not be blank"); - } - - @Test - public void fail_when_background_color_has_wrong_size() { - assertThatThrownBy(() -> Display.builder() - .setIconPath("/static/authgithub/github.svg") - .setBackgroundColor("1234") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Background color must begin with a sharp followed by 6 characters"); - } - - @Test - public void fail_when_background_color_doesnt_begin_with_sharp() { - assertThatThrownBy(() -> Display.builder() - .setIconPath("/static/authgithub/github.svg") - .setBackgroundColor("*123456") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Background color must begin with a sharp followed by 6 characters"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/authentication/UserIdentityTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/authentication/UserIdentityTest.java deleted file mode 100644 index 266959f46f1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/authentication/UserIdentityTest.java +++ /dev/null @@ -1,226 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.authentication; - -import com.google.common.base.Strings; -import org.junit.Test; - -import static com.google.common.collect.Sets.newHashSet; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class UserIdentityTest { - - @Test - public void create_user() { - UserIdentity underTest = UserIdentity.builder() - .setProviderId("4321") - .setProviderLogin("john") - .setName("John") - .setEmail("john@email.com") - .build(); - - assertThat(underTest.getProviderId()).isEqualTo("4321"); - assertThat(underTest.getProviderLogin()).isEqualTo("john"); - assertThat(underTest.getName()).isEqualTo("John"); - assertThat(underTest.getEmail()).isEqualTo("john@email.com"); - assertThat(underTest.shouldSyncGroups()).isFalse(); - assertThat(underTest.getGroups()).isEmpty(); - } - - @Test - public void create_user_with_minimum_fields() { - UserIdentity underTest = UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .build(); - - assertThat(underTest.getProviderLogin()).isEqualTo("john"); - assertThat(underTest.getName()).isEqualTo("John"); - assertThat(underTest.getProviderId()).isNull(); - assertThat(underTest.getEmail()).isNull(); - assertThat(underTest.shouldSyncGroups()).isFalse(); - assertThat(underTest.getGroups()).isEmpty(); - } - - @Test - public void fail_when_id_is_too_long() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderId(Strings.repeat("1", 256)) - .setProviderLogin("john") - .setName("John") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("ID is too big (255 characters max)"); - } - - @Test - public void fail_when_provider_login_is_null() { - assertThatThrownBy(() -> UserIdentity.builder() - .setName("John") - .setEmail("john@email.com") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Provider login must not be blank"); - } - - @Test - public void fail_when_provider_login_is_empty() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("") - .setName("John") - .setEmail("john@email.com") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Provider login must not be blank"); - } - - @Test - public void fail_when_provider_login_is_too_long() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin(Strings.repeat("1", 256)) - .setName("John") - .setEmail("john@email.com") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Provider login size is incorrect (maximum 255 characters)"); - } - - @Test - public void fail_when_name_is_null() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setEmail("john@email.com") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("User name must not be blank"); - } - - @Test - public void fail_when_name_is_empty() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName("") - .setEmail("john@email.com") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("User name must not be blank"); - } - - @Test - public void fail_when_name_is_loo_long() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName(Strings.repeat("1", 201)) - .setEmail("john@email.com") - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("User name size is too big (200 characters max)"); - } - - @Test - public void fail_when_email_is_loo_long() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .setEmail(Strings.repeat("1", 101)) - .build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("User email size is too big (100 characters max)"); - } - - @Test - public void create_user_with_groups() { - UserIdentity underTest = UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .setEmail("john@email.com") - .setGroups(newHashSet("admin", "user")) - .build(); - - assertThat(underTest.shouldSyncGroups()).isTrue(); - assertThat(underTest.getGroups()).containsOnly("admin", "user"); - } - - @Test - public void fail_when_groups_are_null() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setEmail("john@email.com") - .setGroups(null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Groups cannot be null, please don't use this method if groups should not be synchronized."); - } - - @Test - public void fail_when_groups_contain_empty_group_name() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setEmail("john@email.com") - .setGroups(newHashSet(""))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be empty"); - } - - @Test - public void fail_when_groups_contain_only_blank_space() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .setEmail("john@email.com") - .setGroups(newHashSet(" "))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be empty"); - } - - @Test - public void fail_when_groups_contain_null_group_name() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .setEmail("john@email.com") - .setGroups(newHashSet((String)null))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be empty"); - } - - @Test - public void fail_when_groups_contain_anyone() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .setEmail("john@email.com") - .setGroups(newHashSet("Anyone"))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Anyone group cannot be used"); - } - - @Test - public void fail_when_groups_contain_too_long_group_name() { - assertThatThrownBy(() -> UserIdentity.builder() - .setProviderLogin("john") - .setName("John") - .setEmail("john@email.com") - .setGroups(newHashSet(Strings.repeat("group", 300)))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be longer than 255 characters"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/debt/DefaultDebtRemediationFunctionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/debt/DefaultDebtRemediationFunctionTest.java deleted file mode 100644 index c9f15eaf520..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/debt/DefaultDebtRemediationFunctionTest.java +++ /dev/null @@ -1,166 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.debt; - -import org.junit.Test; -import org.sonar.api.server.debt.internal.DefaultDebtRemediationFunction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class DefaultDebtRemediationFunctionTest { - - @Test - public void create_linear() { - DebtRemediationFunction function = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, "10h", null); - assertThat(function.type()).isEqualTo(DefaultDebtRemediationFunction.Type.LINEAR); - assertThat(function.gapMultiplier()).isEqualTo("10h"); - assertThat(function.baseEffort()).isNull(); - } - - @Test - public void create_linear_with_offset() { - DebtRemediationFunction function = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "10h", "5min"); - assertThat(function.type()).isEqualTo(DefaultDebtRemediationFunction.Type.LINEAR_OFFSET); - assertThat(function.gapMultiplier()).isEqualTo("10h"); - assertThat(function.baseEffort()).isEqualTo("5min"); - } - - @Test - public void create_constant_per_issue() { - DebtRemediationFunction function = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, "10h"); - assertThat(function.type()).isEqualTo(DefaultDebtRemediationFunction.Type.CONSTANT_ISSUE); - assertThat(function.gapMultiplier()).isNull(); - assertThat(function.baseEffort()).isEqualTo("10h"); - } - - @Test - public void sanitize_remediation_coefficient_and_offset() { - DebtRemediationFunction function = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, " 1 h ", " 10 min"); - - assertThat(function.gapMultiplier()).isEqualTo("1h"); - assertThat(function.baseEffort()).isEqualTo("10min"); - } - - @Test - public void fail_to_when_no_type() { - try { - new DefaultDebtRemediationFunction(null, "5min", "10h"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Remediation function type cannot be null"); - } - } - - @Test - public void fail_to_create_linear_when_no_coefficient() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, null, "10h"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Linear functions must only have a non empty gap multiplier"); - } - } - - @Test - public void fail_to_create_linear_when_offset() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, "5min", "10h"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Linear functions must only have a non empty gap multiplier"); - } - } - - @Test - public void fail_to_create_constant_per_issue_when_no_offset() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, "10h", null); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Constant/issue functions must only have a non empty base effort"); - } - } - - @Test - public void fail_to_create_constant_per_issue_when_coefficient() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, "5min", "10h"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Constant/issue functions must only have a non empty base effort"); - } - } - - @Test - public void fail_to_create_linear_with_offset_when_no_coefficient() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "", "10h"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Linear with offset functions must have both non null gap multiplier and base effort"); - } - } - - @Test - public void fail_to_create_linear_with_offset_when_no_offset() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "5min", ""); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Linear with offset functions must have both non null gap multiplier and base effort"); - } - } - - @Test - public void test_equals_and_hashcode() { - DebtRemediationFunction function = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "10h", "5min"); - DebtRemediationFunction functionWithSameValue = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "10h", "5min"); - DebtRemediationFunction functionWithDifferentType = new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, "5min"); - - assertThat(function).isEqualTo(function) - .isEqualTo(functionWithSameValue) - .isNotEqualTo(functionWithDifferentType) - .isNotEqualTo(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "11h", "5min")) - .isNotEqualTo(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "10h", "6min")) - .isNotEqualTo(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, "10h", null)) - .isNotEqualTo(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.CONSTANT_ISSUE, null, "6min")) - .hasSameHashCodeAs(function) - .hasSameHashCodeAs(functionWithSameValue); - assertThat(function.hashCode()).isNotEqualTo(functionWithDifferentType.hashCode()); - } - - @Test - public void test_to_string() { - assertThat(new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR_OFFSET, "10h", "5min").toString()) - .isEqualTo("DebtRemediationFunction{type=LINEAR_OFFSET, gap multiplier=10h, base effort=5min}"); - } - - @Test - public void fail_if_bad_coefficient_format() { - try { - new DefaultDebtRemediationFunction(DebtRemediationFunction.Type.LINEAR, "foo", null); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Invalid gap multiplier: foo (Duration 'foo' is invalid, it should use the following sample format : 2d 10h 15min)"); - } - - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/profile/BuiltInQualityProfileAnnotationLoaderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/profile/BuiltInQualityProfileAnnotationLoaderTest.java deleted file mode 100644 index dac99689dd3..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/profile/BuiltInQualityProfileAnnotationLoaderTest.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.profile; - -import org.junit.Test; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.Severity; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInQualityProfile; -import org.sonar.check.BelongsToProfile; -import org.sonar.check.Priority; - -import static org.assertj.core.api.Assertions.assertThat; - -public class BuiltInQualityProfileAnnotationLoaderTest { - - @Test - public void shouldParseAnnotatedClasses() { - BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); - NewBuiltInQualityProfile newProfile = context.createBuiltInQualityProfile("Foo way", "java"); - - new BuiltInQualityProfileAnnotationLoader().load(newProfile, "squid", FakeRule.class, RuleNoProfile.class); - newProfile.done(); - - assertThat(context.profile("java", "Foo way").rule(RuleKey.of("squid", "fake")).overriddenSeverity()).isEqualTo(Severity.BLOCKER); - } - - @Test - public void shouldParseOnlyWantedProfile() { - BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); - NewBuiltInQualityProfile newProfile = context.createBuiltInQualityProfile("Foo way", "java"); - - new BuiltInQualityProfileAnnotationLoader().load(newProfile, "squid", FakeRule.class, RuleOnOtherProfile.class, RuleNoProfile.class); - newProfile.done(); - - assertThat(context.profile("java", "Foo way").rule(RuleKey.of("squid", "fake"))).isNotNull(); - assertThat(context.profile("java", "Foo way").rule(RuleKey.of("squid", "other"))).isNull(); - } -} - -@BelongsToProfile(title = "Other profile", priority = Priority.BLOCKER) -@org.sonar.check.Rule(key = "other", priority = Priority.CRITICAL) -class RuleOnOtherProfile { -} - -@org.sonar.check.Rule(key = "no", priority = Priority.CRITICAL) -class RuleNoProfile { -} - -@BelongsToProfile(title = "Foo way", priority = Priority.BLOCKER) -@org.sonar.check.Rule(key = "fake", priority = Priority.CRITICAL) -class FakeRule { -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/profile/BuiltInQualityProfilesDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/profile/BuiltInQualityProfilesDefinitionTest.java deleted file mode 100644 index 87149929bc0..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/profile/BuiltInQualityProfilesDefinitionTest.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.profile; - -import java.util.Map; -import java.util.function.Consumer; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.BuiltInQualityProfile; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInActiveRule; -import org.sonar.api.server.profile.BuiltInQualityProfilesDefinition.NewBuiltInQualityProfile; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.groups.Tuple.tuple; - -public class BuiltInQualityProfilesDefinitionTest { - - - @Test - public void coverage() { - assertThat(new BuiltInQualityProfilesDefinition.Context().profile("Foo", "xoo")).isNull(); - } - - @Test - public void createEmptyProfile() { - Map<String, Map<String, BuiltInQualityProfile>> profiles = define(c -> c.createBuiltInQualityProfile("Foo", "xoo").done()); - assertThat(profiles).containsOnlyKeys("xoo"); - assertThat(profiles.get("xoo")).containsOnlyKeys("Foo"); - BuiltInQualityProfile profile = profiles.get("xoo").get("Foo"); - assertThat(profile.name()).isEqualTo("Foo"); - assertThat(profile.language()).isEqualTo("xoo"); - assertThat(profile.isDefault()).isFalse(); - } - - @Test - public void sanityEqualCheck() { - Map<String, Map<String, BuiltInQualityProfile>> profiles = define(c -> { - NewBuiltInQualityProfile profile1 = c.createBuiltInQualityProfile("Foo1", "xoo"); - NewBuiltInActiveRule rule = profile1.activateRule("repo", "rule"); - profile1.done(); - NewBuiltInQualityProfile profile2 = c.createBuiltInQualityProfile("Foo2", "xoo"); - profile2.done(); - NewBuiltInQualityProfile profile3 = c.createBuiltInQualityProfile("Foo1", "xoo2"); - profile3.done(); - - assertThat(profile1).isNotNull(); - assertThat(profile1).isNotEqualTo(profile2); - assertThat(profile1).isNotEqualTo(profile3); - - assertThat(profile1.hashCode()).isNotEqualTo(profile2.hashCode()); - - assertThat(profile1.name()).isNotEqualTo("Foo"); - assertThat(profile1.toString()).hasToString("NewBuiltInQualityProfile{name='Foo1', language='xoo', default='false'}"); - assertThat(rule.toString()).hasToString("[repository=repo, key=rule]"); - }); - - BuiltInQualityProfile profile1 = profiles.get("xoo").get("Foo1"); - BuiltInQualityProfile profile2 = profiles.get("xoo").get("Foo2"); - BuiltInQualityProfile profile3 = profiles.get("xoo2").get("Foo1"); - - assertThat(profile1) - .isNotNull() - .isNotEqualTo(profile2) - .isNotEqualTo(profile3); - assertThat(profile1.hashCode()).isNotEqualTo(profile2.hashCode()); - - assertThat(profile1.name()).isNotEqualTo("Foo"); - assertThat(profile1.toString()).hasToString("BuiltInQualityProfile{name='Foo1', language='xoo', default='false'}"); - assertThat(profile1.rule(RuleKey.of("repo", "rule")).toString()).hasToString("[repository=repo, key=rule]"); - } - - @Test - public void createDefaultProfile() { - Map<String, Map<String, BuiltInQualityProfile>> profiles = define(c -> { - c.createBuiltInQualityProfile("Foo", "xoo") - .setDefault(true) - .done(); - }); - assertThat(profiles).containsOnlyKeys("xoo"); - assertThat(profiles.get("xoo")).containsOnlyKeys("Foo"); - BuiltInQualityProfile profile = profiles.get("xoo").get("Foo"); - assertThat(profile.name()).isEqualTo("Foo"); - assertThat(profile.language()).isEqualTo("xoo"); - assertThat(profile.isDefault()).isTrue(); - } - - @Test - public void duplicateProfile() { - assertThatThrownBy(() -> define(c -> { - c.createBuiltInQualityProfile("Foo", "xoo").done(); - c.createBuiltInQualityProfile("Foo", "xoo").done(); - })) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("There is already a quality profile with name 'Foo' for language 'xoo'"); - } - - @Test - public void createProfileWithRules() { - Map<String, Map<String, BuiltInQualityProfile>> profiles = define(c -> { - NewBuiltInQualityProfile profile = c.createBuiltInQualityProfile("Foo", "xoo"); - profile.activateRule("repo", "ruleWithoutParam"); - profile.activateRule("repo", "ruleWithSeverity").overrideSeverity("CRITICAL"); - profile.activateRule("repo", "ruleWithParam").overrideParam("param", "value"); - profile.done(); - }); - assertThat(profiles).containsOnlyKeys("xoo"); - assertThat(profiles.get("xoo")).containsOnlyKeys("Foo"); - BuiltInQualityProfile profile = profiles.get("xoo").get("Foo"); - assertThat(profile.name()).isEqualTo("Foo"); - assertThat(profile.language()).isEqualTo("xoo"); - assertThat(profile.isDefault()).isFalse(); - assertThat(profile.rules()) - .extracting(BuiltInQualityProfilesDefinition.BuiltInActiveRule::repoKey, BuiltInQualityProfilesDefinition.BuiltInActiveRule::ruleKey, - BuiltInQualityProfilesDefinition.BuiltInActiveRule::overriddenSeverity, r -> r.overriddenParams().size()) - .containsOnly( - tuple("repo", "ruleWithoutParam", null, 0), - tuple("repo", "ruleWithSeverity", "CRITICAL", 0), - tuple("repo", "ruleWithParam", null, 1)); - assertThat(profile.rule(RuleKey.of("repo", "ruleWithParam")).overriddenParam("param").key()).isEqualTo("param"); - assertThat(profile.rule(RuleKey.of("repo", "ruleWithParam")).overriddenParam("param").overriddenValue()).isEqualTo("value"); - } - - @Test - public void createProfileWithDuplicateRules() { - - define(c -> { - NewBuiltInQualityProfile profile = c.createBuiltInQualityProfile("Foo", "xoo"); - profile.activateRule("repo", "rule"); - - assertThatThrownBy(() -> profile.activateRule("repo", "rule")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The rule 'repo:rule' is already activated"); - }); - } - - private Map<String, Map<String, BuiltInQualityProfile>> define(Consumer<BuiltInQualityProfilesDefinition.Context> consumer) { - BuiltInQualityProfilesDefinition.Context context = new BuiltInQualityProfilesDefinition.Context(); - new FakeProfile(consumer).define(context); - return context.profilesByLanguageAndName(); - } - - private static class FakeProfile implements BuiltInQualityProfilesDefinition { - - private Consumer<Context> consumer; - - public FakeProfile(Consumer<Context> consumer) { - this.consumer = consumer; - } - - @Override - public void define(Context context) { - consumer.accept(context); - } - - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleParamTypeTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleParamTypeTest.java deleted file mode 100644 index 36b076bf208..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleParamTypeTest.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RuleParamTypeTest { - - @Test - public void testEquals() { - RuleParamType noOptions = RuleParamType.INTEGER; - RuleParamType withOptions1 = RuleParamType.singleListOfValues("one", "two"); - RuleParamType withOptions2 = RuleParamType.singleListOfValues("three", "four"); - - assertThat(RuleParamType.INTEGER) - .isEqualTo(RuleParamType.INTEGER) - .isNotEqualTo(RuleParamType.STRING) - .isNotEqualTo("INTEGER") - .isNotEqualTo(withOptions1) - .isNotNull(); - - assertThat(withOptions1) - .isEqualTo(withOptions1) - .isNotEqualTo(noOptions) - .isNotEqualTo(withOptions2) - .isNotEqualTo("SINGLE_SELECT_LIST,values=one,two,") - .isNotNull(); - } - - @Test - public void testHashCode() { - assertThat(RuleParamType.INTEGER).hasSameHashCodeAs(RuleParamType.INTEGER); - } - - @Test - public void testInteger() { - RuleParamType type = RuleParamType.INTEGER; - assertThat(type.toString()).isEqualTo("INTEGER"); - assertThat(RuleParamType.parse(type.toString()).type()).isEqualTo("INTEGER"); - assertThat(RuleParamType.parse(type.toString()).values()).isEmpty(); - assertThat(RuleParamType.parse(type.toString()).toString()).isEqualTo("INTEGER"); - } - - @Test - public void testListOfValues() { - RuleParamType selectList = RuleParamType.parse("SINGLE_SELECT_LIST,values=\"foo,bar\","); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "bar"); - assertThat(selectList.multiple()).isFalse(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,values=\"foo,bar,\""); - - selectList = RuleParamType.parse("SINGLE_SELECT_LIST,values=\"foo,bar\",multiple=false"); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "bar"); - assertThat(selectList.multiple()).isFalse(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,values=\"foo,bar,\""); - - selectList = RuleParamType.parse("SINGLE_SELECT_LIST,\"values=foo,bar\",multiple=false"); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "bar"); - assertThat(selectList.multiple()).isFalse(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,values=\"foo,bar,\""); - - // escape values - selectList = RuleParamType.singleListOfValues("foo", "one,two|three,four"); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "one,two|three,four"); - assertThat(selectList.multiple()).isFalse(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,values=\"foo,\"\"one,two|three,four\"\",\""); - } - - @Test - public void testMultipleListOfValues() { - RuleParamType selectList = RuleParamType.parse("SINGLE_SELECT_LIST,values=\"foo,bar\",multiple=true"); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "bar"); - assertThat(selectList.multiple()).isTrue(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,multiple=true,values=\"foo,bar,\""); - - selectList = RuleParamType.parse("SINGLE_SELECT_LIST,\"values=foo,bar\",multiple=true"); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "bar"); - assertThat(selectList.multiple()).isTrue(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,multiple=true,values=\"foo,bar,\""); - - // escape values - selectList = RuleParamType.multipleListOfValues("foo", "one,two|three,four"); - assertThat(selectList.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(selectList.values()).containsOnly("foo", "one,two|three,four"); - assertThat(selectList.multiple()).isTrue(); - assertThat(selectList.toString()).isEqualTo("SINGLE_SELECT_LIST,multiple=true,values=\"foo,\"\"one,two|three,four\"\",\""); - } - - @Test - public void support_deprecated_formats() { - assertThat(RuleParamType.parse("b")).isEqualTo(RuleParamType.BOOLEAN); - assertThat(RuleParamType.parse("i")).isEqualTo(RuleParamType.INTEGER); - assertThat(RuleParamType.parse("i{}")).isEqualTo(RuleParamType.INTEGER); - assertThat(RuleParamType.parse("s")).isEqualTo(RuleParamType.STRING); - assertThat(RuleParamType.parse("s{}")).isEqualTo(RuleParamType.STRING); - assertThat(RuleParamType.parse("r")).isEqualTo(RuleParamType.STRING); - assertThat(RuleParamType.parse("TEXT")).isEqualTo(RuleParamType.TEXT); - assertThat(RuleParamType.parse("STRING")).isEqualTo(RuleParamType.STRING); - assertThat(RuleParamType.parse("REGULAR_EXPRESSION")).isEqualTo(RuleParamType.STRING); - RuleParamType list = RuleParamType.parse("s[FOO,BAR]"); - assertThat(list.type()).isEqualTo("SINGLE_SELECT_LIST"); - assertThat(list.values()).containsOnly("FOO", "BAR"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleTagFormatTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleTagFormatTest.java deleted file mode 100644 index 8120a0e82e1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleTagFormatTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule; - -import java.util.Collections; -import org.junit.Test; - -import static java.util.Arrays.asList; -import static java.util.Collections.singletonList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class RuleTagFormatTest { - - @Test - public void isValid() { - assertThat(RuleTagFormat.isValid(null)).isFalse(); - assertThat(RuleTagFormat.isValid("")).isFalse(); - assertThat(RuleTagFormat.isValid(" ")).isFalse(); - assertThat(RuleTagFormat.isValid("coding style")).isFalse(); - assertThat(RuleTagFormat.isValid("Style")).isFalse(); - assertThat(RuleTagFormat.isValid("sTyle")).isFalse(); - assertThat(RuleTagFormat.isValid("@style")).isFalse(); - - assertThat(RuleTagFormat.isValid("style")).isTrue(); - assertThat(RuleTagFormat.isValid("c++")).isTrue(); - assertThat(RuleTagFormat.isValid("f#")).isTrue(); - assertThat(RuleTagFormat.isValid("c++11")).isTrue(); - assertThat(RuleTagFormat.isValid("c.d")).isTrue(); - } - - @Test - public void validate() { - RuleTagFormat.validate("style"); - // no error - } - - @Test - public void validate_and_fail() { - try { - RuleTagFormat.validate(" "); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Tag ' ' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); - } - } - - @Test - public void validate_and_sanitize_collection_of_tags() { - assertThat(RuleTagFormat.validate(asList("style", "coding-style", ""))).containsExactly("coding-style", "style"); - assertThat(RuleTagFormat.validate(asList("style", "coding-style", null))).containsExactly("coding-style", "style"); - assertThat(RuleTagFormat.validate(asList("style", "style", null))).containsExactly("style"); - assertThat(RuleTagFormat.validate(singletonList("Uppercase"))).containsExactly("uppercase"); - assertThat(RuleTagFormat.validate(Collections.emptyList())).isEmpty(); - } - - @Test - public void fail_to_validate_collection_of_tags() { - try { - RuleTagFormat.validate(asList("coding style", "Stylé", "valid")); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Tags 'coding style, stylé' are invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleTagsToTypeConverterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleTagsToTypeConverterTest.java deleted file mode 100644 index 42f2910c8ec..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RuleTagsToTypeConverterTest.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule; - -import java.util.Collections; -import org.junit.Test; -import org.sonar.api.rules.RuleType; -import org.sonar.api.utils.TestUtils; - -import static java.util.Arrays.asList; -import static org.assertj.core.api.Assertions.assertThat; -import static org.sonar.api.server.rule.RuleTagsToTypeConverter.convert; - -public class RuleTagsToTypeConverterTest { - - @Test - public void type_is_bug_if_has_tag_bug() { - assertThat(convert(asList("misra", "bug"))).isEqualTo(RuleType.BUG); - // "bug" has priority on "security" - assertThat(convert(asList("security", "bug"))).isEqualTo(RuleType.BUG); - } - - @Test - public void type_is_vulnerability_if_has_tag_security() { - assertThat(convert(asList("misra", "security"))).isEqualTo(RuleType.VULNERABILITY); - } - - @Test - public void default_is_code_smell() { - assertThat(convert(asList("clumsy", "spring"))).isEqualTo(RuleType.CODE_SMELL); - assertThat(convert(Collections.emptyList())).isEqualTo(RuleType.CODE_SMELL); - } - - @Test - public void only_statics() { - assertThat(TestUtils.hasOnlyPrivateConstructors(RuleTagsToTypeConverter.class)).isTrue(); - - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionAnnotationLoaderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionAnnotationLoaderTest.java deleted file mode 100644 index 884e6185999..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionAnnotationLoaderTest.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule; - -import org.junit.Test; -import org.sonar.api.impl.server.RulesDefinitionContext; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; -import org.sonar.api.server.rule.RulesDefinition.NewRule; -import org.sonar.check.Priority; - -import static org.assertj.core.api.Assertions.assertThat; - -public class RulesDefinitionAnnotationLoaderTest { - - - RulesDefinitionAnnotationLoader annotationLoader = new RulesDefinitionAnnotationLoader(); - - @Test - public void rule_with_property() { - RulesDefinition.Repository repository = load(RuleWithProperty.class); - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo("foo"); - assertThat(rule.status()).isEqualTo(RuleStatus.BETA); - assertThat(rule.name()).isEqualTo("bar"); - assertThat(rule.htmlDescription()).isEqualTo("Foo Bar"); - assertThat(rule.severity()).isEqualTo(Severity.BLOCKER); - assertThat(rule.params()).hasSize(1); - assertThat(rule.tags()).isEmpty(); - - RulesDefinition.Param prop = rule.param("property"); - assertThat(prop.key()).isEqualTo("property"); - assertThat(prop.description()).isEqualTo("Ignore ?"); - assertThat(prop.defaultValue()).isEqualTo("false"); - assertThat(prop.type()).isEqualTo(RuleParamType.STRING); - } - - @Test - public void override_annotation_programmatically() { - RulesDefinition.Context context = new RulesDefinitionContext(); - RulesDefinition.NewRepository newRepository = context.createRepository("squid", "java"); - NewRule newRule = annotationLoader.loadRule(newRepository, RuleWithProperty.class); - newRule.setName("Overridden name"); - newRule.param("property").setDefaultValue("true"); - newRule.param("property").setDescription("Overridden"); - newRepository.done(); - - RulesDefinition.Repository repository = context.repository("squid"); - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo("foo"); - assertThat(rule.status()).isEqualTo(RuleStatus.BETA); - assertThat(rule.name()).isEqualTo("Overridden name"); - assertThat(rule.htmlDescription()).isEqualTo("Foo Bar"); - assertThat(rule.severity()).isEqualTo(Severity.BLOCKER); - assertThat(rule.params()).hasSize(1); - - RulesDefinition.Param prop = rule.param("property"); - assertThat(prop.key()).isEqualTo("property"); - assertThat(prop.description()).isEqualTo("Overridden"); - assertThat(prop.defaultValue()).isEqualTo("true"); - assertThat(prop.type()).isEqualTo(RuleParamType.STRING); - } - - @Test - public void rule_with_integer_property() { - RulesDefinition.Repository repository = load(RuleWithIntegerProperty.class); - - RulesDefinition.Param prop = repository.rules().get(0).param("property"); - assertThat(prop.description()).isEqualTo("Max"); - assertThat(prop.defaultValue()).isEqualTo("12"); - assertThat(prop.type()).isEqualTo(RuleParamType.INTEGER); - } - - @Test - public void rule_with_text_property() { - RulesDefinition.Repository repository = load(RuleWithTextProperty.class); - - RulesDefinition.Param prop = repository.rules().get(0).param("property"); - assertThat(prop.description()).isEqualTo("text"); - assertThat(prop.defaultValue()).isEqualTo("Long text"); - assertThat(prop.type()).isEqualTo(RuleParamType.TEXT); - } - - @Test - public void should_recognize_type() { - assertThat(RulesDefinitionAnnotationLoader.guessType(Integer.class)).isEqualTo(RuleParamType.INTEGER); - assertThat(RulesDefinitionAnnotationLoader.guessType(int.class)).isEqualTo(RuleParamType.INTEGER); - assertThat(RulesDefinitionAnnotationLoader.guessType(Float.class)).isEqualTo(RuleParamType.FLOAT); - assertThat(RulesDefinitionAnnotationLoader.guessType(float.class)).isEqualTo(RuleParamType.FLOAT); - assertThat(RulesDefinitionAnnotationLoader.guessType(Boolean.class)).isEqualTo(RuleParamType.BOOLEAN); - assertThat(RulesDefinitionAnnotationLoader.guessType(boolean.class)).isEqualTo(RuleParamType.BOOLEAN); - assertThat(RulesDefinitionAnnotationLoader.guessType(String.class)).isEqualTo(RuleParamType.STRING); - assertThat(RulesDefinitionAnnotationLoader.guessType(Object.class)).isEqualTo(RuleParamType.STRING); - } - - @Test - public void use_classname_when_missing_key() { - RulesDefinition.Repository repository = load(RuleWithoutKey.class); - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo(RuleWithoutKey.class.getCanonicalName()); - assertThat(rule.name()).isEqualTo("foo"); - } - - @Test - public void rule_with_tags() { - RulesDefinition.Repository repository = load(RuleWithTags.class); - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.tags()).containsOnly("misra", "clumsy"); - } - - @Test - public void overridden_class() { - RulesDefinition.Repository repository = load(OverridingRule.class); - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo("overriding_foo"); - assertThat(rule.name()).isEqualTo("Overriding Foo"); - assertThat(rule.severity()).isEqualTo(Severity.MAJOR); - assertThat(rule.htmlDescription()).isEqualTo("Desc of Overriding Foo"); - assertThat(rule.params()).hasSize(2); - } - - private RulesDefinition.Repository load(Class annotatedClass) { - RulesDefinition.Context context = new RulesDefinitionContext(); - RulesDefinition.NewExtendedRepository newRepository = context.createRepository("squid", "java"); - annotationLoader.load(newRepository, annotatedClass); - newRepository.done(); - return context.repository("squid"); - } - - @org.sonar.check.Rule(name = "foo", description = "Foo") - static class RuleWithoutKey { - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", priority = Priority.BLOCKER, status = "BETA") - static class RuleWithProperty { - @org.sonar.check.RuleProperty(description = "Ignore ?", defaultValue = "false") - private String property; - } - - @org.sonar.check.Rule(key = "overriding_foo", name = "Overriding Foo", description = "Desc of Overriding Foo") - static class OverridingRule extends RuleWithProperty { - @org.sonar.check.RuleProperty - private String additionalProperty; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", priority = Priority.BLOCKER) - static class RuleWithIntegerProperty { - @org.sonar.check.RuleProperty(description = "Max", defaultValue = "12") - private Integer property; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", priority = Priority.BLOCKER) - static class RuleWithTextProperty { - @org.sonar.check.RuleProperty(description = "text", defaultValue = "Long text", type = "TEXT") - protected String property; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Foo Bar", priority = Priority.BLOCKER) - static class RuleWithInvalidPropertyType { - @org.sonar.check.RuleProperty(description = "text", defaultValue = "Long text", type = "INVALID") - public String property; - } - - @org.sonar.check.Rule(key = "foo", name = "bar", description = "Bar", tags = {"misra", "clumsy"}) - static class RuleWithTags { - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionTest.java deleted file mode 100644 index fc8d783272d..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionTest.java +++ /dev/null @@ -1,595 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Ordering; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; -import java.net.URL; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.sonar.api.impl.server.RulesDefinitionContext; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleScope; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RuleType; -import org.sonar.api.server.debt.DebtRemediationFunction; -import org.sonar.api.utils.log.LogTester; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.fail; - -@RunWith(DataProviderRunner.class) -public class RulesDefinitionTest { - - RulesDefinition.Context context = new RulesDefinitionContext(); - - @Rule - public LogTester logTester = new LogTester(); - - @Test - public void define_repositories() { - assertThat(context.repositories()).isEmpty(); - - context.createRepository("findbugs", "java").setName("Findbugs").done(); - context.createRepository("checkstyle", "java").done(); - - assertThat(context.repositories()).hasSize(2); - RulesDefinition.Repository findbugs = context.repository("findbugs"); - assertThat(findbugs).isNotNull(); - assertThat(findbugs.key()).isEqualTo("findbugs"); - assertThat(findbugs.language()).isEqualTo("java"); - assertThat(findbugs.name()).isEqualTo("Findbugs"); - assertThat(findbugs.rules()).isEmpty(); - RulesDefinition.Repository checkstyle = context.repository("checkstyle"); - assertThat(checkstyle).isNotNull(); - assertThat(checkstyle.key()).isEqualTo("checkstyle"); - assertThat(checkstyle.language()).isEqualTo("java"); - - // default name is key - assertThat(checkstyle.name()).isEqualTo("checkstyle"); - assertThat(checkstyle.rules()).isEmpty(); - assertThat(context.repository("unknown")).isNull(); - } - - @Test - public void override_sonaranalyzer_repositories_name() { - context.createRepository("k", "java").setName("SonarAnalyzer").done(); - RulesDefinition.Repository repo = context.repository("k"); - assertThat(repo).isNotNull(); - assertThat(repo.name()).isEqualTo("SonarQube"); - } - - @Test - public void define_rules() { - RulesDefinition.NewRepository newRepo = context.createRepository("findbugs", "java"); - newRepo.createRule("NPE") - .setName("Detect NPE") - .setHtmlDescription("Detect <code>java.lang.NullPointerException</code>") - .setSeverity(Severity.BLOCKER) - .setInternalKey("/something") - .setStatus(RuleStatus.BETA) - .setTags("one", "two") - .setScope(RuleScope.ALL) - .addOwaspTop10(RulesDefinition.OwaspTop10.A1, RulesDefinition.OwaspTop10.A3) - .addCwe(1, 2, 123) - .addTags("two", "three", "four"); - - newRepo.createRule("ABC").setName("ABC").setMarkdownDescription("ABC"); - newRepo.done(); - - RulesDefinition.Repository repo = context.repository("findbugs"); - assertThat(repo.rules()).hasSize(2); - assertThat(repo.isExternal()).isFalse(); - - RulesDefinition.Rule rule = repo.rule("NPE"); - assertThat(rule).isNotNull(); - assertThat(rule.scope()).isEqualTo(RuleScope.ALL); - assertThat(rule.key()).isEqualTo("NPE"); - assertThat(rule.name()).isEqualTo("Detect NPE"); - assertThat(rule.severity()).isEqualTo(Severity.BLOCKER); - assertThat(rule.htmlDescription()).isEqualTo("Detect <code>java.lang.NullPointerException</code>"); - assertThat(rule.markdownDescription()).isNull(); - assertThat(rule.tags()).containsOnly("one", "two", "three", "four"); - assertThat(rule.securityStandards()).containsOnly("cwe:1", "cwe:123", "cwe:2", "owaspTop10:a1", "owaspTop10:a3"); - assertThat(rule.params()).isEmpty(); - assertThat(rule.internalKey()).isEqualTo("/something"); - assertThat(rule.template()).isFalse(); - assertThat(rule.status()).isEqualTo(RuleStatus.BETA); - assertThat(rule.toString()).hasToString("[repository=findbugs, key=NPE]"); - assertThat(rule.repository()).isSameAs(repo); - - RulesDefinition.Rule otherRule = repo.rule("ABC"); - assertThat(otherRule.htmlDescription()).isNull(); - assertThat(otherRule.markdownDescription()).isEqualTo("ABC"); - } - - @Test - public void define_rules_with_remediation_function() { - RulesDefinition.NewRepository newRepo = context.createRepository("common-java", "java"); - RulesDefinition.NewRule newRule = newRepo.createRule("InsufficientBranchCoverage") - .setName("Insufficient condition coverage") - .setHtmlDescription("Insufficient condition coverage by unit tests") - .setSeverity(Severity.MAJOR) - .setGapDescription("Effort to test one uncovered branch"); - newRule.setDebtRemediationFunction(newRule.debtRemediationFunctions().linearWithOffset("1h", "10min")); - newRepo.done(); - - RulesDefinition.Repository repo = context.repository("common-java"); - assertThat(repo.rules()).hasSize(1); - - RulesDefinition.Rule rule = repo.rule("InsufficientBranchCoverage"); - assertThat(rule.debtRemediationFunction().type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET); - assertThat(rule.debtRemediationFunction().gapMultiplier()).isEqualTo("1h"); - assertThat(rule.debtRemediationFunction().baseEffort()).isEqualTo("10min"); - assertThat(rule.gapDescription()).isEqualTo("Effort to test one uncovered branch"); - } - - @Test - public void define_rule_with_default_fields() { - RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java"); - newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE"); - newFindbugs.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.key()).isEqualTo("NPE"); - assertThat(rule.severity()).isEqualTo(Severity.MAJOR); - assertThat(rule.params()).isEmpty(); - assertThat(rule.internalKey()).isNull(); - assertThat(rule.status()).isEqualTo(RuleStatus.defaultStatus()); - assertThat(rule.tags()).isEmpty(); - assertThat(rule.securityStandards()).isEmpty(); - assertThat(rule.debtRemediationFunction()).isNull(); - } - - @Test - public void define_external_rules() { - RulesDefinition.NewRepository newRepo = context.createExternalRepository("eslint", "js"); - newRepo.createRule("NPE") - .setName("Detect NPE") - .setHtmlDescription("Detect <code>java.lang.NullPointerException</code>") - .setSeverity(Severity.BLOCKER) - .setInternalKey("/something") - .setStatus(RuleStatus.BETA) - .setTags("one", "two") - .setScope(RuleScope.ALL) - .addOwaspTop10(RulesDefinition.OwaspTop10.A1, RulesDefinition.OwaspTop10.A3) - .addCwe(1, 2, 123) - .addTags("two", "three", "four"); - - newRepo.createRule("ABC").setName("ABC").setMarkdownDescription("ABC"); - newRepo.done(); - - assertThat(context.repository("eslint")).isNull(); - RulesDefinition.Repository repo = context.repository("external_eslint"); - assertThat(repo.rules()).hasSize(2); - assertThat(repo.isExternal()).isTrue(); - - RulesDefinition.Rule rule = repo.rule("NPE"); - assertThat(rule).isNotNull(); - assertThat(rule.scope()).isEqualTo(RuleScope.ALL); - assertThat(rule.key()).isEqualTo("NPE"); - assertThat(rule.name()).isEqualTo("Detect NPE"); - assertThat(rule.severity()).isEqualTo(Severity.BLOCKER); - assertThat(rule.htmlDescription()).isEqualTo("Detect <code>java.lang.NullPointerException</code>"); - assertThat(rule.markdownDescription()).isNull(); - assertThat(rule.tags()).containsOnly("one", "two", "three", "four"); - assertThat(rule.securityStandards()).containsOnly("cwe:1", "cwe:123", "cwe:2", "owaspTop10:a1", "owaspTop10:a3"); - assertThat(rule.params()).isEmpty(); - assertThat(rule.internalKey()).isEqualTo("/something"); - assertThat(rule.template()).isFalse(); - assertThat(rule.status()).isEqualTo(RuleStatus.BETA); - assertThat(rule.toString()).hasToString("[repository=external_eslint, key=NPE]"); - assertThat(rule.repository()).isSameAs(repo); - - RulesDefinition.Rule otherRule = repo.rule("ABC"); - assertThat(otherRule.htmlDescription()).isNull(); - assertThat(otherRule.markdownDescription()).isEqualTo("ABC"); - } - - @Test - public void define_rule_parameters() { - RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java"); - RulesDefinition.NewRule newNpe = newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE"); - newNpe.createParam("level").setDefaultValue("LOW").setName("Level").setDescription("The level").setType(RuleParamType.INTEGER); - newNpe.createParam("effort"); - newFindbugs.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.params()).hasSize(2); - - RulesDefinition.Param level = rule.param("level"); - assertThat(level).isNotNull(); - assertThat(level.key()).isEqualTo("level"); - assertThat(level.name()).isEqualTo("Level"); - assertThat(level.description()).isEqualTo("The level"); - assertThat(level.defaultValue()).isEqualTo("LOW"); - assertThat(level.type()).isEqualTo(RuleParamType.INTEGER); - - RulesDefinition.Param effort = rule.param("effort"); - assertThat(effort.key()).isEqualTo("effort").isEqualTo(effort.name()); - assertThat(effort.description()).isNull(); - assertThat(effort.defaultValue()).isNull(); - assertThat(effort.type()).isEqualTo(RuleParamType.STRING); - } - - @Test - public void define_rule_parameter_with_empty_default_value() { - RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java"); - RulesDefinition.NewRule newNpe = newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE"); - newNpe.createParam("level").setDefaultValue("").setName("Level").setDescription("The level").setType(RuleParamType.INTEGER); - newFindbugs.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.params()).hasSize(1); - - RulesDefinition.Param level = rule.param("level"); - assertThat(level.key()).isEqualTo("level"); - assertThat(level.name()).isEqualTo("Level"); - assertThat(level.description()).isEqualTo("The level"); - // Empty value is converted in null value - assertThat(level.defaultValue()).isNull(); - assertThat(level.type()).isEqualTo(RuleParamType.INTEGER); - } - - @Test - @UseDataProvider("nullOrEmpty") - public void addDeprecatedRuleKey_fails_with_IAE_if_repository_is_null_or_empty(String nullOrEmpty) { - RulesDefinition.NewRepository newRepository = context.createRepository("foo", "bar"); - RulesDefinition.NewRule newRule = newRepository.createRule("doh"); - - assertThatThrownBy(() -> newRule.addDeprecatedRuleKey(nullOrEmpty, "oldKey")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Repository must be set"); - } - - @Test - @UseDataProvider("nullOrEmpty") - public void addDeprecatedRuleKey_fails_with_IAE_if_key_is_null_or_empty(String nullOrEmpty) { - RulesDefinition.NewRepository newRepository = context.createRepository("foo", "bar"); - RulesDefinition.NewRule newRule = newRepository.createRule("doh"); - - assertThatThrownBy(() -> newRule.addDeprecatedRuleKey("oldRepo", nullOrEmpty)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Rule must be set"); - } - - @DataProvider - public static Object[][] nullOrEmpty() { - return new Object[][]{ - {null}, - {""} - }; - } - - @Test - public void getDeprecatedKeys_returns_empty_if_addDeprecatedKeys_never_called() { - String repositoryKey = "foo"; - String ruleKey = "doh"; - RulesDefinition.NewRepository newRepository = context.createRepository(repositoryKey, "bar"); - newRepository.createRule(ruleKey) - .setName("doh rule") - .setHtmlDescription("doh description"); - newRepository.done(); - RulesDefinition.Repository repository = context.repository(repositoryKey); - RulesDefinition.Rule rule = repository.rule(ruleKey); - - assertThat(rule.deprecatedRuleKeys()).isEmpty(); - } - - @Test - public void getDeprecatedKeys_returns_keys_in_order_of_addDeprecatedKeys_calls() { - Set<RuleKey> ruleKeys = ImmutableSet.of(RuleKey.of("foo", "AAA"), - RuleKey.of("bar", "CCCC"), RuleKey.of("doh", "CCCC"), RuleKey.of("foo", "BBBBBBBBBB")); - List<RuleKey> sortedRuleKeys = ruleKeys.stream().sorted(Ordering.natural().onResultOf(RuleKey::toString)).collect(Collectors.toList()); - - // ensure we don't have the same order - Assume.assumeTrue(!ImmutableList.copyOf(ruleKeys).equals(sortedRuleKeys)); - - String repositoryKey = "foo"; - String ruleKey = "doh"; - RulesDefinition.NewRepository newRepository = context.createRepository(repositoryKey, "bar"); - RulesDefinition.NewRule newRule = newRepository.createRule(ruleKey) - .setName("doh rule") - .setHtmlDescription("doh description"); - sortedRuleKeys.forEach(r -> newRule.addDeprecatedRuleKey(r.repository(), r.rule())); - newRepository.done(); - RulesDefinition.Repository repository = context.repository(repositoryKey); - RulesDefinition.Rule rule = repository.rule(ruleKey); - - assertThat(ImmutableList.copyOf(rule.deprecatedRuleKeys())) - .isEqualTo(sortedRuleKeys); - } - - @Test - public void getDeprecatedKeys_does_not_return_the_same_key_more_than_once() { - RuleKey duplicatedRuleKey = RuleKey.of("foo", "AAA"); - RuleKey ruleKey2 = RuleKey.of("bar", "CCCC"); - RuleKey ruleKey3 = RuleKey.of("foo", "BBBBBBBBBB"); - List<RuleKey> ruleKeys = ImmutableList.of(duplicatedRuleKey, ruleKey2, duplicatedRuleKey, duplicatedRuleKey, ruleKey3); - - String repositoryKey = "foo"; - String ruleKey = "doh"; - RulesDefinition.NewRepository newRepository = context.createRepository(repositoryKey, "bar"); - RulesDefinition.NewRule newRule = newRepository.createRule(ruleKey) - .setName("doh rule") - .setHtmlDescription("doh description"); - ruleKeys.forEach(r -> newRule.addDeprecatedRuleKey(r.repository(), r.rule())); - newRepository.done(); - RulesDefinition.Repository repository = context.repository(repositoryKey); - RulesDefinition.Rule rule = repository.rule(ruleKey); - - assertThat(rule.deprecatedRuleKeys()) - .containsExactly(ruleKey2, duplicatedRuleKey, ruleKey3); - } - - @Test - public void sanitize_rule_name() { - RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java"); - newFindbugs.createRule("NPE").setName(" \n NullPointer \n ").setHtmlDescription("NPE"); - newFindbugs.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.name()).isEqualTo("NullPointer"); - } - - @Test - public void default_scope_should_be_main() { - RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java"); - newFindbugs.createRule("key").setName("name").setHtmlDescription("NPE"); - newFindbugs.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("key"); - assertThat(rule.scope()).isEqualTo(RuleScope.MAIN); - } - - @Test - public void add_rules_to_existing_repository() { - RulesDefinition.NewRepository newFindbugs = context.createRepository("findbugs", "java").setName("Findbugs"); - newFindbugs.createRule("NPE").setName("NPE").setHtmlDescription("NPE"); - newFindbugs.done(); - - RulesDefinition.NewRepository newFbContrib = context.createRepository("findbugs", "java"); - newFbContrib.createRule("VULNERABILITY").setName("Vulnerability").setMarkdownDescription("Detect vulnerability"); - newFbContrib.done(); - - assertThat(context.repositories()).hasSize(1); - RulesDefinition.Repository findbugs = context.repository("findbugs"); - assertThat(findbugs.key()).isEqualTo("findbugs"); - assertThat(findbugs.language()).isEqualTo("java"); - assertThat(findbugs.name()).isEqualTo("Findbugs"); - assertThat(findbugs.rules()).extracting("key").containsOnly("NPE", "VULNERABILITY"); - } - - /** - * This is temporarily accepted only for the support of the common-rules that are still declared - * by plugins. It could be removed in 7.0 - * - * @since 5.2 - */ - @Test - public void allow_to_replace_an_existing_common_rule() { - RulesDefinition.NewRepository newCommonJava1 = context.createRepository("common-java", "java").setName("Common Java"); - newCommonJava1.createRule("coverage").setName("Lack of coverage").setHtmlDescription("Coverage must be high"); - newCommonJava1.done(); - - RulesDefinition.NewRepository newCommonJava2 = context.createRepository("common-java", "java"); - newCommonJava2.createRule("coverage").setName("Lack of coverage (V2)").setMarkdownDescription("Coverage must be high (V2)"); - newCommonJava2.done(); - - RulesDefinition.Repository commonJava = context.repository("common-java"); - assertThat(commonJava.rules()).hasSize(1); - RulesDefinition.Rule rule = commonJava.rule("coverage"); - assertThat(rule.name()).isEqualTo("Lack of coverage (V2)"); - - // replacement but not merge -> keep only the v2 (which has markdown but not html description) - assertThat(rule.markdownDescription()).isEqualTo("Coverage must be high (V2)"); - assertThat(rule.htmlDescription()).isNull(); - - // do not log warning - assertThat(logTester.logs()).isEmpty(); - } - - @Test - public void cant_set_blank_repository_name() { - context.createRepository("findbugs", "java").setName(null).done(); - - assertThat(context.repository("findbugs").name()).isEqualTo("findbugs"); - } - - @Test - public void fail_if_duplicated_rule_keys_in_the_same_repository() { - RulesDefinition.NewRepository findbugs = context.createRepository("findbugs", "java"); - findbugs.createRule("NPE"); - - assertThatThrownBy(() -> findbugs.createRule("NPE")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_duplicated_rule_param_keys() { - RulesDefinition.NewRule rule = context.createRepository("findbugs", "java").createRule("NPE"); - rule.createParam("level"); - try { - rule.createParam("level"); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("The parameter 'level' is declared several times on the rule [repository=findbugs, key=NPE]"); - } - } - - @Test - public void fail_if_blank_rule_name() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName(null).setHtmlDescription("NPE"); - try { - newRepository.done(); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalStateException.class).hasMessage("Name of rule [repository=findbugs, key=NPE] is empty"); - } - } - - @Test - public void fail_if_bad_rule_tag() { - try { - // whitespaces are not allowed in tags - context.createRepository("findbugs", "java").createRule("NPE").setTags("coding style"); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class) - .hasMessage("Tag 'coding style' is invalid. Rule tags accept only the characters: a-z, 0-9, '+', '-', '#', '.'"); - } - } - - @Test - public void load_rule_html_description_from_file() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE").setHtmlDescription(getClass().getResource("/org/sonar/api/server/rule/RulesDefinitionTest/sample.html")); - newRepository.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.htmlDescription()).isEqualTo("description of rule loaded from file"); - } - - @Test - public void load_rule_markdown_description_from_file() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE").setMarkdownDescription(getClass().getResource("/org/sonar/api/server/rule/RulesDefinitionTest/sample.md")); - newRepository.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.markdownDescription()).isEqualTo("description of rule loaded from file"); - } - - @Test - public void fail_to_load_html_rule_description_from_file() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE").setHtmlDescription((URL) null); - try { - newRepository.done(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("One of HTML description or Markdown description must be defined for rule [repository=findbugs, key=NPE]"); - } - } - - @Test - public void fail_to_load_markdown_rule_description_from_file() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE").setMarkdownDescription((URL) null); - try { - newRepository.done(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("One of HTML description or Markdown description must be defined for rule [repository=findbugs, key=NPE]"); - } - } - - @Test - public void fail_if_no_rule_description() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE"); - try { - newRepository.done(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("One of HTML description or Markdown description must be defined for rule [repository=findbugs, key=NPE]"); - } - } - - @Test - public void fail_if_rule_already_has_html_description() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - try { - newRepository.createRule("NPE").setName("NPE").setHtmlDescription("polop").setMarkdownDescription("palap"); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Rule '[repository=findbugs, key=NPE]' already has an HTML description"); - } - } - - @Test - public void fail_if_rule_already_has_markdown_description() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - try { - newRepository.createRule("NPE").setName("NPE").setMarkdownDescription("palap").setHtmlDescription("polop"); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Rule '[repository=findbugs, key=NPE]' already has a Markdown description"); - } - } - - @Test - public void fail_if_bad_rule_severity() { - try { - context.createRepository("findbugs", "java").createRule("NPE").setSeverity("VERY HIGH"); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Severity of rule [repository=findbugs, key=NPE] is not correct: VERY HIGH"); - } - } - - @Test - public void fail_if_removed_status() { - try { - context.createRepository("findbugs", "java").createRule("NPE").setStatus(RuleStatus.REMOVED); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Status 'REMOVED' is not accepted on rule '[repository=findbugs, key=NPE]'"); - } - } - - @Test - public void type_is_defined() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE").setHtmlDescription("desc") - .setType(RuleType.VULNERABILITY).setTags("bug", "misra"); - newRepository.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - // type VULNERABILITY is kept even if the tag "bug" is present - assertThat(rule.type()).isEqualTo(RuleType.VULNERABILITY); - // tag "bug" is reserved and removed. - assertThat(rule.tags()).containsOnly("misra"); - } - - @Test - public void guess_type_from_tags_if_type_is_missing() { - RulesDefinition.NewRepository newRepository = context.createRepository("findbugs", "java"); - newRepository.createRule("NPE").setName("NPE").setHtmlDescription("desc").setTags("bug", "misra"); - newRepository.done(); - - RulesDefinition.Rule rule = context.repository("findbugs").rule("NPE"); - assertThat(rule.type()).isEqualTo(RuleType.BUG); - // tag "bug" is reserved and removed - assertThat(rule.tags()).containsOnly("misra"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest.java deleted file mode 100644 index 89dcb919e2f..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest.java +++ /dev/null @@ -1,302 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule; - -import java.io.InputStream; -import java.io.StringReader; -import java.nio.charset.StandardCharsets; -import org.apache.commons.io.IOUtils; -import org.junit.Test; -import org.sonar.api.impl.server.RulesDefinitionContext; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rule.Severity; -import org.sonar.api.rules.RuleType; -import org.sonar.api.server.debt.DebtRemediationFunction; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class RulesDefinitionXmlLoaderTest { - - RulesDefinitionXmlLoader underTest = new RulesDefinitionXmlLoader(); - - @Test - public void parse_xml() { - InputStream input = getClass().getResourceAsStream("RulesDefinitionXmlLoaderTest/rules.xml"); - RulesDefinition.Repository repository = load(input, StandardCharsets.UTF_8.name()); - assertThat(repository.rules()).hasSize(2); - - RulesDefinition.Rule rule = repository.rule("complete"); - assertThat(rule.key()).isEqualTo("complete"); - assertThat(rule.name()).isEqualTo("Complete"); - assertThat(rule.htmlDescription()).isEqualTo("Description of Complete"); - assertThat(rule.severity()).isEqualTo(Severity.BLOCKER); - assertThat(rule.template()).isTrue(); - assertThat(rule.status()).isEqualTo(RuleStatus.BETA); - assertThat(rule.internalKey()).isEqualTo("Checker/TreeWalker/LocalVariableName"); - assertThat(rule.type()).isEqualTo(RuleType.BUG); - assertThat(rule.tags()).containsOnly("misra", "spring"); - - assertThat(rule.params()).hasSize(2); - RulesDefinition.Param ignore = rule.param("ignore"); - assertThat(ignore.key()).isEqualTo("ignore"); - assertThat(ignore.description()).isEqualTo("Ignore ?"); - assertThat(ignore.defaultValue()).isEqualTo("false"); - - rule = repository.rule("minimal"); - assertThat(rule.key()).isEqualTo("minimal"); - assertThat(rule.name()).isEqualTo("Minimal"); - assertThat(rule.htmlDescription()).isEqualTo("Description of Minimal"); - assertThat(rule.params()).isEmpty(); - assertThat(rule.status()).isEqualTo(RuleStatus.READY); - assertThat(rule.severity()).isEqualTo(Severity.MAJOR); - assertThat(rule.type()).isEqualTo(RuleType.CODE_SMELL); - } - - @Test - public void fail_if_missing_rule_key() { - assertThatThrownBy(() -> load(IOUtils.toInputStream("<rules><rule><name>Foo</name></rule></rules>"), StandardCharsets.UTF_8.name())) - .isInstanceOf(IllegalStateException.class); - } - - @Test - public void fail_if_missing_property_key() { - assertThatThrownBy(() -> load(IOUtils.toInputStream("<rules><rule><key>foo</key><name>Foo</name><param></param></rule></rules>"), - StandardCharsets.UTF_8.name())) - .isInstanceOf(IllegalStateException.class); - } - - @Test - public void fail_on_invalid_rule_parameter_type() { - assertThatThrownBy(() -> load(IOUtils.toInputStream("<rules><rule><key>foo</key><name>Foo</name><param><key>key</key><type>INVALID</type></param></rule></rules>"), - StandardCharsets.UTF_8.name())) - .isInstanceOf(IllegalStateException.class); - } - - @Test - public void fail_if_invalid_xml() { - InputStream input = getClass().getResourceAsStream("RulesDefinitionXmlLoaderTest/invalid.xml"); - - assertThatThrownBy(() -> load(input, StandardCharsets.UTF_8.name())) - .isInstanceOf(IllegalStateException.class) - .hasMessage("XML is not valid"); - } - - @Test - public void test_utf8_encoding() { - InputStream input = getClass().getResourceAsStream("RulesDefinitionXmlLoaderTest/utf8.xml"); - RulesDefinition.Repository repository = load(input, StandardCharsets.UTF_8.name()); - - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo("com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck"); - assertThat(rule.name()).isEqualTo("M & M"); - assertThat(rule.htmlDescription().charAt(0)).isEqualTo('\u00E9'); - assertThat(rule.htmlDescription().charAt(1)).isEqualTo('\u00E0'); - assertThat(rule.htmlDescription().charAt(2)).isEqualTo('\u0026'); - } - - @Test - public void test_utf8_encoding_with_bom() { - InputStream input = getClass().getResourceAsStream("RulesDefinitionXmlLoaderTest/utf8-with-bom.xml"); - RulesDefinition.Repository repository = load(input, StandardCharsets.UTF_8.name()); - - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo("com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck"); - assertThat(rule.name()).isEqualTo("M & M"); - assertThat(rule.htmlDescription().charAt(0)).isEqualTo('\u00E9'); - assertThat(rule.htmlDescription().charAt(1)).isEqualTo('\u00E0'); - assertThat(rule.htmlDescription().charAt(2)).isEqualTo('\u0026'); - } - - @Test - public void support_deprecated_format() { - // the deprecated format uses some attributes instead of nodes - InputStream input = getClass().getResourceAsStream("RulesDefinitionXmlLoaderTest/deprecated.xml"); - RulesDefinition.Repository repository = load(input, StandardCharsets.UTF_8.name()); - - assertThat(repository.rules()).hasSize(1); - RulesDefinition.Rule rule = repository.rules().get(0); - assertThat(rule.key()).isEqualTo("org.sonar.it.checkstyle.MethodsCountCheck"); - assertThat(rule.internalKey()).isEqualTo("Checker/TreeWalker/org.sonar.it.checkstyle.MethodsCountCheck"); - assertThat(rule.severity()).isEqualTo(Severity.CRITICAL); - assertThat(rule.htmlDescription()).isEqualTo("Count methods"); - assertThat(rule.param("minMethodsCount")).isNotNull(); - } - - @Test - public void test_linear_remediation_function() { - String xml = "" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - - " <gapDescription>lines</gapDescription>" + - " <remediationFunction>LINEAR</remediationFunction>" + - " <remediationFunctionGapMultiplier>2d 3h</remediationFunctionGapMultiplier>" + - " </rule>" + - "</rules>"; - RulesDefinition.Rule rule = load(xml).rule("1"); - assertThat(rule.gapDescription()).isEqualTo("lines"); - DebtRemediationFunction function = rule.debtRemediationFunction(); - assertThat(function).isNotNull(); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR); - assertThat(function.gapMultiplier()).isEqualTo("2d3h"); - assertThat(function.baseEffort()).isNull(); - } - - @Test - public void test_linear_with_offset_remediation_function() { - String xml = "" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - - " <effortToFixDescription>lines</effortToFixDescription>" + - " <remediationFunction>LINEAR_OFFSET</remediationFunction>" + - " <remediationFunctionGapMultiplier>2d 3h</remediationFunctionGapMultiplier>" + - " <remediationFunctionBaseEffort>5min</remediationFunctionBaseEffort>" + - " </rule>" + - "</rules>"; - RulesDefinition.Rule rule = load(xml).rule("1"); - assertThat(rule.gapDescription()).isEqualTo("lines"); - DebtRemediationFunction function = rule.debtRemediationFunction(); - assertThat(function).isNotNull(); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET); - assertThat(function.gapMultiplier()).isEqualTo("2d3h"); - assertThat(function.baseEffort()).isEqualTo("5min"); - } - - @Test - public void test_constant_remediation_function() { - String xml = "" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - " <remediationFunction>CONSTANT_ISSUE</remediationFunction>" + - " <remediationFunctionBaseEffort>5min</remediationFunctionBaseEffort>" + - " </rule>" + - "</rules>"; - RulesDefinition.Rule rule = load(xml).rule("1"); - DebtRemediationFunction function = rule.debtRemediationFunction(); - assertThat(function).isNotNull(); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.CONSTANT_ISSUE); - assertThat(function.gapMultiplier()).isNull(); - assertThat(function.baseEffort()).isEqualTo("5min"); - } - - @Test - public void fail_if_invalid_remediation_function() { - assertThatThrownBy(() -> load("" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - " <remediationFunction>UNKNOWN</remediationFunction>" + - " </rule>" + - "</rules>")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Fail to load the rule with key [squid:1]") - .hasCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("No enum constant org.sonar.api.server.debt.DebtRemediationFunction.Type.UNKNOWN"); - } - - @Test - public void markdown_description() { - String xml = "" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - " <descriptionFormat>MARKDOWN</descriptionFormat>" + - " </rule>" + - "</rules>"; - RulesDefinition.Rule rule = load(xml).rule("1"); - assertThat(rule.markdownDescription()).isEqualTo("Desc"); - assertThat(rule.htmlDescription()).isNull(); - } - - @Test - public void fail_if_unsupported_description_format() { - String xml = "" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - " <descriptionFormat>UNKNOWN</descriptionFormat>" + - " </rule>" + - "</rules>"; - - assertThatThrownBy(() -> load(xml).rule("1")) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Fail to load the rule with key [squid:1]") - .hasCauseInstanceOf(IllegalArgumentException.class) - .hasRootCauseMessage("No enum constant org.sonar.api.server.rule.RulesDefinitionXmlLoader.DescriptionFormat.UNKNOWN"); - } - - @Test - public void test_deprecated_remediation_function() { - String xml = "" + - "<rules>" + - " <rule>" + - " <key>1</key>" + - " <name>One</name>" + - " <description>Desc</description>" + - " <effortToFixDescription>lines</effortToFixDescription>" + - " <debtRemediationFunction>LINEAR_OFFSET</debtRemediationFunction>" + - " <debtRemediationFunctionCoefficient>2d 3h</debtRemediationFunctionCoefficient>" + - " <debtRemediationFunctionOffset>5min</debtRemediationFunctionOffset>" + - " </rule>" + - "</rules>"; - RulesDefinition.Rule rule = load(xml).rule("1"); - assertThat(rule.gapDescription()).isEqualTo("lines"); - DebtRemediationFunction function = rule.debtRemediationFunction(); - assertThat(function).isNotNull(); - assertThat(function.type()).isEqualTo(DebtRemediationFunction.Type.LINEAR_OFFSET); - assertThat(function.gapMultiplier()).isEqualTo("2d3h"); - assertThat(function.baseEffort()).isEqualTo("5min"); - } - - private RulesDefinition.Repository load(InputStream input, String encoding) { - RulesDefinition.Context context = new RulesDefinitionContext(); - RulesDefinition.NewRepository newRepository = context.createRepository("squid", "java"); - underTest.load(newRepository, input, encoding); - newRepository.done(); - return context.repository("squid"); - } - - private RulesDefinition.Repository load(String xml) { - RulesDefinition.Context context = new RulesDefinitionContext(); - RulesDefinition.NewRepository newRepository = context.createRepository("squid", "java"); - underTest.load(newRepository, new StringReader(xml)); - newRepository.done(); - return context.repository("squid"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultNewRuleTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultNewRuleTest.java deleted file mode 100644 index d4e82b5b7ce..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultNewRuleTest.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule.internal; - -import org.junit.Test; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleScope; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rules.RuleType; -import org.sonar.api.server.debt.DebtRemediationFunction; -import org.sonar.api.server.rule.RulesDefinition; -import org.sonar.api.server.rule.RulesDefinition.OwaspTop10; -import org.sonar.api.server.rule.RulesDefinition.OwaspTop10Version; -import org.sonar.api.server.rule.RulesDefinition.PciDssVersion; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; - -public class DefaultNewRuleTest { - - private final DefaultNewRule rule = new DefaultNewRule("plugin", "repo", "key"); - - @Test - public void testSimpleSetGet() { - assertThat(rule.pluginKey()).isEqualTo("plugin"); - assertThat(rule.repoKey()).isEqualTo("repo"); - assertThat(rule.key()).isEqualTo("key"); - - rule.setScope(RuleScope.MAIN); - assertThat(rule.scope()).isEqualTo(RuleScope.MAIN); - - rule.setName(" name "); - assertThat(rule.name()).isEqualTo("name"); - - rule.setHtmlDescription(" html "); - assertThat(rule.htmlDescription()).isEqualTo("html"); - - rule.setTemplate(true); - assertThat(rule.template()).isTrue(); - - rule.setActivatedByDefault(true); - assertThat(rule.activatedByDefault()).isTrue(); - - RulesDefinition.NewParam param1 = rule.createParam("param1"); - assertThat(rule.param("param1")).isEqualTo(param1); - assertThat(rule.params()).containsOnly(param1); - - rule.setTags("tag1", "tag2"); - rule.addTags("tag3"); - assertThat(rule.tags()).containsExactly("tag1", "tag2", "tag3"); - - rule.setGapDescription("effort"); - assertThat(rule.gapDescription()).isEqualTo("effort"); - - rule.setInternalKey("internal"); - assertThat(rule.internalKey()).isEqualTo("internal"); - - rule.addDeprecatedRuleKey("deprecatedrepo", "deprecatedkey"); - assertThat(rule.deprecatedRuleKeys()).containsOnly(RuleKey.of("deprecatedrepo", "deprecatedkey")); - - rule.setStatus(RuleStatus.READY); - assertThat(rule.status()).isEqualTo(RuleStatus.READY); - - rule.addCwe(12); - rule.addCwe(10); - assertThat(rule.securityStandards()).containsOnly("cwe:10", "cwe:12"); - - rule.addOwaspTop10(OwaspTop10.A1, OwaspTop10.A2); - rule.addOwaspTop10(OwaspTop10Version.Y2017, OwaspTop10.A4); - rule.addOwaspTop10(OwaspTop10Version.Y2021, OwaspTop10.A5, OwaspTop10.A3); - assertThat(rule.securityStandards()) - .contains("owaspTop10:a1", "owaspTop10:a2", "owaspTop10:a4", "owaspTop10-2021:a3", "owaspTop10-2021:a5"); - - rule.addPciDss(PciDssVersion.V3_2, "6.5.1"); - rule.addPciDss(PciDssVersion.V3_2, "6.5"); - rule.addPciDss(PciDssVersion.V4_0, "6.5.2", "6.5.10"); - - assertThat(rule.securityStandards()) - .contains("pciDss-3.2:6.5.1", "pciDss-3.2:6.5", "pciDss-4.0:6.5.2", "pciDss-4.0:6.5.10"); - - rule.setType(RuleType.SECURITY_HOTSPOT); - assertThat(rule.type()).isEqualTo(RuleType.SECURITY_HOTSPOT); - - DebtRemediationFunction f = mock(DebtRemediationFunction.class); - rule.setDebtRemediationFunction(f); - assertThat(rule.debtRemediationFunction()).isEqualTo(f); - - rule.setSeverity("MAJOR"); - assertThat(rule.severity()).isEqualTo("MAJOR"); - } - - @Test - public void validate_fails() { - rule.setHtmlDescription("html"); - - assertThatThrownBy(() -> rule.validate()) - .isInstanceOf(IllegalStateException.class); - } - - @Test - public void validate_succeeds() { - rule.setHtmlDescription("html"); - rule.setName("name"); - rule.validate(); - } - - @Test - public void set_markdown_description() { - rule.setMarkdownDescription("markdown"); - assertThat(rule.markdownDescription()).isEqualTo("markdown"); - } - - @Test - public void fail_if_severity_is_invalid() { - assertThatThrownBy(() -> rule.setSeverity("invalid")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_setting_markdown_if_html_is_set() { - rule.setHtmlDescription("html"); - - assertThatThrownBy(() -> rule.setMarkdownDescription("markdown")) - .isInstanceOf(IllegalStateException.class); - } - - @Test - public void fail_if_set_status_to_removed() { - assertThatThrownBy(() -> rule.setStatus(RuleStatus.REMOVED)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_null_owasp_version() { - assertThatThrownBy(() -> rule.addOwaspTop10((OwaspTop10Version) null, OwaspTop10.A1)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Owasp version must not be null"); - } - - @Test - public void fail_if_null_pci_dss_version() { - assertThatThrownBy(() -> rule.addPciDss(null, "6.5.1")) - .isInstanceOf(NullPointerException.class) - .hasMessage("PCI DSS version must not be null"); - } - - @Test - public void fail_if_null_pci_dss_array() { - assertThatThrownBy(() -> rule.addPciDss(PciDssVersion.V3_2, null)) - .isInstanceOf(NullPointerException.class) - .hasMessage("Requirements for PCI DSS standard must not be null"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultRepositoryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultRepositoryTest.java deleted file mode 100644 index 522ac871505..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultRepositoryTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule.internal; - -import org.junit.Test; -import org.sonar.api.impl.server.RulesDefinitionContext; -import org.sonar.api.server.rule.RulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class DefaultRepositoryTest { - @Test - public void create_simple_repo() { - RulesDefinitionContext ctx = mock(RulesDefinitionContext.class); - DefaultNewRepository newRepo = new DefaultNewRepository(ctx, "key", "lang", false); - newRepo.createRule("rule1") - .setName("rule1") - .setHtmlDescription("desc"); - newRepo.setName("name"); - DefaultRepository repo = new DefaultRepository(newRepo, null); - - assertThat(repo.isExternal()).isFalse(); - assertThat(repo.key()).isEqualTo("key"); - assertThat(repo.language()).isEqualTo("lang"); - assertThat(repo.isExternal()).isFalse(); - assertThat(repo.name()).isEqualTo("name"); - assertThat(repo.rules()).extracting(RulesDefinition.Rule::key).containsOnly("rule1"); - - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultRuleTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultRuleTest.java deleted file mode 100644 index 0116c3eb42c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/rule/internal/DefaultRuleTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.rule.internal; - -import org.junit.Test; -import org.sonar.api.rule.RuleKey; -import org.sonar.api.rule.RuleScope; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.rules.RuleType; -import org.sonar.api.server.debt.DebtRemediationFunction; -import org.sonar.api.server.rule.RulesDefinition; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.mock; - -public class DefaultRuleTest { - @Test - public void getters() { - DefaultRepository repo = mock(DefaultRepository.class); - DefaultNewRule rule = new DefaultNewRule("plugin", "repo", "key"); - - rule.setScope(RuleScope.MAIN); - rule.setName(" name "); - rule.setHtmlDescription(" html "); - rule.setTemplate(true); - rule.setActivatedByDefault(true); - RulesDefinition.NewParam param1 = rule.createParam("param1"); - rule.setTags("tag1", "tag2"); - rule.addTags("tag3"); - rule.setGapDescription("gap"); - rule.setInternalKey("internal"); - rule.addDeprecatedRuleKey("deprecatedrepo", "deprecatedkey"); - rule.setStatus(RuleStatus.READY); - rule.addCwe(12); - rule.addCwe(10); - rule.setType(RuleType.SECURITY_HOTSPOT); - DebtRemediationFunction f = mock(DebtRemediationFunction.class); - rule.setDebtRemediationFunction(f); - rule.setSeverity("MAJOR"); - - DefaultRule defaultRule = new DefaultRule(repo, rule); - assertThat(defaultRule.scope()).isEqualTo(RuleScope.MAIN); - assertThat(defaultRule.name()).isEqualTo("name"); - assertThat(defaultRule.htmlDescription()).isEqualTo("html"); - assertThat(defaultRule.template()).isTrue(); - assertThat(defaultRule.activatedByDefault()).isTrue(); - assertThat(defaultRule.params()).containsOnly(new DefaultParam(new DefaultNewParam("param1"))); - assertThat(defaultRule.tags()).containsOnly("tag1", "tag2", "tag3"); - assertThat(defaultRule.gapDescription()).isEqualTo("gap"); - assertThat(defaultRule.internalKey()).isEqualTo("internal"); - assertThat(defaultRule.deprecatedRuleKeys()).containsOnly(RuleKey.of("deprecatedrepo", "deprecatedkey")); - assertThat(defaultRule.status()).isEqualTo(RuleStatus.READY); - assertThat(rule.securityStandards()).containsOnly("cwe:10", "cwe:12"); - assertThat(defaultRule.type()).isEqualTo(RuleType.SECURITY_HOTSPOT); - assertThat(defaultRule.debtRemediationFunction()).isEqualTo(f); - assertThat(defaultRule.markdownDescription()).isNull(); - assertThat(defaultRule.severity()).isEqualTo("MAJOR"); - } - - @Test - public void to_string() { - DefaultRepository repo = mock(DefaultRepository.class); - DefaultNewRule rule = new DefaultNewRule("plugin", "repo", "key"); - DefaultRule defaultRule = new DefaultRule(repo, rule); - - assertThat(defaultRule).hasToString("[repository=repo, key=key]"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/RequestTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/RequestTest.java deleted file mode 100644 index 4c491d03375..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/RequestTest.java +++ /dev/null @@ -1,745 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.ws; - -import com.google.common.collect.ArrayListMultimap; -import com.google.common.collect.ListMultimap; -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; -import java.io.InputStream; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.function.Consumer; -import java.util.stream.Collectors; -import javax.annotation.Nullable; -import org.apache.commons.io.IOUtils; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.sonar.api.impl.ws.PartImpl; -import org.sonar.api.impl.ws.ValidatingRequest; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.utils.DateUtils; - -import static com.google.common.base.Strings.repeat; -import static com.google.common.collect.Lists.newArrayList; -import static java.lang.String.format; -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.fail; -import static org.mockito.Mockito.mock; -import static org.sonar.api.utils.DateUtils.parseDate; -import static org.sonar.api.utils.DateUtils.parseDateTime; - -@RunWith(DataProviderRunner.class) -public class RequestTest { - - private FakeRequest underTest = new FakeRequest(); - - @Before - public void before() { - WebService.Context context = new WebService.Context(); - new FakeWs().define(context); - - underTest.setAction(context.controller("my_controller").action("my_action")); - } - - @Test - public void has_param() { - underTest.setParam("a_required_string", "foo"); - - assertThat(underTest.hasParam("a_required_string")).isTrue(); - assertThat(underTest.hasParam("unknown")).isFalse(); - } - - @Test - public void required_param_is_missing() { - assertThatThrownBy(() -> underTest.mandatoryParam("required_param")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The 'required_param' parameter is missing"); - } - - @Test - public void required_param() { - underTest.setParam("a_required_string", "foo"); - underTest.setParam("a_required_number", "42"); - underTest.setParam("a_required_boolean", "true"); - underTest.setParam("a_required_enum", "BETA"); - - assertThat(underTest.mandatoryParam("a_required_string")).isEqualTo("foo"); - assertThat(underTest.mandatoryParamAsBoolean("a_required_boolean")).isTrue(); - assertThat(underTest.mandatoryParamAsInt("a_required_number")).isEqualTo(42); - assertThat(underTest.mandatoryParamAsLong("a_required_number")).isEqualTo(42L); - assertThat(underTest.mandatoryParamAsEnum("a_required_enum", RuleStatus.class)).isEqualTo(RuleStatus.BETA); - } - - @Test - public void maximum_length_ok() { - String parameter = "maximum_length_param"; - defineParameterTestAction(newParam -> newParam.setMaximumLength(10), parameter); - String value = repeat("X", 10); - - String param = underTest.setParam(parameter, value).param(parameter); - - assertThat(param).isEqualTo(value); - } - - @Test - public void maximum_length_not_ok() { - String parameter = "maximum_length_param"; - defineParameterTestAction(newParam -> newParam.setMaximumLength(10), parameter); - - assertThatThrownBy(() -> underTest.setParam(parameter, repeat("X", 11)).param(parameter)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(format("'%s' length (11) is longer than the maximum authorized (10)", parameter)); - } - - @Test - public void maximum_value_ok() { - String param = "maximum_value_param"; - defineParameterTestAction(newParam -> newParam.setMaximumValue(10), param); - String expected = "10"; - - String actual = underTest.setParam(param, expected).param(param); - - assertThat(actual).isEqualTo(expected); - } - - @Test - public void maximum_value_not_ok() { - String param = "maximum_value_param"; - defineParameterTestAction(newParam -> newParam.setMaximumValue(10), param); - - assertThatThrownBy(() -> underTest.setParam(param, "11").param(param)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage(format("'%s' value (11) must be less than 10", param)); - } - - @Test - public void paramAsInt_throws_IAE_if_maximum_defined_and_value_not_a_number() { - String param = "maximum_value_param"; - defineParameterTestAction(newParam -> newParam.setMaximumValue(10), param); - - assertThatThrownBy(() -> underTest.setParam(param, "foo").paramAsInt(param)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("'maximum_value_param' value 'foo' cannot be parsed as an integer"); - } - - @Test - public void required_param_as_strings() { - underTest.setParam("a_required_string", "foo,bar"); - - assertThat(underTest.mandatoryParamAsStrings("a_required_string")).containsExactly("foo", "bar"); - } - - @Test - public void fail_if_no_required_param_as_strings() { - assertThatThrownBy(() -> underTest.mandatoryParamAsStrings("a_required_string")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The 'a_required_string' parameter is missing"); - } - - @Test - public void multi_param() { - assertThat(underTest.multiParam("a_required_multi_param")).isEmpty(); - - underTest.setMultiParam("a_required_multi_param", newArrayList("firstValue", "secondValue", "thirdValue")); - assertThat(underTest.multiParam("a_required_multi_param")).containsExactly("firstValue", "secondValue", "thirdValue"); - } - - @Test - public void fail_when_multi_param_has_more_values_than_maximum_values() { - underTest.setMultiParam("has_maximum_values", newArrayList("firstValue", "secondValue", "thirdValue")); - - assertThatThrownBy(() -> underTest.multiParam("has_maximum_values")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("'has_maximum_values' can contains only 2 values, got 3"); - } - - @Test - public void mandatory_multi_param() { - underTest.setMultiParam("a_required_multi_param", newArrayList("firstValue", "secondValue", "thirdValue")); - - List<String> result = underTest.mandatoryMultiParam("a_required_multi_param"); - - assertThat(result).containsExactly("firstValue", "secondValue", "thirdValue"); - } - - @Test - public void fail_when_no_multi_param() { - assertThatThrownBy(() -> underTest.mandatoryMultiParam("a_required_multi_param")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The 'a_required_multi_param' parameter is missing"); - } - - @Test - public void default_value_of_optional_param() { - assertThat(underTest.param("has_default_string")).isEqualTo("the_default_string"); - } - - @Test - public void param_as_string() { - assertThat(underTest.setParam("a_string", "foo").param("a_string")).isEqualTo("foo"); - assertThat(underTest.setParam("a_string", " f o o \r\n ").param("a_string")).isEqualTo("f o o"); - } - - @Test - public void param_contains_NUL_char_should_throw_exception() { - underTest.setParam("a_string", "value\0value"); - - assertThatThrownBy(() -> underTest.param("a_string")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Request parameters are not allowed to contain NUL character"); - } - - @Test - public void null_param() { - assertThat(underTest.param("a_string")).isNull(); - assertThat(underTest.paramAsBoolean("a_boolean")).isNull(); - assertThat(underTest.paramAsInt("a_number")).isNull(); - assertThat(underTest.paramAsLong("a_number")).isNull(); - } - - @Test - public void paramAsInt() { - assertThat(underTest.setParam("a_number", "123").paramAsInt("a_number")).isEqualTo(123); - } - - @Test - public void fail_when_param_is_not_an_int() { - assertThatThrownBy(() -> underTest.setParam("a_number", "not-an-int").paramAsInt("a_number")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The 'a_number' parameter cannot be parsed as an integer value: not-an-int"); - } - - @Test - public void param_as_long() { - assertThat(underTest.setParam("a_number", "123").paramAsLong("a_number")).isEqualTo(123L); - } - - @Test - public void fail_when_param_is_not_a_long() { - assertThatThrownBy(() -> underTest.setParam("a_number", "not_a_long").paramAsLong("a_number")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The 'a_number' parameter cannot be parsed as a long value: not_a_long"); - } - - @Test - public void param_as_boolean() { - assertThat(underTest.setParam("a_boolean", "true").paramAsBoolean("a_boolean")).isTrue(); - assertThat(underTest.setParam("a_boolean", "yes").paramAsBoolean("a_boolean")).isTrue(); - assertThat(underTest.setParam("a_boolean", "false").paramAsBoolean("a_boolean")).isFalse(); - assertThat(underTest.setParam("a_boolean", "no").paramAsBoolean("a_boolean")).isFalse(); - } - - @Test - public void fail_if_incorrect_param_as_boolean() { - assertThatThrownBy(() -> underTest.setParam("a_boolean", "oui").paramAsBoolean("a_boolean")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Property a_boolean is not a boolean value: oui"); - } - - @Test - public void param_as_enum() { - assertThat(underTest.setParam("a_enum", "BETA").paramAsEnum("a_enum", RuleStatus.class)).isEqualTo(RuleStatus.BETA); - } - - @Test - public void param_as_enums() { - assertThat(underTest.setParam("a_enum", "BETA,READY").paramAsEnums("a_enum", RuleStatus.class)).containsOnly(RuleStatus.BETA, RuleStatus.READY); - assertThat(underTest.setParam("a_enum", "").paramAsEnums("a_enum", RuleStatus.class)).isEmpty(); - } - - @Test - public void param_as_enums_returns_null_when_no_value() { - assertThat(underTest.paramAsEnums("a_enum", RuleStatus.class)).isNull(); - } - - @Test - public void fail_when_param_as_enums_has_more_values_than_maximum_values() { - assertThatThrownBy(() -> underTest.setParam("has_maximum_values", "BETA,READY,REMOVED").paramAsEnums("has_maximum_values", RuleStatus.class)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("'has_maximum_values' can contains only 2 values, got 3"); - } - - @Test - public void param_as_date() { - assertThat(underTest.setParam("a_date", "2014-05-27").paramAsDate("a_date")).isEqualTo(DateUtils.parseDate("2014-05-27")); - } - - @Test - public void getParam_of_missing_string_parameter() { - Request.StringParam stringParam = underTest.getParam("a_string"); - - assertThat(stringParam.isPresent()).isFalse(); - expectSupplierCanNotBeNullNPE(() -> stringParam.or(null)); - assertThat(stringParam.or(() -> "foo")).isEqualTo("foo"); - expectGetValueFailureWithISE(stringParam::getValue); - - Request.StringParam emptyAsNull = stringParam.emptyAsNull(); - assertThat(emptyAsNull).isSameAs(stringParam); - assertThat(emptyAsNull.isPresent()).isFalse(); - expectSupplierCanNotBeNullNPE(() -> emptyAsNull.or(null)); - assertThat(emptyAsNull.or(() -> "bar")).isEqualTo("bar"); - expectGetValueFailureWithISE(emptyAsNull::getValue); - } - - @Test - public void getParam_of_existing_string_parameter_with_non_empty_value() { - underTest.setParam("a_string", "sorry"); - - Request.StringParam stringParam = underTest.getParam("a_string"); - - assertThat(stringParam.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> stringParam.or(null)); - assertThat(stringParam.or(() -> "foo")).isEqualTo("sorry"); - assertThat(stringParam.getValue()).isEqualTo("sorry"); - - Request.StringParam emptyAsNull = stringParam.emptyAsNull(); - assertThat(emptyAsNull).isSameAs(stringParam); - assertThat(emptyAsNull.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> emptyAsNull.or(null)); - assertThat(emptyAsNull.or(() -> "bar")).isEqualTo("sorry"); - assertThat(emptyAsNull.getValue()).isEqualTo("sorry"); - } - - @Test - public void getParam_of_existing_string_parameter_with_empty_value() { - underTest.setParam("a_string", ""); - - Request.StringParam stringParam = underTest.getParam("a_string"); - - assertThat(stringParam.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> stringParam.or(null)); - assertThat(stringParam.or(() -> "foo")).isEmpty(); - assertThat(stringParam.getValue()).isEmpty(); - - Request.StringParam emptyAsNull = stringParam.emptyAsNull(); - assertThat(emptyAsNull).isNotSameAs(stringParam); - assertThat(emptyAsNull.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> emptyAsNull.or(null)); - assertThat(emptyAsNull.or(() -> "bar")).isNull(); - assertThat(emptyAsNull.getValue()).isNull(); - } - - @Test - public void getParam_with_validation_of_missing_string_parameter() { - Request.StringParam stringParam = underTest.getParam("a_string", (str) -> { - throw new IllegalStateException("validator should not be called"); - }); - - assertThat(stringParam.isPresent()).isFalse(); - expectSupplierCanNotBeNullNPE(() -> stringParam.or(null)); - assertThat(stringParam.or(() -> "foo")).isEqualTo("foo"); - expectGetValueFailureWithISE(stringParam::getValue); - - Request.StringParam emptyAsNull = stringParam.emptyAsNull(); - assertThat(emptyAsNull).isSameAs(stringParam); - assertThat(emptyAsNull.isPresent()).isFalse(); - expectSupplierCanNotBeNullNPE(() -> emptyAsNull.or(null)); - assertThat(emptyAsNull.or(() -> "bar")).isEqualTo("bar"); - expectGetValueFailureWithISE(emptyAsNull::getValue); - } - - @Test - public void getParam_with_validation_of_existing_string_parameter_with_non_empty_value() { - underTest.setParam("a_string", "sorry"); - AtomicInteger calls = new AtomicInteger(); - - Request.StringParam stringParam = underTest.getParam("a_string", (str) -> calls.incrementAndGet()); - - assertThat(calls.get()).isOne(); - assertThat(stringParam.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> stringParam.or(null)); - assertThat(stringParam.or(() -> "foo")).isEqualTo("sorry"); - assertThat(stringParam.getValue()).isEqualTo("sorry"); - - Request.StringParam emptyAsNull = stringParam.emptyAsNull(); - assertThat(emptyAsNull).isSameAs(stringParam); - assertThat(emptyAsNull.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> emptyAsNull.or(null)); - assertThat(emptyAsNull.or(() -> "bar")).isEqualTo("sorry"); - assertThat(emptyAsNull.getValue()).isEqualTo("sorry"); - } - - @Test - public void getParam_with_validation_of_existing_string_parameter_with_empty_value() { - underTest.setParam("a_string", ""); - AtomicInteger calls = new AtomicInteger(); - - Request.StringParam stringParam = underTest.getParam("a_string", (str) -> calls.incrementAndGet()); - - assertThat(calls.get()).isOne(); - assertThat(stringParam.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> stringParam.or(null)); - assertThat(stringParam.or(() -> "foo")).isEmpty(); - assertThat(stringParam.getValue()).isEmpty(); - - Request.StringParam emptyAsNull = stringParam.emptyAsNull(); - assertThat(emptyAsNull).isNotSameAs(stringParam); - assertThat(emptyAsNull.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> emptyAsNull.or(null)); - assertThat(emptyAsNull.or(() -> "bar")).isNull(); - assertThat(emptyAsNull.getValue()).isNull(); - } - - @Test - public void getParam_with_validation_of_existing_string_parameter_does_not_catch_unchecked_exception_throws_by_validator() { - underTest.setParam("a_string", "boo"); - IllegalArgumentException expected = new IllegalArgumentException("Faking validation of parameter value failed"); - - try { - underTest.getParam("a_string", (str) -> { - throw expected; - }); - fail("an IllegalStateException should have been raised"); - } catch (IllegalArgumentException e) { - assertThat(e).isSameAs(expected); - } - } - - @Test - public void getParam_of_missing_parameter_of_unspecified_type() { - Request.Param<Object> param = underTest.getParam("a_string", (rqt, key) -> { - throw new IllegalStateException("retrieveAndValidate BiConsumer should not be called"); - }); - - assertThat(param.isPresent()).isFalse(); - expectSupplierCanNotBeNullNPE(() -> param.or(null)); - assertThat(param.or(() -> "foo")).isEqualTo("foo"); - expectGetValueFailureWithISE(param::getValue); - } - - @Test - public void getParam_of_existing_parameter_of_unspecified_type_with_null_value() { - underTest.setParam("a_string", "value in fake request actually does not matter"); - - Request.Param<Object> param = underTest.getParam("a_string", (rqt, key) -> null); - - assertThat(param.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> param.or(null)); - assertThat(param.or(() -> "foo")).isNull(); - assertThat(param.getValue()).isNull(); - } - - @Test - public void getParam_of_existing_parameter_of_unspecified_type_with_empty_string() { - underTest.setParam("a_string", "value in fake request actually does not matter"); - - Request.Param<Object> param = underTest.getParam("a_string", (rqt, key) -> ""); - - assertThat(param.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> param.or(null)); - assertThat(param.or(() -> "foo")).isEqualTo(""); - assertThat(param.getValue()).isEqualTo(""); - } - - @Test - public void getParam_of_existing_parameter_of_unspecified_type_with_object() { - underTest.setParam("a_string", "value in fake request actually does not matter"); - Object value = new Object(); - Request.Param<Object> param = underTest.getParam("a_string", (rqt, key) -> value); - - assertThat(param.isPresent()).isTrue(); - expectSupplierCanNotBeNullNPE(() -> param.or(null)); - assertThat(param.or(() -> "foo")).isSameAs(value); - assertThat(param.getValue()).isSameAs(value); - } - - @Test - public void getParam_of_existing_parameter_of_unspecified_type_does_not_catch_unchecked_exception_thrown_by_BiConsumer() { - underTest.setParam("a_string", "value in fake request actually does not matter"); - RuntimeException expected = new RuntimeException("Faking BiConsumer throwing unchecked exception"); - - try { - underTest.getParam("a_string", (rqt, key) -> { - throw expected; - }); - fail("an RuntimeException should have been raised"); - } catch (RuntimeException e) { - assertThat(e).isSameAs(expected); - } - } - - private void expectGetValueFailureWithISE(Runnable runnable) { - try { - runnable.run(); - fail("An IllegalStateException should have been raised"); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Param has no value. Use isPresent() before calling getValue()"); - } - } - - private void expectSupplierCanNotBeNullNPE(Runnable runnable) { - try { - runnable.run(); - fail("A NullPointerException should have been raised"); - } catch (NullPointerException e) { - assertThat(e).hasMessage("default value supplier can't be null"); - } - } - - @DataProvider - public static Object[][] date_times() { - return new Object[][] { - {"2014-05-27", parseDate("2014-05-27")}, - {"2014-05-27T15:50:45+0100", parseDateTime("2014-05-27T15:50:45+0100")}, - {null, null} - }; - } - - @Test - @UseDataProvider("date_times") - public void param_as__date_time(String stringDate, Date expectedDate) { - assertThat(underTest.setParam("a_date", stringDate).paramAsDateTime("a_date")).isEqualTo(expectedDate); - } - - @Test - public void fail_when_param_as_date_not_a_date() { - assertThatThrownBy(() -> underTest.setParam("a_date", "polop").paramAsDate("a_date")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The date 'polop' does not respect format 'yyyy-MM-dd'"); - } - - @Test - public void fail_when_param_as_datetime_not_a_datetime() { - assertThatThrownBy(() -> underTest.setParam("a_datetime", "polop").paramAsDateTime("a_datetime")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("'polop' cannot be parsed as either a date or date+time"); - } - - @Test - public void param_as_strings() { - assertThat(underTest.paramAsStrings("a_string")).isNull(); - assertThat(underTest.setParam("a_string", "").paramAsStrings("a_string")).isEmpty(); - assertThat(underTest.setParam("a_string", "bar").paramAsStrings("a_string")).containsExactly("bar"); - assertThat(underTest.setParam("a_string", "bar,baz").paramAsStrings("a_string")).containsExactly("bar", "baz"); - assertThat(underTest.setParam("a_string", "bar , baz").paramAsStrings("a_string")).containsExactly("bar", "baz"); - } - - @Test - public void fail_when_param_as_strings_has_more_values_than_maximum_values() { - assertThatThrownBy(() -> underTest.setParam("has_maximum_values", "foo,bar,baz").paramAsStrings("has_maximum_values")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("'has_maximum_values' can contains only 2 values, got 3"); - } - - @Test - public void deprecated_key() { - assertThat(underTest.setParam("deprecated_param", "bar").param("new_param")).isEqualTo("bar"); - } - - @Test - public void fail_if_param_is_not_defined() { - assertThatThrownBy(() -> underTest.param("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("BUG - parameter 'unknown' is undefined for action 'my_action'"); - } - - @Test - public void fail_if_multi_param_is_not_defined() { - assertThatThrownBy(() -> underTest.multiParam("unknown")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Parameter 'unknown' not found for action 'my_action'"); - } - - @Test - public void verify_possible_values() { - underTest.setParam("has_possible_values", "foo"); - assertThat(underTest.param("has_possible_values")).isEqualTo("foo"); - } - - @Test - public void fail_if_not_a_possible_value() { - underTest.setParam("has_possible_values", "not_possible"); - - assertThatThrownBy(() -> underTest.param("has_possible_values")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Value of parameter 'has_possible_values' (not_possible) must be one of: [foo, bar]"); - } - - @Test - public void param_as_input_stream() throws Exception { - assertThat(underTest.paramAsInputStream("a_string")).isNull(); - assertThat(IOUtils.toString(underTest.setParam("a_string", "").paramAsInputStream("a_string"))).isEmpty(); - assertThat(IOUtils.toString(underTest.setParam("a_string", "foo").paramAsInputStream("a_string"))).isEqualTo("foo"); - } - - @Test - public void param_as_part() { - InputStream inputStream = mock(InputStream.class); - underTest.setPart("key", inputStream, "filename"); - - Request.Part part = underTest.paramAsPart("key"); - assertThat(part.getInputStream()).isEqualTo(inputStream); - assertThat(part.getFileName()).isEqualTo("filename"); - - assertThat(underTest.paramAsPart("unknown")).isNull(); - } - - @Test - public void mandatory_param_as_part() { - assertThatThrownBy(() -> underTest.mandatoryParamAsPart("required_param")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("The 'required_param' parameter is missing"); - } - - private void defineParameterTestAction(Consumer<WebService.NewParam> newParam, String parameter) { - String controllerPath = "my_controller"; - String actionPath = "my_action"; - WebService.Context context = new WebService.Context(); - WebService.NewController controller = context.createController(controllerPath); - WebService.NewAction action = controller - .createAction(actionPath) - .setHandler(mock(RequestHandler.class)); - WebService.NewParam param = action.createParam(parameter); - newParam.accept(param); - controller.done(); - underTest.setAction(context.controller(controllerPath).action(actionPath)); - } - - private static class FakeRequest extends ValidatingRequest { - - private final ListMultimap<String, String> multiParams = ArrayListMultimap.create(); - private final Map<String, String> params = new HashMap<>(); - private final Map<String, Part> parts = new HashMap<>(); - private final Map<String, String> headers = new HashMap<>(); - - @Override - public String method() { - return "GET"; - } - - @Override - public String getMediaType() { - return "application/json"; - } - - @Override - public boolean hasParam(String key) { - return params.containsKey(key); - } - - @Override - public String getPath() { - return null; - } - - public FakeRequest setParam(String key, @Nullable String value) { - if (value != null) { - params.put(key, value); - } - return this; - } - - public FakeRequest setMultiParam(String key, List<String> values) { - multiParams.putAll(key, values); - - return this; - } - - @Override - protected String readParam(String key) { - return params.get(key); - } - - @Override - public Map<String, String[]> getParams() { - ArrayListMultimap<String, String> result = ArrayListMultimap.create(multiParams); - params.forEach(result::put); - return result.asMap().entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().toArray(new String[0]))); - } - - @Override - protected List<String> readMultiParam(String key) { - return multiParams.get(key); - } - - @Override - protected InputStream readInputStreamParam(String key) { - String param = readParam(key); - - return param == null ? null : IOUtils.toInputStream(param); - } - - @Override - protected Part readPart(String key) { - return parts.get(key); - } - - public FakeRequest setPart(String key, InputStream input, String fileName) { - parts.put(key, new PartImpl(input, fileName)); - return this; - } - - @Override - public Optional<String> header(String name) { - return Optional.ofNullable(headers.get(name)); - } - } - - private static class FakeWs implements WebService { - - @Override - public void define(Context context) { - NewController controller = context.createController("my_controller"); - NewAction action = controller.createAction("my_action") - .setDescription("Action Description") - .setPost(true) - .setSince("5.2") - .setHandler(mock(RequestHandler.class)); - action - .createParam("required_param") - .setRequired(true); - - action.createParam("a_string"); - action.createParam("a_boolean"); - action.createParam("a_number"); - action.createParam("a_enum"); - action.createParam("a_date"); - action.createParam("a_datetime"); - - action.createParam("a_required_string").setRequired(true); - action.createParam("a_required_boolean").setRequired(true); - action.createParam("a_required_number").setRequired(true); - action.createParam("a_required_enum").setRequired(true); - action.createParam("a_required_multi_param").setRequired(true); - - action.createParam("has_default_string").setDefaultValue("the_default_string"); - action.createParam("has_default_number").setDefaultValue("10"); - action.createParam("has_default_boolean").setDefaultValue("true"); - - action.createParam("has_possible_values").setPossibleValues("foo", "bar"); - - action.createParam("has_maximum_values").setMaxValuesAllowed(2); - - action.createParam("new_param").setDeprecatedKey("deprecated_param", "6.3"); - action.createParam("new_param_with_default_value").setDeprecatedKey("deprecated_new_param_with_default_value", "6.2").setDefaultValue("the_default_string"); - - controller.done(); - } - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java deleted file mode 100644 index 747514f1477..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/server/ws/WebServiceTest.java +++ /dev/null @@ -1,552 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.server.ws; - -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.Collections; -import org.apache.commons.lang.StringUtils; -import org.junit.Rule; -import org.junit.Test; -import org.sonar.api.rule.RuleStatus; -import org.sonar.api.server.ws.WebService.NewAction; -import org.sonar.api.server.ws.WebService.NewController; -import org.sonar.api.utils.log.LogTester; -import org.sonar.api.utils.log.LoggerLevel; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.tuple; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; - -public class WebServiceTest { - - @Rule - public LogTester logTester = new LogTester(); - - private WebService.Context context = new WebService.Context(); - - @Test - public void no_web_services_by_default() { - assertThat(context.controllers()).isEmpty(); - assertThat(context.controller("metric")).isNull(); - } - - @Test - public void define_web_service() { - MetricWs metricWs = new MetricWs(); - - metricWs.define(context); - - WebService.Controller controller = context.controller("api/metric"); - assertThat(controller).isNotNull(); - assertThat(controller.path()).isEqualTo("api/metric"); - assertThat(controller.description()).isEqualTo("Metrics"); - assertThat(controller.since()).isEqualTo("3.2"); - assertThat(controller.actions()).hasSize(2); - assertThat(controller.isInternal()).isFalse(); - WebService.Action showAction = controller.action("show"); - assertThat(showAction).isNotNull(); - assertThat(showAction.key()).isEqualTo("show"); - assertThat(showAction.description()).isEqualTo("Show metric"); - assertThat(showAction.handler()).isNotNull(); - assertThat(showAction.responseExample()).isNotNull(); - assertThat(showAction.responseExampleFormat()).isNotEmpty(); - assertThat(showAction.responseExampleAsString()).isNotEmpty(); - assertThat(showAction.deprecatedSince()).isNull(); - assertThat(showAction.changelog()).isEmpty(); - // same as controller - assertThat(showAction.since()).isEqualTo("4.2"); - assertThat(showAction.isPost()).isFalse(); - assertThat(showAction.isInternal()).isFalse(); - assertThat(showAction.path()).isEqualTo("api/metric/show"); - WebService.Action createAction = controller.action("create"); - assertThat(createAction).isNotNull(); - assertThat(createAction.key()).isEqualTo("create"); - assertThat(createAction.toString()).isEqualTo("api/metric/create"); - assertThat(createAction.deprecatedSince()).isEqualTo("5.3"); - // overrides controller version - assertThat(createAction.since()).isEqualTo("4.1"); - assertThat(createAction.isPost()).isTrue(); - assertThat(createAction.isInternal()).isTrue(); - assertThat(createAction.changelog()).extracting(Change::getVersion, Change::getDescription).containsOnly( - tuple("6.4", "Last event"), tuple("6.0", "Old event"), tuple("4.5.6", "Very old event")); - } - - @Test - public void add_changelog_if_called_twice() { - WebService webService = context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list") - .setDescription("desc") - .setChangelog(new Change("1.0", "change1")) - .setChangelog(new Change("2.0", "change2")); - newController.done(); - }; - - webService.define(context); - assertThat(context.controller("api/rule").action("list").changelog()) - .extracting(Change::getVersion, Change::getDescription) - .containsOnly( - tuple("1.0", "change1"), - tuple("2.0", "change2")); - } - - @Test - public void fail_if_duplicated_ws_keys() { - MetricWs metricWs = new MetricWs(); - metricWs.define(context); - - assertThatThrownBy(() -> ((WebService) context -> { - NewController newController = context.createController("api/metric"); - newDefaultAction(newController, "delete"); - newController.done(); - }).define(context)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("The web service 'api/metric' is defined multiple times"); - } - - @Test - public void fail_if_no_action_handler() { - assertThatThrownBy(() -> ((WebService) context -> { - NewController controller = context.createController("rule"); - newDefaultAction(controller, "show") - .setHandler(null); - controller.done(); - }).define(context)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("RequestHandler is not set on action rule/show"); - } - - @Test - public void fail_if_duplicated_action_keys() { - assertThatThrownBy(() -> ((WebService) context -> { - NewController newController = context.createController("rule"); - newDefaultAction(newController, "create"); - newDefaultAction(newController, "delete"); - newDefaultAction(newController, "delete"); - newController.done(); - }).define(context)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("The action 'delete' is defined multiple times in the web service 'rule'"); - } - - @Test - public void fail_if_no_actions() { - assertThatThrownBy(() -> ((WebService) context -> context.createController("rule").done()).define(context)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("At least one action must be declared in the web service 'rule'"); - } - - @Test - public void fail_if_no_controller_path() { - assertThatThrownBy(() -> ((WebService) context -> context.createController(null).done()).define(context)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("WS controller path must not be empty"); - } - - @Test - public void controller_path_must_not_start_with_slash() { - assertThatThrownBy(() -> ((WebService) context -> context.createController("/hello").done()).define(context)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("WS controller path must not start or end with slash: /hello"); - } - - @Test - public void controller_path_must_not_end_with_slash() { - assertThatThrownBy(() -> ((WebService) context -> context.createController("hello/").done()).define(context)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("WS controller path must not start or end with slash: hello/"); - } - - @Test - public void handle_request() throws Exception { - MetricWs metricWs = new MetricWs(); - metricWs.define(context); - - assertThat(metricWs.showCalled).isFalse(); - assertThat(metricWs.createCalled).isFalse(); - context.controller("api/metric").action("show").handler().handle(mock(Request.class), mock(Response.class)); - assertThat(metricWs.showCalled).isTrue(); - assertThat(metricWs.createCalled).isFalse(); - context.controller("api/metric").action("create").handler().handle(mock(Request.class), mock(Response.class)); - assertThat(metricWs.createCalled).isTrue(); - } - - @Test - public void action_parameters() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - NewAction newAction = newDefaultAction(newController, "create"); - newAction - .createParam("key") - .setDescription("Key of the new rule"); - newAction - .createParam("severity") - .setDefaultValue("MAJOR") - .setSince("4.4") - .setDeprecatedSince("5.3") - .setDeprecatedKey("old-severity", "4.5") - .setPossibleValues("INFO", "MAJOR", "BLOCKER") - .setMaxValuesAllowed(10); - newAction.createParam("internal") - .setInternal(true); - newAction.addPagingParams(20); - newAction.addFieldsParam(Arrays.asList("name", "severity")); - newAction.addSortParams(Arrays.asList("name", "updatedAt", "severity"), "updatedAt", false); - - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/rule").action("create"); - assertThat(action.params()).hasSize(8); - - WebService.Param keyParam = action.param("key"); - assertThat(keyParam.key()).isEqualTo("key"); - assertThat(keyParam.description()).isEqualTo("Key of the new rule"); - assertThat(keyParam.isInternal()).isFalse(); - assertThat(keyParam.toString()).isEqualTo("key"); - - WebService.Param severityParam = action.param("severity"); - assertThat(severityParam.key()).isEqualTo("severity"); - assertThat(severityParam.description()).isNull(); - assertThat(severityParam.deprecatedSince()).isEqualTo("5.3"); - assertThat(severityParam.since()).isEqualTo("4.4"); - assertThat(severityParam.deprecatedKey()).isEqualTo("old-severity"); - assertThat(severityParam.deprecatedKeySince()).isEqualTo("4.5"); - assertThat(severityParam.defaultValue()).isEqualTo("MAJOR"); - assertThat(severityParam.possibleValues()).containsOnly("INFO", "MAJOR", "BLOCKER"); - assertThat(severityParam.maxValuesAllowed()).isEqualTo(10); - - WebService.Param internalParam = action.param("internal"); - assertThat(internalParam.isInternal()).isTrue(); - - // predefined fields - assertThat(action.param("p").defaultValue()).isEqualTo("1"); - assertThat(action.param("p").description()).isNotEmpty(); - assertThat(action.param("ps").defaultValue()).isEqualTo("20"); - assertThat(action.param("ps").description()).isNotEmpty(); - assertThat(action.param("f").possibleValues()).containsOnly("name", "severity"); - assertThat(action.param("s").possibleValues()).containsOnly("name", "severity", "updatedAt"); - assertThat(action.param("s").description()).isNotEmpty(); - assertThat(action.param("asc").defaultValue()).isEqualTo("false"); - } - - @Test - public void param_metadata_as_objects() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - NewAction create = newDefaultAction(newController, "create"); - create.createParam("status") - .setDefaultValue(RuleStatus.BETA) - .setPossibleValues(RuleStatus.BETA, RuleStatus.READY) - .setExampleValue(RuleStatus.BETA); - create.createParam("max") - .setDefaultValue(11) - .setPossibleValues(11, 13, 17) - .setExampleValue(17); - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/rule").action("create"); - assertThat(action.param("status").defaultValue()).isEqualTo("BETA"); - assertThat(action.param("status").possibleValues()).containsOnly("BETA", "READY"); - assertThat(action.param("status").exampleValue()).isEqualTo("BETA"); - assertThat(action.param("max").defaultValue()).isEqualTo("11"); - assertThat(action.param("max").possibleValues()).containsOnly("11", "13", "17"); - assertThat(action.param("max").exampleValue()).isEqualTo("17"); - } - - @Test - public void param_null_metadata() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - NewAction create = newDefaultAction(newController, "create"); - create.createParam("status") - .setDefaultValue(null) - .setPossibleValues(Collections.emptyList()) - .setExampleValue(null); - create.createParam("max") - .setPossibleValues((Object[]) null); - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/rule").action("create"); - assertThat(action.param("status").defaultValue()).isNull(); - assertThat(action.param("status").possibleValues()).isNull(); - assertThat(action.param("status").exampleValue()).isNull(); - assertThat(action.param("max").possibleValues()).isNull(); - } - - @Test - public void param_with_empty_possible_values() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - NewAction create = newDefaultAction(newController, "create"); - create.createParam("status") - .setPossibleValues(Collections.emptyList()); - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/rule").action("create"); - // no possible values -> return null but not empty - assertThat(action.param("status").possibleValues()).isNull(); - } - - @Test - public void param_with_maximum_length() { - ((WebService) context -> { - NewController newController = context.createController("api/custom_measures"); - NewAction create = newDefaultAction(newController, "create"); - create.createParam("string_value") - .setMaximumLength(24); - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/custom_measures").action("create"); - assertThat(action.param("string_value").maximumLength()).isEqualTo(24); - } - - @Test - public void param_with_minimum_length() { - ((WebService) context -> { - NewController newController = context.createController("api/custom_measures"); - NewAction create = newDefaultAction(newController, "create"); - create.createParam("string_value") - .setMinimumLength(3); - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/custom_measures").action("create"); - assertThat(action.param("string_value").minimumLength()).isEqualTo(3); - } - - @Test - public void param_with_maximum_value() { - ((WebService) context -> { - NewController newController = context.createController("api/custom_measures"); - NewAction create = newDefaultAction(newController, "create"); - create.createParam("numeric_value") - .setMaximumValue(10); - newController.done(); - }).define(context); - - WebService.Action action = context.controller("api/custom_measures").action("create"); - assertThat(action.param("numeric_value").maximumValue()).isEqualTo(10); - } - - @Test - public void fail_if_required_param_has_default_value() { - assertThatThrownBy(() -> ((WebService) context -> { - NewController controller = context.createController("api/rule"); - NewAction action = newDefaultAction(controller, "create"); - action.createParam("key").setRequired(true).setDefaultValue("abc"); - controller.done(); - }).define(context)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Default value must not be set on parameter 'api/rule/create?key' as it's marked as required"); - } - - @Test - public void fail_if_duplicated_action_parameters() { - assertThatThrownBy(() -> ((WebService) context -> { - NewController controller = context.createController("api/rule"); - NewAction action = newDefaultAction(controller, "create"); - action.createParam("key"); - action.createParam("key"); - controller.done(); - }).define(context)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("The parameter 'key' is defined multiple times in the action 'create'"); - } - - @Test - public void ws_is_internal_if_all_actions_are_internal() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "create").setInternal(true); - newDefaultAction(newController, "update").setInternal(true); - newController.done(); - }).define(context); - - assertThat(context.controller("api/rule").isInternal()).isTrue(); - } - - @Test - public void response_example() { - MetricWs metricWs = new MetricWs(); - metricWs.define(context); - WebService.Action action = context.controller("api/metric").action("create"); - - assertThat(action.responseExampleFormat()).isEqualTo("txt"); - assertThat(action.responseExample()).isNotNull(); - assertThat(StringUtils.trim(action.responseExampleAsString())).isEqualTo("example of WS response"); - } - - @Test - public void fail_to_open_response_example() { - WebService ws = context -> { - try { - NewController controller = context.createController("foo"); - newDefaultAction(controller, "bar").setResponseExample(new URL("file:/does/not/exist")); - controller.done(); - } catch (MalformedURLException e) { - e.printStackTrace(); - } - }; - ws.define(context); - - WebService.Action action = context.controller("foo").action("bar"); - try { - action.responseExampleAsString(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Fail to load file:/does/not/exist"); - } - } - - @Test - public void post_action_without_response_example() { - WebService ws = context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list").setPost(true).setResponseExample(null); - newController.done(); - }; - ws.define(context); - - assertThat(logTester.logs(LoggerLevel.WARN)) - .doesNotContain("The response example is not set on action api/rule/list"); - } - - @Test - public void fail_if_get_and_no_response_example() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list").setResponseExample(null); - newController.done(); - }).define(context); - - assertThat(logTester.logs(LoggerLevel.WARN)) - .contains("The response example is not set on action api/rule/list"); - } - - @Test - public void log_if_since_on_an_action_is_empty() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list") - .setSince(""); - newController.done(); - }).define(context); - - assertThat(logTester.logs(LoggerLevel.WARN)) - .contains("Since is not set on action api/rule/list"); - } - - @Test - public void log_if_since_on_an_action_is_null() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list") - .setSince(null); - newController.done(); - }).define(context); - - assertThat(logTester.logs(LoggerLevel.WARN)) - .contains("Since is not set on action api/rule/list"); - } - - @Test - public void log_if_action_description_is_empty() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list") - .setDescription(""); - newController.done(); - }).define(context); - - assertThat(logTester.logs(LoggerLevel.WARN)) - .contains("Description is not set on action api/rule/list"); - } - - @Test - public void log_if_action_description_is_null() { - ((WebService) context -> { - NewController newController = context.createController("api/rule"); - newDefaultAction(newController, "list") - .setDescription(null); - newController.done(); - }).define(context); - - assertThat(logTester.logs(LoggerLevel.WARN)) - .contains("Description is not set on action api/rule/list"); - } - - static class MetricWs implements WebService { - boolean showCalled = false; - boolean createCalled = false; - - @Override - public void define(Context context) { - NewController newController = context.createController("api/metric") - .setDescription("Metrics") - .setSince("3.2"); - - newController.createAction("show") - .setDescription("Show metric") - .setSince("4.2") - .setResponseExample(getClass().getResource("WebServiceTest/response-example.txt")) - .setHandler(this::show); - - newController.createAction("create") - .setDescription("Create metric") - .setSince("4.1") - .setDeprecatedSince("5.3") - .setPost(true) - .setInternal(true) - .setResponseExample(getClass().getResource("WebServiceTest/response-example.txt")) - .setChangelog( - new Change("6.4", "Last event"), - new Change("6.0", "Old event"), - new Change("4.5.6", "Very old event")) - .setHandler(this::create); - - newController.done(); - } - - void show(Request request, Response response) { - showCalled = true; - } - - void create(Request request, Response response) { - createCalled = true; - } - } - - private NewAction newDefaultAction(NewController controller, String actionKey) { - return controller.createAction(actionKey) - .setDescription("default description") - .setSince("5.3") - .setResponseExample(getClass().getResource("WebServiceTest/response-example.txt")) - .setHandler(mock(RequestHandler.class)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/task/TaskDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/task/TaskDefinitionTest.java deleted file mode 100644 index b921e1a4094..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/task/TaskDefinitionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.task; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class TaskDefinitionTest { - - @Test - public void should_build() { - TaskDefinition def = TaskDefinition.builder().key("foo").taskClass(FooTask.class).description("Foo").build(); - assertThat(def.key()).isEqualTo("foo"); - assertThat(def.description()).isEqualTo("Foo"); - assertThat(def.taskClass()).isEqualTo(FooTask.class); - assertThat(def.toString()).isEqualTo("Task foo[class=org.sonar.api.task.TaskDefinitionTest$FooTask, desc=Foo]"); - } - - @Test - public void test_equals_and_hashcode() { - TaskDefinition def1 = TaskDefinition.builder().key("one").taskClass(FooTask.class).description("Foo").build(); - TaskDefinition def1bis = TaskDefinition.builder().key("one").taskClass(FooTask.class).description("Foo").build(); - TaskDefinition def2 = TaskDefinition.builder().key("two").taskClass(FooTask.class).description("Foo").build(); - - assertThat(def1) - .isEqualTo(def1) - .isEqualTo(def1bis); - assertThat(def2) - .isNotEqualTo(def1) - .isNotEqualTo("one") - .isNotNull(); - - assertThat(def1) - .hasSameHashCodeAs(def1) - .hasSameHashCodeAs(def1bis); - } - - @Test - public void test_compare() { - TaskDefinition foo = TaskDefinition.builder().key("foo").taskClass(FooTask.class).description("Foo").build(); - TaskDefinition bar = TaskDefinition.builder().key("bar").taskClass(FooTask.class).description("Bar").build(); - - assertThat(foo.compareTo(bar)).isGreaterThan(0); - assertThat(foo).isEqualByComparingTo(foo); - assertThat(bar.compareTo(foo)).isLessThan(0); - } - - @Test - public void description_should_be_required() { - assertThatThrownBy(() -> TaskDefinition.builder().key("foo").taskClass(FooTask.class).build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Description must be set for task 'foo'"); - } - - @Test - public void key_should_be_required() { - assertThatThrownBy(() -> TaskDefinition.builder().description("Foo").taskClass(FooTask.class).build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Task key must be set"); - } - - @Test - public void key_should_not_contain_spaces() { - assertThatThrownBy(() -> TaskDefinition.builder().key("fo o").description("foo").taskClass(FooTask.class).build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Task key 'fo o' must match " + TaskDefinition.KEY_PATTERN); - } - - @Test - public void class_should_be_required() { - assertThatThrownBy(() -> TaskDefinition.builder().key("foo").description("Foo").build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Class must be set for task 'foo'"); - } - - private static class FooTask implements Task { - public void execute() { - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/user/UserGroupValidationTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/user/UserGroupValidationTest.java deleted file mode 100644 index d6337de1b51..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/user/UserGroupValidationTest.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.user; - -import com.google.common.base.Strings; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class UserGroupValidationTest { - - @Test - public void fail_when_group_name_is_Anyone() { - assertThatThrownBy(() -> UserGroupValidation.validateGroupName("AnyOne")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Anyone group cannot be used"); - } - - @Test - public void fail_when_group_name_is_empty() { - assertThatThrownBy(() -> UserGroupValidation.validateGroupName("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be empty"); - } - - @Test - public void fail_when_group_name_contains_only_blank() { - assertThatThrownBy(() -> UserGroupValidation.validateGroupName(" ")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be empty"); - } - - @Test - public void fail_when_group_name_is_too_big() { - assertThatThrownBy(() -> UserGroupValidation.validateGroupName(Strings.repeat("name", 300))) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be longer than 255 characters"); - } - - @Test - public void fail_when_group_name_is_null() { - assertThatThrownBy(() -> UserGroupValidation.validateGroupName(null)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Group name cannot be empty"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/user/UserQueryTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/user/UserQueryTest.java deleted file mode 100644 index 9d8a0bbe7d2..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/user/UserQueryTest.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.user; - -import org.junit.Test; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class UserQueryTest { - @Test - public void test_all_actives() { - assertThat(UserQuery.ALL_ACTIVES.includeDeactivated()).isFalse(); - assertThat(UserQuery.ALL_ACTIVES.logins()).isNull(); - assertThat(UserQuery.ALL_ACTIVES.searchText()).isNull(); - assertThat(UserQuery.ALL_ACTIVES.searchTextSql).isNull(); - } - - @Test - public void test_all() { - UserQuery all = UserQuery.builder().includeDeactivated().build(); - assertThat(all.includeDeactivated()).isTrue(); - assertThat(all.logins()).isNull(); - } - - @Test - public void test_logins() { - UserQuery query = UserQuery.builder().logins("simon", "loic").build(); - assertThat(query.includeDeactivated()).isFalse(); - assertThat(query.logins()).containsOnly("simon", "loic"); - - query = UserQuery.builder().logins(Arrays.asList("simon", "loic")).build(); - assertThat(query.logins()).containsOnly("simon", "loic"); - } - - @Test - public void should_limit_number_of_logins() { - List<String> logins = new ArrayList<>(); - for (int i = 0; i < 1010; i++) { - logins.add(String.valueOf(i)); - } - try { - UserQuery.builder().logins(logins).build(); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("Max number of logins is 1000. Got 1010"); - } - } - - @Test - public void searchText() { - UserQuery query = UserQuery.builder().searchText("sim").build(); - assertThat(query.searchText()).isEqualTo("sim"); - assertThat(query.searchTextSql).isEqualTo("%sim%"); - } - - @Test - public void searchText_escape_special_characters_in_like() { - UserQuery query = UserQuery.builder().searchText("%sim_").build(); - assertThat(query.searchText()).isEqualTo("%sim_"); - assertThat(query.searchTextSql).isEqualTo("%/%sim/_%"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/AnnotationUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/AnnotationUtilsTest.java deleted file mode 100644 index f6d09eb46cc..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/AnnotationUtilsTest.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import static org.assertj.core.api.Assertions.assertThat; - -public class AnnotationUtilsTest { - - @Test - public void getClassAnnotation() { - FakeAnnotation annotation = AnnotationUtils.getAnnotation(new SuperClass(), FakeAnnotation.class); - assertThat(annotation.value()).isEqualTo("foo"); - } - - @Test - public void searchClassAnnotationInSuperClass() { - FakeAnnotation annotation = AnnotationUtils.getAnnotation(new ChildClass(), FakeAnnotation.class); - assertThat(annotation.value()).isEqualTo("foo"); - } - - @Test - public void searchClassAnnotationInInterface() { - FakeAnnotation annotation = AnnotationUtils.getAnnotation(new ImplementedClass(), FakeAnnotation.class); - assertThat(annotation.value()).isEqualTo("foo"); - } - - @Test - public void noClassAnnotation() { - FakeAnnotation annotation = AnnotationUtils.getAnnotation("a string", FakeAnnotation.class); - assertThat(annotation).isNull(); - } - - @Test - public void shouldAcceptClasses() { - FakeAnnotation annotation = AnnotationUtils.getAnnotation(SuperClass.class, FakeAnnotation.class); - assertThat(annotation.value()).isEqualTo("foo"); - - annotation = AnnotationUtils.getAnnotation(ChildClass.class, FakeAnnotation.class); - assertThat(annotation.value()).isEqualTo("foo"); - } - -} - -@Retention(RetentionPolicy.RUNTIME) -@Target(ElementType.TYPE) - @interface FakeAnnotation { - String value(); -} - -@FakeAnnotation("foo") -class SuperClass { -} - -class ChildClass extends SuperClass { - -} - -@FakeAnnotation("foo") -interface AnnotatedInterface { -} - -abstract class AbstractClass implements AnnotatedInterface { - -} -class ImplementedClass extends AbstractClass { - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/DateUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/DateUtilsTest.java deleted file mode 100644 index 60a9893a983..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/DateUtilsTest.java +++ /dev/null @@ -1,195 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import com.tngtech.java.junit.dataprovider.DataProvider; -import com.tngtech.java.junit.dataprovider.DataProviderRunner; -import com.tngtech.java.junit.dataprovider.UseDataProvider; -import java.time.LocalDate; -import java.time.OffsetDateTime; -import java.time.ZoneId; -import java.util.Date; -import org.junit.Test; -import org.junit.runner.RunWith; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.api.utils.DateUtils.parseDateOrDateTime; -import static org.sonar.api.utils.DateUtils.parseEndingDateOrDateTime; -import static org.sonar.api.utils.DateUtils.parseStartingDateOrDateTime; - -@RunWith(DataProviderRunner.class) -public class DateUtilsTest { - - @Test - public void parseDate_valid_format() { - Date date = DateUtils.parseDate("2010-05-18"); - assertThat(date.getDate()).isEqualTo(18); - } - - @Test - public void parseDate_not_valid_format() { - assertThatThrownBy(() -> DateUtils.parseDate("2010/05/18")) - .isInstanceOf(MessageException.class); - } - - @Test - public void parseDate_not_lenient() { - assertThatThrownBy(() -> DateUtils.parseDate("2010-13-18")) - .isInstanceOf(MessageException.class); - } - - @Test - public void parseDateQuietly() { - assertThat(DateUtils.parseDateQuietly("2010/05/18")).isNull(); - Date date = DateUtils.parseDateQuietly("2010-05-18"); - assertThat(date.getDate()).isEqualTo(18); - } - - @Test - public void parseDate_fail_if_additional_characters() { - assertThatThrownBy(() -> DateUtils.parseDate("1986-12-04foo")) - .isInstanceOf(MessageException.class); - } - - @Test - public void parseDateTime_valid_format() { - Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100"); - assertThat(date.getMinutes()).isEqualTo(50); - } - - @Test - public void parseDateTime_not_valid_format() { - assertThatThrownBy(() -> DateUtils.parseDate("2010/05/18 10:55")) - .isInstanceOf(MessageException.class); - } - - @Test - public void parseDateTime_fail_if_additional_characters() { - assertThatThrownBy(() -> DateUtils.parseDate("1986-12-04T01:02:03+0300foo")) - .isInstanceOf(MessageException.class); - } - - @Test - public void parseDateTimeQuietly() { - assertThat(DateUtils.parseDateTimeQuietly("2010/05/18 10:55")).isNull(); - Date date = DateUtils.parseDateTimeQuietly("2010-05-18T15:50:45+0100"); - assertThat(date.getMinutes()).isEqualTo(50); - } - - @Test - public void shouldFormatDate() { - assertThat(DateUtils.formatDate(new Date())).startsWith("20"); - assertThat(DateUtils.formatDate(new Date())).hasSize(10); - } - - @Test - public void shouldFormatDateTime() { - assertThat(DateUtils.formatDateTime(new Date())).startsWith("20"); - assertThat(DateUtils.formatDateTime(new Date()).length()).isGreaterThan(20); - } - - @Test - public void shouldFormatDateTime_with_long() { - assertThat(DateUtils.formatDateTime(System.currentTimeMillis())).startsWith("20"); - assertThat(DateUtils.formatDateTime(System.currentTimeMillis()).length()).isGreaterThan(20); - } - - @Test - public void format_date_time_null_safe() { - assertThat(DateUtils.formatDateTimeNullSafe(new Date())).startsWith("20"); - assertThat(DateUtils.formatDateTimeNullSafe(new Date()).length()).isGreaterThan(20); - assertThat(DateUtils.formatDateTimeNullSafe(null)).isEmpty(); - } - - @Test - public void long_to_date() { - Date date = new Date(); - assertThat(DateUtils.longToDate(date.getTime())).isEqualTo(date); - assertThat(DateUtils.longToDate(null)).isNull(); - } - - @Test - public void date_to_long() { - Date date = new Date(); - assertThat(DateUtils.dateToLong(date)).isEqualTo(date.getTime()); - assertThat(DateUtils.dateToLong(null)).isNull(); - } - - @DataProvider - public static Object[][] date_times() { - return new Object[][]{ - {"2014-05-27", Date.from(LocalDate.parse("2014-05-27").atStartOfDay(ZoneId.systemDefault()).toInstant())}, - {"2014-05-27T15:50:45+0100", Date.from(OffsetDateTime.parse("2014-05-27T15:50:45+01:00").toInstant())}, - {null, null} - }; - } - - @Test - @UseDataProvider("date_times") - public void param_as__date_time(String stringDate, Date expectedDate) { - assertThat(parseDateOrDateTime(stringDate)).isEqualTo(expectedDate); - assertThat(parseStartingDateOrDateTime(stringDate)).isEqualTo(expectedDate); - } - - @Test - public void param_as__date_time_provided_timezone() { - final ZoneId zoneId = ZoneId.of("Europe/Moscow"); - assertThat(parseDateOrDateTime("2020-05-27", zoneId)).isEqualTo(Date.from(OffsetDateTime.parse("2020-05-27T00:00:00+03:00").toInstant())); - assertThat(parseStartingDateOrDateTime("2020-05-27", zoneId)).isEqualTo(Date.from(OffsetDateTime.parse("2020-05-27T00:00:00+03:00").toInstant())); - } - - @Test - public void param_as_ending_date_time_default_timezone() { - assertThat(parseEndingDateOrDateTime("2014-05-27")).isEqualTo(Date.from(LocalDate.parse("2014-05-28").atStartOfDay(ZoneId.systemDefault()).toInstant())); - assertThat(parseEndingDateOrDateTime("2014-05-27T15:50:45+0100")).isEqualTo(Date.from(OffsetDateTime.parse("2014-05-27T15:50:45+01:00").toInstant())); - assertThat(parseEndingDateOrDateTime(null)).isNull(); - } - - @Test - public void param_as_ending_date_time_provided_timezone() { - final ZoneId zoneId = ZoneId.of("Europe/Moscow"); - assertThat(parseEndingDateOrDateTime("2020-05-27", zoneId)).isEqualTo(Date.from(OffsetDateTime.parse("2020-05-28T00:00:00+03:00").toInstant())); - assertThat(parseEndingDateOrDateTime("2014-05-27T15:50:45+0100", zoneId)).isEqualTo(Date.from(OffsetDateTime.parse("2014-05-27T15:50:45+01:00").toInstant())); - assertThat(parseEndingDateOrDateTime(null, zoneId)).isNull(); - } - - @Test - public void fail_when_param_as_date_or_datetime_not_a_datetime() { - assertThatThrownBy(() -> parseDateOrDateTime("polop")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Date 'polop' cannot be parsed as either a date or date+time"); - } - - @Test - public void fail_when_param_as_starting_datetime_not_a_datetime() { - assertThatThrownBy(() -> parseStartingDateOrDateTime("polop")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Date 'polop' cannot be parsed as either a date or date+time"); - } - - @Test - public void fail_when_param_as_ending_datetime_not_a_datetime() { - assertThatThrownBy(() -> parseEndingDateOrDateTime("polop")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessageContaining("'polop' cannot be parsed as either a date or date+time"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/DurationTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/DurationTest.java deleted file mode 100644 index d0bf21fc3ee..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/DurationTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class DurationTest { - - static final int HOURS_IN_DAY = 8; - - static final Long ONE_MINUTE = 1L; - static final Long ONE_HOUR_IN_MINUTES = ONE_MINUTE * 60; - static final Long ONE_DAY_IN_MINUTES = ONE_HOUR_IN_MINUTES * HOURS_IN_DAY; - - @Test - public void create_from_duration_in_minutes() { - Duration duration = Duration.create(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE); - assertThat(duration.toMinutes()).isEqualTo(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE); - } - - @Test - public void encode() { - assertThat(Duration.create(2 * ONE_DAY_IN_MINUTES + 5 * ONE_HOUR_IN_MINUTES + 46 * ONE_MINUTE).encode(HOURS_IN_DAY)).isEqualTo("2d5h46min"); - assertThat(Duration.create(ONE_DAY_IN_MINUTES).encode(HOURS_IN_DAY)).isEqualTo("1d"); - assertThat(Duration.create(ONE_HOUR_IN_MINUTES).encode(HOURS_IN_DAY)).isEqualTo("1h"); - assertThat(Duration.create(HOURS_IN_DAY * ONE_HOUR_IN_MINUTES).encode(HOURS_IN_DAY)).isEqualTo("1d"); - assertThat(Duration.create(ONE_MINUTE).encode(HOURS_IN_DAY)).isEqualTo("1min"); - assertThat(Duration.create(0).encode(HOURS_IN_DAY)).isEqualTo("0min"); - } - - @Test - public void decode() { - assertThat(Duration.decode(" 15 d 23 h 42min ", HOURS_IN_DAY)).isEqualTo(Duration.create(15 * ONE_DAY_IN_MINUTES + 23 * ONE_HOUR_IN_MINUTES + 42 * ONE_MINUTE)); - assertThat(Duration.decode("15d23h42min", HOURS_IN_DAY)).isEqualTo(Duration.create(15 * ONE_DAY_IN_MINUTES + 23 * ONE_HOUR_IN_MINUTES + 42 * ONE_MINUTE)); - assertThat(Duration.decode("23h", HOURS_IN_DAY)).isEqualTo(Duration.create(23 * ONE_HOUR_IN_MINUTES)); - assertThat(Duration.decode("15d", HOURS_IN_DAY)).isEqualTo(Duration.create(15 * ONE_DAY_IN_MINUTES)); - assertThat(Duration.decode("42min", HOURS_IN_DAY)).isEqualTo(Duration.create(42 * ONE_MINUTE)); - assertThat(Duration.decode("0min", HOURS_IN_DAY)).isEqualTo(Duration.create(0)); - - assertThat(Duration.decode("25h61min", HOURS_IN_DAY)).isEqualTo(Duration.create(25 * ONE_HOUR_IN_MINUTES + 61)); - } - - @Test - public void fail_to_decode_if_unit_with_invalid_number() { - try { - Duration.decode("Xd", HOURS_IN_DAY); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Duration 'Xd' is invalid, it should use the following sample format : 2d 10h 15min"); - } - } - - @Test - public void fail_to_decode_if_no_valid_duration() { - try { - Duration.decode("foo", HOURS_IN_DAY); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Duration 'foo' is invalid, it should use the following sample format : 2d 10h 15min"); - } - } - - @Test - public void fail_to_decode_if_only_number() { - try { - Duration.decode("15", HOURS_IN_DAY); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Duration '15' is invalid, it should use the following sample format : 2d 10h 15min"); - } - } - - @Test - public void fail_to_decode_if_valid_unit_with_invalid_duration() { - try { - Duration.decode("15min foo", HOURS_IN_DAY); - fail(); - } catch (Exception e) { - assertThat(e).isInstanceOf(IllegalArgumentException.class).hasMessage("Duration '15min foo' is invalid, it should use the following sample format : 2d 10h 15min"); - } - } - - @Test - public void is_greater_than() { - assertThat(Duration.decode("1h", HOURS_IN_DAY).isGreaterThan(Duration.decode("1min", HOURS_IN_DAY))).isTrue(); - assertThat(Duration.decode("1min", HOURS_IN_DAY).isGreaterThan(Duration.decode("1d", HOURS_IN_DAY))).isFalse(); - assertThat(Duration.decode("1d", HOURS_IN_DAY).isGreaterThan(Duration.decode("1d", HOURS_IN_DAY))).isFalse(); - assertThat(Duration.decode("1d", 10).isGreaterThan(Duration.decode("1d", 8))).isTrue(); - } - - @Test - public void add() { - assertThat(Duration.decode("1h", HOURS_IN_DAY).add(Duration.decode("1min", HOURS_IN_DAY))).isEqualTo(Duration.decode("1h1min", HOURS_IN_DAY)); - } - - @Test - public void subtract() { - assertThat(Duration.decode("1h", HOURS_IN_DAY).subtract(Duration.decode("1min", HOURS_IN_DAY))).isEqualTo(Duration.decode("59min", HOURS_IN_DAY)); - } - - @Test - public void multiply() { - assertThat(Duration.decode("1h", HOURS_IN_DAY).multiply(2)).isEqualTo(Duration.decode("2h", HOURS_IN_DAY)); - } - - @Test - public void test_equals_and_hashcode() throws Exception { - Duration duration = Duration.create(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE); - Duration durationWithSameValue = Duration.create(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE); - Duration durationWithDifferentValue = Duration.create(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES); - - assertThat(duration) - .isEqualTo(duration) - .isEqualTo(durationWithSameValue) - .isNotEqualTo(durationWithDifferentValue) - .isNotNull() - .hasSameHashCodeAs(duration); - assertThat(durationWithSameValue).hasSameHashCodeAs(duration); - assertThat(durationWithDifferentValue.hashCode()).isNotEqualTo(duration.hashCode()); - } - - @Test - public void test_toString() throws Exception { - assertThat(Duration.create(ONE_DAY_IN_MINUTES + ONE_HOUR_IN_MINUTES + ONE_MINUTE).toString()).isNotNull(); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/DurationsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/DurationsTest.java deleted file mode 100644 index ef7de512a82..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/DurationsTest.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class DurationsTest { - - private static final int HOURS_IN_DAY = 8; - - private static final long ONE_MINUTE = 1L; - private static final long ONE_HOUR = ONE_MINUTE * 60; - private static final long ONE_DAY = HOURS_IN_DAY * ONE_HOUR; - - private Durations underTest = new Durations(); - - @Test - public void create_from_minutes() { - assertThat(underTest.create(10L).toMinutes()).isEqualTo(10L); - } - - @Test - public void decode() { - // 1 working day -> 8 hours - assertThat(underTest.decode("1d").toMinutes()).isEqualTo(8L * ONE_HOUR); - // 8 hours - assertThat(underTest.decode("8h").toMinutes()).isEqualTo(8L * ONE_HOUR); - } - - @Test - public void format() { - assertThat(underTest.format(Duration.create(5 * ONE_DAY))).isEqualTo("5d"); - assertThat(underTest.format(Duration.create(2 * ONE_HOUR))).isEqualTo("2h"); - assertThat(underTest.format(Duration.create(ONE_MINUTE))).isEqualTo("1min"); - - assertThat(underTest.format(Duration.create(5 * ONE_DAY + 2 * ONE_HOUR))).isEqualTo("5d 2h"); - assertThat(underTest.format(Duration.create(2 * ONE_HOUR + ONE_MINUTE))).isEqualTo("2h 1min"); - assertThat(underTest.format(Duration.create(5 * ONE_DAY + 2 * ONE_HOUR + ONE_MINUTE))).isEqualTo("5d 2h"); - } - - @Test - public void not_display_following_element_when_bigger_than_ten() { - assertThat(underTest.format(Duration.create(15 * ONE_DAY + 7 * ONE_HOUR + ONE_MINUTE))).isEqualTo("15d"); - } - - @Test - public void display_zero_without_unit() { - assertThat(underTest.format(Duration.create(0))).isEqualTo("0"); - } - - @Test - public void display_negative_duration() { - assertThat(underTest.format(Duration.create(-5 * ONE_DAY))).isEqualTo("-5d"); - assertThat(underTest.format(Duration.create(-2 * ONE_HOUR))).isEqualTo("-2h"); - assertThat(underTest.format(Duration.create(-1 * ONE_MINUTE))).isEqualTo("-1min"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ExceptionCauseMatcher.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/ExceptionCauseMatcher.java deleted file mode 100644 index 90f2ee4d7d6..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ExceptionCauseMatcher.java +++ /dev/null @@ -1,91 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.util.Objects; -import javax.annotation.CheckForNull; -import javax.annotation.Nullable; -import javax.annotation.concurrent.Immutable; -import org.hamcrest.Description; -import org.hamcrest.Matcher; -import org.hamcrest.TypeSafeMatcher; - -/** - * Matchers designed to be used as an argument of {@link org.junit.rules.ExpectedException#expectCause(Matcher)} such as: - * - * <pre> - * expectedException.expect(VisitException.class); - * expectedException.expectCause(hasType(IllegalArgumentException.class).andMessage("file and otherFile Components can not be the same")); - * </pre> - * - * Class strongly inspired from {@code CauseMatcher} class from {@code http://blog.codeleak.pl/2014/03/junit-expectedexception-rule-beyond.html} - */ -@Immutable -public class ExceptionCauseMatcher extends TypeSafeMatcher<Throwable> { - private static final String EXPECT_NO_MESSAGE_CONSTANT = "RQXG8QTUCXOT7HZ3APPKBKUE5"; - - private final Class<? extends Throwable> type; - @CheckForNull - private final String expectedMessage; - - private ExceptionCauseMatcher(Class<? extends Throwable> type, @Nullable String expectedMessage) { - this.type = type; - this.expectedMessage = expectedMessage; - } - - public static ExceptionCauseMatcher hasType(Class<? extends Throwable> type) { - return new ExceptionCauseMatcher(type, null); - } - - public ExceptionCauseMatcher andMessage(String expectedMessage) { - return new ExceptionCauseMatcher(type, Objects.requireNonNull(expectedMessage)); - } - - public ExceptionCauseMatcher andNoMessage() { - return new ExceptionCauseMatcher(type, EXPECT_NO_MESSAGE_CONSTANT); - } - - @Override - protected boolean matchesSafely(Throwable item) { - if (!type.isAssignableFrom(item.getClass())) { - return false; - } - if (expectedMessage == null) { - return true; - } - if (EXPECT_NO_MESSAGE_CONSTANT.equals(expectedMessage)) { - return item.getMessage() == null; - } - return item.getMessage().contains(expectedMessage); - } - - @Override - public void describeTo(Description description) { - description.appendText("of type ") - .appendValue(type); - if (EXPECT_NO_MESSAGE_CONSTANT.equals(expectedMessage)) { - description.appendText(" and no message"); - } else if (expectedMessage != null) { - description.appendText(" and message ") - .appendValue(expectedMessage); - } - description.appendText(" but"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/FieldUtils2Test.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/FieldUtils2Test.java deleted file mode 100644 index 1af2027d74e..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/FieldUtils2Test.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.lang.reflect.Field; -import java.util.List; -import java.util.stream.Collectors; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class FieldUtils2Test { - - @Test - public void shouldGetFieldsOfSingleClass() { - List<String> fields = fieldsName(FieldUtils2.getFields(FieldsWithDifferentModifiers.class, true)); - assertThat(fields).contains("publicField"); - assertThat(fields).contains("protectedField"); - assertThat(fields).contains("packageField"); - assertThat(fields).contains("privateField"); - assertThat(fields).contains("publicStaticField"); - assertThat(fields).contains("protectedStaticField"); - assertThat(fields).contains("packageStaticField"); - assertThat(fields).contains("privateStaticField"); - } - - @Test - public void shouldGetFieldsOfClassHierarchy() { - List<String> fields = fieldsName(FieldUtils2.getFields(Child.class, true)); - assertThat(fields).contains("publicField"); - assertThat(fields).contains("protectedField"); - assertThat(fields).contains("packageField"); - assertThat(fields).contains("privateField"); - assertThat(fields).contains("publicStaticField"); - assertThat(fields).contains("protectedStaticField"); - assertThat(fields).contains("packageStaticField"); - assertThat(fields).contains("privateStaticField"); - assertThat(fields).contains("childPrivateField"); - } - - @Test - public void shouldGetOnlyAccessibleFields() { - List<String> fields = fieldsName(FieldUtils2.getFields(Child.class, false)); - - assertThat(fields).contains("publicField"); - assertThat(fields).contains("publicStaticField"); - } - - @Test - public void shouldGetFieldsOfInterface() { - List<String> fields = fieldsName(FieldUtils2.getFields(InterfaceWithFields.class, true)); - - assertThat(fields).contains("INTERFACE_FIELD"); - } - - @Test - public void shouldGetFieldsOfInterfaceImplementation() { - List<String> fields = fieldsName(FieldUtils2.getFields(InterfaceImplementation.class, true)); - - assertThat(fields).contains("INTERFACE_FIELD"); - } - - private static List<String> fieldsName(List<Field> fields) { - return fields.stream().map(f -> f != null ? f.getName() : null).collect(Collectors.toList()); - } - - interface InterfaceWithFields { - String INTERFACE_FIELD = "foo"; - } - - static class InterfaceImplementation implements InterfaceWithFields { - } - - static class FieldsWithDifferentModifiers { - public String publicField; - protected String protectedField; - String packageField; - private String privateField; - - public static String publicStaticField; - protected static String protectedStaticField; - static String packageStaticField; - private static String privateStaticField; - } - - static class Child extends FieldsWithDifferentModifiers { - private String childPrivateField; - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/KeyValueFormatTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/KeyValueFormatTest.java deleted file mode 100644 index 5f940231ba8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/KeyValueFormatTest.java +++ /dev/null @@ -1,239 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import com.google.common.collect.ImmutableMap; -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.TreeMap; -import org.junit.Test; -import org.sonar.api.rules.RulePriority; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.entry; - -public class KeyValueFormatTest { - - @Test - public void test_parser() { - KeyValueFormat.FieldParser reader = new KeyValueFormat.FieldParser("abc=def;ghi=jkl"); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("def"); - assertThat(reader.nextKey()).isEqualTo("ghi"); - assertThat(reader.nextVal()).isEqualTo("jkl"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=1;ghi=2"); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("1"); - assertThat(reader.nextKey()).isEqualTo("ghi"); - assertThat(reader.nextVal()).isEqualTo("2"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=;ghi=jkl"); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEmpty(); - assertThat(reader.nextKey()).isEqualTo("ghi"); - assertThat(reader.nextVal()).isEqualTo("jkl"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=def"); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("def"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=\"def\";ghi=\"jkl\""); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("def"); - assertThat(reader.nextKey()).isEqualTo("ghi"); - assertThat(reader.nextVal()).isEqualTo("jkl"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("\"abc\"=\"def\";\"ghi\"=\"jkl\""); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("def"); - assertThat(reader.nextKey()).isEqualTo("ghi"); - assertThat(reader.nextVal()).isEqualTo("jkl"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=\"def\\\"ghi\""); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("def\"ghi"); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser(""); - assertThat(reader.nextKey()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=;def="); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEmpty(); - assertThat(reader.nextKey()).isEqualTo("def"); - assertThat(reader.nextVal()).isNull(); - - reader = new KeyValueFormat.FieldParser("abc=\"1=2;3\";def=\"4;5=6\""); - assertThat(reader.nextKey()).isEqualTo("abc"); - assertThat(reader.nextVal()).isEqualTo("1=2;3"); - assertThat(reader.nextKey()).isEqualTo("def"); - assertThat(reader.nextVal()).isEqualTo("4;5=6"); - assertThat(reader.nextKey()).isNull(); - } - - @Test - public void keep_order_of_linked_map() { - Map<String, String> map = new LinkedHashMap<>(); - map.put("lucky", "luke"); - map.put("aste", "rix"); - String s = KeyValueFormat.format(map); - assertThat(s).isEqualTo("lucky=luke;aste=rix"); - } - - @Test - public void shouldFormatMapOfIntegerString() { - Map<Integer, String> map = new LinkedHashMap<>(); - map.put(3, "three"); - map.put(5, "five"); - String s = KeyValueFormat.formatIntString(map); - assertThat(s).isEqualTo("3=three;5=five"); - } - - @Test - public void shouldFormatMapOfIntDouble() { - Map<Integer, Double> map = new LinkedHashMap<>(); - map.put(13, 2.0); - map.put(5, 5.75); - String s = KeyValueFormat.formatIntDouble(map); - assertThat(s).isEqualTo("13=2.0;5=5.75"); - } - - @Test - public void shouldSetEmptyFieldWhenNullValue() { - Map<Integer, Double> map = new LinkedHashMap<>(); - map.put(13, null); - map.put(5, 5.75); - String s = KeyValueFormat.formatIntDouble(map); - assertThat(s).isEqualTo("13=;5=5.75"); - } - - @Test - public void shouldFormatBlank() { - Map<Integer, String> map = new TreeMap<>(); - String s = KeyValueFormat.formatIntString(map); - assertThat(s).isEmpty(); - } - - @Test - public void shouldFormatDate() throws ParseException { - Map<Integer, Date> map = new LinkedHashMap<>(); - map.put(4, new SimpleDateFormat("yyyy-MM-dd").parse("2010-12-25")); - map.put(20, new SimpleDateFormat("yyyy-MM-dd").parse("2009-05-28")); - map.put(12, null); - String s = KeyValueFormat.formatIntDate(map); - assertThat(s).isEqualTo("4=2010-12-25;20=2009-05-28;12="); - } - - @Test - public void shouldParseStrings() { - Map<String, String> map = KeyValueFormat.parse("one=un;two=deux"); - assertThat(map.size()).isEqualTo(2); - assertThat(map) - .containsEntry("one", "un") - .containsEntry("two", "deux"); - assertThat(map.keySet().iterator().next()).isEqualTo("one");// same order as in string - } - - @Test - public void helper_parse_methods() { - assertThat(KeyValueFormat.parseIntDate("1=2014-01-15")).hasSize(1); - assertThat(KeyValueFormat.parseIntDateTime("1=2014-01-15T15:50:45+0100")).hasSize(1); - assertThat(KeyValueFormat.parseIntDouble("1=3.14")).hasSize(1); - assertThat(KeyValueFormat.parseIntInt("1=10")).containsOnly(entry(1, 10)); - assertThat(KeyValueFormat.parseIntString("1=one")).containsOnly(entry(1, "one")); - assertThat(KeyValueFormat.parseIntString("1=\"escaped\"")).containsOnly(entry(1, "escaped")); - assertThat(KeyValueFormat.parseStringInt("one=1")).containsOnly(entry("one", 1)); - assertThat(KeyValueFormat.parseStringDouble("pi=3.14")).containsOnly(entry("pi", 3.14)); - } - - @Test - public void helper_format_methods() { - assertThat(KeyValueFormat.formatIntDateTime(ImmutableMap.of(1, new Date()))).startsWith("1="); - assertThat(KeyValueFormat.formatIntDate(ImmutableMap.of(1, new Date()))).startsWith("1="); - assertThat(KeyValueFormat.formatIntDouble(ImmutableMap.of(1, 3.14))).startsWith("1="); - assertThat(KeyValueFormat.formatIntString(ImmutableMap.of(1, "one"))).isEqualTo("1=one"); - assertThat(KeyValueFormat.formatStringInt(ImmutableMap.of("one", 1))).isEqualTo("one=1"); - } - - @Test - public void parse_blank() { - Map<String, String> map = KeyValueFormat.parse(""); - assertThat(map).isEmpty(); - } - - @Test - public void parse_null() { - Map<String, String> map = KeyValueFormat.parse(null); - assertThat(map).isEmpty(); - } - - @Test - public void parse_empty_values() { - Map<Integer, Double> map = KeyValueFormat.parseIntDouble("4=4.2;2=;6=6.68"); - assertThat(map.size()).isEqualTo(3); - assertThat(map.get(4)).isEqualTo(4.2); - // key is present but value is null - assertThat(map.containsKey(2)).isTrue(); - assertThat(map.get(2)).isNull(); - assertThat(map.get(6)).isEqualTo(6.68); - } - - @Test - public void convert_deprecated_priority() { - assertThat(KeyValueFormat.newPriorityConverter().format(RulePriority.BLOCKER)).isEqualTo("BLOCKER"); - assertThat(KeyValueFormat.newPriorityConverter().format(null)).isEmpty(); - - assertThat(KeyValueFormat.newPriorityConverter().parse("MAJOR")).isEqualTo(RulePriority.MAJOR); - assertThat(KeyValueFormat.newPriorityConverter().parse("")).isNull(); - } - - @Test - public void escape_strings() { - Map<String, String> input = new LinkedHashMap<>(); - input.put("foo", "a=b=c"); - input.put("bar", "a;b;c"); - input.put("baz", "double\"quote"); - String csv = KeyValueFormat.format(input); - assertThat(csv).isEqualTo("foo=\"a=b=c\";bar=\"a;b;c\";baz=double\"quote"); - - Map<String, String> output = KeyValueFormat.parse(csv); - assertThat(output) - .containsEntry("foo", "a=b=c") - .containsEntry("bar", "a;b;c") - .containsEntry("baz", "double\"quote"); - } - - @Test - public void not_instantiable() { - // only static methods. Bad pattern, should be improved. - TestUtils.hasOnlyPrivateConstructors(KeyValueFormat.class); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/LocalizedMessagesTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/LocalizedMessagesTest.java deleted file mode 100644 index 18ff235768a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/LocalizedMessagesTest.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import com.google.common.collect.Iterators; -import com.google.common.collect.Lists; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.Test; - -import java.util.Enumeration; -import java.util.List; -import java.util.Locale; -import java.util.MissingResourceException; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LocalizedMessagesTest { - private static final Locale DEFAULT_LOCALE = Locale.getDefault(); - - @BeforeClass - public static void beforeAll() { - Locale.setDefault(Locale.ENGLISH); - } - - @AfterClass - public static void afterAll() { - Locale.setDefault(DEFAULT_LOCALE); - } - - @Test - public void mergeBundles() { - LocalizedMessages messages = new LocalizedMessages(Locale.ENGLISH, "Test", "PluginFoo"); - - assertThat(messages.getString("test.one")).isEqualTo("One"); - assertThat(messages.getString("test.two")).isEqualTo("Two"); - assertThat(messages.getString("foo.hello")).isEqualTo("Hello"); - } - - @Test - public void mergeBundlesByLocale() { - LocalizedMessages messages = new LocalizedMessages(Locale.FRENCH, "Test", "PluginFoo"); - - assertThat(messages.getString("test.one")).isEqualTo("Un"); - assertThat(messages.getString("test.two")).isEqualTo("Deux"); - assertThat(messages.getString("foo.hello")).isEqualTo("Hello");// not in french, use the default locale - } - - @Test - public void useDefaultWhenMissingLocale() { - LocalizedMessages messages = new LocalizedMessages(Locale.JAPANESE, "Test", "PluginFoo"); - - assertThat(messages.getString("test.one")).isEqualTo("One"); - assertThat(messages.getString("foo.hello")).isEqualTo("Hello"); - } - - @Test(expected = MissingResourceException.class) - public void failIfMissingKey() { - LocalizedMessages messages = new LocalizedMessages(Locale.FRENCH, "Test", "PluginFoo"); - messages.getString("unknown"); - } - - @Test - public void format() { - LocalizedMessages messages = new LocalizedMessages(Locale.ENGLISH, "Test", "PluginFoo"); - assertThat(messages.format("test.one")).isEqualTo("One"); - } - - @Test - public void formatNeverFails() { - LocalizedMessages messages = new LocalizedMessages(Locale.ENGLISH, "Test", "PluginFoo"); - assertThat(messages.format("unknown")).isEqualTo("unknown"); - } - - @Test - public void formatParameters() { - LocalizedMessages messages = new LocalizedMessages(Locale.ENGLISH, "Test", "PluginFoo"); - assertThat(messages.format("with.string.params", "inspection", "rock")).isEqualTo("Continuous inspection will rock !"); - assertThat(messages.format("with.string.params", "rock", "inspection")).isEqualTo("Continuous rock will inspection !"); - } - - @Test - public void getKeys() { - LocalizedMessages messages = new LocalizedMessages(Locale.ENGLISH, "Test", "PluginFoo"); - assertThat(toList(messages.getKeys())).contains("test.one", "test.two", "foo.hello"); - - LocalizedMessages spanishMessages = new LocalizedMessages(new Locale("es"), "Test", "PluginFoo"); - assertThat(toList(spanishMessages.getKeys())).contains("test.one", "only.in.spanish"); - } - - private List<String> toList(Enumeration<String> enumeration) { - return Lists.newArrayList(Iterators.forEnumeration(enumeration)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ManifestUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/ManifestUtilsTest.java deleted file mode 100644 index 1c0f7787ffd..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ManifestUtilsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.OutputStream; -import java.net.URLClassLoader; -import java.util.List; -import java.util.jar.Attributes; -import java.util.jar.JarOutputStream; -import java.util.jar.Manifest; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ManifestUtilsTest { - - @Rule - public TemporaryFolder tempDir = new TemporaryFolder(); - - @Test - public void emptyManifest() throws Exception { - Manifest mf = new Manifest(); - File jar = createJar(mf, "emptyManifest.jar"); - - URLClassLoader classloader = new URLClassLoader(FileUtils.toURLs(jar)); - assertThat(ManifestUtils.getPropertyValues(classloader, "foo")).isEmpty(); - } - - @Test - public void singleManifest() throws Exception { - Manifest mf = new Manifest(); - mf.getMainAttributes().putValue("foo", "bar"); - mf.getMainAttributes().putValue("other", "value"); - File jar = createJar(mf, "singleManifest.jar"); - - URLClassLoader classloader = new URLClassLoader(FileUtils.toURLs(jar)); - List<String> values = ManifestUtils.getPropertyValues(classloader, "foo"); - assertThat(values).containsOnly("bar"); - } - - @Test - public void manyManifests() throws Exception { - Manifest mf1 = new Manifest(); - mf1.getMainAttributes().putValue("foo", "bar"); - File jar1 = createJar(mf1, "manyManifests-one.jar"); - - Manifest mf2 = new Manifest(); - mf2.getMainAttributes().putValue("foo", "otherbar"); - File jar2 = createJar(mf2, "manyManifests-two.jar"); - - URLClassLoader classloader = new URLClassLoader(FileUtils.toURLs(jar1, jar2)); - List<String> values = ManifestUtils.getPropertyValues(classloader, "foo"); - assertThat(values).containsOnly("bar", "otherbar"); - } - - private File createJar(Manifest mf, String name) throws Exception { - mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); - File file = tempDir.newFile(name); - OutputStream out = new JarOutputStream(new FileOutputStream(file), mf); - out.flush(); - IOUtils.closeQuietly(out); - return file; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/MessageExceptionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/MessageExceptionTest.java deleted file mode 100644 index eae9414c2cb..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/MessageExceptionTest.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class MessageExceptionTest { - - @Test - public void should_create_exception() { - String message = "the message"; - MessageException exception = MessageException.of(message); - assertThat(exception.getMessage()).isEqualTo(message); - assertThat(exception).isInstanceOf(RuntimeException.class); - } - - @Test - public void should_create_exception_with_status_and_l10n_message_with_param(){ - MessageException exception = MessageException.ofL10n("key", "value"); - assertThat(exception.l10nKey()).isEqualTo("key"); - assertThat(exception.l10nParams()).containsOnly("value"); - } - - @Test - public void should_create_exception_with_status_and_l10n_message_without_param(){ - MessageException exception = MessageException.ofL10n("key", (Object[])null); - assertThat(exception.l10nKey()).isEqualTo("key"); - assertThat(exception.l10nParams()).isEmpty(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/PagingTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/PagingTest.java deleted file mode 100644 index 20f9a6a7446..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/PagingTest.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.api.utils.Paging.forPageIndex; - -public class PagingTest { - - @Test - public void test_pagination() { - Paging paging = forPageIndex(1).withPageSize(5).andTotal(20); - - assertThat(paging.pageSize()).isEqualTo(5); - assertThat(paging.pageIndex()).isOne(); - assertThat(paging.total()).isEqualTo(20); - - assertThat(paging.offset()).isZero(); - assertThat(paging.pages()).isEqualTo(4); - } - - @Test - public void test_offset() { - assertThat(forPageIndex(1).withPageSize(5).andTotal(20).offset()).isZero(); - assertThat(forPageIndex(2).withPageSize(5).andTotal(20).offset()).isEqualTo(5); - } - - @Test - public void test_number_of_pages() { - assertThat(forPageIndex(2).withPageSize(5).andTotal(20).pages()).isEqualTo(4); - assertThat(forPageIndex(2).withPageSize(5).andTotal(21).pages()).isEqualTo(5); - assertThat(forPageIndex(2).withPageSize(5).andTotal(25).pages()).isEqualTo(5); - assertThat(forPageIndex(2).withPageSize(5).andTotal(26).pages()).isEqualTo(6); - } - - @Test - public void page_size_should_be_strictly_positive() { - assertThatThrownBy(() -> forPageIndex(5).withPageSize(0).andTotal(5)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Page size must be strictly positive. Got 0"); - } - - @Test - public void page_index_should_be_strictly_positive() { - assertThatThrownBy(() -> forPageIndex(0).withPageSize(5).andTotal(5)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Page index must be strictly positive. Got 0"); - } - - @Test - public void total_items_should_be_positive() { - assertThatThrownBy(() -> forPageIndex(5).withPageSize(5).andTotal(-1)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Total items must be positive. Got -1"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ParsingUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/ParsingUtilsTest.java deleted file mode 100644 index 565ddf6baa8..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ParsingUtilsTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.text.ParseException; -import java.util.Locale; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ParsingUtilsTest { - - @Test - public void scaleValue() { - assertThat(ParsingUtils.scaleValue(23.3333333)).isEqualTo(23.33); - assertThat(ParsingUtils.scaleValue(23.777777)).isEqualTo(23.78); - - assertThat(ParsingUtils.scaleValue(23.3333333, 0)).isEqualTo(23.0); - assertThat(ParsingUtils.scaleValue(23.777777, 0)).isEqualTo(24.0); - } - - @Test - public void parseString() throws ParseException { - assertThat(ParsingUtils.parseNumber("23.12", Locale.ENGLISH)).isEqualTo(23.12); - assertThat(ParsingUtils.parseNumber("12345.67", Locale.ENGLISH)).isEqualTo(12345.67); - assertThat(ParsingUtils.parseNumber("12345,67", Locale.FRENCH)).isEqualTo(12345.67); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/PathUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/PathUtilsTest.java deleted file mode 100644 index 92583ae68a0..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/PathUtilsTest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FilenameUtils; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @since 4.0 - */ -public class PathUtilsTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void sanitize_succeeds() { - assertThat(PathUtils.sanitize("foo/bar/..")).isEqualTo("foo/"); - assertThat(PathUtils.sanitize("C:\\foo\\..\\bar")).isEqualTo("C:/bar"); - assertThat(PathUtils.sanitize(null)).isNull(); - } - - @Test - public void sanitize_invalid_paths_returns_null() { - assertThat(PathUtils.sanitize("../foo")).isNull(); - } - - @Test - public void canonicalPath_succeeds() throws Exception { - File file = temp.newFile(); - String path = PathUtils.canonicalPath(file); - assertThat(path).isEqualTo(FilenameUtils.separatorsToUnix(file.getCanonicalPath())); - } - - @Test - public void canonicalPath_returns_null_if_null_input() { - assertThat(PathUtils.canonicalPath(null)).isNull(); - } - - @Test - public void canonicalPath_fails_to_get_canonical_path() throws Exception { - File file = mock(File.class); - when(file.getCanonicalPath()).thenThrow(new IOException()); - - try { - PathUtils.canonicalPath(file); - fail(); - } catch (IllegalStateException e) { - assertThat(e.getCause()).isInstanceOf(IOException.class); - } - } - - @Test - public void only_statics() { - assertThat(TestUtils.hasOnlyPrivateConstructors(PathUtils.class)).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/System2Test.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/System2Test.java deleted file mode 100644 index 1292c7e1a86..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/System2Test.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.io.Closeable; -import java.io.IOException; -import java.util.Map; -import java.util.Properties; -import java.util.TimeZone; -import org.apache.commons.lang.SystemUtils; -import org.junit.Test; - -import static java.util.UUID.randomUUID; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class System2Test { - @Test - public void testNow() { - long start = System.currentTimeMillis(); - long now = System2.INSTANCE.now(); - long end = System.currentTimeMillis(); - assertThat(now).isGreaterThanOrEqualTo(start).isLessThanOrEqualTo(end); - } - - @Test - public void testProperties() { - Properties expected = System.getProperties(); - assertThat(System2.INSTANCE.properties()).isNotNull().isEqualTo(expected); - } - - @Test - public void testProperty() { - String expected = System.getProperty("java.version"); - assertThat(System2.INSTANCE.property("java.version")).isNotNull().isEqualTo(expected); - } - - @Test - public void testSetProperty() { - String key = "System2Test.testSetProperty"; - String value = randomUUID().toString(); - System2.INSTANCE.setProperty(key, value); - assertThat(System2.INSTANCE.property(key)).isEqualTo(value); - } - - @Test - public void testEnvVariables() { - Map<String, String> expected = System.getenv(); - assertThat(System2.INSTANCE.envVariables()).isNotNull().isEqualTo(expected); - } - - @Test - public void testEnvVariable() { - // assume that there's at least one env variable - if (System.getenv().isEmpty()) { - fail("Test can't succeed because there are no env variables. How is it possible ?"); - } - String key = System.getenv().keySet().iterator().next(); - String expected = System.getenv(key); - assertThat(System2.INSTANCE.envVariable(key)).isNotNull().isEqualTo(expected); - assertThat(System2.INSTANCE.envVariable("UNKNOWN_VAR")).isNull(); - } - - @Test - public void testIsOsWindows() { - assertThat(System2.INSTANCE.isOsWindows()).isEqualTo(SystemUtils.IS_OS_WINDOWS); - } - - @Test - public void testIsOsMac() { - assertThat(System2.INSTANCE.isOsMac()).isEqualTo(SystemUtils.IS_OS_MAC); - } - - @Test - public void testPrintln() { - // well, how to assert that ? Adding a System3 dependency to System2 ? :-) - System2.INSTANCE.println("foo"); - } - - @Test - public void testGetResource() { - String name = "META-INF/MANIFEST.MF"; - assertThat(System2.INSTANCE.getResource(name)).isEqualTo(getClass().getResource(name)); - } - - @Test - public void close() { - class MyCloseable implements Closeable { - boolean isClosed = false; - - @Override - public void close() { - isClosed = true; - } - } - - MyCloseable closeable = new MyCloseable(); - System2.INSTANCE.close(closeable); - assertThat(closeable.isClosed).isTrue(); - } - - @Test - public void close_throws_exception_on_error() { - Closeable closeable = () -> { - throw new IOException("expected"); - }; - try { - System2.INSTANCE.close(closeable); - fail(); - } catch (IllegalStateException e) { - assertThat(e.getCause().getMessage()).isEqualTo("expected"); - } - } - - @Test - public void getDefaultTimezone() { - assertThat(System2.INSTANCE.getDefaultTimeZone().getID()).isEqualTo(TimeZone.getDefault().getID()); - - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TestUtils.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/TestUtils.java deleted file mode 100644 index df2c7a9b2c1..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TestUtils.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Modifier; - -/** - * Utilities for unit tests - * - * @since 2.2 - */ -public final class TestUtils { - - private TestUtils() { - } - - /** - * Asserts that all constructors are private, usually for helper classes with - * only static methods. If a constructor does not have any parameters, then - * it's instantiated. - */ - public static boolean hasOnlyPrivateConstructors(Class clazz) { - boolean ok = true; - for (Constructor constructor : clazz.getDeclaredConstructors()) { - ok &= Modifier.isPrivate(constructor.getModifiers()); - if (constructor.getParameterTypes().length == 0) { - constructor.setAccessible(true); - try { - constructor.newInstance(); - } catch (Exception e) { - throw new IllegalStateException(String.format("Fail to instantiate %s", clazz), e); - } - } - } - return ok; - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeUtilsTest.java deleted file mode 100644 index 7c266b26e34..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/TimeUtilsTest.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class TimeUtilsTest { - @Test - public void formatDuration() { - assertThat(TimeUtils.formatDuration(0)).isEqualTo("0ms"); - assertThat(TimeUtils.formatDuration(100)).isEqualTo("100ms"); - assertThat(TimeUtils.formatDuration(1000)).isEqualTo("1s"); - assertThat(TimeUtils.formatDuration(10000)).isEqualTo("10s"); - assertThat(TimeUtils.formatDuration(100000)).isEqualTo("1min 40s"); - assertThat(TimeUtils.formatDuration(600000)).isEqualTo("10min"); - assertThat(TimeUtils.formatDuration(1000000)).isEqualTo("16min 40s"); - assertThat(TimeUtils.formatDuration(10000000)).isEqualTo("166min 40s"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/UriReaderTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/UriReaderTest.java deleted file mode 100644 index b60dbee875e..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/UriReaderTest.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; -import org.junit.Before; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class UriReaderTest { - - private static URI testFile; - - @Before - public void init() throws URISyntaxException { - testFile = UriReaderTest.class.getResource("/org/sonar/api/utils/UriReaderTest/foo.txt").toURI(); - } - - @Test - public void file_processor_is_always_available() { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - - assertThat(uriReader.searchForSupportedProcessor(testFile)).isNotNull(); - } - - @Test - public void file_readString() { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - assertThat(uriReader.readString(testFile, StandardCharsets.UTF_8)).isEqualTo("in foo"); - } - - @Test - public void file_readBytes() { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - assertThat(new String(uriReader.readBytes(testFile))).isEqualTo("in foo"); - } - - @Test - public void file_readString_fails_if_file_not_found() throws Exception { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - - assertThatThrownBy(() -> uriReader.readString(new URI("file:/notfound"), StandardCharsets.UTF_8)) - .isInstanceOf(RuntimeException.class); - } - - @Test - public void file_readBytes_fails_if_file_not_found() throws Exception { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - assertThatThrownBy(() -> uriReader.readBytes(new URI("file:/notfound"))) - .isInstanceOf(RuntimeException.class); - } - - @Test - public void file_description() { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - - // the prefix file:/ is removed - assertThat(uriReader.description(testFile)).doesNotMatch("file:/.*"); - assertThat(uriReader.description(testFile)).matches(".*foo\\.txt"); - } - - @Test - public void fail_if_unknown_scheme() { - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[0]); - - assertThatThrownBy(() -> uriReader.readBytes(new URI("ftp://sonarsource.org"))) - .isInstanceOf(RuntimeException.class); - } - - @Test - public void register_processors() throws Exception { - UriReader.SchemeProcessor processor = mock(UriReader.SchemeProcessor.class); - when(processor.getSupportedSchemes()).thenReturn(new String[] {"ftp"}); - UriReader uriReader = new UriReader(new UriReader.SchemeProcessor[] {processor}); - - assertThat(uriReader.searchForSupportedProcessor(new URI("ftp://sonarsource.org"))).isNotNull(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ValidationMessagesTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/ValidationMessagesTest.java deleted file mode 100644 index 31b6fdb83ff..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ValidationMessagesTest.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; -import org.sonar.api.utils.log.Logger; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.*; - -public class ValidationMessagesTest { - - @Test - public void emptyMessages() { - ValidationMessages messages = ValidationMessages.create(); - assertThat(messages.hasErrors()).isFalse(); - assertThat(messages.hasWarnings()).isFalse(); - assertThat(messages.hasInfos()).isFalse(); - - Logger logger = mock(Logger.class); - messages.log(logger); - verify(logger, never()).error(anyString()); - verify(logger, never()).warn(anyString()); - verify(logger, never()).info(anyString()); - - org.slf4j.Logger slf4j = mock(org.slf4j.Logger.class); - messages.log(slf4j); - verify(slf4j, never()).error(anyString()); - verify(slf4j, never()).warn(anyString()); - verify(slf4j, never()).info(anyString()); - } - - @Test - public void addError() { - ValidationMessages messages = ValidationMessages.create(); - messages.addErrorText("my error"); - assertThat(messages.hasErrors()).isTrue(); - assertThat(messages.hasWarnings()).isFalse(); - assertThat(messages.hasInfos()).isFalse(); - assertThat(messages.getErrors()).hasSize(1); - assertThat(messages.getErrors()).contains("my error"); - assertThat(messages.toString()).contains("my error"); - - Logger logger = mock(Logger.class); - messages.log(logger); - verify(logger, times(1)).error("my error"); - verify(logger, never()).warn(anyString()); - verify(logger, never()).info(anyString()); - - org.slf4j.Logger slf4j = mock(org.slf4j.Logger.class); - messages.log(slf4j); - verify(slf4j, times(1)).error("my error"); - verify(slf4j, never()).warn(anyString()); - verify(slf4j, never()).info(anyString()); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/VersionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/VersionTest.java deleted file mode 100644 index f091eb0f8b5..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/VersionTest.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.api.utils.Version.parse; - -public class VersionTest { - - @Test - public void test_parse() { - assertVersion(parse(""), 0, 0, 0, 0, ""); - assertVersion(parse("1"), 1, 0, 0, 0, ""); - assertVersion(parse("1.2"), 1, 2, 0, 0,""); - assertVersion(parse("1.2.3"), 1, 2, 3, 0,""); - assertVersion(parse("1.2-beta-1"), 1, 2, 0, 0,"beta-1"); - assertVersion(parse("1.2.3-beta1"), 1, 2, 3, 0,"beta1"); - assertVersion(parse("1.2.3-beta-1"), 1, 2, 3, 0,"beta-1"); - assertVersion(parse("1.2.3.4567"), 1, 2, 3, 4567,""); - assertVersion(parse("1.2.3.4567-alpha"), 1, 2, 3, 4567,"alpha"); - } - - @Test - public void parse_throws_IAE_if_more_than_4_fields() { - assertThatThrownBy(() -> parse("1.2.3.456.7")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Maximum 4 fields are accepted: 1.2.3.456.7"); - } - - @Test - public void test_equals() { - Version one = parse("1"); - assertThat(one).isEqualTo(one); - assertThat(one).isEqualTo(parse("1")); - assertThat(one).isEqualTo(parse("1.0")); - assertThat(one).isEqualTo(parse("1.0.0")); - assertThat(one).isNotEqualTo(parse("1.2.3")); - assertThat(one).isNotEqualTo("1"); - - assertThat(parse("1.2.3")).isEqualTo(parse("1.2.3")); - assertThat(parse("1.2.3")).isNotEqualTo(parse("1.2.4")); - assertThat(parse("1.2.3")).isEqualTo(parse("1.2.3-b1")); - assertThat(parse("1.2.3-b1")).isEqualTo(parse("1.2.3-b2")); - } - - @Test - public void test_hashCode() { - assertThat(parse("1")).hasSameHashCodeAs(parse("1")); - assertThat(parse("1")).hasSameHashCodeAs(parse("1.0.0")); - assertThat(parse("1.2.3-beta1")).hasSameHashCodeAs(parse("1.2.3")); - } - - @Test - public void test_compareTo() { - assertThat(parse("1.2")).isEqualByComparingTo(parse("1.2.0")); - assertThat(parse("1.2.3")).isEqualByComparingTo(parse("1.2.3")); - assertThat(parse("1.2.3").compareTo(parse("1.2.4"))).isLessThan(0); - assertThat(parse("1.2.3").compareTo(parse("1.3"))).isLessThan(0); - assertThat(parse("1.2.3").compareTo(parse("2.1"))).isLessThan(0); - assertThat(parse("1.2.3").compareTo(parse("2.0.0"))).isLessThan(0); - assertThat(parse("2.0").compareTo(parse("1.2"))).isGreaterThan(0); - } - - @Test - public void compareTo_handles_build_number() { - assertThat(parse("1.2")).isEqualByComparingTo(parse("1.2.0.0")); - assertThat(parse("1.2.3.1234").compareTo(parse("1.2.3.4567"))).isLessThan(0); - assertThat(parse("1.2.3.1234").compareTo(parse("1.2.3"))).isGreaterThan(0); - assertThat(parse("1.2.3.1234").compareTo(parse("1.2.4"))).isLessThan(0); - assertThat(parse("1.2.3.9999").compareTo(parse("1.2.4.1111"))).isLessThan(0); - } - - @Test - public void qualifier_is_ignored_from_comparison() { - assertThat(parse("1.2.3")).isEqualTo(parse("1.2.3-build1")); - assertThat(parse("1.2.3")).isEqualTo(parse("1.2.3-build1")); - assertThat(parse("1.2.3")).isEqualByComparingTo(parse("1.2.3-build1")); - } - - @Test - public void test_toString() { - assertThat(parse("1").toString()).isEqualTo("1.0"); - assertThat(parse("1.2").toString()).isEqualTo("1.2"); - assertThat(parse("1.2.3").toString()).isEqualTo("1.2.3"); - assertThat(parse("1.2-b1").toString()).isEqualTo("1.2-b1"); - assertThat(parse("1.2.3-b1").toString()).isEqualTo("1.2.3-b1"); - assertThat(parse("1.2.3.4567").toString()).isEqualTo("1.2.3.4567"); - assertThat(parse("1.2.3.4567-beta1").toString()).isEqualTo("1.2.3.4567-beta1"); - - // do not display zero numbers when possible - assertThat(parse("1.2.0.0").toString()).isEqualTo("1.2"); - assertThat(parse("1.2.0.1").toString()).isEqualTo("1.2.0.1"); - assertThat(parse("1.2.1.0").toString()).isEqualTo("1.2.1"); - assertThat(parse("1.2.1.0-beta").toString()).isEqualTo("1.2.1-beta"); - } - - @Test - public void test_create() { - assertVersion(Version.create(1, 2), 1, 2, 0, 0, ""); - assertVersion(Version.create(1, 2, 3), 1, 2, 3, 0, ""); - - } - - private static void assertVersion(Version version, - int expectedMajor, int expectedMinor, int expectedPatch, long expectedBuildNumber, String expectedQualifier) { - assertThat(version.major()).isEqualTo(expectedMajor); - assertThat(version.minor()).isEqualTo(expectedMinor); - assertThat(version.patch()).isEqualTo(expectedPatch); - assertThat(version.buildNumber()).isEqualTo(expectedBuildNumber); - assertThat(version.qualifier()).isEqualTo(expectedQualifier); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/WildcardPatternTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/WildcardPatternTest.java deleted file mode 100644 index 14c2ceafa70..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/WildcardPatternTest.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class WildcardPatternTest { - - private boolean match(String pattern, String value, String separator) { - return new WildcardPattern(pattern, separator).match(value); - } - - private boolean match(String pattern, String value) { - return new WildcardPattern(pattern, "/").match(value); - } - - @Test - public void examples() { - assertThat(match("org/T?st.java", "org/Test.java")).isTrue(); - assertThat(match("org/T?st.java", "org/Tost.java")).isTrue(); - - assertThat(match("org/*.java", "org/Foo.java")).isTrue(); - assertThat(match("org/*.java", "org/Bar.java")).isTrue(); - - assertThat(match("org/**", "org/Foo.java")).isTrue(); - assertThat(match("org/**", "org/foo/bar.jsp")).isTrue(); - - assertThat(match("org/**/Test.java", "org/Test.java")).isTrue(); - assertThat(match("org/**/Test.java", "org/foo/Test.java")).isTrue(); - assertThat(match("org/**/Test.java", "org/foo/bar/Test.java")).isTrue(); - - assertThat(match("org/**/*.java", "org/Foo.java")).isTrue(); - assertThat(match("org/**/*.java", "org/foo/Bar.java")).isTrue(); - assertThat(match("org/**/*.java", "org/foo/bar/Baz.java")).isTrue(); - } - - @Test - public void javaResourcesShouldMatchWildcards() { - assertThat(match("Foo", "Foo", ".")).isTrue(); - assertThat(match("Foo", "Bar", ".")).isFalse(); - - assertThat(match("org/sonar/**", "org.sonar.commons.Foo", ".")).isTrue(); - assertThat(match("org/sonar/**", "org.sonar.Foo", ".")).isTrue(); - assertThat(match("xxx/org/sonar/**", "org.sonar.Foo", ".")).isFalse(); - - assertThat(match("org/sonar/**/**", "org.sonar.commons.Foo", ".")).isTrue(); - assertThat(match("org/sonar/**/**", "org.sonar.commons.sub.Foo", ".")).isTrue(); - assertThat(match("org/sonar/**/Foo", "org.sonar.commons.sub.Foo", ".")).isTrue(); - assertThat(match("org/sonar/**/Foo", "org.sonar.Foo", ".")).isTrue(); - - assertThat(match("*/foo/*", "org.foo.Bar", ".")).isTrue(); - assertThat(match("*/foo/*", "foo.Bar", ".")).isFalse(); - assertThat(match("*/foo/*", "foo", ".")).isFalse(); - assertThat(match("*/foo/*", "org.foo.bar.Hello", ".")).isFalse(); - - assertThat(match("hell?", "hello", ".")).isTrue(); - assertThat(match("hell?", "helloworld", ".")).isFalse(); - assertThat(match("hell?", "hell", ".")).isFalse(); - - assertThat(match("a.b.c", "a.b.c", ".")).isTrue(); - assertThat(match("*/a.b.c", "foo.a.b.c", ".")).isTrue(); - assertThat(match("*/a.b.c", "foo/aabbc", ".")).isFalse(); - - assertThat(match("**/Reader", "java.io.Reader", ".")).isTrue(); - assertThat(match("**/Reader", "org.sonar.channel.CodeReader", ".")).isFalse(); - - assertThat(match("**", "java.io.Reader", ".")).isTrue(); - } - - @Test - public void directoriesShouldMatchWildcards() { - assertThat(match("Foo", "Foo")).isTrue(); - assertThat(match("Foo", "Bar")).isFalse(); - - assertThat(match("org/sonar/**", "org/sonar/commons/Foo")).isTrue(); - assertThat(match("org/sonar/**", "org/sonar/Foo.java")).isTrue(); - assertThat(match("xxx/org/sonar/**", "org/sonar/Foo")).isFalse(); - - assertThat(match("org/sonar/**/**", "org/sonar/commons/Foo")).isTrue(); - assertThat(match("org/sonar/**/**", "org/sonar/commons/sub/Foo.java")).isTrue(); - assertThat(match("org/sonar/**/Foo", "org/sonar/commons/sub/Foo")).isTrue(); - assertThat(match("org/sonar/**/Foo", "org/sonar/Foo")).isTrue(); - - assertThat(match("*/foo/*", "org/foo/Bar")).isTrue(); - assertThat(match("*/foo/*", "foo/Bar")).isFalse(); - assertThat(match("*/foo/*", "foo")).isFalse(); - assertThat(match("*/foo/*", "org/foo/bar/Hello")).isFalse(); - - assertThat(match("hell?", "hello")).isTrue(); - assertThat(match("hell?", "helloworld")).isFalse(); - assertThat(match("hell?", "hell")).isFalse(); - - assertThat(match("a.b.c", "a.b.c")).isTrue(); - assertThat(match("*/a.b.c", "foo/a.b.c")).isTrue(); - assertThat(match("*/a.b.c", "foo/aabbc")).isFalse(); - - assertThat(match("**/Reader", "java/io/Reader")).isTrue(); - assertThat(match("**/Reader", "org/sonar/channel/CodeReader")).isFalse(); - - assertThat(match("**", "java/io/Reader")).isTrue(); - } - - /** - * See http://jira.sonarsource.com/browse/SONAR-2193 - */ - @Test - public void issue2193() { - assertThat(match("**/app/**", "com.app.Utils", ".")).isTrue(); - assertThat(match("**/app/**", "com.application.MyService", ".")).isFalse(); - - assertThat(match("**/app/**", "com/app/Utils")).isTrue(); - assertThat(match("**/app/**", "com/application/MyService")).isFalse(); - } - - /** - * See SONAR-2762 - */ - @Test - public void shouldEscapeRegexpSpecificCharacters() { - assertThat(match("**/*$*", "foo/bar")).isFalse(); - assertThat(match("**/*$*", "foo/bar$baz")).isTrue(); - - assertThat(match("a+", "aa")).isFalse(); - assertThat(match("a+", "a+")).isTrue(); - - assertThat(match("[ab]", "a")).isFalse(); - assertThat(match("[ab]", "[ab]")).isTrue(); - - assertThat(match("()[]^$.{}+|", "()[]^$.{}+|")).as("all regexp-specific characters").isTrue(); - } - - @Test - public void backslash() { - assertThat(match("\\n", "\n")).as("backslash is not an escape character").isFalse(); - assertThat(match("foo\\bar", "foo/bar")).as("backslash is the same as forward slash").isTrue(); - } - - @Test - public void shouldIgnoreStartingSlash() { - assertThat(match("/foo", "foo")).isTrue(); - assertThat(match("\\foo", "foo")).isTrue(); - } - - /** - * Godin: in my opinion this is invalid pattern, however it might be constructed by {@link org.sonar.api.resources.JavaFile#matchFilePattern(String)}, - * so it should be supported at least for now for backward compatibility. - */ - @Test - public void cornerCase() { - assertThat(match("org/**.*", "org.sonar.commons.Foo.java", ".")).isTrue(); - } - - @Test - public void multiplePatterns() { - WildcardPattern[] patterns = WildcardPattern.create(new String[] {"Foo", "Bar"}); - assertThat(WildcardPattern.match(patterns, "Foo")).isTrue(); - assertThat(WildcardPattern.match(patterns, "Bar")).isTrue(); - assertThat(WildcardPattern.match(patterns, "Other")).isFalse(); - - assertThat(WildcardPattern.create((String[]) null)).isEmpty(); - } - - @Test - public void testToString() { - assertThat(WildcardPattern.create("foo*").toString()).isEqualTo("foo*"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ZipUtilsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/ZipUtilsTest.java deleted file mode 100644 index 31296d0d231..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/ZipUtilsTest.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.util.ArrayList; -import java.util.Collections; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; -import org.apache.commons.io.FileUtils; -import org.assertj.core.util.Files; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class ZipUtilsTest { - - @Rule - public TemporaryFolder temp = new TemporaryFolder(); - - @Test - public void zip_directory() throws IOException { - File foo = FileUtils.toFile(getClass().getResource("/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/foo.txt")); - File dir = foo.getParentFile(); - File zip = temp.newFile(); - - ZipUtils.zipDir(dir, zip); - - assertThat(zip).exists().isFile(); - assertThat(zip.length()).isGreaterThan(1L); - ArrayList<? extends ZipEntry> zipEntries = Collections.list(new ZipFile(zip).entries()); - assertThat(zipEntries).hasSize(4); - - File unzipDir = temp.newFolder(); - ZipUtils.unzip(zip, unzipDir); - assertThat(new File(unzipDir, "bar.txt")).exists().isFile(); - assertThat(new File(unzipDir, "foo.txt")).exists().isFile(); - assertThat(new File(unzipDir, "dir1/hello.properties")).exists().isFile(); - } - - @Test - public void unzipping_creates_target_directory_if_it_does_not_exist() throws IOException { - File zip = FileUtils.toFile(urlToZip()); - File tempDir = temp.newFolder(); - Files.delete(tempDir); - - File subDir = new File(tempDir, "subDir"); - ZipUtils.unzip(zip, subDir); - assertThat(subDir.list()).hasSize(3); - } - - @Test - public void unzip_file() throws IOException { - File zip = FileUtils.toFile(urlToZip()); - File toDir = temp.newFolder(); - ZipUtils.unzip(zip, toDir); - assertThat(toDir.list()).hasSize(3); - } - - @Test - public void unzip_stream() throws Exception { - InputStream zip = urlToZip().openStream(); - File toDir = temp.newFolder(); - ZipUtils.unzip(zip, toDir); - assertThat(toDir.list()).hasSize(3); - } - - @Test - public void fail_if_unzipping_file_outside_target_directory() throws Exception { - File zip = new File(getClass().getResource("ZipUtilsTest/zip-slip.zip").toURI()); - File toDir = temp.newFolder(); - - assertThatThrownBy(() -> ZipUtils.unzip(zip, toDir)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Unzipping an entry outside the target directory is not allowed: ../../../../../../../../../../../../../../../../" + - "../../../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt"); - } - - @Test - public void fail_if_unzipping_stream_outside_target_directory() throws Exception { - File zip = new File(getClass().getResource("ZipUtilsTest/zip-slip.zip").toURI()); - File toDir = temp.newFolder(); - - - try (InputStream input = new FileInputStream(zip)) { - assertThatThrownBy(() -> ZipUtils.unzip(input, toDir)) - .isInstanceOf(IllegalStateException.class) - .hasMessage("Unzipping an entry outside the target directory is not allowed: ../../../../../../../../../../../../../../../../../.." + - "/../../../../../../../../../../../../../../../../../../../../../../tmp/evil.txt"); - } - } - - private URL urlToZip() { - return getClass().getResource("/org/sonar/api/utils/ZipUtilsTest/shouldUnzipFile.zip"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java deleted file mode 100644 index 164e5cf1891..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandExecutorTest.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.command; - -import java.io.File; -import java.io.IOException; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang.SystemUtils; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.rules.TestName; -import org.sonar.api.utils.System2; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.fail; - -public class CommandExecutorTest { - - @Rule - public TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - public TestName testName = new TestName(); - - private File workDir; - - @Before - public void before() throws IOException { - workDir = tempFolder.newFolder(testName.getMethodName()); - } - - @Test(timeout = 3000L) - public void should_consume_StdOut_and_StdErr() throws Exception { - // too many false-positives on MS windows - if (!SystemUtils.IS_OS_WINDOWS) { - StringBuilder stdOutBuilder = new StringBuilder(); - StreamConsumer stdOutConsumer = line -> stdOutBuilder.append(line).append(SystemUtils.LINE_SEPARATOR); - StringBuilder stdErrBuilder = new StringBuilder(); - StreamConsumer stdErrConsumer = line -> stdErrBuilder.append(line).append(SystemUtils.LINE_SEPARATOR); - Command command = Command.create(getScript("output")).setDirectory(workDir); - int exitCode = CommandExecutor.create().execute(command, stdOutConsumer, stdErrConsumer, 1000L); - assertThat(exitCode).isZero(); - - String stdOut = stdOutBuilder.toString(); - String stdErr = stdErrBuilder.toString(); - assertThat(stdOut).contains("stdOut: first line"); - assertThat(stdOut).contains("stdOut: second line"); - assertThat(stdErr).contains("stdErr: first line"); - assertThat(stdErr).contains("stdErr: second line"); - } - } - - @Test(timeout = 3000L) - public void stdOut_consumer_can_throw_exception() throws Exception { - Command command = Command.create(getScript("output")).setDirectory(workDir); - - assertThatThrownBy(() -> CommandExecutor.create().execute(command, BAD_CONSUMER, NOP_CONSUMER, 1000L)) - .isInstanceOf(CommandException.class) - .hasMessageContaining("Error inside stdOut stream"); - } - - @Test(timeout = 3000L) - public void stdErr_consumer_can_throw_exception() throws Exception { - Command command = Command.create(getScript("output")).setDirectory(workDir); - - assertThatThrownBy(() -> CommandExecutor.create().execute(command, NOP_CONSUMER, BAD_CONSUMER, 1500L)) - .isInstanceOf(CommandException.class) - .hasMessageContaining("Error inside stdErr stream"); - } - - private static final StreamConsumer NOP_CONSUMER = line -> { - }; - - private static final StreamConsumer BAD_CONSUMER = line -> { - throw new RuntimeException(); - }; - - @Test - public void should_use_working_directory_to_store_argument_and_environment_variable() throws Exception { - Command command = Command.create(getScript("echo")) - .setDirectory(workDir) - .addArgument("1") - .setEnvironmentVariable("ENVVAR", "2"); - int exitCode = CommandExecutor.create().execute(command, 1000L); - assertThat(exitCode).isZero(); - File logFile = new File(workDir, "echo.log"); - assertThat(logFile).exists(); - String log = FileUtils.readFileToString(logFile); - assertThat(log).contains(workDir.getAbsolutePath()); - assertThat(log).contains("Parameter: 1"); - assertThat(log).contains("Environment variable: 2"); - } - - @Test(timeout = 6000L) - public void should_stop_after_timeout() throws IOException { - try { - String executable = getScript("forever"); - CommandExecutor.create().execute(Command.create(executable).setDirectory(workDir), 100); - fail(); - } catch (TimeoutException e) { - // ok - } - } - - @Test(timeout = 6000L) - public void should_stop_after_timeout_and_new_shell() throws IOException { - String executable = getScript("forever"); - - assertThatThrownBy(() -> { - CommandExecutor.create().execute(Command.create(executable).setNewShell(true).setDirectory(workDir), 100); - fail(); - - }) - .isInstanceOf(TimeoutException.class); - } - - @Test - public void should_fail_if_script_not_found() { - assertThatThrownBy(() -> CommandExecutor.create().execute(Command.create("notfound").setDirectory(workDir), 1000L)) - .isInstanceOf(CommandException.class); - } - - private static String getScript(String name) throws IOException { - String filename; - if (System2.INSTANCE.isOsWindows()) { - filename = name + ".bat"; - } else { - filename = name + ".sh"; - } - return new File("src/test/scripts/" + filename).getCanonicalPath(); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandTest.java deleted file mode 100644 index 9700d5ad12c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/command/CommandTest.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.command; - -import com.google.common.collect.ImmutableMap; -import java.io.File; -import java.util.Arrays; -import org.junit.Test; -import org.sonar.api.utils.System2; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class CommandTest { - - @Test - public void fail_if_blank_executable() { - assertThatThrownBy(() -> Command.create(" ")) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_null_executable() { - assertThatThrownBy(() -> Command.create(null)) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void create_command() { - Command command = Command.create("java"); - command.addArgument("-Xmx512m"); - command.addArguments(Arrays.asList("-a", "-b")); - command.addArguments(new String[] {"-x", "-y"}); - assertThat(command.getExecutable()).isEqualTo("java"); - assertThat(command.getArguments()).hasSize(5); - assertThat(command.toCommandLine()).isEqualTo("java -Xmx512m -a -b -x -y"); - } - - @Test - public void create_command_with_masked_arguments() { - Command command = Command.create("java"); - command.addArgument("-Xmx512m"); - command.addMaskedArgument("s3cr3t"); - command.addArguments(new String[] {"-x", "-y"}); - assertThat(command.getExecutable()).isEqualTo("java"); - assertThat(command.getArguments()).hasSize(4); - assertThat(command.toCommandLine()).isEqualTo("java -Xmx512m s3cr3t -x -y"); - assertThat(command.toString()).isEqualTo("java -Xmx512m ******** -x -y"); - } - - @Test - public void toString_is_the_command_line() { - Command command = Command.create("java"); - command.addArgument("-Xmx512m"); - assertThat(command.toString()).isEqualTo(command.toCommandLine()); - } - - @Test - public void working_directory() { - Command command = Command.create("java"); - assertThat(command.getDirectory()).isNull(); - - File working = new File("working"); - command = Command.create("java").setDirectory(working); - assertThat(command.getDirectory()).isEqualTo(working); - } - - @Test - public void initialize_with_current_env() { - Command command = Command.create("java"); - assertThat(command.getEnvironmentVariables()).isNotEmpty(); - } - - @Test - public void override_env_variables() { - System2 system = mock(System2.class); - when(system.envVariables()).thenReturn(ImmutableMap.of("JAVA_HOME", "/default/path/to/java")); - - Command command = new Command("java", system); - command.setEnvironmentVariable("JAVA_HOME", "/new/path/to/java"); - assertThat(command.getEnvironmentVariables()).containsEntry("JAVA_HOME", "/new/path/to/java"); - } - - @Test - public void should_use_cmd_for_new_shell_on_windows() { - System2 system = mock(System2.class); - when(system.isOsWindows()).thenReturn(true); - Command command = new Command("foo.bat", system); - command.setNewShell(true); - assertThat(command.toCommandLine()).isEqualTo("cmd /C call foo.bat"); - assertThat(command.isNewShell()).isTrue(); - - } - - @Test - public void should_use_sh_for_new_shell_on_unix() { - System2 system = mock(System2.class); - when(system.isOsWindows()).thenReturn(false); - Command command = new Command("foo.sh", system); - - command.setNewShell(true); - assertThat(command.toCommandLine()).isEqualTo("sh foo.sh"); - assertThat(command.isNewShell()).isTrue(); - } - - @Test - public void shouldnt_use_new_shell_by_default() { - Command command = Command.create("foo.sh"); - - assertThat(command.isNewShell()).isFalse(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/dag/DirectAcyclicGraphTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/dag/DirectAcyclicGraphTest.java deleted file mode 100644 index ecd308570e7..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/dag/DirectAcyclicGraphTest.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.dag; - -import static org.junit.Assert.assertEquals; -import org.junit.Test; - -import java.util.List; - -public class DirectAcyclicGraphTest { - - @Test(expected = CyclicDependenciesException.class) - public void shouldFailIfCyclicDependencies() { - DirectAcyclicGraph dag = new DirectAcyclicGraph(); - dag.add("m3", "m1"); - dag.add("m1", "m3"); - dag.sort(); - } - - @Test - public void sortByDependencies() { - DirectAcyclicGraph dag = new DirectAcyclicGraph(); - dag.add("m1", "m3"); - dag.add("m3", "m2"); - dag.add("m4"); - dag.add("m2", "m4"); - List result = dag.sort(); - assertEquals(4, result.size()); - assertEquals("m4", result.get(0)); - assertEquals("m2", result.get(1)); - assertEquals("m3", result.get(2)); - assertEquals("m1", result.get(3)); - } - - @Test - public void keepInsertionOrderWhenNoDependencies() { - DirectAcyclicGraph dag = new DirectAcyclicGraph("m3", "m2", "m1"); - List result = dag.sort(); - assertEquals(3, result.size()); - assertEquals("m3", result.get(0)); - assertEquals("m2", result.get(1)); - assertEquals("m1", result.get(2)); - } - - @Test - public void complexGraph() { - DirectAcyclicGraph dag = new DirectAcyclicGraph(); - dag.add("m2", "m4"); - dag.add("m1", "m2", "m3"); - dag.add("m3", "m2"); - List result = dag.sort(); - - assertEquals(4, result.size()); - assertEquals("m4", result.get(0)); - assertEquals("m2", result.get(1)); - assertEquals("m3", result.get(2)); - assertEquals("m1", result.get(3)); - } - - @Test - public void aNodeShouldDependOnItself() { - DirectAcyclicGraph graph = new DirectAcyclicGraph(); - graph.add("m1", "m1"); - List result = graph.sort(); - assertEquals(1, result.size()); - assertEquals("m1", result.get(0)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/BaseLoggerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/BaseLoggerTest.java deleted file mode 100644 index 16417332656..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/BaseLoggerTest.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; - -public class BaseLoggerTest { - - @Test - public void log() { - new ConsoleLogger().log(LoggerLevel.WARN, "message"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleFormatterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleFormatterTest.java deleted file mode 100644 index 148531f6a1b..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleFormatterTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; -import org.sonar.api.utils.TestUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ConsoleFormatterTest { - - @Test - public void format() { - assertThat(ConsoleFormatter.format("foo")).isEqualTo("foo"); - assertThat(ConsoleFormatter.format("arg: {}", "foo")).isEqualTo("arg: foo"); - assertThat(ConsoleFormatter.format("two args: {} and {}", "foo", 42)).isEqualTo("two args: foo and 42"); - assertThat(ConsoleFormatter.format("args: {}, {} and {}", true, 42, 2L)).isEqualTo("args: true, 42 and 2"); - assertThat(ConsoleFormatter.format("args: {}, {} and {}", null, null, null)).isEqualTo("args: null, null and null"); - } - - @Test - public void only_static_methods() { - assertThat(TestUtils.hasOnlyPrivateConstructors(ConsoleFormatter.class)).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java deleted file mode 100644 index 0c4d98d490a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggerTest.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import java.io.PrintStream; -import org.junit.Rule; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.startsWith; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoInteractions; - -public class ConsoleLoggerTest { - - private PrintStream stream = mock(PrintStream.class); - private ConsoleLogger underTest = new ConsoleLogger(stream); - - @Rule - public LogTester tester = new LogTester(); - - @Test - public void debug_enabled() { - tester.setLevel(LoggerLevel.DEBUG); - assertThat(underTest.isDebugEnabled()).isTrue(); - assertThat(underTest.isTraceEnabled()).isFalse(); - underTest.debug("message"); - underTest.debug("message {}", "foo"); - underTest.debug("message {} {}", "foo", "bar"); - underTest.debug("message {} {} {}", "foo", "bar", "baz"); - verify(stream).println("DEBUG message"); - verify(stream).println("DEBUG message foo"); - verify(stream).println("DEBUG message foo bar"); - verify(stream).println("DEBUG message foo bar baz"); - assertThat(tester.logs(LoggerLevel.DEBUG)).containsExactly( - "message", "message foo", "message foo bar", "message foo bar baz"); - } - - @Test - public void debug_disabled() { - tester.setLevel(LoggerLevel.INFO); - assertThat(underTest.isDebugEnabled()).isFalse(); - assertThat(underTest.isTraceEnabled()).isFalse(); - underTest.debug("message"); - underTest.debug("message {}", "foo"); - underTest.debug("message {} {}", "foo", "bar"); - underTest.debug("message {} {} {}", "foo", "bar", "baz"); - verifyNoInteractions(stream); - } - - @Test - public void trace_enabled() { - tester.setLevel(LoggerLevel.TRACE); - assertThat(underTest.isDebugEnabled()).isTrue(); - assertThat(underTest.isTraceEnabled()).isTrue(); - underTest.trace("message"); - underTest.trace("message {}", "foo"); - underTest.trace("message {} {}", "foo", "bar"); - underTest.trace("message {} {} {}", "foo", "bar", "baz"); - verify(stream, times(4)).println(anyString()); - } - - @Test - public void trace_disabled() { - tester.setLevel(LoggerLevel.DEBUG); - assertThat(underTest.isTraceEnabled()).isFalse(); - underTest.trace("message"); - underTest.trace("message {}", "foo"); - underTest.trace("message {} {}", "foo", "bar"); - underTest.trace("message {} {} {}", "foo", "bar", "baz"); - verifyNoInteractions(stream); - } - - @Test - public void log_info() { - underTest.info("message"); - underTest.info("message {}", "foo"); - underTest.info("message {} {}", "foo", "bar"); - underTest.info("message {} {} {}", "foo", "bar", "baz"); - verify(stream).println("INFO message"); - verify(stream).println("INFO message foo"); - verify(stream).println("INFO message foo bar"); - verify(stream).println("INFO message foo bar baz"); - assertThat(tester.logs(LoggerLevel.INFO)).containsExactly( - "message", "message foo", "message foo bar", "message foo bar baz"); - } - - @Test - public void log_warn() { - Throwable throwable = mock(Throwable.class); - - underTest.warn("message"); - underTest.warn("message {}", "foo"); - underTest.warn("message {} {}", "foo", "bar"); - underTest.warn("message {} {} {}", "foo", "bar", "baz"); - underTest.warn("message with exception", throwable); - ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class); - verify(stream, times(5)).println(captor.capture()); - for (String msg : captor.getAllValues()) { - assertThat(msg).startsWith("WARN "); - } - verify(throwable).printStackTrace(); - assertThat(tester.logs(LoggerLevel.WARN)).containsExactly( - "message", "message foo", "message foo bar", "message foo bar baz", "message with exception"); - } - - @Test - public void log_error() { - underTest.error("message"); - underTest.error("message {}", "foo"); - underTest.error("message {} {}", "foo", "bar"); - underTest.error("message {} {} {}", "foo", "bar", "baz"); - underTest.error("message with exception", new IllegalArgumentException()); - verify(stream, times(5)).println(startsWith("ERROR ")); - assertThat(tester.logs(LoggerLevel.ERROR)).containsExactly( - "message", "message foo", "message foo bar", "message foo bar baz", "message with exception"); - } - - @Test - public void level_change_not_implemented_yet() { - assertThat(underTest.setLevel(LoggerLevel.DEBUG)).isFalse(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java deleted file mode 100644 index 79ea3b60e87..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ConsoleLoggersTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ConsoleLoggersTest { - - ConsoleLoggers underTest = new ConsoleLoggers(); - - @Test - public void newInstance() { - Logger logger = underTest.newInstance("foo"); - assertThat(logger).isInstanceOf(ConsoleLogger.class); - } - - @Test - public void level() { - // INFO by default - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.INFO); - - underTest.setLevel(LoggerLevel.DEBUG); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.DEBUG); - - underTest.setLevel(LoggerLevel.INFO); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/DefaultProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/DefaultProfilerTest.java deleted file mode 100644 index 5b53d7b380a..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/DefaultProfilerTest.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Rule; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; - -public class DefaultProfilerTest { - - @Rule - public LogTester tester = new LogTester(); - - Profiler underTest = Profiler.create(Loggers.get("DefaultProfilerTest")); - - @Test - public void test_levels() { - // info by default - assertThat(underTest.isDebugEnabled()).isFalse(); - assertThat(underTest.isTraceEnabled()).isFalse(); - - tester.setLevel(LoggerLevel.DEBUG); - assertThat(underTest.isDebugEnabled()).isTrue(); - assertThat(underTest.isTraceEnabled()).isFalse(); - - tester.setLevel(LoggerLevel.TRACE); - assertThat(underTest.isDebugEnabled()).isTrue(); - assertThat(underTest.isTraceEnabled()).isTrue(); - } - - @Test - public void stop_reuses_start_message() { - tester.setLevel(LoggerLevel.TRACE); - - // trace - underTest.startTrace("Register rules"); - assertThat(tester.logs()).containsOnly("Register rules"); - underTest.stopTrace(); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time="); - tester.clear(); - - // debug - underTest.startDebug("Register rules"); - assertThat(tester.logs()).containsOnly("Register rules"); - underTest.stopTrace(); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time="); - tester.clear(); - - // info - underTest.startInfo("Register rules"); - assertThat(tester.logs()).containsOnly("Register rules"); - underTest.stopTrace(); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(1)).startsWith("Register rules (done) | time="); - } - - @Test - public void different_start_and_stop_messages() { - tester.setLevel(LoggerLevel.TRACE); - - // start TRACE and stop DEBUG - underTest.startTrace("Register rules"); - underTest.stopDebug("Rules registered"); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(0)).contains("Register rules"); - assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); - tester.clear(); - - // start DEBUG and stop INFO - underTest.startDebug("Register rules"); - underTest.stopInfo("Rules registered"); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(0)).contains("Register rules"); - assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); - tester.clear(); - - // start INFO and stop TRACE - underTest.startInfo("Register rules"); - underTest.stopTrace("Rules registered"); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(0)).contains("Register rules"); - assertThat(tester.logs().get(1)).startsWith("Rules registered | time="); - } - - @Test - public void log_on_at_stop() { - tester.setLevel(LoggerLevel.TRACE); - - // trace - underTest.start(); - underTest.stopTrace("Rules registered"); - assertThat(tester.logs()).hasSize(1); - assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); - tester.clear(); - - // debug - underTest.start(); - underTest.stopDebug("Rules registered"); - assertThat(tester.logs()).hasSize(1); - assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); - tester.clear(); - - // info - underTest.start(); - underTest.stopInfo("Rules registered"); - assertThat(tester.logs()).hasSize(1); - assertThat(tester.logs().get(0)).startsWith("Rules registered | time="); - } - - @Test - public void add_context() { - Profiler profiler = Profiler.create(Loggers.get("DefaultProfilerTest")); - profiler.addContext("a_string", "bar"); - profiler.addContext("null_value", null); - profiler.addContext("an_int", 42); - profiler.start(); - // do not write context as there's no message - assertThat(tester.logs()).isEmpty(); - - profiler.addContext("after_start", true); - profiler.stopInfo("Rules registered"); - assertThat(tester.logs()).hasSize(1); - assertThat(tester.logs().get(0)) - .startsWith("Rules registered | time=") - .endsWith("ms | a_string=bar | an_int=42 | after_start=true"); - } - - @Test - public void empty_message() { - underTest.addContext("foo", "bar"); - underTest.startInfo(""); - assertThat(tester.logs()).containsOnly("foo=bar"); - - underTest.addContext("after_start", true); - underTest.stopInfo(""); - assertThat(tester.logs()).hasSize(2); - assertThat(tester.logs().get(1)) - .startsWith("time=") - .endsWith("ms | foo=bar | after_start=true"); - } - - @Test - public void fail_if_stop_without_message() { - underTest.start(); - try { - underTest.stopInfo(); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Profiler#stopXXX() can't be called without any message defined in start methods"); - } - } - - @Test - public void fail_if_stop_without_start() { - try { - underTest.stopDebug("foo"); - fail(); - } catch (IllegalStateException e) { - assertThat(e).hasMessage("Profiler must be started before being stopped"); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogInterceptorsTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogInterceptorsTest.java deleted file mode 100644 index 13067874f2b..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogInterceptorsTest.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; -import org.sonar.api.utils.TestUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LogInterceptorsTest { - - @Test - public void default_is_null_interceptor() { - // production-ready - assertThat(LogInterceptors.get()).isInstanceOf(NullInterceptor.class); - } - - @Test(expected = IllegalArgumentException.class) - public void instance_cant_be_null() { - LogInterceptors.set(null); - } - - @Test - public void private_constructor() { - assertThat(TestUtils.hasOnlyPrivateConstructors(LogInterceptors.class)).isTrue(); - } -} - - diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterJUnit5Test.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterJUnit5Test.java deleted file mode 100644 index 9d33ffc4512..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterJUnit5Test.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LogTesterJUnit5Test { - - LogTesterJUnit5 underTest = new LogTesterJUnit5(); - - @Test - public void info_level_by_default() throws Throwable { - // when LogTester is used, then info logs are enabled by default - underTest.beforeTestExecution(null); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.INFO); - assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.INFO); - - // change - underTest.setLevel(LoggerLevel.DEBUG); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.DEBUG); - assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.DEBUG); - - // reset to initial level after execution of test - underTest.afterTestExecution(null); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.INFO); - assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.INFO); - } - - @Test - public void intercept_logs() throws Throwable { - underTest.beforeTestExecution(null); - Loggers.get("logger1").info("an information"); - Loggers.get("logger2").warn("warning: {}", 42); - - assertThat(underTest.logs()).containsExactly("an information", "warning: 42"); - assertThat(underTest.logs(LoggerLevel.ERROR)).isEmpty(); - assertThat(underTest.logs(LoggerLevel.INFO)).containsOnly("an information"); - assertThat(underTest.logs(LoggerLevel.WARN)).containsOnly("warning: 42"); - - underTest.clear(); - assertThat(underTest.logs()).isEmpty(); - assertThat(underTest.logs(LoggerLevel.INFO)).isEmpty(); - - underTest.afterTestExecution(null); - assertThat(LogInterceptors.get()).isSameAs(NullInterceptor.NULL_INSTANCE); - } - - @Test - public void use_suppliers() throws Throwable { - // when LogTester is used, then info logs are enabled by default - underTest.beforeTestExecution(null); - AtomicBoolean touchedTrace = new AtomicBoolean(); - AtomicBoolean touchedDebug = new AtomicBoolean(); - Loggers.get("logger1").trace(() -> { - touchedTrace.set(true); - return "a trace information"; - }); - Loggers.get("logger1").debug(() -> { - touchedDebug.set(true); - return "a debug information"; - }); - - assertThat(underTest.logs()).isEmpty(); - assertThat(touchedTrace.get()).isFalse(); - assertThat(touchedDebug.get()).isFalse(); - - // change level to DEBUG - underTest.setLevel(LoggerLevel.DEBUG); - Loggers.get("logger1").trace(() -> { - touchedTrace.set(true); - return "a trace information"; - }); - Loggers.get("logger1").debug(() -> { - touchedDebug.set(true); - return "a debug information"; - }); - - assertThat(underTest.logs()).containsOnly("a debug information"); - assertThat(touchedTrace.get()).isFalse(); - assertThat(touchedDebug.get()).isTrue(); - touchedDebug.set(false); - underTest.clear(); - - // change level to TRACE - underTest.setLevel(LoggerLevel.TRACE); - Loggers.get("logger1").trace(() -> { - touchedTrace.set(true); - return "a trace information"; - }); - Loggers.get("logger1").debug(() -> { - touchedDebug.set(true); - return "a debug information"; - }); - - assertThat(underTest.logs()).containsExactly("a trace information", "a debug information"); - assertThat(touchedTrace.get()).isTrue(); - assertThat(touchedDebug.get()).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java deleted file mode 100644 index 36ac39c36fd..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogTesterTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import java.util.concurrent.atomic.AtomicBoolean; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LogTesterTest { - - LogTester underTest = new LogTester(); - - @Test - public void info_level_by_default() throws Throwable { - // when LogTester is used, then info logs are enabled by default - underTest.before(); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.INFO); - assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.INFO); - - // change - underTest.setLevel(LoggerLevel.DEBUG); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.DEBUG); - assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.DEBUG); - - // reset to initial level after execution of test - underTest.after(); - assertThat(underTest.getLevel()).isEqualTo(LoggerLevel.INFO); - assertThat(Loggers.getFactory().getLevel()).isEqualTo(LoggerLevel.INFO); - } - - @Test - public void intercept_logs() throws Throwable { - underTest.before(); - Loggers.get("logger1").info("an information"); - Loggers.get("logger2").warn("warning: {}", 42); - - assertThat(underTest.logs()).containsExactly("an information", "warning: 42"); - assertThat(underTest.logs(LoggerLevel.ERROR)).isEmpty(); - assertThat(underTest.logs(LoggerLevel.INFO)).containsOnly("an information"); - assertThat(underTest.logs(LoggerLevel.WARN)).containsOnly("warning: 42"); - - underTest.clear(); - assertThat(underTest.logs()).isEmpty(); - assertThat(underTest.logs(LoggerLevel.INFO)).isEmpty(); - - underTest.after(); - assertThat(LogInterceptors.get()).isSameAs(NullInterceptor.NULL_INSTANCE); - } - - @Test - public void use_suppliers() throws Throwable { - // when LogTester is used, then info logs are enabled by default - underTest.before(); - AtomicBoolean touchedTrace = new AtomicBoolean(); - AtomicBoolean touchedDebug = new AtomicBoolean(); - Loggers.get("logger1").trace(() -> { - touchedTrace.set(true); - return "a trace information"; - }); - Loggers.get("logger1").debug(() -> { - touchedDebug.set(true); - return "a debug information"; - }); - - assertThat(underTest.logs()).isEmpty(); - assertThat(touchedTrace.get()).isFalse(); - assertThat(touchedDebug.get()).isFalse(); - - // change level to DEBUG - underTest.setLevel(LoggerLevel.DEBUG); - Loggers.get("logger1").trace(() -> { - touchedTrace.set(true); - return "a trace information"; - }); - Loggers.get("logger1").debug(() -> { - touchedDebug.set(true); - return "a debug information"; - }); - - assertThat(underTest.logs()).containsOnly("a debug information"); - assertThat(touchedTrace.get()).isFalse(); - assertThat(touchedDebug.get()).isTrue(); - touchedDebug.set(false); - underTest.clear(); - - // change level to TRACE - underTest.setLevel(LoggerLevel.TRACE); - Loggers.get("logger1").trace(() -> { - touchedTrace.set(true); - return "a trace information"; - }); - Loggers.get("logger1").debug(() -> { - touchedDebug.set(true); - return "a debug information"; - }); - - assertThat(underTest.logs()).containsExactly("a trace information", "a debug information"); - assertThat(touchedTrace.get()).isTrue(); - assertThat(touchedDebug.get()).isTrue(); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java deleted file mode 100644 index 5a1acbb27b0..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LogbackLoggerTest.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import ch.qos.logback.classic.Level; -import org.junit.Rule; -import org.junit.Test; -import org.slf4j.LoggerFactory; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LogbackLoggerTest { - - LogbackLogger underTest = new LogbackLogger((ch.qos.logback.classic.Logger)LoggerFactory.getLogger(getClass())); - - @Rule - public LogTester tester = new LogTester(); - - @Test - public void log() { - // no assertions. Simply verify that calls do not fail. - underTest.trace("message"); - underTest.trace("message {}", "foo"); - underTest.trace("message {} {}", "foo", "bar"); - underTest.trace("message {} {} {}", "foo", "bar", "baz"); - - underTest.debug("message"); - underTest.debug("message {}", "foo"); - underTest.debug("message {} {}", "foo", "bar"); - underTest.debug("message {} {} {}", "foo", "bar", "baz"); - - underTest.info("message"); - underTest.info("message {}", "foo"); - underTest.info("message {} {}", "foo", "bar"); - underTest.info("message {} {} {}", "foo", "bar", "baz"); - - underTest.warn("message"); - underTest.warn("message {}", "foo"); - underTest.warn("message {} {}", "foo", "bar"); - underTest.warn("message {} {} {}", "foo", "bar", "baz"); - underTest.warn("message", new NullPointerException("boom!")); - - underTest.error("message"); - underTest.error("message {}", "foo"); - underTest.error("message {} {}", "foo", "bar"); - underTest.error("message {} {} {}", "foo", "bar", "baz"); - underTest.error("message", new IllegalArgumentException("")); - } - - @Test - public void change_level() { - assertThat(underTest.setLevel(LoggerLevel.ERROR)).isTrue(); - assertThat(underTest.isDebugEnabled()).isFalse(); - assertThat(underTest.isTraceEnabled()).isFalse(); - assertThat(underTest.logbackLogger().getLevel()).isEqualTo(Level.ERROR); - - assertThat(underTest.setLevel(LoggerLevel.WARN)).isTrue(); - assertThat(underTest.isDebugEnabled()).isFalse(); - assertThat(underTest.isTraceEnabled()).isFalse(); - assertThat(underTest.logbackLogger().getLevel()).isEqualTo(Level.WARN); - - assertThat(underTest.setLevel(LoggerLevel.INFO)).isTrue(); - assertThat(underTest.logbackLogger().getLevel()).isEqualTo(Level.INFO); - assertThat(underTest.isDebugEnabled()).isFalse(); - assertThat(underTest.isTraceEnabled()).isFalse(); - - assertThat(underTest.setLevel(LoggerLevel.DEBUG)).isTrue(); - assertThat(underTest.isDebugEnabled()).isTrue(); - assertThat(underTest.isTraceEnabled()).isFalse(); - assertThat(underTest.logbackLogger().getLevel()).isEqualTo(Level.DEBUG); - - assertThat(underTest.setLevel(LoggerLevel.TRACE)).isTrue(); - assertThat(underTest.isDebugEnabled()).isTrue(); - assertThat(underTest.isTraceEnabled()).isTrue(); - assertThat(underTest.logbackLogger().getLevel()).isEqualTo(Level.TRACE); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java deleted file mode 100644 index dfb7c4e834c..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/LoggersTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; -import org.sonar.api.Plugin; - -import static org.assertj.core.api.Assertions.assertThat; - -public class LoggersTest { - - @Test - public void factory() { - // logback is used by sonar-plugin-api - assertThat(Loggers.getFactory()).isInstanceOf(LogbackLoggers.class); - - assertThat(Loggers.get("foo")).isInstanceOf(LogbackLogger.class); - assertThat(Loggers.get(Plugin.class)).isInstanceOf(LogbackLogger.class); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullInterceptorTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullInterceptorTest.java deleted file mode 100644 index 06f42fbd5e5..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullInterceptorTest.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; - -import static org.mockito.Mockito.mock; - -public class NullInterceptorTest { - - @Test - public void do_not_throws_exception() { - // verify that... it does nothing - NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo"); - NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo {}", 42); - NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo {} {}", 42, 66); - NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo {} {} {}", 42, 66, 84); - NullInterceptor.NULL_INSTANCE.log(LoggerLevel.INFO, "foo", mock(Exception.class)); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullProfilerTest.java deleted file mode 100644 index 93b47d290be..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/NullProfilerTest.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class NullProfilerTest { - - NullProfiler underTest = NullProfiler.NULL_INSTANCE; - - @Test - public void do_not_fail() { - assertThat(underTest.start()).isSameAs(underTest); - assertThat(underTest.startTrace("")).isSameAs(underTest); - assertThat(underTest.startDebug("")).isSameAs(underTest); - assertThat(underTest.startInfo("")).isSameAs(underTest); - - assertThat(underTest.stopTrace()).isSameAs(underTest); - assertThat(underTest.stopTrace("")).isSameAs(underTest); - assertThat(underTest.stopDebug("")).isSameAs(underTest); - assertThat(underTest.stopDebug()).isSameAs(underTest); - assertThat(underTest.stopInfo()).isSameAs(underTest); - assertThat(underTest.stopInfo("")).isSameAs(underTest); - - assertThat(underTest.isDebugEnabled()).isFalse(); - assertThat(underTest.isTraceEnabled()).isFalse(); - assertThat(underTest.addContext("foo", "bar")).isSameAs(underTest); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ProfilerTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ProfilerTest.java deleted file mode 100644 index 29e82be22e7..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/log/ProfilerTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.log; - -import org.junit.Rule; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ProfilerTest { - @Rule - public LogTester tester = new LogTester(); - - @Test - public void create() { - Profiler profiler = Profiler.create(Loggers.get("foo")); - assertThat(profiler).isInstanceOf(DefaultProfiler.class); - } - - @Test - public void create_null_profiler_if_trace_level_is_disabled() { - tester.setLevel(LoggerLevel.TRACE); - Profiler profiler = Profiler.createIfTrace(Loggers.get("foo")); - assertThat(profiler).isInstanceOf(DefaultProfiler.class); - - tester.setLevel(LoggerLevel.DEBUG); - profiler = Profiler.createIfTrace(Loggers.get("foo")); - assertThat(profiler).isInstanceOf(NullProfiler.class); - } - - @Test - public void create_null_profiler_if_debug_level_is_disabled() { - tester.setLevel(LoggerLevel.TRACE); - Profiler profiler = Profiler.createIfDebug(Loggers.get("foo")); - assertThat(profiler).isInstanceOf(DefaultProfiler.class); - - tester.setLevel(LoggerLevel.INFO); - profiler = Profiler.createIfDebug(Loggers.get("foo")); - assertThat(profiler).isInstanceOf(NullProfiler.class); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/CsvWriterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/CsvWriterTest.java deleted file mode 100644 index 78549643750..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/CsvWriterTest.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.text; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - -public class CsvWriterTest { - - @Test - public void write_csv() throws Exception { - StringWriter output = new StringWriter(); - CsvWriter writer = CsvWriter.of(output); - - writer.values("France", "Paris"); - writer.values("Sweden", "Stockholm"); - writer.close(); - - BufferedReader reader = new BufferedReader(new StringReader(output.toString())); - String line1 = reader.readLine(); - assertThat(line1).isEqualTo("France,Paris"); - - String line2 = reader.readLine(); - assertThat(line2).isEqualTo("Sweden,Stockholm"); - - assertThat(reader.readLine()).isNull(); - } - - @Test - public void escape_value() throws Exception { - StringWriter output = new StringWriter(); - CsvWriter writer = CsvWriter.of(output); - - writer.values("no double-quotes", "contains \"double-quotes\"", "contains , commas"); - writer.close(); - - BufferedReader reader = new BufferedReader(new StringReader(output.toString())); - assertThat(reader.readLine()).isEqualTo("no double-quotes,\"contains \"\"double-quotes\"\"\",\"contains , commas\""); - - assertThat(reader.readLine()).isNull(); - } - - @Test - public void fail_to_write_to_stream() throws Exception { - Writer output = mock(Writer.class); - IOException cause = new IOException("bad"); - doThrow(cause).when(output).append(anyString()); - - CsvWriter writer = CsvWriter.of(output); - - try { - writer.values("foo"); - fail(); - } catch (WriterException e) { - assertThat(e).hasMessage("Fail to generate CSV with value: foo"); - assertThat(e.getCause()).isSameAs(cause); - } - } - - @Test - public void fail_to_close_stream() throws Exception { - Writer output = mock(Writer.class); - IOException cause = new IOException("bad"); - doThrow(cause).when(output).close(); - - CsvWriter writer = CsvWriter.of(output); - writer.values("foo"); - - try { - writer.close(); - fail(); - } catch (WriterException e) { - assertThat(e).hasMessage("Fail to close CSV output"); - assertThat(e.getCause()).isSameAs(cause); - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/JsonWriterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/JsonWriterTest.java deleted file mode 100644 index 5629ba501e4..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/JsonWriterTest.java +++ /dev/null @@ -1,224 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.text; - -import com.google.common.collect.ImmutableMap; -import java.io.IOException; -import java.io.StringWriter; -import java.util.Arrays; -import java.util.Date; -import java.util.Map; -import java.util.concurrent.atomic.AtomicInteger; -import org.junit.Test; -import org.sonar.api.utils.DateUtils; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.fail; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class JsonWriterTest { - - private static final String EMPTY_STRING = ""; - - private StringWriter stringWriter = new StringWriter(); - - private JsonWriter underTest = JsonWriter.of(stringWriter); - - @Test - public void empty_object() { - underTest.beginObject().endObject().close(); - expect("{}"); - } - - @Test - public void empty_array() { - underTest.beginArray().endArray().close(); - expect("[]"); - } - - @Test - public void stop_while_streaming() { - underTest.beginObject().name("foo").value("bar"); - // endObject() and close() are missing - expect("{\"foo\":\"bar\""); - } - - @Test - public void objects_and_arrays() { - underTest.beginObject().name("issues") - .beginArray() - .beginObject().prop("key", "ABC").endObject() - .beginObject().prop("key", "DEF").endObject() - .endArray() - .endObject().close(); - expect("{\"issues\":[{\"key\":\"ABC\"},{\"key\":\"DEF\"}]}"); - } - - @Test - public void array_values() { - underTest.beginArray().values(Arrays.asList("foo", "bar", "baz")).endArray().close(); - expect("[\"foo\",\"bar\",\"baz\"]"); - } - - @Test - public void type_of_values() { - Date date = DateUtils.parseDateTime("2010-05-18T15:50:45+0100"); - underTest.beginObject() - .prop("aBoolean", true) - .prop("aInt", 123) - .prop("aLong", 1000L) - .prop("aDouble", 3.14) - .prop("aNumber", new AtomicInteger(123456789)) - .prop("aString", "bar") - .propDate("aDate", date) - .endObject().close(); - expect("{\"aBoolean\":true,\"aInt\":123,\"aLong\":1000,\"aDouble\":3.14,\"aNumber\":123456789,\"aString\":\"bar\",\"aDate\":\"2010-05-18\"}"); - } - - @Test - public void ignore_null_values_by_default() { - underTest.beginObject() - .prop("nullNumber", (Number) null) - .prop("nullString", (String) null) - .name("nullNumber").value((Number) null) - .name("nullString").value((String) null) - .name("nullDate").valueDate(null) - .name("nullDateTime").valueDate(null) - .endObject().close(); - expect("{}"); - } - - @Test - public void serialize_null_values() { - underTest.setSerializeNulls(true); - underTest.beginObject() - .prop("nullNumber", (Number) null) - .prop("nullString", (String) null) - .name("nullNumber").value((Number) null) - .name("nullString").value((String) null) - .name("nullDate").valueDate(null) - .name("nullDateTime").valueDate(null) - .endObject().close(); - expect("{\"nullNumber\":null,\"nullString\":null,\"nullNumber\":null,\"nullString\":null,\"nullDate\":null,\"nullDateTime\":null}"); - } - - @Test - public void serialize_empty_strings_by_default() { - underTest.beginObject() - .prop("emptyString", EMPTY_STRING) - .name("emptyStringAsObject").valueObject(EMPTY_STRING) - .endObject().close(); - expect("{" + - "\"emptyString\":\"\"," + - "\"emptyStringAsObject\":\"\"" + - "}"); - } - - @Test - public void ignore_empty_strings_when_requested() { - underTest.setSerializeEmptys(false) - .beginObject() - .prop("emptyString", EMPTY_STRING) - .name("emptyStringAsObject").valueObject(EMPTY_STRING) - .endObject().close(); - expect("{}"); - } - - @Test - public void escape_values() { - underTest.beginObject() - .prop("foo", "<hello \"world\">") - .endObject().close(); - expect("{\"foo\":\"\\u003chello \\\"world\\\"\\u003e\"}"); - } - - @Test - public void escape_html_characters() { - underTest.beginObject() - .prop("foo", "123<>abc") - .endObject().close(); - expect("{\"foo\":\"123\\u003c\\u003eabc\"}"); - } - - @Test - public void valueObject() { - underTest.beginObject() - .name("aString").valueObject("stringValue") - .name("aBoolean").valueObject(true) - .name("aInt").valueObject(42) - .name("aFloat").valueObject(3.14) - .name("aLong").valueObject(42L) - .name("aList").valueObject(Arrays.asList("one", 2, "three")) - .name("anEnum").valueObject(ColorEnum.GREEN) - .name("aMap").valueObject(ImmutableMap.of("hello", "world", "good", "bye")) - .endObject().close(); - expect( - "{\"aString\":\"stringValue\",\"aBoolean\":true,\"aInt\":42,\"aFloat\":3.14,\"aLong\":42,\"aList\":[\"one\",2,\"three\"],\"anEnum\":\"GREEN\",\"aMap\":{\"hello\":\"world\",\"good\":\"bye\"}}"); - } - - @Test - public void valueObject_recursive() { - Map map = ImmutableMap.of("a", ImmutableMap.of("b", "c")); - underTest.valueObject(map).close(); - expect("{\"a\":{\"b\":\"c\"}}"); - } - - @Test - public void valueObject_unsupported_type() { - try { - underTest.beginObject().valueObject(new StringWriter()).endObject().close(); - fail(); - } catch (IllegalArgumentException e) { - assertThat(e).hasMessage("class org.sonar.api.utils.text.JsonWriter does not support encoding of type: class java.io.StringWriter"); - } - } - - @Test - public void fail_on_NaN_value() { - assertThatThrownBy(() -> underTest.beginObject().prop("foo", Double.NaN).endObject().close()) - .isInstanceOf(WriterException.class); - } - - @Test - public void fail_if_not_valid() { - assertThatThrownBy(() -> underTest.beginObject().endArray().close()) - .isInstanceOf(WriterException.class); - } - - @Test - public void fail_to_begin_array() throws Exception { - com.google.gson.stream.JsonWriter gson = mock(com.google.gson.stream.JsonWriter.class); - when(gson.beginArray()).thenThrow(new IOException("the reason")); - - assertThatThrownBy(() -> new JsonWriter(gson).beginArray()) - .isInstanceOf(WriterException.class) - .hasMessage("Fail to write JSON"); - } - - private void expect(String s) { - assertThat(stringWriter.toString()).isEqualTo(s); - } - - private enum ColorEnum { - RED, GREEN - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/XmlWriterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/XmlWriterTest.java deleted file mode 100644 index e103662480e..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/utils/text/XmlWriterTest.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.utils.text; - -import java.io.StringWriter; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class XmlWriterTest { - - StringWriter xml = new StringWriter(); - XmlWriter writer = XmlWriter.of(xml); - - private void expect(String s) { - assertThat(xml.toString()).isEqualTo(s); - } - - @Test - public void declaration() { - writer.declaration().begin("foo").end().close(); - expect("<?xml version=\"1.0\" encoding=\"UTF-8\"?><foo></foo>"); - } - - @Test - public void end_with_unused_parameter() { - writer.begin("foo").end("foo").close(); - expect("<foo></foo>"); - } - - @Test - public void only_root() { - writer.begin("foo").end().close(); - expect("<foo></foo>"); - } - - @Test - public void escape_value() { - writer.prop("foo", "1<2 & 2>=2").close(); - expect("<foo>1<2 & 2>=2</foo>"); - } - - @Test - public void only_root_with_value() { - writer.prop("foo", "bar").close(); - expect("<foo>bar</foo>"); - } - - @Test - public void ignore_null_values() { - writer.begin("root") - .prop("nullNumber", (Number) null) - .prop("nullString", (String) null) - .end().close(); - expect("<root></root>"); - } - - @Test - public void fail_on_NaN_value() { - assertThatThrownBy(() -> writer.begin("root").prop("foo", Double.NaN).end().close()) - .isInstanceOf(WriterException.class) - .hasMessage("Fail to write XML. Double value is not valid: NaN"); - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/web/ServletFilterTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/web/ServletFilterTest.java deleted file mode 100644 index 1f2111125ad..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/web/ServletFilterTest.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.web; - -import javax.servlet.FilterChain; -import javax.servlet.FilterConfig; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; - -public class ServletFilterTest { - - @Test - public void include_all() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.create("/*"); - assertThat(pattern.matches("/")).isTrue(); - assertThat(pattern.matches("/foo/ooo")).isTrue(); - - assertThat(pattern.getInclusions()).containsOnly("/*"); - assertThat(pattern.getExclusions()).isEmpty(); - } - - @Test - public void include_end_of_url() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.create("*foo"); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/hello/foo")).isTrue(); - assertThat(pattern.matches("/hello/bar")).isFalse(); - assertThat(pattern.matches("/foo")).isTrue(); - assertThat(pattern.matches("/foo2")).isFalse(); - } - - @Test - public void include_beginning_of_url() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.create("/foo/*"); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/foo")).isTrue(); - assertThat(pattern.matches("/foo/bar")).isTrue(); - assertThat(pattern.matches("/bar")).isFalse(); - } - - @Test - public void include_exact_url() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.create("/foo"); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/foo")).isTrue(); - assertThat(pattern.matches("/foo/")).isFalse(); - assertThat(pattern.matches("/bar")).isFalse(); - } - - @Test - public void exclude_all() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .excludes("/*") - .build(); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/foo/ooo")).isFalse(); - } - - @Test - public void exclude_end_of_url() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .excludes("*foo") - .build(); - - assertThat(pattern.matches("/")).isTrue(); - assertThat(pattern.matches("/hello/foo")).isFalse(); - assertThat(pattern.matches("/hello/bar")).isTrue(); - assertThat(pattern.matches("/foo")).isFalse(); - assertThat(pattern.matches("/foo2")).isTrue(); - } - - @Test - public void exclude_beginning_of_url() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .excludes("/foo/*") - .build(); - - assertThat(pattern.matches("/")).isTrue(); - assertThat(pattern.matches("/foo")).isFalse(); - assertThat(pattern.matches("/foo/bar")).isFalse(); - assertThat(pattern.matches("/bar")).isTrue(); - } - - @Test - public void exclude_exact_url() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .excludes("/foo") - .build(); - - assertThat(pattern.matches("/")).isTrue(); - assertThat(pattern.matches("/foo")).isFalse(); - assertThat(pattern.matches("/foo/")).isTrue(); - assertThat(pattern.matches("/bar")).isTrue(); - } - - @Test - public void use_multiple_include_patterns() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .includes("/foo", "/foo2") - .build(); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/foo")).isTrue(); - assertThat(pattern.matches("/foo2")).isTrue(); - assertThat(pattern.matches("/foo/")).isFalse(); - assertThat(pattern.matches("/bar")).isFalse(); - } - - @Test - public void use_multiple_exclude_patterns() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .excludes("/foo", "/foo2") - .build(); - assertThat(pattern.matches("/")).isTrue(); - assertThat(pattern.matches("/foo")).isFalse(); - assertThat(pattern.matches("/foo2")).isFalse(); - assertThat(pattern.matches("/foo/")).isTrue(); - assertThat(pattern.matches("/bar")).isTrue(); - } - - @Test - public void use_include_and_exclude_patterns() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .includes("/foo/*", "/foo/lo*") - .excludes("/foo/login", "/foo/logout", "/foo/list") - .build(); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/foo")).isTrue(); - assertThat(pattern.matches("/foo/login")).isFalse(); - assertThat(pattern.matches("/foo/logout")).isFalse(); - assertThat(pattern.matches("/foo/list")).isFalse(); - assertThat(pattern.matches("/foo/locale")).isTrue(); - assertThat(pattern.matches("/foo/index")).isTrue(); - } - - @Test - public void use_include_and_exclude_prefix() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .includes("/foo_2") - .excludes("/foo") - .build(); - assertThat(pattern.matches("/")).isFalse(); - assertThat(pattern.matches("/foo_2")).isTrue(); - assertThat(pattern.matches("/foo")).isFalse(); - } - - @Test - public void exclude_pattern_has_higher_priority_than_include_pattern() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .includes("/foo") - .excludes("/foo") - .build(); - assertThat(pattern.matches("/foo")).isFalse(); - } - - @Test - public void accept_empty_patterns() { - ServletFilter.UrlPattern pattern = ServletFilter.UrlPattern.builder() - .excludes() - .includes() - .build(); - assertThat(pattern.matches("/")).isTrue(); - assertThat(pattern.matches("/foo/bar")).isTrue(); - } - - @Test - public void create_throws_IAE_if_empty_url() { - assertThatThrownBy(() -> ServletFilter.UrlPattern.create("")) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("URL pattern must start with slash '/': "); - } - - @Test - public void filter_should_return_url_pattern() { - ServletFilter filter = new FakeFilter(); - assertThat(filter.doGetPattern()).isNotNull(); - } - - @Test - public void filter_should_apply_to_all_urls_by_default() { - ServletFilter filter = new DefaultFilter(); - assertThat(filter.doGetPattern().matches("/")).isTrue(); - assertThat(filter.doGetPattern().matches("/foo/bar")).isTrue(); - } - - @Test - public void getUrl_returns_single_inclusion() { - assertThat(ServletFilter.UrlPattern.create("/*").getInclusions()).containsOnly("/*"); - assertThat(ServletFilter.UrlPattern.create("/foo/bar").getInclusions()).containsOnly("/foo/bar"); - } - - @Test - public void test_staticResourcePatterns() { - assertThat(ServletFilter.UrlPattern.Builder.staticResourcePatterns()).containsOnly( - "*.css", - "*.css.map", - "*.ico", - "*.png", - "*.jpg", - "*.jpeg", - "*.gif", - "*.svg", - "*.js", - "*.js.map", - "*.pdf", - "/json/*", - "/static/*", - "/robots.txt", - "/favicon.ico", - "/apple-touch-icon*", - "/mstile*"); - } - - @Test - public void test_label() { - assertThat(ServletFilter.UrlPattern.builder().build().label()).isEqualTo("UrlPattern{inclusions=[], exclusions=[]}"); - assertThat(ServletFilter.UrlPattern.builder() - .includes("/foo/*") - .excludes("/foo/login") - .build().label()).isEqualTo("UrlPattern{inclusions=[/foo/*], exclusions=[/foo/login]}"); - assertThat(ServletFilter.UrlPattern.builder() - .includes("/foo/*", "/foo/lo*") - .excludes("/foo/login", "/foo/logout", "/foo/list") - .build().label()).isEqualTo("UrlPattern{inclusions=[/foo/*, ...], exclusions=[/foo/login, ...]}"); - } - - private static class FakeFilter extends ServletFilter { - @Override - public UrlPattern doGetPattern() { - return UrlPattern.create("/fake"); - } - - public void init(FilterConfig filterConfig) { - } - - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { - } - - public void destroy() { - } - } - - private static class DefaultFilter extends ServletFilter { - public void init(FilterConfig filterConfig) { - } - - public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) { - } - - public void destroy() { - } - } -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/web/page/ContextTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/web/page/ContextTest.java deleted file mode 100644 index f8348e3e65b..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/web/page/ContextTest.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.web.page; - -import java.util.Collection; -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.assertj.core.api.Assertions.tuple; - -public class ContextTest { - - private Context underTest = new Context(); - - private Page page = Page.builder("governance/project_export").setName("Project Export").build(); - - @Test - public void no_pages_with_the_same_path() { - underTest.addPage(page); - - assertThatThrownBy(() -> underTest.addPage(page)) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Page 'Project Export' cannot be loaded. Another page with key 'governance/project_export' already exists."); - } - - @Test - public void ordered_by_name() { - underTest - .addPage(Page.builder("fake/K1").setName("N2").build()) - .addPage(Page.builder("fake/K2").setName("N3").build()) - .addPage(Page.builder("fake/K3").setName("N1").build()); - - Collection<Page> result = underTest.getPages(); - - assertThat(result).extracting(Page::getKey, Page::getName) - .containsOnly( - tuple("fake/K3", "N1"), - tuple("fake/K1", "N2"), - tuple("fake/K2", "N3")); - } - - @Test - public void empty_pages_by_default() { - Collection<Page> result = underTest.getPages(); - - assertThat(result).isEmpty(); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/web/page/PageDefinitionTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/web/page/PageDefinitionTest.java deleted file mode 100644 index e9eee5498fd..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/web/page/PageDefinitionTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.web.page; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * Used for the documentation - */ -public class PageDefinitionTest { - @Test - public void test_page_definition() { - PageDefinition underTest = context -> context.addPage(Page.builder("my_plugin/my_page").setName("My Page").build()); - Context context = new Context(); - - underTest.define(context); - - assertThat(context.getPages()).extracting(Page::getKey).contains("my_plugin/my_page"); - } - -} diff --git a/sonar-plugin-api/src/test/java/org/sonar/api/web/page/PageTest.java b/sonar-plugin-api/src/test/java/org/sonar/api/web/page/PageTest.java deleted file mode 100644 index 68c03fe3571..00000000000 --- a/sonar-plugin-api/src/test/java/org/sonar/api/web/page/PageTest.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * SonarQube - * Copyright (C) 2009-2022 SonarSource SA - * mailto:info AT sonarsource DOT com - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 3 of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with this program; if not, write to the Free Software Foundation, - * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. - */ -package org.sonar.api.web.page; - -import org.junit.Test; -import org.sonar.api.resources.Qualifiers; -import org.sonar.api.web.page.Page.Qualifier; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.sonar.api.web.page.Page.Qualifier.APP; -import static org.sonar.api.web.page.Page.Qualifier.MODULE; -import static org.sonar.api.web.page.Page.Qualifier.PROJECT; -import static org.sonar.api.web.page.Page.Qualifier.SUB_VIEW; -import static org.sonar.api.web.page.Page.Qualifier.VIEW; -import static org.sonar.api.web.page.Page.Scope.COMPONENT; -import static org.sonar.api.web.page.Page.Scope.GLOBAL; - -public class PageTest { - - private Page.Builder underTest = Page.builder("governance/project_dump").setName("Project Dump"); - - @Test - public void full_test() { - Page result = underTest - .setComponentQualifiers(PROJECT, MODULE) - .setScope(COMPONENT) - .setAdmin(true) - .build(); - - assertThat(result.getKey()).isEqualTo("governance/project_dump"); - assertThat(result.getPluginKey()).isEqualTo("governance"); - assertThat(result.getName()).isEqualTo("Project Dump"); - assertThat(result.getComponentQualifiers()).containsOnly(PROJECT, MODULE); - assertThat(result.getScope()).isEqualTo(COMPONENT); - assertThat(result.isAdmin()).isTrue(); - } - - @Test - public void qualifiers_map_to_key() { - assertThat(Qualifier.PROJECT.getKey()).isEqualTo(org.sonar.api.resources.Qualifiers.PROJECT); - assertThat(Qualifier.MODULE.getKey()).isEqualTo(org.sonar.api.resources.Qualifiers.MODULE); - assertThat(Qualifier.VIEW.getKey()).isEqualTo(org.sonar.api.resources.Qualifiers.VIEW); - assertThat(Qualifier.APP.getKey()).isEqualTo(org.sonar.api.resources.Qualifiers.APP); - assertThat(Qualifier.SUB_VIEW.getKey()).isEqualTo(org.sonar.api.resources.Qualifiers.SUBVIEW); - } - - @Test - public void authorized_qualifiers() { - Qualifier[] qualifiers = Qualifier.values(); - - assertThat(qualifiers).containsExactlyInAnyOrder(PROJECT, MODULE, VIEW, SUB_VIEW, APP); - } - - @Test - public void default_values() { - Page result = underTest.build(); - - assertThat(result.getComponentQualifiers()).isEmpty(); - assertThat(result.getScope()).isEqualTo(GLOBAL); - assertThat(result.isAdmin()).isFalse(); - } - - @Test - public void all_qualifiers_when_component_page() { - Page result = underTest.setScope(COMPONENT).build(); - - assertThat(result.getComponentQualifiers()).containsOnly(Qualifier.values()); - } - - @Test - public void qualifiers_from_key() { - assertThat(Qualifier.fromKey(Qualifiers.PROJECT)).isEqualTo(Qualifier.PROJECT); - assertThat(Qualifier.fromKey("42")).isNull(); - } - - @Test - public void fail_if_null_qualifiers() { - assertThatThrownBy(() -> underTest.setComponentQualifiers((Qualifier[])null).build()) - .isInstanceOf(NullPointerException.class); - } - - @Test - public void fail_if_a_page_has_a_null_key() { - assertThatThrownBy(() -> Page.builder(null).setName("Say my name").build()) - .isInstanceOf(NullPointerException.class); - } - - @Test - public void fail_if_a_page_has_an_empty_key() { - assertThatThrownBy(() -> Page.builder("").setName("Say my name").build()) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_a_page_has_a_null_name() { - assertThatThrownBy(() -> Page.builder("governance/project_dump").build()) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_a_page_has_an_empty_name() { - assertThatThrownBy(() -> Page.builder("governance/project_dump").setName("").build()) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_qualifiers_without_scope() { - assertThatThrownBy(() -> underTest.setComponentQualifiers(PROJECT).build()) - .isInstanceOf(IllegalArgumentException.class); - } - - @Test - public void fail_if_key_does_not_contain_a_slash() { - assertThatThrownBy(() -> Page.builder("project_dump").setName("Project Dump").build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Page key [project_dump] is not valid. It must contain a single slash, for example my_plugin/my_page."); - } - - @Test - public void fail_if_key_contains_more_than_one_slash() { - assertThatThrownBy(() -> Page.builder("governance/project/dump").setName("Project Dump").build()) - .isInstanceOf(IllegalArgumentException.class) - .hasMessage("Page key [governance/project/dump] is not valid. It must contain a single slash, for example my_plugin/my_page."); - } -} diff --git a/sonar-plugin-api/src/test/resources/META-INF/MANIFEST.MF b/sonar-plugin-api/src/test/resources/META-INF/MANIFEST.MF deleted file mode 100644 index ce807b4fa4a..00000000000 --- a/sonar-plugin-api/src/test/resources/META-INF/MANIFEST.MF +++ /dev/null @@ -1,6 +0,0 @@ -Manifest-Version: 1.0 -Archiver-Version: Plexus Archiver -Created-By: Apache Maven -Built-By: Sonar -Build-Jdk: 1.5.0_09 -Plugin-Class: org.sonar.api.FakePlugin diff --git a/sonar-plugin-api/src/test/resources/logback-test.xml b/sonar-plugin-api/src/test/resources/logback-test.xml deleted file mode 100644 index e6a726d8d0b..00000000000 --- a/sonar-plugin-api/src/test/resources/logback-test.xml +++ /dev/null @@ -1,22 +0,0 @@ -<?xml version="1.0" encoding="UTF-8" ?> -<configuration debug="false"> - <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator"/> - - <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> - <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder"> - <pattern> - [%d{yyyy.MM.dd HH:mm:ss}][%logger{15}][%-5level] %msg%n - </pattern> - </encoder> - </appender> - - <root> - <level value="INFO"/> - <appender-ref ref="CONSOLE"/> - </root> - - <logger name="ch.qos.logback"> - <level value="WARN"/> - </logger> - -</configuration> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/getConfigurationFromReport.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/getConfigurationFromReport.xml deleted file mode 100644 index 25bb3a64c1b..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/getConfigurationFromReport.xml +++ /dev/null @@ -1,21 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <reporting> - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - <configuration> - <foo>bar</foo> - </configuration> - </plugin> - </plugins> - </reporting> - -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/keepPluginDependencies.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/keepPluginDependencies.xml deleted file mode 100644 index fd83ec272d4..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/keepPluginDependencies.xml +++ /dev/null @@ -1,23 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <build> - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - <dependencies> - <dependency> - <artifactId>commons-lang</artifactId> - <version>2.3</version> - </dependency> - </dependencies> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/keepPluginManagementDependencies.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/keepPluginManagementDependencies.xml deleted file mode 100644 index 1e5250aadfe..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/keepPluginManagementDependencies.xml +++ /dev/null @@ -1,25 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - <dependencies> - <dependency> - <artifactId>commons-lang</artifactId> - <version>2.3</version> - </dependency> - </dependencies> - </plugin> - </plugins> - </pluginManagement> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/mergeSettings.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/mergeSettings.xml deleted file mode 100644 index 4e06eed3b23..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/mergeSettings.xml +++ /dev/null @@ -1,29 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - </plugin> - </plugins> - </pluginManagement> - - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <configuration> - <foo>bar</foo> - </configuration> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overridePluginManagementSection.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overridePluginManagementSection.xml deleted file mode 100644 index b0627726fed..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overridePluginManagementSection.xml +++ /dev/null @@ -1,24 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>other</groupId> - <artifactId>my.artifact</artifactId> - <version>2.0</version> - </plugin> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - </plugin> - </plugins> - </pluginManagement> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overrideVersion.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overrideVersion.xml deleted file mode 100644 index 53187e02b8c..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overrideVersion.xml +++ /dev/null @@ -1,21 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <build> - - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - <configuration> - <foo>bar</foo> - </configuration> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overrideVersionFromPluginManagement.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overrideVersionFromPluginManagement.xml deleted file mode 100644 index 4e06eed3b23..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/overrideVersionFromPluginManagement.xml +++ /dev/null @@ -1,29 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <version>0.9</version> - </plugin> - </plugins> - </pluginManagement> - - <plugins> - <plugin> - <groupId>mygroup</groupId> - <artifactId>my.artifact</artifactId> - <configuration> - <foo>bar</foo> - </configuration> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/registerNewPlugin.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/registerNewPlugin.xml deleted file mode 100644 index 5ea792e368e..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPluginTest/registerNewPlugin.xml +++ /dev/null @@ -1,8 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.1-SNAPSHOT</version> - -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPom.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPom.xml deleted file mode 100644 index 8da37df2821..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPom.xml +++ /dev/null @@ -1,25 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.2-SNAPSHOT</version> - <packaging>jar</packaging> - <build> - <plugins> - <plugin> - <groupId>ch.hortis.sonar</groupId> - <artifactId>sonar-core-maven-plugin</artifactId> - <version>0.1.1</version> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.4</source> - <target>1.5</target> - </configuration> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPomPM.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPomPM.xml deleted file mode 100644 index 77ce90dd2f4..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPomPM.xml +++ /dev/null @@ -1,27 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.2-SNAPSHOT</version> - <packaging>jar</packaging> - <build> - <pluginManagement> - <plugins> - <plugin> - <groupId>ch.hortis.sonar</groupId> - <artifactId>sonar-core-maven-plugin</artifactId> - <version>0.1.1</version> - </plugin> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.4</source> - <target>1.5</target> - </configuration> - </plugin> - </plugins> - </pluginManagement> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPomWithSourceEncoding.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPomWithSourceEncoding.xml deleted file mode 100644 index 3106fec7097..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenPomWithSourceEncoding.xml +++ /dev/null @@ -1,23 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.2-SNAPSHOT</version> - <packaging>jar</packaging> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.4</source> - <target>1.5</target> - </configuration> - </plugin> - </plugins> - </build> - <properties> - <project.build.sourceEncoding>UTF-16</project.build.sourceEncoding> - </properties> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenSurefireUtilsTest/MavenPom.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenSurefireUtilsTest/MavenPom.xml deleted file mode 100644 index 15defb7b33c..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenSurefireUtilsTest/MavenPom.xml +++ /dev/null @@ -1,20 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>foo</groupId> - <artifactId>bar</artifactId> - <version>0.2-SNAPSHOT</version> - <packaging>jar</packaging> - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.4</source> - <target>1.5</target> - </configuration> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenUtilsTest/getJavaVersion.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenUtilsTest/getJavaVersion.xml deleted file mode 100644 index 3949dafe898..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenUtilsTest/getJavaVersion.xml +++ /dev/null @@ -1,22 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>org.sonar.tests</groupId> - <artifactId>java4</artifactId> - <version>1.0-SNAPSHOT</version> - <packaging>jar</packaging> - <name>Sonar tests - java4 syntax</name> - - <build> - <plugins> - <plugin> - <groupId>org.apache.maven.plugins</groupId> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.4</source> - <target>1.4</target> - </configuration> - </plugin> - </plugins> - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenUtilsTest/getJavaVersionFromPluginManagement.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenUtilsTest/getJavaVersionFromPluginManagement.xml deleted file mode 100644 index e03f53f5980..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/batch/maven/MavenUtilsTest/getJavaVersionFromPluginManagement.xml +++ /dev/null @@ -1,24 +0,0 @@ -<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" - xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> - <modelVersion>4.0.0</modelVersion> - <groupId>org.sonar.tests</groupId> - <artifactId>java4</artifactId> - <version>1.0-SNAPSHOT</version> - <packaging>jar</packaging> - <name>Sonar tests - java4 syntax</name> - - <build> - <pluginManagement> - <plugins> - <plugin> - <artifactId>maven-compiler-plugin</artifactId> - <configuration> - <source>1.4</source> - <target>1.4</target> - </configuration> - </plugin> - </plugins> - </pluginManagement> - - </build> -</project>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfile.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfile.xml deleted file mode 100644 index 772e980dadf..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfile.xml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <name>sonar way</name> - <language>java</language> - <rules> - <rule> - <repositoryKey>checkstyle</repositoryKey> - <key>IllegalRegexp</key> - <priority>CRITICAL</priority> - </rule> - </rules> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfileWithRuleParameters.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfileWithRuleParameters.xml deleted file mode 100644 index 6df8c00aeb4..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfileWithRuleParameters.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <name>sonar way</name> - <language>java</language> - <rules> - <rule> - <repositoryKey>checkstyle</repositoryKey> - <key>IllegalRegexp</key> - <priority>BLOCKER</priority> - <parameters> - <parameter> - <key>format</key> - <value>foo</value> - </parameter> - <parameter> - <key>message</key> - <value>with special characters < > &</value> - </parameter> - </parameters> - </rule> - </rules> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfileWithUnknownRuleParameter.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfileWithUnknownRuleParameter.xml deleted file mode 100644 index 4eea58fc72f..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/importProfileWithUnknownRuleParameter.xml +++ /dev/null @@ -1,19 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <name>sonar way</name> - <language>java</language> - <rules> - <rule> - <repositoryKey>checkstyle</repositoryKey> - <key>IllegalRegexp</key> - <priority>BLOCKER</priority> - <parameters> - <parameter> - <key>unknown</key> - <value>foo</value> - </parameter> - </parameters> - </rule> - </rules> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/nameAndLanguageShouldBeMandatory.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/nameAndLanguageShouldBeMandatory.xml deleted file mode 100644 index 4a5844349ca..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileParserTest/nameAndLanguageShouldBeMandatory.xml +++ /dev/null @@ -1,11 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <rules> - <rule> - <repositoryKey>checkstyle</repositoryKey> - <key>IllegalRegexp</key> - <priority>CRITICAL</priority> - </rule> - </rules> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportEmptyProfile.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportEmptyProfile.xml deleted file mode 100644 index 351657f74ae..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportEmptyProfile.xml +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <name>sonar way</name> - <language>java</language> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportProfile.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportProfile.xml deleted file mode 100644 index 70366f085a6..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportProfile.xml +++ /dev/null @@ -1,13 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <name>sonar way</name> - <language>java</language> - <rules> - <rule> - <repositoryKey>checkstyle</repositoryKey> - <key>IllegalRegexp</key> - <priority>BLOCKER</priority> - </rule> - </rules> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportRuleParameters.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportRuleParameters.xml deleted file mode 100644 index 6df8c00aeb4..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/profiles/XMLProfileSerializerTest/exportRuleParameters.xml +++ /dev/null @@ -1,23 +0,0 @@ -<?xml version="1.0" encoding="UTF-8"?> -<!-- Generated by SonarQube --> -<profile> - <name>sonar way</name> - <language>java</language> - <rules> - <rule> - <repositoryKey>checkstyle</repositoryKey> - <key>IllegalRegexp</key> - <priority>BLOCKER</priority> - <parameters> - <parameter> - <key>format</key> - <value>foo</value> - </parameter> - <parameter> - <key>message</key> - <value>with special characters < > &</value> - </parameter> - </parameters> - </rule> - </rules> -</profile> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionTest/sample.html b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionTest/sample.html deleted file mode 100644 index 86c36936b5c..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionTest/sample.html +++ /dev/null @@ -1 +0,0 @@ -description of rule loaded from file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionTest/sample.md b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionTest/sample.md deleted file mode 100644 index 86c36936b5c..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionTest/sample.md +++ /dev/null @@ -1 +0,0 @@ -description of rule loaded from file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/deprecated.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/deprecated.xml deleted file mode 100644 index 2938ea70377..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/deprecated.xml +++ /dev/null @@ -1,10 +0,0 @@ -<rules> - <rule key="org.sonar.it.checkstyle.MethodsCountCheck" priority="CRITICAL"> - <name>Methods Count Check</name> - <configKey>Checker/TreeWalker/org.sonar.it.checkstyle.MethodsCountCheck</configKey> - <description>Count methods</description> - <param key="minMethodsCount" type="i"> - <description>description of param</description> - </param> - </rule> -</rules>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/invalid.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/invalid.xml deleted file mode 100644 index de3d00c00aa..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/invalid.xml +++ /dev/null @@ -1,2 +0,0 @@ -<rules> - <rule> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/rules.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/rules.xml deleted file mode 100644 index 05c3084cbac..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/rules.xml +++ /dev/null @@ -1,42 +0,0 @@ -<rules> - <rule> - <!-- with exhaustive fields --> - <key>complete</key> - <name>Complete</name> - <description> - <![CDATA[Description of Complete]]> - </description> - <internalKey>Checker/TreeWalker/LocalVariableName</internalKey> - <severity>BLOCKER</severity> - <cardinality>MULTIPLE</cardinality> - <status>BETA</status> - <type>BUG</type> - <tag>misra</tag> - <tag>spring</tag> - <param> - <key>tokens</key> - <description> - <![CDATA[ - Controls whether the check applies to variable declarations or catch clause parameters - ]]> - </description> - </param> - <param> - <key>ignore</key> - <description> - Ignore ? - </description> - <defaultValue>false</defaultValue> - </param> - </rule> - - - <rule> - <!-- with only required fields --> - <key>minimal</key> - <name>Minimal</name> - <description> - <![CDATA[Description of Minimal]]> - </description> - </rule> -</rules> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/utf8-with-bom.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/utf8-with-bom.xml deleted file mode 100644 index 0c0b5c88c33..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/utf8-with-bom.xml +++ /dev/null @@ -1,11 +0,0 @@ -<rules> - <rule> - <key>com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck</key> - <priority>BLOCKER</priority> - <configKey>Checker/TreeWalker/LocalVariableName</configKey> - <name>M & M</name> - <description> - <![CDATA[éà&]]> - </description> - </rule> -</rules> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/utf8.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/utf8.xml deleted file mode 100644 index 6197e030057..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/rule/RulesDefinitionXmlLoaderTest/utf8.xml +++ /dev/null @@ -1,11 +0,0 @@ -<rules> - <rule> - <key>com.puppycrawl.tools.checkstyle.checks.naming.LocalVariableNameCheck</key> - <priority>BLOCKER</priority> - <configKey>Checker/TreeWalker/LocalVariableName</configKey> - <name>M & M</name> - <description> - <![CDATA[éà&]]> - </description> - </rule> -</rules> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/server/ws/WebServiceTest/response-example.txt b/sonar-plugin-api/src/test/resources/org/sonar/api/server/ws/WebServiceTest/response-example.txt deleted file mode 100644 index 21c78ddf02b..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/server/ws/WebServiceTest/response-example.txt +++ /dev/null @@ -1 +0,0 @@ -example of WS response diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/StaxParserTest/xml-dtd-test.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/StaxParserTest/xml-dtd-test.xml deleted file mode 100644 index 7e643b8b6fe..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/StaxParserTest/xml-dtd-test.xml +++ /dev/null @@ -1,5 +0,0 @@ -<?xml version="1.0"?> -<!DOCTYPE test SYSTEM "http://com.foo.bar/fake.dtd"> -<test> - <another-test/> -</test>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/StaxParserTest/xml-xsd-test.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/StaxParserTest/xml-xsd-test.xml deleted file mode 100644 index 69f7f0e1ac1..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/StaxParserTest/xml-xsd-test.xml +++ /dev/null @@ -1,6 +0,0 @@ -<?xml version="1.0"?> -<test xmlns="http://www.test.org" - xmlns:xsi="http://www.w3.org/1999/XMLSchema/instance" - xsi:schemaLocation="http://www.test.org http://foo.bar.org/test.xsd"> - <another-test/> -</test> diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/UriReaderTest/foo.txt b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/UriReaderTest/foo.txt deleted file mode 100644 index be36d7b95db..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/UriReaderTest/foo.txt +++ /dev/null @@ -1 +0,0 @@ -in foo
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/XpathParserTest/sample.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/XpathParserTest/sample.xml deleted file mode 100644 index 84ad41252a7..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/XpathParserTest/sample.xml +++ /dev/null @@ -1,9 +0,0 @@ -<samples> - <sample id="1" name="one"> - <foo>bar</foo> - </sample> - - <sample id="2" name="two"> - <foo>toto</foo> - </sample> -</samples>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/XpathParserTest/unvalid.xml b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/XpathParserTest/unvalid.xml deleted file mode 100644 index 148118c9bd7..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/XpathParserTest/unvalid.xml +++ /dev/null @@ -1,3 +0,0 @@ -<samples> - <sample not valid -</samples>
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldUnzipFile.zip b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldUnzipFile.zip Binary files differdeleted file mode 100644 index a540bc5b5ca..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldUnzipFile.zip +++ /dev/null diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/bar.txt b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/bar.txt deleted file mode 100644 index 164ff71f4e7..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/bar.txt +++ /dev/null @@ -1 +0,0 @@ -barrrrrrrrr
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/dir1/hello.properties b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/dir1/hello.properties deleted file mode 100644 index 1c6a1a9e8f5..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/dir1/hello.properties +++ /dev/null @@ -1 +0,0 @@ -a=b
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/foo.txt b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/foo.txt deleted file mode 100644 index 4c290181ef5..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/shouldZipDirectory/foo.txt +++ /dev/null @@ -1 +0,0 @@ -fooooooooooo
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/zip-slip.zip b/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/zip-slip.zip Binary files differdeleted file mode 100644 index 38b3f499de0..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/utils/ZipUtilsTest/zip-slip.zip +++ /dev/null diff --git a/sonar-plugin-api/src/test/resources/org/sonar/api/web/AbstractRubyTemplateTest/template.erb b/sonar-plugin-api/src/test/resources/org/sonar/api/web/AbstractRubyTemplateTest/template.erb deleted file mode 100644 index b5754e20373..00000000000 --- a/sonar-plugin-api/src/test/resources/org/sonar/api/web/AbstractRubyTemplateTest/template.erb +++ /dev/null @@ -1 +0,0 @@ -ok
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/sonar/bundles/PluginFoo.properties b/sonar-plugin-api/src/test/resources/sonar/bundles/PluginFoo.properties deleted file mode 100644 index 7669c6daabb..00000000000 --- a/sonar-plugin-api/src/test/resources/sonar/bundles/PluginFoo.properties +++ /dev/null @@ -1,2 +0,0 @@ -foo.hello=Hello -foo.world=World
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/sonar/bundles/PluginFoo_es.properties b/sonar-plugin-api/src/test/resources/sonar/bundles/PluginFoo_es.properties deleted file mode 100644 index 61318faee2b..00000000000 --- a/sonar-plugin-api/src/test/resources/sonar/bundles/PluginFoo_es.properties +++ /dev/null @@ -1,3 +0,0 @@ -foo.hello=Hola -foo.world=Mundo -only.in.spanish=bueno
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/sonar/bundles/Test.properties b/sonar-plugin-api/src/test/resources/sonar/bundles/Test.properties deleted file mode 100644 index e7076859e91..00000000000 --- a/sonar-plugin-api/src/test/resources/sonar/bundles/Test.properties +++ /dev/null @@ -1,3 +0,0 @@ -test.one=One -test.two=Two -with.string.params=Continuous %1$s will %2$s !
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/resources/sonar/bundles/Test_fr.properties b/sonar-plugin-api/src/test/resources/sonar/bundles/Test_fr.properties deleted file mode 100644 index 4765adc3e2f..00000000000 --- a/sonar-plugin-api/src/test/resources/sonar/bundles/Test_fr.properties +++ /dev/null @@ -1,2 +0,0 @@ -test.one=Un -test.two=Deux
\ No newline at end of file diff --git a/sonar-plugin-api/src/test/scripts/echo.bat b/sonar-plugin-api/src/test/scripts/echo.bat deleted file mode 100755 index 6622b994668..00000000000 --- a/sonar-plugin-api/src/test/scripts/echo.bat +++ /dev/null @@ -1,4 +0,0 @@ -@ECHO OFF -@ECHO %CD% > echo.log -@ECHO Parameter: %1 >> echo.log -@ECHO Environment variable: %ENVVAR% >> echo.log diff --git a/sonar-plugin-api/src/test/scripts/echo.sh b/sonar-plugin-api/src/test/scripts/echo.sh deleted file mode 100755 index 8931fd8e903..00000000000 --- a/sonar-plugin-api/src/test/scripts/echo.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -WORKING_DIR=`pwd` -echo $WORKING_DIR > echo.log -echo "Parameter: $1" >> echo.log -echo "Environment variable: $ENVVAR" >> echo.log diff --git a/sonar-plugin-api/src/test/scripts/forever.bat b/sonar-plugin-api/src/test/scripts/forever.bat deleted file mode 100755 index a7d921821f5..00000000000 --- a/sonar-plugin-api/src/test/scripts/forever.bat +++ /dev/null @@ -1,6 +0,0 @@ -@ECHO OFF - -:LOOP - @rem Next line may lead to freeze of build process on Windows 7 due to non-terminated ping-processes - @rem ping 1.1.1.1 -n 2 -w 60000 > nul -GOTO LOOP diff --git a/sonar-plugin-api/src/test/scripts/forever.sh b/sonar-plugin-api/src/test/scripts/forever.sh deleted file mode 100755 index b05525430d5..00000000000 --- a/sonar-plugin-api/src/test/scripts/forever.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -while test "notempty" -do - sleep 5s -done diff --git a/sonar-plugin-api/src/test/scripts/output.bat b/sonar-plugin-api/src/test/scripts/output.bat deleted file mode 100755 index 967bc6092fb..00000000000 --- a/sonar-plugin-api/src/test/scripts/output.bat +++ /dev/null @@ -1,5 +0,0 @@ -@ECHO OFF -@ECHO stdOut: first line -@ECHO stdOut: second line -@ECHO stdErr: first line 1>&2 -@ECHO stdErr: second line 1>&2 diff --git a/sonar-plugin-api/src/test/scripts/output.sh b/sonar-plugin-api/src/test/scripts/output.sh deleted file mode 100755 index cbb0fea9e0f..00000000000 --- a/sonar-plugin-api/src/test/scripts/output.sh +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -echo stdOut: first line -echo stdOut: second line -echo stdErr: first line 1>&2 -echo stdErr: second line 1>&2 |