diff --git a/docs/pages/7_0_0_release_notes.md b/docs/pages/7_0_0_release_notes.md index d1751efbb1..57d67a9a5e 100644 --- a/docs/pages/7_0_0_release_notes.md +++ b/docs/pages/7_0_0_release_notes.md @@ -242,6 +242,7 @@ The following previously deprecated rules have been finally removed: * miscellaneous * [#896](https://github.com/pmd/pmd/issues/896): \[all] Use slf4j + * [#3797](https://github.com/pmd/pmd/issues/3797): \[all] Use JUnit5 * [#1451](https://github.com/pmd/pmd/issues/1451): \[core] RulesetFactoryCompatibility stores the whole ruleset file in memory as a string * ant * [#4080](https://github.com/pmd/pmd/issues/4080): \[ant] Split off Ant integration into a new submodule @@ -389,6 +390,15 @@ The metrics framework has been made simpler and more general. * {% jdoc_old core::lang.metrics.Signature %}s, their implementations, and the interface `SignedNode` have been removed. Node streams allow replacing their usages very easily. +#### Testing framework + +* PMD 7 has been upgraded to use JUnit 5 only. That means, that JUnit4 related classes have been removed, namely + * `net.sourceforge.pmd.testframework.PMDTestRunner` + * `net.sourceforge.pmd.testframework.RuleTestRunner` + * `net.sourceforge.pmd.testframework.TestDescriptor` +* Rule tests, that use {% jdoc test::testframework.SimpleAggregatorTst %} or {% jdoc test::testframework.PmdRuleTst %} work as before without change, but use + now JUnit5 under the hood. If you added additional JUnit4 tests to your rule test classes, then you'll need to upgrade them to use JUnit5. + ### External Contributions * [#1658](https://github.com/pmd/pmd/pull/1658): \[core] Node support for Antlr-based languages - [Matías Fraga](https://github.com/matifraga) diff --git a/docs/pages/pmd/userdocs/extending/testing.md b/docs/pages/pmd/userdocs/extending/testing.md index 7464dfd4af..e075ef3d0c 100644 --- a/docs/pages/pmd/userdocs/extending/testing.md +++ b/docs/pages/pmd/userdocs/extending/testing.md @@ -3,7 +3,7 @@ title: Testing your rules tags: [extending, userdocs] summary: "Learn how to use PMD's simple test framework for unit testing rules." permalink: pmd_userdocs_extending_testing.html -last_updated: July 2022 +last_updated: January 2023 author: Andreas Dangel --- @@ -15,7 +15,7 @@ Of course, the more tests, the better the rule is verified. If the rule is more with which the behavior can be modified, then these different cases can also be tested. And if there is a bug fix for a rule, be it a false positive or a false negative case, it should be accompanied -with an additional test case, so that the bug is not accidentally reintroduced later on. +by an additional test case, so that the bug is not accidentally reintroduced later on. ## How it works @@ -26,7 +26,7 @@ We have one test class per rule, which executes all test cases for a single rule stored in separate XML files, for each rule a separate file is used. All the test classes inherit from `net.sourceforge.pmd.testframework.PmdRuleTst`, -which provides the seamless integration with JUnit. This base class determines the language, the category name +which provides the seamless integration with JUnit5. This base class determines the language, the category name and the rule name from the concrete test class. It then searches the test code on its own. E.g. the individual rule test class `net.sourceforge.pmd.lang.java.rule.bestpractices.AbstractClassWithoutAbstractMethodTest` tests the @@ -62,7 +62,7 @@ In general, the class name and file name pattern for the test class and data is src/test/resources/net/sourceforge/pmd/lang//rule//xml/.xml {%include tip.html content="This convention allows you to quickly find the test cases for a given rule: -Just search in the project for a file `.xml`. Search for a class `Test` to find the +Just search in the project for a file `.xml`. Search for a class `Test` to find the unit test class for the given rule. And if the rule is a Java-based rule, the search for `Rule` finds the rule implementation class." %} @@ -81,7 +81,7 @@ package net.sourceforge.pmd.lang.java.rule.bestpractices; import net.sourceforge.pmd.testframework.PmdRuleTst; -public class AbstractClassWithoutAbstractMethodTest extends PmdRuleTst { +class AbstractClassWithoutAbstractMethodTest extends PmdRuleTst { // no additional unit tests } ``` @@ -129,7 +129,7 @@ The root element is ``. It can contain one or more `` and Each `` element defines a single test case. `` elements are used to share code snippets between different test cases. -{%include note.html content="The XML schema is available at [rule-tests.xsd](https://github.com/pmd/pmd/blob/master/pmd-test/src/main/resources/rule-tests_1_0_0.xsd)." %} +{%include note.html content="The XML schema is available at [rule-tests.xsd](https://github.com/pmd/pmd/blob/master/pmd-test-schema/src/main/resources/net/sourceforge/pmd/test/schema/rule-tests_1_0_0.xsd)." %} ### `` attributes @@ -139,17 +139,6 @@ The `` elements understands the following optional attributes: * **focused**: By default, it's `false`. Set it to `true`, to ignore all other test cases. -* **useAuxClasspath**: _deprecated since PMD 6.48.0: assumed true, has no effect anymore._ - By default, it's `true`. Set it to `false` to reproduce issues which only - appear without type resolution. - -* **reinitializeRule**: _deprecated since PMD 6.48.0: assumed true, has no effect anymore._ - By default, it's `true`, so each test case starts with a fresh instantiated rule. Set it - to `false` to reproduce cases, where the previous run has influences. - -* **regressionTest**: _deprecated since PMD 6.48.0: Use `disabled` instead. Note: It has the opposite boolean - semantic._ By default, it's `true`. Set it to `false`, to ignore and skip a test case. - ### `` children * **``**: Short description of the test case. This will be the JUnit test name in the report. @@ -196,7 +185,7 @@ in a "CDATA" section, so that no further XML escapes (entity references such as xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/rule-tests https://pmd.sourceforge.io/rule-tests_1_0_0.xsd"> - + Just a description, will be used as the test name for JUnit in the reports propValue 2 @@ -237,7 +226,7 @@ better readability. The description can be written directly without a CDATA sect ## Using the test framework externally It is also possible to use the test framework for custom rules developed outside the PMD source base. -Therefore you just need to reference the dependency `net.sourceforge.pmd:pmd-test`. +In order to use the test framework you just need to reference the dependency `net.sourceforge.pmd:pmd-test`. For maven, you can use this snippet: @@ -260,9 +249,9 @@ package com.example.pmd.rules; import net.sourceforge.pmd.testframework.SimpleAggregatorTst; -public class CustomRuleTest extends SimpleAggregatorTst { +class CustomRuleTest extends SimpleAggregatorTst { @Override - public void setUp() { + protected void setUp() { addRule("com/example/pmd/ruleset.xml", "CustomRule"); } } @@ -276,27 +265,19 @@ The test data should be placed in an xml file located in "src/test/resources" un ## How the test framework is implemented -The framework uses a custom JUnit test runner under the hood, among a couple of utility classes: +The framework uses the [dynamic test feature](https://junit.org/junit5/docs/current/user-guide/#writing-tests-dynamic-tests) +of JUnit5 under the hood, among a couple of utility classes: * `PmdRuleTst`: This is the base class for tests in PMD's code base. It is a subclass of `RuleTst` and just - contains the logic to determine the test resources based on the test class name. + contains the logic to determine the test resources based on the test class name. -* `SimpleAggregatorTst`: This is a more generic base class for the test classes and defines - the custom JUnit test runner. It doesn't register any test cases on its own. - It itself is a subclass of `RuleTst`. +* `SimpleAggregatorTst`: This is a more generic base class for the test classes. + It doesn't register any test cases on its own. You can register your own rule tests. + It itself is a subclass of `RuleTst`. * The maven module "pmd-test-schema" contains the logic to parse the XML files and provide a `RuleTestCollection`. This in turn contains a list of `RuleTestDescriptor`s. Each rule test descriptor describes a single test case. * `RuleTst`: uses the `TestSchemaParser` from module "pmd-test-schema" to parse the test cases, executes each - rule test descriptor and asserts the results. - -* `PMDTestRunner`: A custom JUnit test runner, that combines two separate test runners: The custom `RuleTestRunner` - and the standard `JUnit4` test runner. This combination allows you to add additional standard unit test methods - annotated with `@Test` to your test class. - - *Note:* Since the test class is executed through two test runners, it is actually instantiated twice. Be aware - of this, if you do any initialization in the constructor. Also, the static hooks `@BeforeClass` and `@AfterClass` - will be executed twice. - -* `RuleTestRunner`: This test runner executes the test descriptors with the help of `RuleTst`. + rule test descriptor and asserts the results. It defines a test method `ruleTests()` which is a test factory + and returns one dynamic test per rule test. diff --git a/pmd-ant/pom.xml b/pmd-ant/pom.xml index 68f3463143..7001eeddfc 100644 --- a/pmd-ant/pom.xml +++ b/pmd-ant/pom.xml @@ -42,11 +42,6 @@ test-jar - - org.apache.ant - ant-testutil - test - org.slf4j slf4j-simple @@ -72,21 +67,11 @@ junit-platform-suite test - - pl.pragmatists - JUnitParams - test - org.mockito mockito-core test - - com.github.stefanbirkner - system-rules - test - com.github.stefanbirkner system-lambda diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/LanguageVersionTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/LanguageVersionTest.java index 011ef5b8c3..fe132bcb61 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/LanguageVersionTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/LanguageVersionTest.java @@ -7,20 +7,12 @@ package net.sourceforge.pmd.lang.apex; import java.util.Arrays; import java.util.Collection; -import org.junit.runners.Parameterized.Parameters; - import net.sourceforge.pmd.AbstractLanguageVersionTest; -import net.sourceforge.pmd.lang.LanguageVersion; -public class LanguageVersionTest extends AbstractLanguageVersionTest { +class LanguageVersionTest extends AbstractLanguageVersionTest { - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { { ApexLanguageModule.NAME, ApexLanguageModule.TERSE_NAME, "54", - getLanguage("Apex").getVersion("54"), }, }); + static Collection data() { + return Arrays.asList(new TestDescriptor(ApexLanguageModule.NAME, ApexLanguageModule.TERSE_NAME, "35", + getLanguage("Apex").getVersion("35"))); } } diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/RuleSetFactoryTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/RuleSetFactoryTest.java index b2e1a042c4..fb955369af 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/RuleSetFactoryTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/RuleSetFactoryTest.java @@ -6,5 +6,6 @@ package net.sourceforge.pmd.lang.apex; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional tests yet } diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexCommentTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexCommentTest.java index d0f5c75c4e..0680821a12 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexCommentTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexCommentTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test; class ApexCommentTest extends ApexParserTestBase { @Test - public void testContainsComment1() { + void testContainsComment1() { ASTApexFile file = apex.parse("class Foo {void foo(){try {\n" + "} catch (Exception e) {\n" + " /* OK: block comment inside of empty catch block; should not be reported */\n" diff --git a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexQualifiedNameTest.java b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexQualifiedNameTest.java index a39a40ed23..1dfcfc1d6f 100644 --- a/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexQualifiedNameTest.java +++ b/pmd-apex/src/test/java/net/sourceforge/pmd/lang/apex/ast/ApexQualifiedNameTest.java @@ -94,7 +94,7 @@ class ApexQualifiedNameTest extends ApexParserTestBase { @Test - public void testUnqualifiedEnum() { + void testUnqualifiedEnum() { ASTUserEnum root = (ASTUserEnum) parse("public enum primaryColor { RED, YELLOW, BLUE }"); ApexQualifiedName enumQName = root.getQualifiedName(); @@ -107,7 +107,7 @@ class ApexQualifiedNameTest extends ApexParserTestBase { } @Test - public void testQualifiedEnum() { + void testQualifiedEnum() { ASTUserClass root = (ASTUserClass) parse("public class Outer { public enum Inner { OK } }"); ASTUserEnum enumNode = root.descendants(ASTUserEnum.class).firstOrThrow(); diff --git a/pmd-cli/pom.xml b/pmd-cli/pom.xml index aa24372f48..5d65824a77 100644 --- a/pmd-cli/pom.xml +++ b/pmd-cli/pom.xml @@ -290,21 +290,11 @@ junit-platform-suite test - - pl.pragmatists - JUnitParams - test - org.mockito mockito-core test - - com.github.stefanbirkner - system-rules - test - com.github.stefanbirkner system-lambda diff --git a/pmd-cli/src/test/java/net/sourceforge/pmd/cli/CpdCliTest.java b/pmd-cli/src/test/java/net/sourceforge/pmd/cli/CpdCliTest.java index 5107c86b99..48ae61586c 100644 --- a/pmd-cli/src/test/java/net/sourceforge/pmd/cli/CpdCliTest.java +++ b/pmd-cli/src/test/java/net/sourceforge/pmd/cli/CpdCliTest.java @@ -191,7 +191,7 @@ class CpdCliTest extends BaseCliTest { * See: https://sourceforge.net/p/pmd/bugs/1178/ */ @Test - public void testSkipLexicalErrors() throws Exception { + void testSkipLexicalErrors() throws Exception { runCli(VIOLATIONS_FOUND, "--minimum-tokens", "10", "-d", BASE_RES_PATH + "badandgood/", @@ -205,21 +205,21 @@ class CpdCliTest extends BaseCliTest { @Test - public void jsShouldFindDuplicatesWithDifferentFileExtensions() throws Exception { + void jsShouldFindDuplicatesWithDifferentFileExtensions() throws Exception { runCli(VIOLATIONS_FOUND, "--minimum-tokens", "5", "--language", "js", "-d", BASE_RES_PATH + "tsFiles/File1.ts", BASE_RES_PATH + "tsFiles/File2.ts") .checkStdOut(containsString("Found a 9 line (32 tokens) duplication in the following files")); } @Test - public void jsShouldFindNoDuplicatesWithDifferentFileExtensions() throws Exception { + void jsShouldFindNoDuplicatesWithDifferentFileExtensions() throws Exception { runCli(OK, "--minimum-tokens", "5", "--language", "js", "-d", BASE_RES_PATH + "tsFiles/") .checkStdOut(emptyString()); } @Test - public void renderEmptyReportXml() throws Exception { + void renderEmptyReportXml() throws Exception { runCli(OK, "--minimum-tokens", "5", "--language", "js", "-f", "xml", "-d", BASE_RES_PATH + "tsFiles/") diff --git a/pmd-cli/src/test/java/net/sourceforge/pmd/cli/ForceLanguageCliTest.java b/pmd-cli/src/test/java/net/sourceforge/pmd/cli/ForceLanguageCliTest.java index c3fe2cc605..faa57c1f40 100644 --- a/pmd-cli/src/test/java/net/sourceforge/pmd/cli/ForceLanguageCliTest.java +++ b/pmd-cli/src/test/java/net/sourceforge/pmd/cli/ForceLanguageCliTest.java @@ -13,7 +13,7 @@ import java.util.List; import org.junit.jupiter.api.Test; -public class ForceLanguageCliTest extends BaseCliTest { +class ForceLanguageCliTest extends BaseCliTest { private static final String BASE_DIR = "src/test/resources/net/sourceforge/pmd/cli/forceLanguage/"; private static final String RULE_MESSAGE = "Violation from ReportAllRootNodes"; @@ -29,19 +29,19 @@ public class ForceLanguageCliTest extends BaseCliTest { } @Test - public void analyzeSingleXmlWithoutForceLanguage() throws Exception { + void analyzeSingleXmlWithoutForceLanguage() throws Exception { runCli(OK, "-d", BASE_DIR + "src/file1.ext") .verify(r -> r.checkStdOut(containsStringNTimes(0, RULE_MESSAGE))); } @Test - public void analyzeSingleXmlWithForceLanguage() throws Exception { + void analyzeSingleXmlWithForceLanguage() throws Exception { runCli(VIOLATIONS_FOUND, "-d", BASE_DIR + "src/file1.ext", "--force-language", "dummy") .verify(r -> r.checkStdOut(containsStringNTimes(1, RULE_MESSAGE))); } @Test - public void analyzeDirectoryWithForceLanguage() throws Exception { + void analyzeDirectoryWithForceLanguage() throws Exception { runCli(VIOLATIONS_FOUND, "-d", BASE_DIR + "src/", "--force-language", "dummy") .verify(r -> r.checkStdOut(containsStringNTimes(3, RULE_MESSAGE))); } diff --git a/pmd-core/pom.xml b/pmd-core/pom.xml index 78e142e78c..f96c3256be 100644 --- a/pmd-core/pom.xml +++ b/pmd-core/pom.xml @@ -133,21 +133,11 @@ junit-platform-suite test - - pl.pragmatists - JUnitParams - test - org.mockito mockito-core test - - com.github.stefanbirkner - system-rules - test - com.github.stefanbirkner system-lambda diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractRule.java b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractRule.java index da338d043c..44bd929606 100644 --- a/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractRule.java +++ b/pmd-core/src/main/java/net/sourceforge/pmd/lang/rule/AbstractRule.java @@ -4,6 +4,7 @@ package net.sourceforge.pmd.lang.rule; +import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collections; @@ -396,7 +397,9 @@ public abstract class AbstractRule extends AbstractPropertySource implements Rul public Rule deepCopy() { Rule result; try { - result = getClass().getConstructor().newInstance(); + Constructor declaredConstructor = getClass().getDeclaredConstructor(); + declaredConstructor.setAccessible(true); + result = declaredConstructor.newInstance(); } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ignored) { // Can't happen... we already have an instance throw new RuntimeException(ignored); // in case it happens anyway, something is really wrong... diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java index b1d5081108..7058041d45 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/AbstractRuleTest.java @@ -4,6 +4,7 @@ package net.sourceforge.pmd; +import static net.sourceforge.pmd.ReportTestUtil.getReportForRuleApply; import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; @@ -27,9 +28,9 @@ import net.sourceforge.pmd.properties.PropertyFactory; import net.sourceforge.pmd.reporting.FileAnalysisListener; -public class AbstractRuleTest { +class AbstractRuleTest { - public static class MyRule extends AbstractRule { + private static class MyRule extends AbstractRule { private static final PropertyDescriptor FOO_PROPERTY = PropertyFactory.stringProperty("foo").desc("foo property").defaultValue("x").build(); private static final PropertyDescriptor FOO_DEFAULT_PROPERTY = PropertyFactory.stringProperty("fooDefault") .defaultValue("bar") @@ -38,7 +39,7 @@ public class AbstractRuleTest { private static final PropertyDescriptor XPATH_PROPERTY = PropertyFactory.stringProperty("xpath").desc("xpath property").defaultValue("").build(); - public MyRule() { + MyRule() { definePropertyDescriptor(FOO_PROPERTY); definePropertyDescriptor(XPATH_PROPERTY); definePropertyDescriptor(FOO_DEFAULT_PROPERTY); @@ -110,7 +111,7 @@ public class AbstractRuleTest { DummyRootNode s = helper.parse("abc()", "filename"); - RuleViolation rv = RuleContextTest.getReportForRuleApply(r, s).getViolations().get(0); + RuleViolation rv = getReportForRuleApply(r, s).getViolations().get(0); assertEquals("Message foo ${className} ${methodName} ${variableName} 10 ${noSuchProperty}", rv.getDescription()); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java index 06d3a64781..679e34375c 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/PmdAnalysisTest.java @@ -38,7 +38,7 @@ import net.sourceforge.pmd.util.log.internal.NoopReporter; /** * @author Clément Fournier */ -public class PmdAnalysisTest { +class PmdAnalysisTest { @Test void testPmdAnalysisWithEmptyConfig() { @@ -167,8 +167,8 @@ public class PmdAnalysisTest { } } - public static class TestRule extends AbstractRule { - public TestRule() { + private static class TestRule extends AbstractRule { + TestRule() { setLanguage(Dummy2LanguageModule.getInstance()); setMessage("dummy 2 test rule"); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java index 380742c4e5..e2bd21c114 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTest.java @@ -27,7 +27,7 @@ import net.sourceforge.pmd.renderers.XMLRenderer; import net.sourceforge.pmd.reporting.FileAnalysisListener; import net.sourceforge.pmd.reporting.GlobalAnalysisListener; -public class ReportTest { +class ReportTest { // Files are grouped together now. @Test diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/ReportTestUtil.java b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTestUtil.java new file mode 100644 index 0000000000..752d4d580c --- /dev/null +++ b/pmd-core/src/test/java/net/sourceforge/pmd/ReportTestUtil.java @@ -0,0 +1,39 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd; + +import java.util.function.BiConsumer; + +import net.sourceforge.pmd.lang.LanguageProcessorRegistry; +import net.sourceforge.pmd.lang.ast.Node; +import net.sourceforge.pmd.lang.ast.RootNode; +import net.sourceforge.pmd.lang.document.TestMessageReporter; + +public final class ReportTestUtil { + private ReportTestUtil() { + // utility + } + + public static Report getReport(Rule rule, BiConsumer sideEffects) { + return Report.buildReport(listener -> sideEffects.accept(rule, RuleContext.create(listener, rule))); + } + + public static Report getReportForRuleApply(Rule rule, Node node) { + return getReport(rule, (r, ctx) -> { + r.initialize(node.getAstInfo().getLanguageProcessor()); + r.apply(node, ctx); + }); + } + + public static Report getReportForRuleSetApply(RuleSet ruleset, RootNode node) { + return Report.buildReport(listener -> { + RuleSets ruleSets = new RuleSets(ruleset); + LanguageProcessorRegistry registry = LanguageProcessorRegistry.singleton(node.getAstInfo().getLanguageProcessor()); + ruleSets.initializeRules(registry, new TestMessageReporter()); + ruleSets.apply(node, listener); + }); + } + +} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleContextTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleContextTest.java index bbd98335fa..d0e1682f0c 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleContextTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleContextTest.java @@ -4,38 +4,16 @@ package net.sourceforge.pmd; +import static net.sourceforge.pmd.ReportTestUtil.getReport; import static org.junit.jupiter.api.Assertions.assertEquals; -import java.util.function.BiConsumer; - import org.junit.jupiter.api.Test; -import net.sourceforge.pmd.lang.LanguageProcessorRegistry; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; -import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.ast.RootNode; import net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil; -import net.sourceforge.pmd.lang.document.TestMessageReporter; -public class RuleContextTest { +class RuleContextTest { - static Report getReport(Rule rule, BiConsumer sideEffects) { - return Report.buildReport(listener -> sideEffects.accept(rule, RuleContext.create(listener, rule))); - } - - public static Report getReportForRuleApply(Rule rule, Node node) { - rule.initialize(node.getAstInfo().getLanguageProcessor()); - return getReport(rule, (r, ctx) -> r.apply(node, ctx)); - } - - static Report getReportForRuleSetApply(RuleSet ruleset, RootNode node) { - return Report.buildReport(listener -> { - RuleSets ruleSets = new RuleSets(ruleset); - ruleSets.initializeRules(LanguageProcessorRegistry.singleton(node.getAstInfo().getLanguageProcessor()), - new TestMessageReporter()); - ruleSets.apply(node, listener); - }); - } @Test void testMessage() throws Exception { diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryMessagesTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryMessagesTest.java index 05538f6c2b..00534146e7 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryMessagesTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryMessagesTest.java @@ -11,10 +11,10 @@ import org.junit.jupiter.api.Test; import com.github.stefanbirkner.systemlambda.SystemLambda; -public class RuleSetFactoryMessagesTest extends RulesetFactoryTestBase { +class RuleSetFactoryMessagesTest extends RulesetFactoryTestBase { @Test - public void testFullMessage() throws Exception { + void testFullMessage() throws Exception { String log = SystemLambda.tapSystemErr(() -> assertCannotParse( rulesetXml( dummyRule( @@ -31,6 +31,4 @@ public class RuleSetFactoryMessagesTest extends RulesetFactoryTestBase { + " ^^^^^^^^^ Not a valid priority: 'not a priority', expected a number in [1,5]" )); } - - } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java index 28e4339354..b0940021fb 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java @@ -213,7 +213,7 @@ class RuleSetFactoryTest extends RulesetFactoryTestBase { * @see [java] TestClassWithoutTestCases - can not set test pattern to empty #4279 */ @Test - public void testEmptyStringProperty() { + void testEmptyStringProperty() { Rule r = loadFirstRule("\n" + "\n " + " ruleset desc\n " @@ -753,7 +753,7 @@ class RuleSetFactoryTest extends RulesetFactoryTestBase { } @Test - public void testDirectDeprecatedRule() { + void testDirectDeprecatedRule() { Rule r = loadFirstRule(rulesetXml( dummyRule(attrs -> attrs.put(DEPRECATED, "true")) )); @@ -980,7 +980,7 @@ class RuleSetFactoryTest extends RulesetFactoryTestBase { } @Test - public void testMissingRuleSetDescriptionIsWarning() { + void testMissingRuleSetDescriptionIsWarning() { loadRuleSetWithDeprecationWarnings( "\n" + " expected) throws Exception { - Report report = RuleContextTest.getReportForRuleSetApply(ruleset, makeCompilationUnits()); + Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits()); assertEquals(expected.size(), report.getViolations().size(), "Invalid number of Violations Reported"); @@ -497,7 +498,7 @@ class RuleSetTest { }) .build(); - Report report = RuleContextTest.getReportForRuleSetApply(ruleset, makeCompilationUnits()); + Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits()); List errors = report.getProcessingErrors(); assertThat(errors, hasSize(1)); @@ -522,7 +523,7 @@ class RuleSetTest { } }).build(); - Report report = RuleContextTest.getReportForRuleSetApply(ruleset, makeCompilationUnits("samplefile.dummy")); + Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits("samplefile.dummy")); List errors = report.getProcessingErrors(); assertThat(errors, hasSize(1)); @@ -561,7 +562,7 @@ class RuleSetTest { } }).build(); - Report report = RuleContextTest.getReportForRuleSetApply(ruleset, makeCompilationUnits()); + Report report = getReportForRuleSetApply(ruleset, makeCompilationUnits()); List errors = report.getProcessingErrors(); assertThat(errors, hasSize(1)); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java index cbf9ab007d..6e7426a73c 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cli/ZipFileTest.java @@ -12,20 +12,20 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; -import org.junit.Test; +import org.junit.jupiter.api.Test; import net.sourceforge.pmd.PMDConfiguration; import net.sourceforge.pmd.PmdAnalysis; import net.sourceforge.pmd.internal.util.IOUtil; import net.sourceforge.pmd.lang.document.TextFile; -public class ZipFileTest { +class ZipFileTest { private static final String ZIP_PATH = "src/test/resources/net/sourceforge/pmd/cli/zipWithSources.zip"; private final Path zipPath = Paths.get(ZIP_PATH); @Test - public void testZipFile() { + void testZipFile() { PMDConfiguration conf = new PMDConfiguration(); conf.addInputPath(zipPath); // no relativizeRoot paths configured -> we use the relative path @@ -40,7 +40,7 @@ public class ZipFileTest { } @Test - public void testZipFileRelativizeWith() { + void testZipFileRelativizeWith() { PMDConfiguration conf = new PMDConfiguration(); conf.addInputPath(zipPath); conf.addRelativizeRoot(Paths.get("src/test/resources")); @@ -55,7 +55,7 @@ public class ZipFileTest { } @Test - public void testZipFileRelativizeWithRoot() { + void testZipFileRelativizeWithRoot() { PMDConfiguration conf = new PMDConfiguration(); conf.addInputPath(zipPath); // this configures "/" as the relativizeRoot -> result are absolute paths diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDReportTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDReportTest.java index e888146e36..744bdfdd18 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDReportTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/CPDReportTest.java @@ -4,8 +4,8 @@ package net.sourceforge.pmd.cpd; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.Arrays; import java.util.HashMap; @@ -14,14 +14,14 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.junit.Test; +import org.junit.jupiter.api.Test; import net.sourceforge.pmd.util.Predicate; -public class CPDReportTest { +class CPDReportTest { @Test - public void testFilterMatches() { + void testFilterMatches() { List originalMatches = Arrays.asList( createMatch("file1.java", "file2.java", 1), createMatch("file1.java", "file3.java", 2), diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/XMLRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/XMLRendererTest.java index 1dba8631af..41a1d74c2f 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/cpd/XMLRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/cpd/XMLRendererTest.java @@ -216,7 +216,7 @@ class XMLRendererTest { } @Test - public void testGetDuplicationStartEnd() throws IOException, ParserConfigurationException, SAXException { + void testGetDuplicationStartEnd() throws IOException, ParserConfigurationException, SAXException { TokenEntry.clearImages(); final CPDReportRenderer renderer = new XMLRenderer(); final List matches = new ArrayList<>(); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/junit/LocaleRule.java b/pmd-core/src/test/java/net/sourceforge/pmd/junit/LocaleRule.java deleted file mode 100644 index adefc78fb0..0000000000 --- a/pmd-core/src/test/java/net/sourceforge/pmd/junit/LocaleRule.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.junit; - -import java.util.Locale; -import java.util.Objects; - -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; - -/** - * - * Based on digulla/DefaultLocaleRule.java. - * - */ -public class LocaleRule extends TestWatcher { - - private Locale localeForTest; - private Locale originalDefault; - - private LocaleRule(Locale localeForTest) { - this.localeForTest = Objects.requireNonNull(localeForTest); - } - - @Override - protected void starting(Description description) { - originalDefault = Locale.getDefault(); - Locale.setDefault(localeForTest); - } - - @Override - protected void finished(Description description) { - Locale.setDefault(originalDefault); - } - - public void setDefault(Locale newLocale) { - Locale.setDefault(Objects.requireNonNull(newLocale)); - } - - public static LocaleRule en() { - return new LocaleRule(Locale.ENGLISH); - } - - public static LocaleRule de() { - return new LocaleRule(Locale.GERMAN); - } -} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/LanguageRegistryTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/LanguageRegistryTest.java index b6bdf2bbd9..4d4109ffa5 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/LanguageRegistryTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/LanguageRegistryTest.java @@ -16,7 +16,7 @@ class LanguageRegistryTest { private final LanguageRegistry languageRegistry = LanguageRegistry.PMD; @Test - public void getDefaultVersionLanguageTest() { + void getDefaultVersionLanguageTest() { Language dummy = languageRegistry.getLanguageById("dummy"); LanguageVersion dummy12 = dummy.getVersion("1.2"); assertNotNull(dummy12); @@ -28,7 +28,7 @@ class LanguageRegistryTest { } @Test - public void getLanguageVersionByAliasTest() { + void getLanguageVersionByAliasTest() { Language dummy = languageRegistry.getLanguageById("dummy"); LanguageVersion dummy17 = dummy.getVersion("1.7"); diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java index 6638422a3a..4cf26d092e 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/document/NioTextFileTest.java @@ -4,7 +4,7 @@ package net.sourceforge.pmd.lang.document; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.FileOutputStream; import java.nio.charset.StandardCharsets; diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java index b600945b01..db7379a963 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/lang/rule/XPathRuleTest.java @@ -5,6 +5,7 @@ package net.sourceforge.pmd.lang.rule; import static net.sourceforge.pmd.PmdCoreTestUtils.setDummyLanguage; +import static net.sourceforge.pmd.ReportTestUtil.getReportForRuleApply; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -15,7 +16,6 @@ import org.junit.jupiter.api.extension.RegisterExtension; import net.sourceforge.pmd.DummyParsingHelper; import net.sourceforge.pmd.Report; -import net.sourceforge.pmd.RuleContextTest; import net.sourceforge.pmd.lang.ast.DummyNode; import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode; import net.sourceforge.pmd.lang.ast.DummyNodeWithDeprecatedAttribute; @@ -48,7 +48,7 @@ class XPathRuleTest { String log = SystemLambda.tapSystemErrAndOut(() -> { // with another rule forked from the same one (in multithreaded processor) - Report report = RuleContextTest.getReportForRuleApply(xpr, firstNode); + Report report = getReportForRuleApply(xpr, firstNode); assertEquals(1, report.getViolations().size()); }); assertThat(log, Matchers.containsString("Use of deprecated attribute 'dummyNode/@Size' by XPath rule 'SomeRule'")); @@ -57,7 +57,7 @@ class XPathRuleTest { log = SystemLambda.tapSystemErrAndOut(() -> { // with another node - Report report = RuleContextTest.getReportForRuleApply(xpr, newNode()); + Report report = getReportForRuleApply(xpr, newNode()); assertEquals(1, report.getViolations().size()); }); assertEquals("", log); // no additional warnings @@ -65,7 +65,7 @@ class XPathRuleTest { log = SystemLambda.tapSystemErrAndOut(() -> { // with another rule forked from the same one (in multithreaded processor) - Report report = RuleContextTest.getReportForRuleApply(xpr.deepCopy(), newNode()); + Report report = getReportForRuleApply(xpr.deepCopy(), newNode()); assertEquals(1, report.getViolations().size()); }); assertEquals("", log); // no additional warnings @@ -75,7 +75,7 @@ class XPathRuleTest { otherRule.setRuleSetName("rset.xml"); log = SystemLambda.tapSystemErrAndOut(() -> { - Report report = RuleContextTest.getReportForRuleApply(otherRule, firstNode); + Report report = getReportForRuleApply(otherRule, firstNode); assertEquals(1, report.getViolations().size()); }); assertThat(log, Matchers.containsString("Use of deprecated attribute 'dummyNode/@Size' by XPath rule 'OtherRule' (in ruleset 'rset.xml')")); @@ -140,7 +140,7 @@ class XPathRuleTest { } Report executeRule(net.sourceforge.pmd.Rule rule, DummyNode node) { - return RuleContextTest.getReportForRuleApply(rule, node); + return getReportForRuleApply(rule, node); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java index f104eb19ba..150f74ce45 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/renderers/XSLTRendererTest.java @@ -9,20 +9,61 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.FooRule; -import net.sourceforge.pmd.ReportTest; +import net.sourceforge.pmd.Report; import net.sourceforge.pmd.RuleViolation; import net.sourceforge.pmd.lang.document.FileLocation; import net.sourceforge.pmd.lang.document.TextRange2d; import net.sourceforge.pmd.lang.rule.ParametricRuleViolation; -class XSLTRendererTest { +class XSLTRendererTest extends AbstractRendererTest { + + @Override + Renderer getRenderer() { + return new XSLTRenderer(); + } + + @Override + String getExpected() { + return readFile("expected.html"); + } + + @Override + String getExpectedEmpty() { + return readFile("empty.html"); + } + + @Override + String getExpectedMultiple() { + return readFile("expected-multiple.html"); + } + + @Override + String getExpectedError(Report.ProcessingError error) { + return readFile("expected-error.html"); + } + + @Override + String getExpectedError(Report.ConfigurationError error) { + return readFile("expected-error.html"); + } + + @Override + String filter(String expected) { + return expected.replaceAll("

PMD unknown Report\\. Generated on .+

", + "

PMD unknown Report. Generated on ...

") + .replaceAll("\r\n", "\n"); // make the test run on Windows, too + } @Test void testDefaultStylesheet() throws Exception { XSLTRenderer renderer = new XSLTRenderer(); FileLocation loc = FileLocation.range("file", TextRange2d.range2d(1, 1, 1, 2)); RuleViolation rv = new ParametricRuleViolation(new FooRule(), loc, "violation message"); - String result = ReportTest.render(renderer, it -> it.onRuleViolation(rv)); + String result = renderReport(renderer, it -> it.onRuleViolation(rv)); assertTrue(result.contains("violation message")); } + + protected String readFile(String relativePath) { + return super.readFile("xslt/" + relativePath); + } } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java index 189040c97b..a39eda5269 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/util/StringUtilTest.java @@ -60,7 +60,7 @@ class StringUtilTest { } @Test - public void testTrimIndent() { + void testTrimIndent() { assertTrimIndent(" \n b \n c", "\nb\nc"); @@ -86,7 +86,7 @@ class StringUtilTest { } @Test - public void substringAfterLast() { + void substringAfterLast() { assertEquals("abc", StringUtil.substringAfterLast("a.abc", '.')); assertEquals("abc", StringUtil.substringAfterLast("abc", '.')); } diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/util/datasource/internal/PathDataSourceTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/util/datasource/internal/PathDataSourceTest.java index 195e78e1e0..f8b594bf0a 100644 --- a/pmd-core/src/test/java/net/sourceforge/pmd/util/datasource/internal/PathDataSourceTest.java +++ b/pmd-core/src/test/java/net/sourceforge/pmd/util/datasource/internal/PathDataSourceTest.java @@ -4,7 +4,7 @@ package net.sourceforge.pmd.util.datasource.internal; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.FileOutputStream; import java.net.URI; diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/empty.html b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/empty.html new file mode 100644 index 0000000000..498c13d777 --- /dev/null +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/empty.html @@ -0,0 +1,153 @@ + + + + + PMD unknown Report + + + + + + + + +
+ +

PMD unknown Report. Generated on ...

+
+
+

Summary

+ + + + + + + + + + + + + + + + + + + +
FilesTotal +
Priority 1
+
+
Priority 2
+
+
Priority 3
+
+
Priority 4
+
+
Priority 5
+
0000000
+
+

Rules

+ + + + + + +
RuleViolationsSeverity
+
+

Files

+ + + + + + + + + +
File +
5
+
+
4
+
+
3
+
+
2
+
+
1
+
+
+
+ + diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected-error.html b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected-error.html new file mode 100644 index 0000000000..498c13d777 --- /dev/null +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected-error.html @@ -0,0 +1,153 @@ + + + + + PMD unknown Report + + + +
+ + + + +
+ +

PMD unknown Report. Generated on ...

+
+
+

Summary

+ + + + + + + + + + + + + + + + + + + +
FilesTotal +
Priority 1
+
+
Priority 2
+
+
Priority 3
+
+
Priority 4
+
+
Priority 5
+
0000000
+
+

Rules

+ + + + + + +
RuleViolationsSeverity
+
+

Files

+ + + + + + + + + +
File +
5
+
+
4
+
+
3
+
+
2
+
+
1
+
+
+
+ + diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected-multiple.html b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected-multiple.html new file mode 100644 index 0000000000..7bfe920036 --- /dev/null +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected-multiple.html @@ -0,0 +1,217 @@ + + + + + PMD unknown Report + + + +
+ + + + +
+ +

PMD unknown Report. Generated on ...

+
+
+

Summary

+ + + + + + + + + + + + + + + + + + + +
FilesTotal +
Priority 1
+
+
Priority 2
+
+
Priority 3
+
+
Priority 4
+
+
Priority 5
+
1210001
+
+

Rules

+ + + + + + + + + + + + + + + + +
RuleViolationsSeverity
+ [RuleSet] Foo1 +
5
+
+ [RuleSet] Boo1 +
1
+
+
+

Files

+ + + + + + + + + + + + + + + + + +
File +
5
+
+
4
+
+
3
+
+
2
+
+
1
+
+ notAvailable.ext + 10001
+
+
+

File notAvailable.ext

+ + + + + + + + + + + + + + + + +
ViolationError DescriptionLine
+
5
+
+ [RuleSet.Foo] + - + +blah +1 - 1
+
1
+
+ [RuleSet.Boo] + - + +blah +1 - 1
+
Back to top +
+ + diff --git a/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected.html b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected.html new file mode 100644 index 0000000000..862d6005d4 --- /dev/null +++ b/pmd-core/src/test/resources/net/sourceforge/pmd/renderers/xslt/expected.html @@ -0,0 +1,197 @@ + + + + + PMD unknown Report + + + + + + + + +
+ +

PMD unknown Report. Generated on ...

+
+
+

Summary

+ + + + + + + + + + + + + + + + + + + +
FilesTotal +
Priority 1
+
+
Priority 2
+
+
Priority 3
+
+
Priority 4
+
+
Priority 5
+
1100001
+
+

Rules

+ + + + + + + + + + + +
RuleViolationsSeverity
+ [RuleSet] Foo1 +
5
+
+
+

Files

+ + + + + + + + + + + + + + + + + +
File +
5
+
+
4
+
+
3
+
+
2
+
+
1
+
+ notAvailable.ext + 10000
+
+
+

File notAvailable.ext

+ + + + + + + + + + + +
ViolationError DescriptionLine
+
5
+
+ [RuleSet.Foo] + - + +blah +1 - 1
+
Back to top +
+ + diff --git a/pmd-dist/pom.xml b/pmd-dist/pom.xml index ed647fd309..fe3ba1b036 100644 --- a/pmd-dist/pom.xml +++ b/pmd-dist/pom.xml @@ -304,11 +304,6 @@ junit-jupiter test
- - junit - junit - test - org.hamcrest hamcrest diff --git a/pmd-dist/src/test/java/net/sourceforge/pmd/it/BinaryDistributionIT.java b/pmd-dist/src/test/java/net/sourceforge/pmd/it/BinaryDistributionIT.java index dab324f1df..8961324ae8 100644 --- a/pmd-dist/src/test/java/net/sourceforge/pmd/it/BinaryDistributionIT.java +++ b/pmd-dist/src/test/java/net/sourceforge/pmd/it/BinaryDistributionIT.java @@ -35,10 +35,10 @@ class BinaryDistributionIT extends AbstractBinaryDistributionTest { + " java-11, java-12, java-13, java-14, java-15," + System.lineSeparator() + " java-16, java-17, java-18, java-18-preview," + System.lineSeparator() + " java-19, java-19-preview, java-5, java-6, java-7," + System.lineSeparator() - + " java-8, java-9, jsp-, kotlin-1.6, kotlin-1." + System.lineSeparator() - + " 6-rfc+0.1, modelica-, plsql-, pom-, scala-2.10," + System.lineSeparator() - + " scala-2.11, scala-2.12, scala-2.13, swift-, vf-," + System.lineSeparator() - + " vm-, wsdl-, xml-, xsl-"; + + " java-8, java-9, jsp-, kotlin-, kotlin-1.6," + System.lineSeparator() + + " kotlin-1.6-rfc+0.1, modelica-, plsql-, pom-," + System.lineSeparator() + + " scala-2.10, scala-2.11, scala-2.12, scala-2.13," + System.lineSeparator() + + " swift-, vf-, vm-, wsdl-, xml-, xsl-"; } private final String srcDir = new File(".", "src/test/resources/sample-source/java/").getAbsolutePath(); diff --git a/pmd-doc/pom.xml b/pmd-doc/pom.xml index 45b7773695..8c3f7c1dff 100644 --- a/pmd-doc/pom.xml +++ b/pmd-doc/pom.xml @@ -101,11 +101,6 @@ junit-jupiter test - - junit - junit - test - org.hamcrest hamcrest diff --git a/pmd-gherkin/pom.xml b/pmd-gherkin/pom.xml index 7fa212f59b..1497253688 100644 --- a/pmd-gherkin/pom.xml +++ b/pmd-gherkin/pom.xml @@ -45,11 +45,6 @@ junit-jupiter test - - junit - junit - test - net.sourceforge.pmd pmd-test diff --git a/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/LanguageVersionTest.java b/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/LanguageVersionTest.java new file mode 100644 index 0000000000..c1baee0c98 --- /dev/null +++ b/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.html; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(HtmlLanguageModule.NAME, HtmlLanguageModule.TERSE_NAME, "", + getLanguage(HtmlLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/RuleSetFactoryTest.java b/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/RuleSetFactoryTest.java index e9b7776435..7205edf858 100644 --- a/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/RuleSetFactoryTest.java +++ b/pmd-html/src/test/java/net/sourceforge/pmd/lang/html/RuleSetFactoryTest.java @@ -6,6 +6,6 @@ package net.sourceforge.pmd.lang.html; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { // no additional tests yet } diff --git a/pmd-java/pom.xml b/pmd-java/pom.xml index 2fed4e2832..7579a061f3 100644 --- a/pmd-java/pom.xml +++ b/pmd-java/pom.xml @@ -194,21 +194,11 @@ test - - com.github.stefanbirkner - system-rules - test - com.github.stefanbirkner system-lambda test - - org.apache.ant - ant-testutil - test - com.github.oowekyala.treeutils diff --git a/pmd-java/src/main/resources/category/java/codestyle.xml b/pmd-java/src/main/resources/category/java/codestyle.xml index 0fc9c2a18e..08bf3bdad7 100644 --- a/pmd-java/src/main/resources/category/java/codestyle.xml +++ b/pmd-java/src/main/resources/category/java/codestyle.xml @@ -1527,7 +1527,7 @@ public class Foo { minimumLanguageVersion="1.5" message="Unnecessary {0}" class="net.sourceforge.pmd.lang.java.rule.codestyle.UnnecessaryBoxingRule" - externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_bestpractices.html#unnecessaryboxing"> + externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_codestyle.html#unnecessaryboxing"> Reports explicit boxing and unboxing conversions that may safely be removed, either because they would be inserted by the compiler automatically, diff --git a/pmd-java/src/main/resources/category/java/errorprone.xml b/pmd-java/src/main/resources/category/java/errorprone.xml index 326207ef35..aa529d3782 100644 --- a/pmd-java/src/main/resources/category/java/errorprone.xml +++ b/pmd-java/src/main/resources/category/java/errorprone.xml @@ -3033,6 +3033,7 @@ public class Foo { The method name and return type are suspiciously close to hashCode(), which may denote an intention to override the hashCode() method. + 3 @@ -3047,7 +3048,6 @@ to override the hashCode() method. - 3 data() { - Language java = getLanguage(JavaLanguageModule.NAME); - return Arrays.asList(new Object[][] { - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "1.3", - java.getVersion("1.3"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "1.4", - java.getVersion("1.4"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "1.5", - java.getVersion("1.5"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "1.6", - java.getVersion("1.6"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "1.7", - java.getVersion("1.7"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "1.8", - java.getVersion("1.8"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "9", - java.getVersion("9"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "10", - java.getVersion("10"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "11", - java.getVersion("11"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "12", - java.getVersion("12"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "13", - java.getVersion("13"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "14", - java.getVersion("14"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "15", - java.getVersion("15"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "16", - java.getVersion("16"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "16-preview", - java.getVersion("16-preview"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "17", - java.getVersion("17"), }, - { JavaLanguageModule.NAME, JavaLanguageModule.TERSE_NAME, "17-preview", - java.getVersion("17-preview"), }, - - // this one won't be found: case sensitive! - { "JAVA", "JAVA", "1.7", null, }, - }); - } -} diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java index a9b9dbabaa..b4d8e5a12c 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java @@ -4,45 +4,38 @@ package net.sourceforge.pmd.ant; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import java.io.UnsupportedEncodingException; -import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Locale; -import org.junit.AfterClass; -import org.junit.Rule; -import org.junit.Test; -import org.junit.contrib.java.lang.system.RestoreSystemProperties; -import org.junit.rules.ExternalResource; -import org.junit.rules.TestRule; +import org.junit.jupiter.api.Test; -import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration; import net.sourceforge.pmd.internal.util.IOUtil; -public class PMDTaskTest extends AbstractAntTestHelper { +class PMDTaskTest extends AbstractAntTestHelper { - public PMDTaskTest() { - super.antTestScriptFilename = "pmdtasktest.xml"; + PMDTaskTest() { + antTestScriptFilename = "pmdtasktest.xml"; } @Test - public void testNoFormattersValidation() { + void testNoFormattersValidation() { executeTarget("testNoFormattersValidation"); assertOutputContaining("Violation from test-rset-1.xml"); } @Test - public void testNestedRuleset() { + void testNestedRuleset() { executeTarget("testNestedRuleset"); assertOutputContaining("Violation from test-rset-1.xml"); assertOutputContaining("Violation from test-rset-2.xml"); } @Test - public void testFormatterWithProperties() { + void testFormatterWithProperties() { executeTarget("testFormatterWithProperties"); assertOutputContaining("Violation from test-rset-1.xml"); assertOutputContaining("link_prefix"); @@ -50,95 +43,55 @@ public class PMDTaskTest extends AbstractAntTestHelper { } @Test - public void testAbstractNames() { + void testAbstractNames() { executeTarget("testAbstractNames"); assertOutputContaining("Violation from test-rset-1.xml"); assertOutputContaining("Violation from test-rset-2.xml"); } @Test - public void testAbstractNamesInNestedRuleset() { + void testAbstractNamesInNestedRuleset() { executeTarget("testAbstractNamesInNestedRuleset"); assertOutputContaining("Violation from test-rset-1.xml"); assertOutputContaining("Violation from test-rset-2.xml"); } @Test - public void testCommaInRulesetfiles() { + void testCommaInRulesetfiles() { executeTarget("testCommaInRulesetfiles"); assertOutputContaining("Violation from test-rset-1.xml"); assertOutputContaining("Violation from test-rset-2.xml"); } @Test - public void testRelativeRulesets() { + void testRelativeRulesets() { executeTarget("testRelativeRulesets"); assertOutputContaining("Violation from test-rset-1.xml"); } @Test - public void testRelativeRulesetsInRulesetfiles() { + void testRelativeRulesetsInRulesetfiles() { executeTarget("testRelativeRulesetsInRulesetfiles"); assertOutputContaining("Violation from test-rset-1.xml"); } @Test - public void testExplicitRuleInRuleSet() { + void testExplicitRuleInRuleSet() { executeTarget("testExplicitRuleInRuleSet"); assertOutputContaining("Violation from test-rset-1.xml"); } @Test - public void testClasspath() { + void testClasspath() { executeTarget("testClasspath"); } - // restoring system properties: PMDTask might change logging properties - // See Slf4jSimpleConfigurationForAnt and resetLogging - @Rule - public final TestRule restoreSystemProperties = new RestoreSystemProperties(); - - @AfterClass - public static void resetLogging() { - Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null); - } - - @Rule - public final TestRule restoreLocale = new ExternalResource() { - private Locale originalLocale; - - @Override - protected void before() throws Throwable { - originalLocale = Locale.getDefault(); - } - - @Override - protected void after() { - Locale.setDefault(originalLocale); - } - }; - private static void setDefaultCharset(String charsetName) { System.setProperty("file.encoding", charsetName); } - @Rule - public final TestRule restoreDefaultCharset = new ExternalResource() { - private Charset defaultCharset; - - @Override - protected void before() throws Throwable { - defaultCharset = Charset.defaultCharset(); - } - - @Override - protected void after() { - setDefaultCharset(defaultCharset.name()); - } - }; - @Test - public void testFormatterEncodingWithXML() throws Exception { + void testFormatterEncodingWithXML() throws Exception { Locale.setDefault(Locale.FRENCH); setDefaultCharset("cp1252"); @@ -147,52 +100,37 @@ public class PMDTaskTest extends AbstractAntTestHelper { assertTrue(report.contains("someVariableWithÜmlaut")); } - private static String convert(String report) { - // reinterpret output as cp1252 - ant BuildFileRule can only unicode - StringBuilder sb = new StringBuilder(report.length()); - for (int i = 0; i < report.length(); i++) { - char c = report.charAt(i); - if (c > 0x7f) { - sb.append((char) (c & 0xff)); - } else { - sb.append(c); - } - } - return sb.toString(); - } - @Test - public void testFormatterEncodingWithXMLConsole() throws UnsupportedEncodingException { + void testFormatterEncodingWithXMLConsole() throws UnsupportedEncodingException { setDefaultCharset("cp1252"); - executeTarget("testFormatterEncodingWithXMLConsole"); - String report = convert(buildRule.getOutput()); + String report = executeTarget("testFormatterEncodingWithXMLConsole"); assertTrue(report.startsWith("")); assertTrue(report.contains("someVariableWithÜmlaut")); } @Test - public void testMissingCacheLocation() { + void testMissingCacheLocation() { executeTarget("testMissingCacheLocation"); assertOutputContaining("Violation from test-rset-1.xml"); - assertContains(buildRule.getLog(), "This analysis could be faster"); + assertContains(getLog(), "This analysis could be faster"); } @Test - public void testAnalysisCache() { + void testAnalysisCache() { executeTarget("testAnalysisCache"); assertOutputContaining("Violation from test-rset-1.xml"); - assertDoesntContain(buildRule.getLog(), "This analysis could be faster"); + assertDoesntContain(getLog(), "This analysis could be faster"); assertTrue(currentTempFile().exists()); } @Test - public void testDisableIncrementalAnalysis() { + void testDisableIncrementalAnalysis() { executeTarget("testDisableIncrementalAnalysis"); assertOutputContaining("Violation from test-rset-1.xml"); - assertDoesntContain(buildRule.getLog(), "This analysis could be faster"); + assertDoesntContain(getLog(), "This analysis could be faster"); assertFalse(currentTempFile().exists()); } diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/LanguageVersionTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/LanguageVersionTest.java new file mode 100644 index 0000000000..47ccd49bdf --- /dev/null +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/LanguageVersionTest.java @@ -0,0 +1,42 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.java; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; +import net.sourceforge.pmd.lang.Language; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + final String name = JavaLanguageModule.NAME; + final String terseName = JavaLanguageModule.TERSE_NAME; + final Language java = getLanguage(name); + + return Arrays.asList( + new TestDescriptor(name, terseName, "1.3", java.getVersion("1.3")), + new TestDescriptor(name, terseName, "1.4", java.getVersion("1.4")), + new TestDescriptor(name, terseName, "1.5", java.getVersion("1.5")), + new TestDescriptor(name, terseName, "1.6", java.getVersion("1.6")), + new TestDescriptor(name, terseName, "1.7", java.getVersion("1.7")), + new TestDescriptor(name, terseName, "1.8", java.getVersion("1.8")), + new TestDescriptor(name, terseName, "9", java.getVersion("9")), + new TestDescriptor(name, terseName, "10", java.getVersion("10")), + new TestDescriptor(name, terseName, "11", java.getVersion("11")), + new TestDescriptor(name, terseName, "12", java.getVersion("12")), + new TestDescriptor(name, terseName, "13", java.getVersion("13")), + new TestDescriptor(name, terseName, "14", java.getVersion("14")), + new TestDescriptor(name, terseName, "15", java.getVersion("15")), + new TestDescriptor(name, terseName, "16", java.getVersion("16")), + new TestDescriptor(name, terseName, "16-preview", java.getVersion("16-preview")), + new TestDescriptor(name, terseName, "17", java.getVersion("17")), + new TestDescriptor(name, terseName, "17-preview", java.getVersion("17-preview")), + + // this one won't be found: case sensitive! + new TestDescriptor("JAVA", "JAVA", "1.7", null)); + } +} diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/PMD5RulesetTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/PMD5RulesetTest.java index 653090e171..9334683d33 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/PMD5RulesetTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/PMD5RulesetTest.java @@ -15,7 +15,7 @@ import net.sourceforge.pmd.RuleSetLoader; class PMD5RulesetTest { @Test - public void loadRuleset() { + void loadRuleset() { RuleSet ruleset = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/lang/java/pmd5ruleset.xml"); assertNotNull(ruleset); assertNull(ruleset.getRuleByName("GuardLogStatementJavaUtil")); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/RuleSetFactoryTest.java similarity index 71% rename from pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java rename to pmd-java/src/test/java/net/sourceforge/pmd/lang/java/RuleSetFactoryTest.java index be9261d5d8..4efb26bb28 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/RuleSetFactoryTest.java @@ -2,19 +2,24 @@ * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ -package net.sourceforge.pmd; +package net.sourceforge.pmd.lang.java; -import static org.junit.Assert.assertNull; +import static org.junit.jupiter.api.Assertions.assertNull; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; +import net.sourceforge.pmd.Rule; +import net.sourceforge.pmd.RuleSet; +import net.sourceforge.pmd.RuleSetLoader; /** * Test java's rulesets */ -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { @Test - public void testExclusionOfUselessParantheses() { + void testExclusionOfUselessParantheses() { RuleSet ruleset = new RuleSetLoader().loadFromString("", "\n" + " java5.parseResource("jdk14_enum.java")); } @@ -89,17 +89,17 @@ class JDKVersionTest extends BaseJavaTreeDumpTest { } @Test - public void testGenericCtorCalls() { + void testGenericCtorCalls() { java5.parseResource("java5/generic_ctors.java"); } @Test - public void testGenericSuperCtorCalls() { + void testGenericSuperCtorCalls() { java5.parseResource("java5/generic_super_ctor.java"); } @Test - public void testAnnotArrayInitializer() { + void testAnnotArrayInitializer() { java5.parseResource("java5/annotation_array_init.java"); } @@ -237,7 +237,7 @@ class JDKVersionTest extends BaseJavaTreeDumpTest { } @Test - public final void testTypeAnnotations() { + void testTypeAnnotations() { java8.parseResource("java8/type_annotations.java"); } diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JavaCommentTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JavaCommentTest.java index faee16b9c6..97f929ac59 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JavaCommentTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/ast/JavaCommentTest.java @@ -21,10 +21,10 @@ import net.sourceforge.pmd.lang.java.BaseParserTest; /** * @author Clément Fournier */ -public class JavaCommentTest extends BaseParserTest { +class JavaCommentTest extends BaseParserTest { @Test - public void testFilteredLines() { + void testFilteredLines() { JavaComment comment = parseComment( "/**\n" + " * @author Clément Fournier\n" @@ -37,7 +37,7 @@ public class JavaCommentTest extends BaseParserTest { } @Test - public void testFilteredLinesKeepBlankLines() { + void testFilteredLinesKeepBlankLines() { JavaComment comment = parseComment( "/**\n" + " * @author Clément Fournier\n" @@ -56,7 +56,7 @@ public class JavaCommentTest extends BaseParserTest { @Test - public void getLeadingComments() { + void getLeadingComments() { ASTCompilationUnit parsed = java.parse("/** a */ class Fooo { /** b */ int field; }"); List docCommentOwners = parsed.descendants(JavadocCommentOwner.class).toList(); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/AnnotationReflectionTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/AnnotationReflectionTest.java index 52f960132a..df0f40d2ed 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/AnnotationReflectionTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/AnnotationReflectionTest.java @@ -44,15 +44,11 @@ import net.sourceforge.pmd.lang.java.symbols.testdata.MethodAnnotation; import net.sourceforge.pmd.lang.java.symbols.testdata.ParameterAnnotation; import net.sourceforge.pmd.lang.java.symbols.testdata.SomeClass; -public class AnnotationReflectionTest { - - public AnnotationReflectionTest() { - } - +class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testReflectionOfClassMethods(SymImplementation impl) { + void testReflectionOfClassMethods(SymImplementation impl) { Class actualClass = SomeClass.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -62,7 +58,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testReflectionOfAnnotDefaults(SymImplementation impl) { + void testReflectionOfAnnotDefaults(SymImplementation impl) { Class actualClass = AnnotWithDefaults.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -72,7 +68,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testAnnotUseThatUsesDefaults(SymImplementation impl) { + void testAnnotUseThatUsesDefaults(SymImplementation impl) { // note that as the annotation has retention class, we can't use reflection to check /* @@ -100,7 +96,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testAnnotOnAnnot(SymImplementation impl) { + void testAnnotOnAnnot(SymImplementation impl) { // This only checks for Target.ANNOTATION_TYPE annotations Class actualClass = AnnotWithDefaults.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -111,7 +107,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testAnnotOnParameter(SymImplementation impl) { + void testAnnotOnParameter(SymImplementation impl) { // This only checks Target.PARAMETER annotations, do not confuse with TYPE_PARAMETER / TYPE_USE Class actualClass = SomeClass.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -125,7 +121,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testAnnotOnField(SymImplementation impl) { + void testAnnotOnField(SymImplementation impl) { // This only checks Target.FIELD annotations, do not confuse with TYPE_USE annotations Class actualClass = SomeClass.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -136,7 +132,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testAnnotOnMethod(SymImplementation impl) { + void testAnnotOnMethod(SymImplementation impl) { // This only checks Target.METHOD annotations, do not confuse with TYPE_USE on return types Class actualClass = SomeClass.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -148,7 +144,7 @@ public class AnnotationReflectionTest { @ParameterizedTest @EnumSource - public void testAnnotOnConstructor(SymImplementation impl) { + void testAnnotOnConstructor(SymImplementation impl) { // This only checks Target.CONSTRUCTOR annotations, do not confuse with TYPE_USE on return types Class actualClass = SomeClass.class; JClassSymbol sym = impl.getSymbol(actualClass); @@ -158,7 +154,7 @@ public class AnnotationReflectionTest { } @Test - public void testAnnotOnLocalVar() { + void testAnnotOnLocalVar() { // This only checks Target.LOCAL_VAR annotations, do not confuse with TYPE_USE on return types JClassSymbol sym = SymImplementation.AST.getSymbol(SomeClass.class); @@ -172,7 +168,7 @@ public class AnnotationReflectionTest { } @Test - public void testAnnotWithInvalidType() { + void testAnnotWithInvalidType() { @NonNull ASTVariableDeclaratorId field = JavaParsingHelper.DEFAULT.parse( "@interface A {}\n" diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueTest.java index 855cfeafb3..4b1e3a0072 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/SymbolicValueTest.java @@ -4,51 +4,54 @@ package net.sourceforge.pmd.lang.java.symbols; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + import java.util.Arrays; -import org.junit.Assert; -import org.junit.Test; +import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.java.JavaParsingHelper; import net.sourceforge.pmd.lang.java.symbols.SymbolicValue.SymArray; import net.sourceforge.pmd.lang.java.types.TypeSystem; -public class SymbolicValueTest { +class SymbolicValueTest { static final TypeSystem TS = JavaParsingHelper.TEST_TYPE_SYSTEM; - + @Test - public void testSymValueEquality() { - Assert.assertEquals("Array of strings", - symValueOf(new String[] {"ddd", "eee"}), - ofArray(symValueOf("ddd"), symValueOf("eee"))); + void testSymValueEquality() { + assertEquals(symValueOf(new String[] {"ddd", "eee"}), + ofArray(symValueOf("ddd"), symValueOf("eee")), + "Array of strings"); - Assert.assertEquals("Array of booleans", - symValueOf(new boolean[] {true}), - symValueOf(new boolean[] {true})); + assertEquals(symValueOf(new boolean[] {true}), + symValueOf(new boolean[] {true}), + "Array of booleans"); - Assert.assertNotEquals("Array of booleans", - symValueOf(new boolean[] {true}), - symValueOf(new boolean[] {false})); + assertNotEquals(symValueOf(new boolean[] {true}), + symValueOf(new boolean[] {false}), + "Array of booleans"); - Assert.assertTrue("valueEquals for int[]", - symValueOf(new int[] {10, 11}).valueEquals(new int[] {10, 11})); + assertTrue(symValueOf(new int[] {10, 11}).valueEquals(new int[] {10, 11}), + "valueEquals for int[]"); - Assert.assertTrue("valueEquals for boolean[]", - symValueOf(new boolean[] {false}).valueEquals(new boolean[] {false})); + assertTrue(symValueOf(new boolean[] {false}).valueEquals(new boolean[] {false}), + "valueEquals for boolean[]"); - Assert.assertFalse("valueEquals for int[]", - symValueOf(new int[] {10, 11}).valueEquals(new int[] {10})); + assertFalse(symValueOf(new int[] {10, 11}).valueEquals(new int[] {10}), + "valueEquals for int[]"); - Assert.assertFalse("valueEquals for double[] 2", - symValueOf(new int[] {10, 11}).valueEquals(new double[] {10, 11})); + assertFalse(symValueOf(new int[] {10, 11}).valueEquals(new double[] {10, 11}), + "valueEquals for double[] 2"); - Assert.assertFalse("valueEquals for empty arrays", - symValueOf(new int[] {}).valueEquals(new double[] {})); - - Assert.assertTrue("valueEquals for empty arrays", - symValueOf(new double[] {}).valueEquals(new double[] {})); + assertFalse(symValueOf(new int[] {}).valueEquals(new double[] {}), + "valueEquals for empty arrays"); + assertTrue(symValueOf(new double[] {}).valueEquals(new double[] {}), + "valueEquals for empty arrays"); } // test only diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/SymImplementation.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/SymImplementation.java index 2b9428a36a..a9418a1e41 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/SymImplementation.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/SymImplementation.java @@ -4,6 +4,9 @@ package net.sourceforge.pmd.lang.java.symbols.internal; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; @@ -15,7 +18,6 @@ import java.util.Set; import java.util.stream.Collectors; import org.checkerframework.checker.nullness.qual.NonNull; -import org.junit.Assert; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; @@ -78,7 +80,7 @@ public enum SymImplementation { public void assertAllFieldsMatch(Class actualClass, JClassSymbol sym) { List fs = sym.getDeclaredFields(); Set actualFields = Arrays.stream(actualClass.getDeclaredFields()).filter(f -> !f.isSynthetic()).collect(Collectors.toSet()); - Assert.assertEquals(actualFields.size(), fs.size()); + assertEquals(actualFields.size(), fs.size()); for (final Field f : actualFields) { JFieldSymbol fSym = fs.stream().filter(it -> it.getSimpleName().equals(f.getName())) @@ -86,9 +88,9 @@ public enum SymImplementation { // Type matches final JTypeMirror expectedType = typeMirrorOf(sym.getTypeSystem(), f.getType()); - Assert.assertEquals(expectedType, fSym.getTypeMirror(Substitution.EMPTY)); + assertEquals(expectedType, fSym.getTypeMirror(Substitution.EMPTY)); - Assert.assertEquals(f.getModifiers(), fSym.getModifiers()); + assertEquals(f.getModifiers(), fSym.getModifiers()); } } @@ -99,7 +101,7 @@ public enum SymImplementation { public void assertAllMethodsMatch(Class actualClass, JClassSymbol sym) { List ms = sym.getDeclaredMethods(); Set actualMethods = Arrays.stream(actualClass.getDeclaredMethods()).filter(m -> !m.isSynthetic()).collect(Collectors.toSet()); - Assert.assertEquals(actualMethods.size(), ms.size()); + assertEquals(actualMethods.size(), ms.size()); for (final Method m : actualMethods) { JMethodSymbol mSym = ms.stream().filter(it -> it.getSimpleName().equals(m.getName())) @@ -110,7 +112,7 @@ public enum SymImplementation { } public void assertMethodMatch(Method m, JMethodSymbol mSym) { - Assert.assertEquals(m.getParameterCount(), mSym.getArity()); + assertEquals(m.getParameterCount(), mSym.getArity()); final Parameter[] parameters = m.getParameters(); List formals = mSym.getFormalParameters(); @@ -120,27 +122,27 @@ public enum SymImplementation { } // Defaults should match too (even if not an annotation method, both should be null) - Assert.assertEquals(SymbolicValue.of(mSym.getTypeSystem(), m.getDefaultValue()), mSym.getDefaultAnnotationValue()); + assertEquals(SymbolicValue.of(mSym.getTypeSystem(), m.getDefaultValue()), mSym.getDefaultAnnotationValue()); } private void assertParameterMatch(Parameter p, JFormalParamSymbol pSym) { if (supportsDebugSymbols()) { if (p.isNamePresent()) { - Assert.assertEquals(p.getName(), pSym.getSimpleName()); - Assert.assertEquals(Modifier.isFinal(p.getModifiers()), pSym.isFinal()); + assertEquals(p.getName(), pSym.getSimpleName()); + assertEquals(Modifier.isFinal(p.getModifiers()), pSym.isFinal()); } else { System.out.println("WARN: test classes were not compiled with -parameters, parameters not fully checked"); } } else { // note that this asserts, that the param names are unavailable - Assert.assertEquals("", pSym.getSimpleName()); - Assert.assertFalse(pSym.isFinal()); + assertEquals("", pSym.getSimpleName()); + assertFalse(pSym.isFinal()); } // Ensure type matches final JTypeMirror expectedType = typeMirrorOf(pSym.getTypeSystem(), p.getType()); - Assert.assertEquals(expectedType, pSym.getTypeMirror(Substitution.EMPTY)); + assertEquals(expectedType, pSym.getTypeMirror(Substitution.EMPTY)); } } diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionOnMethodsTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionOnMethodsTest.java index e43a30f17e..d66b719c0f 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionOnMethodsTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionOnMethodsTest.java @@ -25,12 +25,12 @@ import net.sourceforge.pmd.lang.java.types.JMethodSig; /** * */ -public class TypeAnnotReflectionOnMethodsTest { +class TypeAnnotReflectionOnMethodsTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnParameter(SymImplementation impl) { + void testTypeAnnotOnParameter(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class); /* @@ -54,7 +54,7 @@ public class TypeAnnotReflectionOnMethodsTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnReturn(SymImplementation impl) { + void testTypeAnnotOnReturn(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class); /* @@ -76,7 +76,7 @@ public class TypeAnnotReflectionOnMethodsTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnThrows(SymImplementation impl) { + void testTypeAnnotOnThrows(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class); /* @@ -92,7 +92,7 @@ public class TypeAnnotReflectionOnMethodsTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnTParam(SymImplementation impl) { + void testTypeAnnotOnTParam(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class); /* @@ -121,7 +121,7 @@ public class TypeAnnotReflectionOnMethodsTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnTParamBound(SymImplementation impl) { + void testTypeAnnotOnTParamBound(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class); /* @@ -157,7 +157,7 @@ public class TypeAnnotReflectionOnMethodsTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnReceiver(SymImplementation impl) { + void testTypeAnnotOnReceiver(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsOnMethods.class); /* diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionTest.java index a65b2b145f..863f719caa 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/internal/TypeAnnotReflectionTest.java @@ -28,12 +28,12 @@ import net.sourceforge.pmd.lang.java.types.JWildcardType; /** * */ -public class TypeAnnotReflectionTest { +class TypeAnnotReflectionTest { @ParameterizedTest @EnumSource - public void testTypeAnnotsOnFields(SymImplementation impl) { + void testTypeAnnotsOnFields(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class); @@ -55,7 +55,7 @@ public class TypeAnnotReflectionTest { @ParameterizedTest @EnumSource - public void testArrayTypeAnnotsOnFields(SymImplementation impl) { + void testArrayTypeAnnotsOnFields(SymImplementation impl) { /* @@ -105,7 +105,7 @@ public class TypeAnnotReflectionTest { @ParameterizedTest @EnumSource - public void testInnerTypeAnnotsOnFields(SymImplementation impl) { + void testInnerTypeAnnotsOnFields(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class); @@ -152,7 +152,7 @@ public class TypeAnnotReflectionTest { @ParameterizedTest @EnumSource - public void testInnerTypeAnnotsWithGenerics(SymImplementation impl) { + void testInnerTypeAnnotsWithGenerics(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class); @@ -205,7 +205,7 @@ public class TypeAnnotReflectionTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnMultipleGenericsAndInner(SymImplementation impl) { + void testTypeAnnotOnMultipleGenericsAndInner(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class); @@ -228,7 +228,7 @@ public class TypeAnnotReflectionTest { @ParameterizedTest @EnumSource - public void testTypeAnnotOnWildcards(SymImplementation impl) { + void testTypeAnnotOnWildcards(SymImplementation impl) { JClassType sym = impl.getDeclaration(ClassWithTypeAnnotationsInside.class); diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/table/internal/AbruptCompletionTests.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/table/internal/AbruptCompletionTests.java index 23a27129f2..615e2365a4 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/table/internal/AbruptCompletionTests.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/table/internal/AbruptCompletionTests.java @@ -86,7 +86,7 @@ class AbruptCompletionTests extends BaseParserTest { @Test - public void testWhileStmt() { + void testWhileStmt() { assertAll( canCompleteNormally("while(foo) { return; }"), canCompleteNormally("while(foo) { break; }"), diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ClassWithTypeAnnotationsInside.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ClassWithTypeAnnotationsInside.java index 1887b5dd2d..ba80fe5006 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ClassWithTypeAnnotationsInside.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/symbols/testdata/ClassWithTypeAnnotationsInside.java @@ -8,10 +8,8 @@ import java.lang.annotation.ElementType; import java.lang.annotation.Target; import java.util.List; -import net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotReflectionTest; - /** - * See {@link TypeAnnotReflectionTest}. + * See {@link net.sourceforge.pmd.lang.java.symbols.internal.TypeAnnotReflectionTest}. * * @author Clément Fournier */ diff --git a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/InvocationMatcherTest.java b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/InvocationMatcherTest.java index d9a949cf8e..e6cf124ab9 100644 --- a/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/InvocationMatcherTest.java +++ b/pmd-java/src/test/java/net/sourceforge/pmd/lang/java/types/InvocationMatcherTest.java @@ -5,12 +5,12 @@ package net.sourceforge.pmd.lang.java.types; import static net.sourceforge.pmd.lang.java.types.InvocationMatcher.parse; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.equalTo; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.hamcrest.MatcherAssert; import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.java.BaseParserTest; @@ -81,10 +81,9 @@ class InvocationMatcherTest extends BaseParserTest { parse("_#_(int,int)"); // does not fail IllegalArgumentException e = assertThrows(IllegalArgumentException.class, () -> parse("_#_(int, int)")); - MatcherAssert.assertThat(e.getMessage(), equalTo("Expected type at index 8:\n" - + " \"_#_(int, int)\"\n" - + " ^\n")); - + assertThat(e.getMessage(), equalTo("Expected type at index 8:\n" + + " \"_#_(int, int)\"\n" + + " ^\n")); } private void assertMatch(InvocationNode call, String sig) { diff --git a/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/symbols/internal/JClassSymbolTest.java b/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/symbols/internal/JClassSymbolTest.java index 5d3f15e829..c2d23e9cb5 100644 --- a/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/symbols/internal/JClassSymbolTest.java +++ b/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/symbols/internal/JClassSymbolTest.java @@ -21,7 +21,7 @@ import net.sourceforge.pmd.lang.java.symbols.testdata.TypeAnnotation; * * @author Clément Fournier */ -public class JClassSymbolTest { +class JClassSymbolTest { @EnumSource @ParameterizedTest diff --git a/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/types/TypesFromReflectionTest.kt b/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/types/TypesFromReflectionTest.kt index 1afc8ec8fc..0e8c5a6cc3 100644 --- a/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/types/TypesFromReflectionTest.kt +++ b/pmd-java/src/test/kotlin/net/sourceforge/pmd/lang/java/types/TypesFromReflectionTest.kt @@ -9,7 +9,7 @@ import io.kotest.matchers.shouldBe import net.sourceforge.pmd.lang.java.JavaParsingHelper import net.sourceforge.pmd.lang.java.symbols.JClassSymbol import org.apache.commons.lang3.reflect.TypeLiteral -import org.junit.Assert +import org.junit.jupiter.api.Assertions.* import java.lang.NullPointerException class TypesFromReflectionTest : FunSpec({ @@ -71,21 +71,21 @@ class TypesFromReflectionTest : FunSpec({ fun assertReflects(expected: Class<*>?, actual: JClassSymbol?) { if (expected == null) { - Assert.assertNull(actual) + assertNull(actual) return } - Assert.assertNotNull("Expected $expected", actual) - Assert.assertEquals("Annot", expected.isAnnotation, actual!!.isAnnotation) - Assert.assertEquals("Array", expected.isArray, actual.isArray) - Assert.assertEquals("Modifiers", expected.modifiers.toLong(), actual.modifiers.toLong()) + assertNotNull(actual, "Expected $expected") + assertEquals(expected.isAnnotation, actual!!.isAnnotation, "Annot") + assertEquals(expected.isArray, actual.isArray, "Array") + assertEquals(expected.modifiers.toLong(), actual.modifiers.toLong(), "Modifiers") if (actual.isArray) { assertReflects(expected.componentType, actual.arrayComponent as JClassSymbol?) // don't test names, the spec of Class::getName and JClassSymbol::getBinaryName // differ for arrays return } - Assert.assertEquals("Binary name", expected.name, actual.binaryName) - Assert.assertEquals("Canonical name", expected.canonicalName, actual.canonicalName) + assertEquals(expected.name, actual.binaryName, "Binary name") + assertEquals(expected.canonicalName, actual.canonicalName, "Canonical name") assertReflects(expected.enclosingClass, actual.enclosingClass) } diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index 5786dc0e26..0000000000 --- a/pmd-javascript/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,27 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.ecmascript.EcmascriptLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { { EcmascriptLanguageModule.NAME, EcmascriptLanguageModule.TERSE_NAME, - "ES6", - getLanguage(EcmascriptLanguageModule.NAME).getDefaultVersion(), }, }); - } -} diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java deleted file mode 100644 index ddcf7a7ab8..0000000000 --- a/pmd-javascript/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -/** - * Test javascript's rulesets - */ -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - // no additional tests yet -} diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java index 294d3f1cf8..79bc52e1f5 100644 --- a/pmd-javascript/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java +++ b/pmd-javascript/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java @@ -4,16 +4,16 @@ package net.sourceforge.pmd.ant; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PMDTaskTest extends AbstractAntTestHelper { +class PMDTaskTest extends AbstractAntTestHelper { - public PMDTaskTest() { + PMDTaskTest() { super.antTestScriptFilename = "pmdtasktest.xml"; } @Test - public void testEcmascript() { + void testEcmascript() { executeTarget("testEcmascript"); assertOutputContaining("A 'return', 'break', 'continue', or 'throw' statement should be the last in a block."); assertOutputContaining("Avoid using global variables"); diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/LanguageVersionTest.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/LanguageVersionTest.java new file mode 100644 index 0000000000..5df250aff5 --- /dev/null +++ b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/LanguageVersionTest.java @@ -0,0 +1,19 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.ecmascript; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList( + new TestDescriptor(EcmascriptLanguageModule.NAME, EcmascriptLanguageModule.TERSE_NAME, "ES6", + getLanguage(EcmascriptLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/RuleSetFactoryTest.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/RuleSetFactoryTest.java new file mode 100644 index 0000000000..551b583deb --- /dev/null +++ b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/RuleSetFactoryTest.java @@ -0,0 +1,14 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.ecmascript; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; + +/** + * Test javascript's rulesets + */ +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional tests yet +} diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/ASTFunctionNodeTest.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/ASTFunctionNodeTest.java index 0fde30852f..a1ef0ed00b 100644 --- a/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/ASTFunctionNodeTest.java +++ b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/ASTFunctionNodeTest.java @@ -12,7 +12,7 @@ import org.junit.jupiter.api.Test; class ASTFunctionNodeTest extends EcmascriptParserTestBase { @Test - public void testGetBody() { + void testGetBody() { ASTAstRoot node = js.parse("function foo() { var a = 'a'; }"); ASTFunctionNode fn = node.getFirstDescendantOfType(ASTFunctionNode.class); assertFalse(fn.isClosure()); diff --git a/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/DefaultLocale.java b/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/DefaultLocale.java deleted file mode 100644 index e0cb18f4a5..0000000000 --- a/pmd-javascript/src/test/java/net/sourceforge/pmd/lang/ecmascript/ast/DefaultLocale.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.lang.ecmascript.ast; - -import java.util.Locale; - -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.Statement; - -/** - * A JUnit rule to change the system locale during a test. - */ -public class DefaultLocale implements TestRule { - - private boolean statementIsExecuting = false; - private Locale loc = Locale.getDefault(); - - /** Set the locale value (overwrites previously set value). */ - public void set(Locale locale) { - if (statementIsExecuting) { - Locale.setDefault(locale); - } else { - this.loc = locale; - } - } - - @Override - public Statement apply(Statement base, Description description) { - return new EnvironmentVariablesStatement(base); - } - - private class EnvironmentVariablesStatement extends Statement { - - final Statement baseStatement; - - EnvironmentVariablesStatement(Statement baseStatement) { - this.baseStatement = baseStatement; - } - - @Override - public void evaluate() throws Throwable { - Locale prev = Locale.getDefault(); - statementIsExecuting = true; - try { - Locale.setDefault(loc); - baseStatement.evaluate(); - } finally { - statementIsExecuting = false; - Locale.setDefault(prev); - } - } - } -} diff --git a/pmd-jsp/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-jsp/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index d146252127..0000000000 --- a/pmd-jsp/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.jsp.JspLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { { JspLanguageModule.NAME, JspLanguageModule.TERSE_NAME, "", - getLanguage(JspLanguageModule.NAME).getDefaultVersion(), }, }); - } -} diff --git a/pmd-jsp/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-jsp/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java deleted file mode 100644 index 950a9fca4a..0000000000 --- a/pmd-jsp/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -/** - * Test jsp's rulesets - */ -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - // no additional tests yet -} diff --git a/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/LanguageVersionTest.java b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/LanguageVersionTest.java new file mode 100644 index 0000000000..4707c22101 --- /dev/null +++ b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.jsp; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(JspLanguageModule.NAME, JspLanguageModule.TERSE_NAME, "", + getLanguage(JspLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/RuleSetFactoryTest.java b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/RuleSetFactoryTest.java new file mode 100644 index 0000000000..80b8ecbf7a --- /dev/null +++ b/pmd-jsp/src/test/java/net/sourceforge/pmd/lang/jsp/RuleSetFactoryTest.java @@ -0,0 +1,14 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.jsp; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; + +/** + * Test jsp's rulesets + */ +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional tests yet +} diff --git a/pmd-kotlin/src/main/resources/category/kotlin/bestpractices.xml b/pmd-kotlin/src/main/resources/category/kotlin/bestpractices.xml index 30a88668f0..e52f8db847 100644 --- a/pmd-kotlin/src/main/resources/category/kotlin/bestpractices.xml +++ b/pmd-kotlin/src/main/resources/category/kotlin/bestpractices.xml @@ -14,7 +14,7 @@ Rules which enforce generally accepted best practices. language="kotlin" message="Function names should have non-cryptic and clear names." class="net.sourceforge.pmd.lang.rule.XPathRule" - externalInfoUrl="${pmd.website.baseurl}/pmd_rules_kotlin_bestpractices.html#functionametooshort"> + externalInfoUrl="${pmd.website.baseurl}/pmd_rules_kotlin_bestpractices.html#functionnametooshort"> Function names should be easy to understand and describe the intention. Makes developers happy. diff --git a/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/LanguageVersionTest.java b/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/LanguageVersionTest.java new file mode 100644 index 0000000000..fbc7248a41 --- /dev/null +++ b/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/LanguageVersionTest.java @@ -0,0 +1,21 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.kotlin; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList( + new TestDescriptor(KotlinLanguageModule.NAME, KotlinLanguageModule.TERSE_NAME, "", + getLanguage(KotlinLanguageModule.NAME).getDefaultVersion()), + new TestDescriptor(KotlinLanguageModule.NAME, KotlinLanguageModule.TERSE_NAME, "1.6", + getLanguage(KotlinLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/RuleSetFactoryTest.java b/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/RuleSetFactoryTest.java index ab10c8550b..9655674f8a 100644 --- a/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/RuleSetFactoryTest.java +++ b/pmd-kotlin/src/test/java/net/sourceforge/pmd/lang/kotlin/RuleSetFactoryTest.java @@ -6,5 +6,6 @@ package net.sourceforge.pmd.lang.kotlin; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional tests yet } diff --git a/pmd-lang-test/pom.xml b/pmd-lang-test/pom.xml index aacab56128..79aba91e81 100644 --- a/pmd-lang-test/pom.xml +++ b/pmd-lang-test/pom.xml @@ -147,11 +147,6 @@ hamcrest compile - - junit - junit - compile - org.jetbrains.kotlin diff --git a/pmd-lua/src/test/java/net/sourceforge/pmd/cpd/LuaTokenizerTest.java b/pmd-lua/src/test/java/net/sourceforge/pmd/cpd/LuaTokenizerTest.java index a1c845b543..5062ebe242 100644 --- a/pmd-lua/src/test/java/net/sourceforge/pmd/cpd/LuaTokenizerTest.java +++ b/pmd-lua/src/test/java/net/sourceforge/pmd/cpd/LuaTokenizerTest.java @@ -41,12 +41,12 @@ class LuaTokenizerTest extends CpdTextComparisonTest { } @Test - public void testLuauTypes() { + void testLuauTypes() { doTest("luauTypes"); } @Test - public void testComment() { + void testComment() { doTest("comment"); } } diff --git a/pmd-matlab/src/test/java/net/sourceforge/pmd/cpd/MatlabTokenizerTest.java b/pmd-matlab/src/test/java/net/sourceforge/pmd/cpd/MatlabTokenizerTest.java index 48d3f50117..4492c55ba9 100644 --- a/pmd-matlab/src/test/java/net/sourceforge/pmd/cpd/MatlabTokenizerTest.java +++ b/pmd-matlab/src/test/java/net/sourceforge/pmd/cpd/MatlabTokenizerTest.java @@ -53,12 +53,12 @@ class MatlabTokenizerTest extends CpdTextComparisonTest { } @Test - public void testDoubleQuotedStrings() { + void testDoubleQuotedStrings() { doTest("doubleQuotedStrings"); } @Test - public void testTabWidth() { + void testTabWidth() { doTest("tabWidth"); } } diff --git a/pmd-modelica/pom.xml b/pmd-modelica/pom.xml index 41433ec193..875e5865a9 100644 --- a/pmd-modelica/pom.xml +++ b/pmd-modelica/pom.xml @@ -116,11 +116,6 @@ kotlin-stdlib test - - org.jetbrains.kotlin - kotlin-test-junit - test - org.jetbrains annotations diff --git a/pmd-modelica/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-modelica/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index 075ff57939..0000000000 --- a/pmd-modelica/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,28 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.modelica.ModelicaLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameterized.Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { - { ModelicaLanguageModule.NAME, ModelicaLanguageModule.TERSE_NAME, "", - getLanguage(ModelicaLanguageModule.NAME).getDefaultVersion(), - }, - }); - } -} diff --git a/pmd-modelica/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-modelica/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java deleted file mode 100644 index 72b4d7d1c4..0000000000 --- a/pmd-modelica/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ /dev/null @@ -1,9 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - // no additional tests yet -} diff --git a/pmd-modelica/src/test/java/net/sourceforge/pmd/lang/modelica/LanguageVersionTest.java b/pmd-modelica/src/test/java/net/sourceforge/pmd/lang/modelica/LanguageVersionTest.java new file mode 100644 index 0000000000..367e843585 --- /dev/null +++ b/pmd-modelica/src/test/java/net/sourceforge/pmd/lang/modelica/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.modelica; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(ModelicaLanguageModule.NAME, ModelicaLanguageModule.TERSE_NAME, "", + getLanguage(ModelicaLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-modelica/src/test/java/net/sourceforge/pmd/lang/modelica/RuleSetFactoryTest.java b/pmd-modelica/src/test/java/net/sourceforge/pmd/lang/modelica/RuleSetFactoryTest.java new file mode 100644 index 0000000000..d515ff6597 --- /dev/null +++ b/pmd-modelica/src/test/java/net/sourceforge/pmd/lang/modelica/RuleSetFactoryTest.java @@ -0,0 +1,11 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.modelica; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; + +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional tests yet +} diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index a2952609ec..0000000000 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.plsql.PLSQLLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { { PLSQLLanguageModule.NAME, PLSQLLanguageModule.TERSE_NAME, "", - getLanguage(PLSQLLanguageModule.NAME).getDefaultVersion(), }, }); - } -} diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java deleted file mode 100644 index 3e7e8ce991..0000000000 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -/** - * Test plsql's rulesets - */ -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - // no additional tests yet -} diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/LanguageVersionTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/LanguageVersionTest.java new file mode 100644 index 0000000000..f28d58964e --- /dev/null +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.plsql; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(PLSQLLanguageModule.NAME, PLSQLLanguageModule.TERSE_NAME, "", + getLanguage(PLSQLLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/RuleSetFactoryTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/RuleSetFactoryTest.java new file mode 100644 index 0000000000..2fa3b962eb --- /dev/null +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/RuleSetFactoryTest.java @@ -0,0 +1,14 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.plsql; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; + +/** + * Test plsql's rulesets + */ +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional tests yet +} diff --git a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTExtractExpressionTest.java b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTExtractExpressionTest.java index e341dae49a..e4c62757c7 100644 --- a/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTExtractExpressionTest.java +++ b/pmd-plsql/src/test/java/net/sourceforge/pmd/lang/plsql/ast/ASTExtractExpressionTest.java @@ -11,7 +11,7 @@ import org.junit.jupiter.api.Test; import net.sourceforge.pmd.lang.plsql.AbstractPLSQLParserTst; -public class ASTExtractExpressionTest extends AbstractPLSQLParserTst { +class ASTExtractExpressionTest extends AbstractPLSQLParserTst { @Test void testXml() { diff --git a/pmd-scala-modules/pmd-scala-common/pom.xml b/pmd-scala-modules/pmd-scala-common/pom.xml index be34d34eaf..1b2dd79036 100644 --- a/pmd-scala-modules/pmd-scala-common/pom.xml +++ b/pmd-scala-modules/pmd-scala-common/pom.xml @@ -149,11 +149,6 @@ kotlin-stdlib test - - org.jetbrains.kotlin - kotlin-test-junit - test - org.jetbrains annotations diff --git a/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index 1b505a1889..0000000000 --- a/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,33 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.scala.ScalaLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { - { ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.13", - getLanguage(ScalaLanguageModule.NAME).getVersion("2.13"), }, - { ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.12", - getLanguage(ScalaLanguageModule.NAME).getVersion("2.12"), }, - { ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.11", - getLanguage(ScalaLanguageModule.NAME).getVersion("2.11"), }, - { ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.10", - getLanguage(ScalaLanguageModule.NAME).getVersion("2.10"), }, }); - } -} diff --git a/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/RulesetFactoryTest.java b/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/RulesetFactoryTest.java deleted file mode 100644 index 534ece277d..0000000000 --- a/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/RulesetFactoryTest.java +++ /dev/null @@ -1,12 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -/** - * Test scala rulesets - */ -public class RulesetFactoryTest extends AbstractRuleSetFactoryTest { - // no rulesets yet -} diff --git a/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/lang/scala/LanguageVersionTest.java b/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/lang/scala/LanguageVersionTest.java new file mode 100644 index 0000000000..9adb6dfb3f --- /dev/null +++ b/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/lang/scala/LanguageVersionTest.java @@ -0,0 +1,25 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.scala; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList( + new TestDescriptor(ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.13", + getLanguage(ScalaLanguageModule.NAME).getVersion("2.13")), + new TestDescriptor(ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.12", + getLanguage(ScalaLanguageModule.NAME).getVersion("2.12")), + new TestDescriptor(ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.11", + getLanguage(ScalaLanguageModule.NAME).getVersion("2.11")), + new TestDescriptor(ScalaLanguageModule.NAME, ScalaLanguageModule.TERSE_NAME, "2.10", + getLanguage(ScalaLanguageModule.NAME).getVersion("2.10"))); + } +} diff --git a/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/lang/scala/RulesetFactoryTest.java b/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/lang/scala/RulesetFactoryTest.java new file mode 100644 index 0000000000..ff8a253296 --- /dev/null +++ b/pmd-scala-modules/pmd-scala-common/src/test/java/net/sourceforge/pmd/lang/scala/RulesetFactoryTest.java @@ -0,0 +1,14 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.scala; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; + +/** + * Test scala rulesets + */ +class RulesetFactoryTest extends AbstractRuleSetFactoryTest { + // no rulesets yet +} diff --git a/pmd-swift/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-swift/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java deleted file mode 100644 index 9ddfb4d2af..0000000000 --- a/pmd-swift/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ /dev/null @@ -1,9 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - // no additional unit tests -} diff --git a/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/LanguageVersionTest.java b/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/LanguageVersionTest.java new file mode 100644 index 0000000000..e56e9f3ca9 --- /dev/null +++ b/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.swift; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(SwiftLanguageModule.NAME, SwiftLanguageModule.TERSE_NAME, "", + getLanguage(SwiftLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/RuleSetFactoryTest.java b/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/RuleSetFactoryTest.java new file mode 100644 index 0000000000..f800ac2bea --- /dev/null +++ b/pmd-swift/src/test/java/net/sourceforge/pmd/lang/swift/RuleSetFactoryTest.java @@ -0,0 +1,11 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.swift; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; + +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + // no additional unit tests +} diff --git a/pmd-test-schema/pom.xml b/pmd-test-schema/pom.xml index 015d10f8a1..044b0c5e2b 100644 --- a/pmd-test-schema/pom.xml +++ b/pmd-test-schema/pom.xml @@ -38,17 +38,14 @@ test - junit - junit + org.junit.jupiter + junit-jupiter test com.github.stefanbirkner - system-rules + system-lambda test - - - diff --git a/pmd-test-schema/src/test/java/net/sourceforge/pmd/test/schema/TestSchemaParserTest.java b/pmd-test-schema/src/test/java/net/sourceforge/pmd/test/schema/TestSchemaParserTest.java index 6a08821766..50dde9dc41 100644 --- a/pmd-test-schema/src/test/java/net/sourceforge/pmd/test/schema/TestSchemaParserTest.java +++ b/pmd-test-schema/src/test/java/net/sourceforge/pmd/test/schema/TestSchemaParserTest.java @@ -4,17 +4,15 @@ package net.sourceforge.pmd.test.schema; +import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertThrows; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.io.IOException; import java.io.StringReader; -import org.hamcrest.MatcherAssert; -import org.junit.Rule; -import org.junit.Test; -import org.junit.contrib.java.lang.system.SystemErrRule; +import org.junit.jupiter.api.Test; import org.xml.sax.InputSource; import net.sourceforge.pmd.RuleContext; @@ -22,17 +20,15 @@ import net.sourceforge.pmd.lang.PlainTextLanguage; import net.sourceforge.pmd.lang.ast.Node; import net.sourceforge.pmd.lang.rule.AbstractRule; +import com.github.stefanbirkner.systemlambda.SystemLambda; + /** * @author Clément Fournier */ -public class TestSchemaParserTest { - - @Rule - public final SystemErrRule errStreamCaptor = new SystemErrRule().muteForSuccessfulTests(); - +class TestSchemaParserTest { @Test - public void testSchemaSimple() throws IOException { + void testSchemaSimple() throws IOException { String file = "\n" + "\n" + "\n" + "
\n"; - errStreamCaptor.enableLog(); - RuleTestCollection parsed = parseFile(file); + String log = SystemLambda.tapSystemErr(() -> { + RuleTestCollection parsed = parseFile(file); + assertEquals(1, parsed.getTests().size()); + }); - assertEquals(1, parsed.getTests().size()); - MatcherAssert.assertThat(errStreamCaptor.getLog(), containsString(" 6| \n" - + " ^^^^^^^^^^^^^^ Attribute 'regressionTest' is deprecated, use 'disabled' with inverted value\n")); + assertThat(log, containsString(" 6| \n" + + " ^^^^^^^^^^^^^^ Attribute 'regressionTest' is deprecated, use 'disabled' with inverted value\n")); } @Test - public void testUnknownProperty() throws IOException { + void testUnknownProperty() throws Exception { String file = "\n" + "\n" + "\n"; - errStreamCaptor.enableLog(); - assertThrows(IllegalStateException.class, () -> parseFile(file)); + String log = SystemLambda.tapSystemErr(() -> { + assertThrows(IllegalStateException.class, () -> parseFile(file)); + }); - MatcherAssert.assertThat(errStreamCaptor.getLog(), containsString(" 8| foo\n" - + " ^^^^ Unknown property, known property names are violationSuppressRegex, violationSuppressXPath\n")); + assertThat(log, containsString(" 8| foo\n" + + " ^^^^ Unknown property, known property names are violationSuppressRegex, violationSuppressXPath\n")); } private RuleTestCollection parseFile(String file) throws IOException { diff --git a/pmd-test/pom.xml b/pmd-test/pom.xml index bd88333abc..67644b89f6 100644 --- a/pmd-test/pom.xml +++ b/pmd-test/pom.xml @@ -33,8 +33,13 @@ compile - junit - junit + org.junit.jupiter + junit-jupiter-params + compile + + + com.github.stefanbirkner + system-lambda compile @@ -53,15 +58,6 @@ org.apache.ant ant - - org.apache.ant - ant-testutil - - - com.github.stefanbirkner - system-rules - compile - com.github.stefanbirkner system-lambda diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java index dd99117639..5a8530a6fb 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractLanguageVersionTest.java @@ -4,16 +4,15 @@ package net.sourceforge.pmd; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; import java.io.IOException; import java.io.InputStream; import java.util.Properties; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import net.sourceforge.pmd.ant.SourceLanguage; import net.sourceforge.pmd.lang.Language; @@ -22,66 +21,83 @@ import net.sourceforge.pmd.lang.LanguageVersion; /** * Base test class for {@link LanguageVersion} implementations.
- * Each language implementation should subclass this and provide a data method. + * Each language implementation should subclass this and provide a method called {@code data}. * *
- * @Parameters
- *     public static Collection<Object[]> data() {
- *       return Arrays.asList(new Object[][] {
- *            { MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.1",
- *              LanguageRegistry.getLanguage(MyLanguageModule.NAME).getVersion("1.1") },
- *            { MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.2",
- *              LanguageRegistry.getLanguage(MyLanguageModule.NAME).getVersion("1.2") },
+ *     static Collection<TestDescriptor> data() {
+ *       return Arrays.asList(
+ *            new TestDescriptor(MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.1",
+ *                               LanguageRegistry.getLanguage(MyLanguageModule.NAME).getVersion("1.1")),
+ *            new TestDescriptor(MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.2",
+ *                               LanguageRegistry.getLanguage(MyLanguageModule.NAME).getVersion("1.2")),
  *
  *            // doesn't exist
- *            { MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.3",
- *              null }
- *       });
+ *            new TestDescriptor(MyLanguageModule.NAME, MyLanguageModule.TERSE_NAME, "1.3", null)
+ *       };
  * 
* *

For the parameters, see the constructor - * {@link #AbstractLanguageVersionTest(String, String, String, LanguageVersion)}.

+ * {@link TestDescriptor#TestDescriptor(String, String, String, LanguageVersion)}.

*/ -@RunWith(Parameterized.class) -public class AbstractLanguageVersionTest { +public abstract class AbstractLanguageVersionTest { - private String name; - private String version; - private String simpleTerseName; - private LanguageVersion expected; + public static class TestDescriptor { + private final String name; + private final String version; + private final String simpleTerseName; + private final LanguageVersion expected; - /** - * Creates a new {@link AbstractLanguageVersionTest} - * - * @param name - * the name under which the language module is registered - * @param terseName - * the terse name under which the language module is registered - * @param version - * the specific version of the language version - * @param expected - * the expected {@link LanguageVersion} instance - */ - public AbstractLanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - this.name = name; - this.version = version; - this.simpleTerseName = terseName; - this.expected = expected; + /** + * Creates a new {@link TestDescriptor} + * + * @param name + * the name under which the language module is registered + * @param terseName + * the terse name under which the language module is registered + * @param version + * the specific version of the language version + * @param expected + * the expected {@link LanguageVersion} instance + */ + public TestDescriptor(String name, String terseName, String version, LanguageVersion expected) { + this.name = name; + this.version = version; + this.simpleTerseName = terseName; + this.expected = expected; + } + + public String getName() { + return name; + } + + public String getVersion() { + return version; + } + + public String getSimpleTerseName() { + return simpleTerseName; + } + + public LanguageVersion getExpected() { + return expected; + } } + protected static Language getLanguage(String name) { return LanguageRegistry.PMD.getLanguageByFullName(name); } /** * Checks that the expected {@link LanguageVersion} can be found via - * {@link #name} and {@link #version}. + * {@link TestDescriptor#name} and {@link TestDescriptor#version}. */ - @Test - public void testFindVersionsForLanguageNameAndVersion() { + @ParameterizedTest + @MethodSource("data") + void testFindVersionsForLanguageNameAndVersion(TestDescriptor testDescriptor) { SourceLanguage sourceLanguage = new SourceLanguage(); - sourceLanguage.setName(name); - sourceLanguage.setVersion(version); + sourceLanguage.setName(testDescriptor.getName()); + sourceLanguage.setVersion(testDescriptor.getVersion()); Language language = getLanguage(sourceLanguage.getName()); LanguageVersion languageVersion = null; @@ -89,7 +105,7 @@ public class AbstractLanguageVersionTest { languageVersion = language.getVersion(sourceLanguage.getVersion()); } - assertEquals(expected, languageVersion); + assertEquals(testDescriptor.getExpected(), languageVersion); } /** @@ -98,14 +114,15 @@ public class AbstractLanguageVersionTest { * @throws Exception * any error */ - @Test - public void testRegisteredRulesets() throws Exception { - if (expected == null) { + @ParameterizedTest + @MethodSource("data") + void testRegisteredRulesets(TestDescriptor testDescriptor) throws Exception { + if (testDescriptor.getExpected() == null) { return; } Properties props = new Properties(); - String rulesetsProperties = "/category/" + simpleTerseName + "/categories.properties"; + String rulesetsProperties = "/category/" + testDescriptor.getSimpleTerseName() + "/categories.properties"; try (InputStream inputStream = getClass().getResourceAsStream(rulesetsProperties)) { if (inputStream == null) { throw new IOException(); @@ -121,15 +138,16 @@ public class AbstractLanguageVersionTest { * @throws Exception * any error */ - @Test - public void testOldRegisteredRulesets() throws Exception { + @ParameterizedTest + @MethodSource("data") + void testOldRegisteredRulesets(TestDescriptor testDescriptor) throws Exception { // only check for languages, that support rules - if (expected == null) { + if (testDescriptor.getExpected() == null) { return; } Properties props = new Properties(); - String rulesetsProperties = "/rulesets/" + simpleTerseName + "/rulesets.properties"; + String rulesetsProperties = "/rulesets/" + testDescriptor.getSimpleTerseName() + "/rulesets.properties"; InputStream inputStream = getClass().getResourceAsStream(rulesetsProperties); if (inputStream != null) { // rulesets.properties file exists @@ -140,8 +158,10 @@ public class AbstractLanguageVersionTest { } } - @Test - public void testVersionsAreDistinct() { + @ParameterizedTest + @MethodSource("data") + void testVersionsAreDistinct(TestDescriptor testDescriptor) { + LanguageVersion expected = testDescriptor.getExpected(); if (expected == null) { return; } @@ -155,8 +175,8 @@ public class AbstractLanguageVersionTest { } } - assertEquals("Expected exactly one occurrence of " + expected - + " in the language versions of its language", 1, count); + assertEquals(1, count, "Expected exactly one occurrence of " + expected + + " in the language versions of its language"); } private void assertRulesetsAndCategoriesProperties(Properties props) throws IOException { diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java index 0012282d64..fc53a72c82 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/AbstractRuleSetFactoryTest.java @@ -4,10 +4,10 @@ package net.sourceforge.pmd; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; import java.io.BufferedReader; import java.io.ByteArrayInputStream; @@ -31,9 +31,8 @@ import java.util.regex.Pattern; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; -import org.junit.BeforeClass; -import org.junit.Test; -import org.junit.contrib.java.lang.system.SystemErrRule; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; @@ -51,8 +50,6 @@ import net.sourceforge.pmd.properties.PropertyDescriptor; * subclassed for each language. */ public abstract class AbstractRuleSetFactoryTest { - @org.junit.Rule - public final SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests(); private static ValidateDefaultHandler validateDefaultHandler; private static SAXParser saxParser; @@ -71,6 +68,7 @@ public abstract class AbstractRuleSetFactoryTest { * skipped because they aren't the primary language which the concrete instance of this class is testing. */ public AbstractRuleSetFactoryTest(String... languagesToSkip) { + this.languagesToSkip.add("dummy"); this.languagesToSkip.addAll(Arrays.asList(languagesToSkip)); validXPathClassNames.add(XPathRule.class.getName()); } @@ -81,8 +79,8 @@ public abstract class AbstractRuleSetFactoryTest { * @throws Exception * any error */ - @BeforeClass - public static void init() throws Exception { + @BeforeAll + static void init() throws Exception { SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); saxParserFactory.setValidating(true); saxParserFactory.setNamespaceAware(true); @@ -107,7 +105,7 @@ public abstract class AbstractRuleSetFactoryTest { * any error */ @Test - public void testAllPMDBuiltInRulesMeetConventions() throws Exception { + void testAllPMDBuiltInRulesMeetConventions() throws Exception { int invalidSinceAttributes = 0; int invalidExternalInfoURL = 0; int invalidClassName = 0; @@ -225,14 +223,14 @@ public abstract class AbstractRuleSetFactoryTest { * any error */ @Test - public void testXmlSchema() throws Exception { + void testXmlSchema() throws Exception { boolean allValid = true; List ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { boolean valid = validateAgainstSchema(fileName); allValid = allValid && valid; } - assertTrue("All XML must parse without producing validation messages.", allValid); + assertTrue(allValid, "All XML must parse without producing validation messages."); } /** @@ -242,14 +240,14 @@ public abstract class AbstractRuleSetFactoryTest { * any error */ @Test - public void testDtd() throws Exception { + void testDtd() throws Exception { boolean allValid = true; List ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { boolean valid = validateAgainstDtd(fileName); allValid = allValid && valid; } - assertTrue("All XML must parse without producing validation messages.", allValid); + assertTrue(allValid, "All XML must parse without producing validation messages."); } /** @@ -260,7 +258,7 @@ public abstract class AbstractRuleSetFactoryTest { * any error */ @Test - public void testReadWriteRoundTrip() throws Exception { + void testReadWriteRoundTrip() throws Exception { List ruleSetFileNames = getRuleSetFileNames(); for (String fileName : ruleSetFileNames) { @@ -294,7 +292,7 @@ public abstract class AbstractRuleSetFactoryTest { List ruleSetFileNames = new ArrayList<>(); Properties properties = new Properties(); @SuppressWarnings("PMD.CloseResource") - InputStream input = getClass().getResourceAsStream(propertiesPath); + InputStream input = loadResourceAsStream(propertiesPath); if (input == null) { // this might happen if a language is only support by CPD, but not // by PMD @@ -384,7 +382,7 @@ public abstract class AbstractRuleSetFactoryTest { } private InputStream loadResourceAsStream(String resource) { - return getClass().getResourceAsStream(resource); + return getClass().getClassLoader().getResourceAsStream(resource); } private void testRuleSet(String fileName) throws IOException, SAXException { @@ -423,14 +421,14 @@ public abstract class AbstractRuleSetFactoryTest { RuleSet ruleSet3 = loader.loadFromString("", xml3); // The 2 written XMLs should all be valid w.r.t Schema/DTD - assertTrue("1st roundtrip RuleSet XML is not valid against Schema (filename: " + fileName + ")", - validateAgainstSchema(new ByteArrayInputStream(xml2.getBytes()))); - assertTrue("2nd roundtrip RuleSet XML is not valid against Schema (filename: " + fileName + ")", - validateAgainstSchema(new ByteArrayInputStream(xml3.getBytes()))); - assertTrue("1st roundtrip RuleSet XML is not valid against DTD (filename: " + fileName + ")", - validateAgainstDtd(new ByteArrayInputStream(xml2.getBytes()))); - assertTrue("2nd roundtrip RuleSet XML is not valid against DTD (filename: " + fileName + ")", - validateAgainstDtd(new ByteArrayInputStream(xml3.getBytes()))); + assertTrue(validateAgainstSchema(new ByteArrayInputStream(xml2.getBytes())), + "1st roundtrip RuleSet XML is not valid against Schema (filename: " + fileName + ")"); + assertTrue(validateAgainstSchema(new ByteArrayInputStream(xml3.getBytes())), + "2nd roundtrip RuleSet XML is not valid against Schema (filename: " + fileName + ")"); + assertTrue(validateAgainstDtd(new ByteArrayInputStream(xml2.getBytes())), + "1st roundtrip RuleSet XML is not valid against DTD (filename: " + fileName + ")"); + assertTrue(validateAgainstDtd(new ByteArrayInputStream(xml3.getBytes())), + "2nd roundtrip RuleSet XML is not valid against DTD (filename: " + fileName + ")"); // All 3 versions of the RuleSet should be the same assertEqualsRuleSet("Original RuleSet and 1st roundtrip Ruleset not the same (filename: " + fileName + ")", @@ -440,63 +438,63 @@ public abstract class AbstractRuleSetFactoryTest { // It's hard to compare the XML DOMs. At least the roundtrip ones should // textually be the same. - assertEquals("1st roundtrip RuleSet XML and 2nd roundtrip RuleSet XML (filename: " + fileName + ")", xml2, - xml3); + assertEquals(xml2, xml3, + "1st roundtrip RuleSet XML and 2nd roundtrip RuleSet XML (filename: " + fileName + ")"); } private void assertEqualsRuleSet(String message, RuleSet ruleSet1, RuleSet ruleSet2) { - assertEquals(message + ", RuleSet name", ruleSet1.getName(), ruleSet2.getName()); - assertEquals(message + ", RuleSet description", ruleSet1.getDescription(), ruleSet2.getDescription()); - assertEquals(message + ", RuleSet exclude patterns", ruleSet1.getFileExclusions(), - ruleSet2.getFileExclusions()); - assertEquals(message + ", RuleSet include patterns", ruleSet1.getFileInclusions(), - ruleSet2.getFileInclusions()); - assertEquals(message + ", RuleSet rule count", ruleSet1.getRules().size(), ruleSet2.getRules().size()); + assertEquals(ruleSet1.getName(), ruleSet2.getName(), message + ", RuleSet name"); + assertEquals(ruleSet1.getDescription(), ruleSet2.getDescription(), message + ", RuleSet description"); + assertEquals(ruleSet1.getFileExclusions(), ruleSet2.getFileExclusions(), + message + ", RuleSet exclude patterns"); + assertEquals(ruleSet1.getFileInclusions(), ruleSet2.getFileInclusions(), + message + ", RuleSet include patterns"); + assertEquals(ruleSet1.getRules().size(), ruleSet2.getRules().size(), message + ", RuleSet rule count"); for (int i = 0; i < ruleSet1.getRules().size(); i++) { Rule rule1 = ((List) ruleSet1.getRules()).get(i); Rule rule2 = ((List) ruleSet2.getRules()).get(i); - assertFalse(message + ", Different RuleReference", - rule1 instanceof RuleReference != rule2 instanceof RuleReference); + assertFalse(rule1 instanceof RuleReference != rule2 instanceof RuleReference, + message + ", Different RuleReference"); if (rule1 instanceof RuleReference) { RuleReference ruleReference1 = (RuleReference) rule1; RuleReference ruleReference2 = (RuleReference) rule2; - assertEquals(message + ", RuleReference overridden minimum language version", - ruleReference1.getOverriddenMinimumLanguageVersion(), - ruleReference2.getOverriddenMinimumLanguageVersion()); - assertEquals(message + ", RuleReference overridden maximum language version", - ruleReference1.getOverriddenMaximumLanguageVersion(), - ruleReference2.getOverriddenMaximumLanguageVersion()); - assertEquals(message + ", RuleReference overridden deprecated", ruleReference1.isOverriddenDeprecated(), - ruleReference2.isOverriddenDeprecated()); - assertEquals(message + ", RuleReference overridden name", ruleReference1.getOverriddenName(), - ruleReference2.getOverriddenName()); - assertEquals(message + ", RuleReference overridden description", - ruleReference1.getOverriddenDescription(), ruleReference2.getOverriddenDescription()); - assertEquals(message + ", RuleReference overridden message", ruleReference1.getOverriddenMessage(), - ruleReference2.getOverriddenMessage()); - assertEquals(message + ", RuleReference overridden external info url", - ruleReference1.getOverriddenExternalInfoUrl(), ruleReference2.getOverriddenExternalInfoUrl()); - assertEquals(message + ", RuleReference overridden priority", ruleReference1.getOverriddenPriority(), - ruleReference2.getOverriddenPriority()); - assertEquals(message + ", RuleReference overridden examples", ruleReference1.getOverriddenExamples(), - ruleReference2.getOverriddenExamples()); + assertEquals(ruleReference1.getOverriddenMinimumLanguageVersion(), + ruleReference2.getOverriddenMinimumLanguageVersion(), + message + ", RuleReference overridden minimum language version"); + assertEquals(ruleReference1.getOverriddenMaximumLanguageVersion(), + ruleReference2.getOverriddenMaximumLanguageVersion(), + message + ", RuleReference overridden maximum language version"); + assertEquals(ruleReference1.isOverriddenDeprecated(), ruleReference2.isOverriddenDeprecated(), + message + ", RuleReference overridden deprecated"); + assertEquals(ruleReference1.getOverriddenName(), ruleReference2.getOverriddenName(), + message + ", RuleReference overridden name"); + assertEquals(ruleReference1.getOverriddenDescription(), ruleReference2.getOverriddenDescription(), + message + ", RuleReference overridden description"); + assertEquals(ruleReference1.getOverriddenMessage(), ruleReference2.getOverriddenMessage(), + message + ", RuleReference overridden message"); + assertEquals(ruleReference1.getOverriddenExternalInfoUrl(), ruleReference2.getOverriddenExternalInfoUrl(), + message + ", RuleReference overridden external info url"); + assertEquals(ruleReference1.getOverriddenPriority(), ruleReference2.getOverriddenPriority(), + message + ", RuleReference overridden priority"); + assertEquals(ruleReference1.getOverriddenExamples(), ruleReference2.getOverriddenExamples(), + message + ", RuleReference overridden examples"); } - assertEquals(message + ", Rule name", rule1.getName(), rule2.getName()); - assertEquals(message + ", Rule class", rule1.getRuleClass(), rule2.getRuleClass()); - assertEquals(message + ", Rule description " + rule1.getName(), rule1.getDescription(), - rule2.getDescription()); - assertEquals(message + ", Rule message", rule1.getMessage(), rule2.getMessage()); - assertEquals(message + ", Rule external info url", rule1.getExternalInfoUrl(), rule2.getExternalInfoUrl()); - assertEquals(message + ", Rule priority", rule1.getPriority(), rule2.getPriority()); - assertEquals(message + ", Rule examples", rule1.getExamples(), rule2.getExamples()); + assertEquals(rule1.getName(), rule2.getName(), message + ", Rule name"); + assertEquals(rule1.getRuleClass(), rule2.getRuleClass(), message + ", Rule class"); + assertEquals(rule1.getDescription(), rule2.getDescription(), + message + ", Rule description " + rule1.getName()); + assertEquals(rule1.getMessage(), rule2.getMessage(), message + ", Rule message"); + assertEquals(rule1.getExternalInfoUrl(), rule2.getExternalInfoUrl(), message + ", Rule external info url"); + assertEquals(rule1.getPriority(), rule2.getPriority(), message + ", Rule priority"); + assertEquals(rule1.getExamples(), rule2.getExamples(), message + ", Rule examples"); List> propertyDescriptors1 = rule1.getPropertyDescriptors(); List> propertyDescriptors2 = rule2.getPropertyDescriptors(); - assertEquals(message + ", Rule property descriptor ", propertyDescriptors1, propertyDescriptors2); + assertEquals(propertyDescriptors1, propertyDescriptors2, message + ", Rule property descriptor "); for (int j = 0; j < propertyDescriptors1.size(); j++) { Object value1 = rule1.getProperty(propertyDescriptors1.get(j)); Object value2 = rule2.getProperty(propertyDescriptors2.get(j)); @@ -505,10 +503,10 @@ public abstract class AbstractRuleSetFactoryTest { value1 = ((Pattern) value1).pattern(); value2 = ((Pattern) value2).pattern(); } - assertEquals(message + ", Rule property value " + j, value1, value2); + assertEquals(value1, value2, message + ", Rule property value " + j); } - assertEquals(message + ", Rule property descriptor count", propertyDescriptors1.size(), - propertyDescriptors2.size()); + assertEquals(propertyDescriptors1.size(), propertyDescriptors2.size(), + message + ", Rule property descriptor count"); } } @@ -560,7 +558,7 @@ public abstract class AbstractRuleSetFactoryTest { String resource = schemaMapping.get(systemId); if (resource != null) { - InputStream inputStream = getClass().getResourceAsStream(resource); + InputStream inputStream = getClass().getClassLoader().getResourceAsStream(resource); if (inputStream == null) { throw new FileNotFoundException(resource); } diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/ant/AbstractAntTestHelper.java b/pmd-test/src/main/java/net/sourceforge/pmd/ant/AbstractAntTestHelper.java index 47e39dce81..f6e3f3eef2 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/ant/AbstractAntTestHelper.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/ant/AbstractAntTestHelper.java @@ -9,103 +9,129 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.not; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.io.PrintStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Locale; -import org.apache.tools.ant.BuildFileRule; +import org.apache.tools.ant.BuildEvent; +import org.apache.tools.ant.DefaultLogger; import org.apache.tools.ant.Project; -import org.junit.Before; -import org.junit.Rule; -import org.junit.contrib.java.lang.system.SystemErrRule; -import org.junit.rules.TemporaryFolder; +import org.apache.tools.ant.ProjectHelper; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; -import net.sourceforge.pmd.annotation.InternalApi; +import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration; +import com.github.stefanbirkner.systemlambda.Statement; +import com.github.stefanbirkner.systemlambda.SystemLambda; /** - * Quite an ugly classe, arguably useful for just 2 units test - nevertheless as - * there is a workaround that must be shared by both tests (PMD and CPD's) I - * felt compelled to move it to a single classes. + * Base test class for ant tests. + * + *

Usage template: + * + *

+ * {@code
+ * class MyPMDTaskTest extends AbstractAntTestHelper {
+ *     MyPMDTaskTest() {
+ *          antTestScriptFilename = "mypmdtasktest.xml";
+ *     }
+ *
+ *     @Test
+ *     void myTest() {
+ *         executeTarget("testMyTarget");
+ *         assertOutputContaining("Expected Violation Message");
+ *     }
+ * }
+ * }
+ * 
* * @author Romain Pelisse <belaran@gmail.com> * */ public abstract class AbstractAntTestHelper { - @Rule - @InternalApi - @Deprecated - public final TemporaryFolder tempFolder = new TemporaryFolder(); - - @Rule - @InternalApi - @Deprecated - public final BuildFileRule buildRule = new BuildFileRule(); - - @Rule - @InternalApi - @Deprecated - public final SystemErrRule systemErrRule = new SystemErrRule().muteForSuccessfulTests(); + @TempDir + private Path tempFolder; protected String pathToTestScript; protected String antTestScriptFilename; - @InternalApi - @Deprecated - public String mvnWorkaround; + + private Project antProject; + private StringBuilder log = new StringBuilder(); + private String output; public AbstractAntTestHelper() { - mvnWorkaround = "pmd/ant/xml"; - if (new File("target/clover/test-classes").exists()) { - pathToTestScript = "target/clover/test-classes/net/sourceforge/" + mvnWorkaround; - } else { - pathToTestScript = "target/test-classes/net/sourceforge/" + mvnWorkaround; - } + pathToTestScript = "target/test-classes/net/sourceforge/pmd/ant/xml"; } - @Before + @BeforeEach public void setUp() throws IOException { validatePostConstruct(); // initialize Ant - buildRule.configureProject(pathToTestScript + separator + antTestScriptFilename); + antProject = new Project(); + antProject.init(); + antProject.addBuildListener(new AntBuildListener()); + ProjectHelper.configureProject(antProject, new File(pathToTestScript + separator + antTestScriptFilename)); - // Each test case gets one temp file name, accessible with ${tmpfile} - final File newFile = tempFolder.newFile(); - newFile.delete(); // It shouldn't exist yet, but we want a unique name - buildRule.getProject().setProperty("tmpfile", newFile.getAbsolutePath()); - - Project project = buildRule.getProject(); - if (!project.getBaseDir().toString().endsWith(mvnWorkaround)) { - // when running from maven, the path needs to be adapted... - // FIXME: this is more a workaround than a good solution... - project.setBasedir(project.getBaseDir().toString() + separator + pathToTestScript); - } + // Each test case gets one temp file name, accessible with property ${tmpfile} + Path tmpFile = Files.createTempFile(tempFolder, "pmd-ant-tests", null); + // we delete the tmpfile again, since we only wanted to have a unique temp filename + // the tmpfile is used for creating reports. + Files.deleteIfExists(tmpFile); + antProject.setProperty("tmpfile", tmpFile.toAbsolutePath().toString()); } + @AfterAll + static void resetLogging() { + Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null); + } /** * Returns the current temporary file. Replaced by a fresh (inexistent) * file before each test. */ public File currentTempFile() { - String tmpname = buildRule.getProject().getProperty("tmpfile"); + String tmpname = antProject.getProperty("tmpfile"); return tmpname == null ? null : new File(tmpname); } private void validatePostConstruct() { if (pathToTestScript == null || "".equals(pathToTestScript) || antTestScriptFilename == null - || "".equals(antTestScriptFilename) || mvnWorkaround == null || "".equals(mvnWorkaround)) { + || "".equals(antTestScriptFilename)) { throw new IllegalStateException("Unit tests for Ant script badly initialized"); } } - public void executeTarget(String target) { - buildRule.executeTarget(target); - System.err.println(buildRule.getLog()); + public String executeTarget(String target) { + try { + restoreLocale(() -> { + // restoring system properties: Test might change file.encoding or might change logging properties + // See Slf4jSimpleConfigurationForAnt and resetLogging + SystemLambda.restoreSystemProperties(() -> { + output = tapSystemOut(() -> { + antProject.executeTarget(target); + }); + }); + }); + return output; + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected String getLog() { + return log.toString(); } public void assertOutputContaining(String text) { - assertThat(buildRule.getOutput(), containsString(text)); + assertThat(output, containsString(text)); } @@ -117,4 +143,57 @@ public abstract class AbstractAntTestHelper { public void assertDoesntContain(String text, String toFind) { assertThat(text, not(containsString(toFind))); } + + private static void restoreLocale(Statement statement) throws Exception { + Locale originalLocale = Locale.getDefault(); + try { + statement.execute(); + } finally { + Locale.setDefault(originalLocale); + } + } + + /** + * This is similar to {@link SystemLambda#tapSystemOut(Statement)}. But this + * method doesn't use the platform default charset as it was when the JVM started. + * Instead, it uses the current system property {@code file.encoding}. This allows + * tests to change the encoding. + * + * @param statement an arbitrary piece of code. + * @return text that is written to stdout. Lineendings are normalized to {@code \n}. + * @throws Exception any exception thrown by the statement + */ + private static String tapSystemOut(Statement statement) throws Exception { + @SuppressWarnings("PMD.CloseResource") // we don't want to close System.out + PrintStream originalOut = System.out; + ByteArrayOutputStream text = new ByteArrayOutputStream(); + String currentDefaultCharset = System.getProperty("file.encoding"); + try { + PrintStream replacement = new PrintStream(text, true, currentDefaultCharset); + System.setOut(replacement); + statement.execute(); + } finally { + System.setOut(originalOut); + } + String result = text.toString(currentDefaultCharset); + return result.replace(System.lineSeparator(), "\n"); + } + + private final class AntBuildListener extends DefaultLogger { + private AntBuildListener() { + msgOutputLevel = Project.MSG_INFO; + } + + @Override + protected void printMessage(String message, PrintStream stream, int priority) { + log.append(message); + } + + @Override + public void messageLogged(BuildEvent buildEvent) { + if (buildEvent.getPriority() <= Project.MSG_INFO) { + log.append(buildEvent.getMessage()); + } + } + } } diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/test/util/JavaUtilLoggingRule.java b/pmd-test/src/main/java/net/sourceforge/pmd/test/util/JavaUtilLoggingRule.java deleted file mode 100644 index e801e7f8c5..0000000000 --- a/pmd-test/src/main/java/net/sourceforge/pmd/test/util/JavaUtilLoggingRule.java +++ /dev/null @@ -1,142 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.test.util; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.containsStringIgnoringCase; -import static org.hamcrest.Matchers.emptyString; - -import java.io.ByteArrayOutputStream; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.logging.Formatter; -import java.util.logging.Handler; -import java.util.logging.Logger; -import java.util.logging.StreamHandler; - -import org.junit.contrib.java.lang.system.SystemErrRule; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runners.model.MultipleFailureException; -import org.junit.runners.model.Statement; - -/** - * Junit Rule, to check for java util logging statements. - * The log is only printed to console if the test fails. - * - * @author Andreas Dangel - * @author Clément Fournier - * @see Testing the presence of log messages with java.util.logging - * - * @deprecated Use {@link SystemErrRule} instead. With the switch to slf4j, the log output appears on System.err. - */ -@Deprecated -@SuppressWarnings("PMD.DoNotUseJavaUtilLogging") -public class JavaUtilLoggingRule implements TestRule { - // copied from pmd core test sources - - private final Logger logger; - private final ByteArrayOutputStream stream; - private final StreamHandler customLogHandler; - - - /** - * Creates a new rule, that attaches a custom log handler - * to the given logger. - * - * @param loggerName the name of the logger to check - */ - public JavaUtilLoggingRule(String loggerName) { - this(Logger.getLogger(loggerName)); - } - - /** - * Creates a new rule, that attaches a custom log handler - * to the given logger. - * - * @param logger the logger - */ - public JavaUtilLoggingRule(Logger logger) { - this.logger = logger; - this.stream = new ByteArrayOutputStream(); - - Logger currentLogger = logger; - while (currentLogger.getHandlers().length == 0) { - currentLogger = currentLogger.getParent(); - } - Handler originalHandler = currentLogger.getHandlers()[0]; - Formatter formatter = originalHandler.getFormatter(); - logger.removeHandler(originalHandler); // disable printing to console - this.customLogHandler = new StreamHandler(stream, formatter); - } - - protected void before() { - logger.addHandler(customLogHandler); - } - - @Override - @SuppressWarnings("PMD.AvoidCatchingThrowable") - public Statement apply(Statement base, Description description) { - return new Statement() { - // this is a copy of the Statement in the ExternalResource base TestRule class, - // except it prints the log if there was an error - @Override - public void evaluate() throws Throwable { - before(); - - List errors = new ArrayList<>(); - try { - base.evaluate(); - } catch (Throwable t) { - errors.add(t); - } finally { - try { - after(); - } catch (Throwable t) { - errors.add(t); - } - } - // this statement is the only difference - if (!errors.isEmpty()) { - System.err.println(getLog()); - } - - MultipleFailureException.assertEmpty(errors); - } - }; - } - - protected void after() { - logger.removeHandler(customLogHandler); - } - - /** - * Gets the complete log. - * - * @return the log - */ - public String getLog() { - customLogHandler.flush(); - return new String(stream.toByteArray(), StandardCharsets.UTF_8); - } - - /** - * Clears the log. - */ - public void clear() { - customLogHandler.flush(); - stream.reset(); - } - - public void assertEmpty() { - assertThat("Log output should be empty", getLog(), is(emptyString())); - } - - public void assertContainsIgnoringCase(String str) { - assertThat(getLog(), containsStringIgnoringCase(str)); - } -} diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/AbstractTokenizerTest.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/AbstractTokenizerTest.java deleted file mode 100644 index ba9f3d3ab5..0000000000 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/AbstractTokenizerTest.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.testframework; - -import static org.junit.Assert.assertEquals; - -import java.io.IOException; -import java.util.List; - -import net.sourceforge.pmd.cpd.SourceCode; -import net.sourceforge.pmd.cpd.TokenEntry; -import net.sourceforge.pmd.cpd.Tokenizer; -import net.sourceforge.pmd.cpd.Tokens; - -/** - * @author Romain PELISSE, belaran@gmail.com - * - * @deprecated Use CpdTextComparisonTest in module pmd-lang-test - */ -@Deprecated -public abstract class AbstractTokenizerTest { - - protected int expectedTokenCount; - protected Tokenizer tokenizer; - protected SourceCode sourceCode; - - public abstract void buildTokenizer() throws IOException; - - public abstract String getSampleCode() throws IOException; - - protected void tokenizeTest() throws IOException { - Tokens tokens = new Tokens(); - tokenizer.tokenize(sourceCode, tokens); - List entries = tokens.getTokens(); - assertEquals(expectedTokenCount, entries.size()); - } - -} diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java deleted file mode 100644 index 88d69bb935..0000000000 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/PMDTestRunner.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.testframework; - -import java.util.Collections; -import java.util.List; - -import org.junit.runner.Description; -import org.junit.runner.Runner; -import org.junit.runner.manipulation.Filter; -import org.junit.runner.manipulation.Filterable; -import org.junit.runner.manipulation.NoTestsRemainException; -import org.junit.runner.manipulation.Sortable; -import org.junit.runner.manipulation.Sorter; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.JUnit4; -import org.junit.runners.ParentRunner; -import org.junit.runners.model.InitializationError; - -/** - * A JUnit Runner, that combines the default {@link JUnit4} - * and our custom {@link RuleTestRunner}. - * It allows to selectively execute single test cases (it is {@link Filterable}). - * - *

Note: Since we actually run two runners one after another, the static {@code BeforeClass} - * and {@Code AfterClass} methods will be executed twice and the test class will be instantiated twice, too.

- * - *

In order to use it, you'll need to subclass {@link SimpleAggregatorTst} and - * annotate your test class with RunWith:

- * - *
- * @RunWith(PMDTestRunner.class)
- * public class MyRuleSetTest extends SimpleAggregatorTst {
- * ...
- * }
- * 
- * - * @deprecated This is not needed anymore with JUnit5. Just extend from {@link SimpleAggregatorTst}. - */ -@Deprecated -public class PMDTestRunner extends Runner implements Filterable, Sortable { - private final Class klass; - private final RuleTestRunner ruleTests; - private final ParentRunner unitTests; - - private final Description description; - - public PMDTestRunner(final Class klass) throws InitializationError { - this.klass = klass; - ruleTests = new RuleTestRunner(klass); - - if (ruleTests.hasUnitTests()) { - unitTests = new JUnit4(klass); - } else { - unitTests = new EmptyRunner(klass); - } - - this.description = createDescription(); - } - - @Override - public void filter(Filter filter) throws NoTestsRemainException { - boolean noRuleTests = false; - try { - ruleTests.filter(filter); - } catch (NoTestsRemainException e) { - noRuleTests = true; - } - - boolean noUnitTests = false; - try { - unitTests.filter(filter); - } catch (NoTestsRemainException e) { - noUnitTests = true; - } - - if (noRuleTests && noUnitTests) { - throw new NoTestsRemainException(); - } - } - - @Override - public Description getDescription() { - return description; - } - - private Description createDescription() { - Description description = Description.createSuiteDescription(klass); - description.addChild(createChildrenDescriptions(ruleTests, "Rule Tests")); - if (ruleTests.hasUnitTests()) { - description.addChild(createChildrenDescriptions(unitTests, "Unit Tests")); - } - return description; - } - - private Description createChildrenDescriptions(Runner runner, String suiteName) { - Description suite = Description.createSuiteDescription(suiteName); - for (Description child : runner.getDescription().getChildren()) { - suite.addChild(child); - } - return suite; - } - - @Override - public void run(RunNotifier notifier) { - ruleTests.run(notifier); - unitTests.run(notifier); - } - - @Override - public void sort(Sorter sorter) { - ruleTests.sort(sorter); - unitTests.sort(sorter); - } - - private static class EmptyRunner extends ParentRunner { - protected EmptyRunner(Class testClass) throws InitializationError { - super(testClass); - } - - @Override - public Description getDescription() { - return Description.EMPTY; - } - - @Override - protected List getChildren() { - return Collections.emptyList(); - } - - @Override - protected Description describeChild(Object child) { - return Description.EMPTY; - } - - @Override - protected void runChild(Object child, RunNotifier notifier) { - // there are no tests - nothing to execute - } - } -} diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTestRunner.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTestRunner.java deleted file mode 100644 index 5e08bf3d3b..0000000000 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTestRunner.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.testframework; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.internal.runners.statements.RunAfters; -import org.junit.internal.runners.statements.RunBefores; -import org.junit.rules.RunRules; -import org.junit.rules.TestRule; -import org.junit.runner.Description; -import org.junit.runner.notification.RunNotifier; -import org.junit.runners.ParentRunner; -import org.junit.runners.model.FrameworkMethod; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.Statement; - -import net.sourceforge.pmd.Rule; -import net.sourceforge.pmd.test.schema.RuleTestCollection; -import net.sourceforge.pmd.test.schema.RuleTestDescriptor; - -/** - * A JUnit Runner, that executes all declared rule tests in the class. It supports Before and After methods as well as - * TestRules. - * - * @author Andreas Dangel - * @deprecated This is not needed anymore with JUnit5 - */ -@Deprecated -public class RuleTestRunner extends ParentRunner { - private ConcurrentMap testDescriptions = new ConcurrentHashMap<>(); - private final RuleTst instance; - - /* default */ RuleTestRunner(final Class testClass) throws InitializationError { - super(testClass); - instance = createTestClass(); - instance.setUp(); - } - - @Override - protected Description describeChild(final TestDescriptor testCase) { - Description description = testDescriptions.get(testCase); - if (description == null) { - description = Description.createTestDescription(getTestClass().getJavaClass().getName(), testCase.getTestMethodName()); - testDescriptions.putIfAbsent(testCase, description); - } - return description; - } - - /** - * Checks whether this test class has additionally unit test methods. - * - * @return true if there is at least one unit test method. - */ - /* default */ boolean hasUnitTests() { - return !getTestClass().getAnnotatedMethods(Test.class).isEmpty(); - } - - @Override - protected List getChildren() { - List rules = new ArrayList<>(instance.getRules()); - rules.sort(Comparator.comparing(Rule::getName)); - - List tests = new ArrayList<>(); - for (Rule r : rules) { - RuleTestCollection ruleTests = instance.parseTestCollection(r); - RuleTestDescriptor focused = ruleTests.getFocusedTestOrNull(); - for (RuleTestDescriptor t : ruleTests.getTests()) { - TestDescriptor td = new TestDescriptor(t, ruleTests.getAbsoluteUriToTestXmlFile()); - if (focused != null && !focused.equals(t)) { - td.setRegressionTest(false); // disable it - } - tests.add(td); - } - } - - return tests; - } - - private RuleTst createTestClass() throws InitializationError { - try { - return (RuleTst) getTestClass().getOnlyConstructor().newInstance(); - } catch (final Exception e) { - throw new InitializationError(e); - } - } - - @Override - protected void runChild(final TestDescriptor testCase, final RunNotifier notifier) { - final Description description = describeChild(testCase); - if (isIgnored(testCase)) { - notifier.fireTestIgnored(description); - } else { - runLeaf(ruleTestBlock(testCase), description, notifier); - } - } - - /** - * Executes the actual test case. If there are Before, After, or TestRules present, they are executed accordingly. - * - * @param testCase the PMD rule test case to be executed - * @return a single statement which includes any rules, if present. - */ - private Statement ruleTestBlock(final TestDescriptor testCase) { - Statement statement = new Statement() { - @Override - public void evaluate() { - instance.runTest(testCase); - } - }; - statement = withBefores(statement); - statement = withAfters(statement); - statement = withRules(testCase, statement); - return statement; - } - - private Statement withBefores(final Statement statement) { - final List befores = getTestClass().getAnnotatedMethods(Before.class); - return befores.isEmpty() ? statement : new RunBefores(statement, befores, instance); - } - - private Statement withAfters(final Statement statement) { - final List afters = getTestClass().getAnnotatedMethods(After.class); - return afters.isEmpty() ? statement : new RunAfters(statement, afters, instance); - } - - private Statement withRules(final TestDescriptor testCase, Statement statement) { - final List testRules = - getTestClass().getAnnotatedFieldValues(instance, org.junit.Rule.class, TestRule.class); - return testRules.isEmpty() ? statement : new RunRules(statement, testRules, describeChild(testCase)); - } - - @Override - protected boolean isIgnored(final TestDescriptor child) { - return TestDescriptor.inRegressionTestMode() && !child.isRegressionTest(); - } -} diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java index 2b047da2c4..57e4791f68 100644 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java +++ b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/RuleTst.java @@ -4,20 +4,22 @@ package net.sourceforge.pmd.testframework; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; +import java.net.URI; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import org.apache.commons.lang3.StringUtils; -import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.DynamicTest; import org.junit.jupiter.api.TestFactory; import org.xml.sax.InputSource; @@ -30,7 +32,6 @@ import net.sourceforge.pmd.RuleSet; import net.sourceforge.pmd.RuleSetLoadException; import net.sourceforge.pmd.RuleSetLoader; import net.sourceforge.pmd.RuleViolation; -import net.sourceforge.pmd.annotation.InternalApi; import net.sourceforge.pmd.lang.LanguageVersion; import net.sourceforge.pmd.lang.document.TextFile; import net.sourceforge.pmd.properties.PropertyDescriptor; @@ -63,26 +64,22 @@ public abstract class RuleTst { RuleSet parsedRset = new RuleSetLoader().warnDeprecated(false).loadFromResource(ruleSet); Rule rule = parsedRset.getRuleByName(ruleName); if (rule == null) { - Assertions.fail("Rule " + ruleName + " not found in ruleset " + ruleSet); + fail("Rule " + ruleName + " not found in ruleset " + ruleSet); } else { rule.setRuleSetName(ruleSet); } return rule; } catch (RuleSetLoadException e) { e.printStackTrace(); - Assertions.fail("Couldn't find ruleset " + ruleSet); + fail("Couldn't find ruleset " + ruleSet); return null; } } /** - * Run the rule on the given code, and check the expected number of - * violations. + * Run the rule on the given code, and check the expected number of violations. */ - @SuppressWarnings("unchecked") - @InternalApi - @Deprecated - public void runTest(TestDescriptor test) { + void runTest(RuleTestDescriptor test) { Rule rule = test.getRule(); // always reinitialize the rule, regardless of test.getReinitializeRule() (#3976 / #3302) @@ -119,11 +116,11 @@ public abstract class RuleTst { e.printStackTrace(); throw new RuntimeException('"' + test.getDescription() + "\" failed", e); } - if (test.getNumberOfProblemsExpected() != res) { + if (test.getExpectedProblems() != res) { printReport(test, report); } - Assertions.assertEquals(test.getNumberOfProblemsExpected(), res, - '"' + test.getDescription() + "\" resulted in wrong number of failures,"); + assertEquals(test.getExpectedProblems(), res, + '"' + test.getDescription() + "\" resulted in wrong number of failures,"); assertMessages(report, test); assertLineNumbers(report, test); } finally { @@ -147,7 +144,7 @@ public abstract class RuleTst { } - private void assertMessages(Report report, TestDescriptor test) { + private void assertMessages(Report report, RuleTestDescriptor test) { if (report == null || test.getExpectedMessages().isEmpty()) { return; } @@ -155,7 +152,7 @@ public abstract class RuleTst { List expectedMessages = test.getExpectedMessages(); if (report.getViolations().size() != expectedMessages.size()) { throw new RuntimeException("Test setup error: number of expected messages doesn't match " - + "number of violations for test case '" + test.getDescription() + "'"); + + "number of violations for test case '" + test.getDescription() + "'"); } int index = 0; @@ -164,13 +161,14 @@ public abstract class RuleTst { if (!expectedMessages.get(index).equals(actual)) { printReport(test, report); } - Assertions.assertEquals(expectedMessages.get(index), actual, - '"' + test.getDescription() + "\" produced wrong message on violation number " + (index + 1) + "."); + assertEquals(expectedMessages.get(index), actual, + '"' + test.getDescription() + "\" produced wrong message on violation number " + (index + 1) + + "."); index++; } } - private void assertLineNumbers(Report report, TestDescriptor test) { + private void assertLineNumbers(Report report, RuleTestDescriptor test) { if (report == null || test.getExpectedLineNumbers().isEmpty()) { return; } @@ -178,8 +176,9 @@ public abstract class RuleTst { List expected = test.getExpectedLineNumbers(); if (report.getViolations().size() != expected.size()) { throw new RuntimeException("Test setup error: number of expected line numbers " + expected.size() - + " doesn't match number of violations " + report.getViolations().size() + " for test case '" - + test.getDescription() + "'"); + + " doesn't match number of violations " + report.getViolations().size() + + " for test case '" + + test.getDescription() + "'"); } int index = 0; @@ -188,22 +187,21 @@ public abstract class RuleTst { if (expected.get(index) != actual.intValue()) { printReport(test, report); } - Assertions.assertEquals(expected.get(index), actual, - '"' + test.getDescription() + "\" violation on wrong line number: violation number " - + (index + 1) + "."); + assertEquals(expected.get(index), actual, + '"' + test.getDescription() + "\" violation on wrong line number: violation number " + + (index + 1) + "."); index++; } } - private void printReport(TestDescriptor test, Report report) { + private void printReport(RuleTestDescriptor test, Report report) { System.out.println("--------------------------------------------------------------"); System.out.println("Test Failure: " + test.getDescription()); - System.out.println(" -> Expected " + test.getNumberOfProblemsExpected() + " problem(s), " + report.getViolations().size() + System.out.println( + " -> Expected " + test.getExpectedProblems() + " problem(s), " + report.getViolations().size() + " problem(s) found."); System.out.println(" -> Expected messages: " + test.getExpectedMessages()); System.out.println(" -> Expected line numbers: " + test.getExpectedLineNumbers()); - System.out.println("Test Method Name: " + test.getTestMethodName()); - System.out.println(" @org.junit.Test public void " + test.getTestMethodName() + "() {}"); System.out.println(); TextRenderer renderer = new TextRenderer(); renderer.setWriter(new StringWriter()); @@ -218,23 +216,14 @@ public abstract class RuleTst { System.out.println("--------------------------------------------------------------"); } - private Report processUsingStringReader(TestDescriptor test, Rule rule) { + private Report processUsingStringReader(RuleTestDescriptor test, Rule rule) { return runTestFromString(test.getCode(), rule, test.getLanguageVersion()); } /** * Run the rule on the given code and put the violations in the report. */ - @InternalApi - @Deprecated - public Report runTestFromString(String code, Rule rule, LanguageVersion languageVersion) { - return runTestFromString(code, rule, languageVersion, true); - } - - @InternalApi - @Deprecated - public Report runTestFromString(String code, Rule rule, LanguageVersion languageVersion, - boolean isUseAuxClasspath) { + Report runTestFromString(String code, Rule rule, LanguageVersion languageVersion) { PMDConfiguration configuration = new PMDConfiguration(); configuration.setIgnoreIncrementalAnalysis(true); configuration.setDefaultLanguageVersion(languageVersion); @@ -249,19 +238,11 @@ public abstract class RuleTst { } } - @InternalApi - @Deprecated - public Report runTestFromString(TestDescriptor test, Rule rule) { - return runTestFromString(test.getCode(), rule, test.getLanguageVersion(), test.isUseAuxClasspath()); - } - /** * getResourceAsStream tries to find the XML file in weird locations if the * ruleName includes the package, so we strip it here. */ - @InternalApi - @Deprecated - protected String getCleanRuleName(Rule rule) { + private String getCleanRuleName(Rule rule) { String fullClassName = rule.getClass().getName(); if (fullClassName.equals(rule.getName())) { // We got the full class name, so we'll use the stripped name @@ -273,19 +254,6 @@ public abstract class RuleTst { } } - /** - * Extract a set of tests from an XML file. The file should be - * ./xml/RuleName.xml relative to the test class. The format is defined in - * test-data.xsd. - */ - @InternalApi - @Deprecated - public TestDescriptor[] extractTestsFromXml(Rule rule) { - String testsFileName = getCleanRuleName(rule); - - return extractTestsFromXml(rule, testsFileName); - } - /** * Extract a set of tests from an XML file. The file should be * ./xml/RuleName.xml relative to the test class. The format is defined in @@ -293,35 +261,13 @@ public abstract class RuleTst { */ RuleTestCollection parseTestCollection(Rule rule) { String testsFileName = getCleanRuleName(rule); + return parseTestCollection(rule, testsFileName); + } + + private RuleTestCollection parseTestCollection(Rule rule, String testsFileName) { return parseTestXml(rule, testsFileName, "xml/"); } - @InternalApi - @Deprecated - public TestDescriptor[] extractTestsFromXml(Rule rule, String testsFileName) { - return extractTestsFromXml(rule, testsFileName, "xml/"); - } - - /** - * Extract a set of tests from an XML file with the given name. The file - * should be ./xml/[testsFileName].xml relative to the test class. The - * format is defined in test-data.xsd. - */ - @InternalApi - @Deprecated - public TestDescriptor[] extractTestsFromXml(Rule rule, String testsFileName, String baseDirectory) { - RuleTestCollection collection = parseTestXml(rule, testsFileName, baseDirectory); - return toLegacyArray(collection); - } - - private TestDescriptor[] toLegacyArray(RuleTestCollection collection) { - TestDescriptor[] result = new TestDescriptor[collection.getTests().size()]; - for (int i = 0; i < collection.getTests().size(); i++) { - result[i] = new TestDescriptor(collection.getTests().get(i), collection.getAbsoluteUriToTestXmlFile()); - } - return result; - } - /** * Extract a set of tests from an XML file with the given name. The file * should be ./xml/[testsFileName].xml relative to the test class. The @@ -355,7 +301,7 @@ public abstract class RuleTst { * defined in test-data.xsd. */ public void runTests(Rule rule) { - runTests(extractTestsFromXml(rule)); + runTests(parseTestCollection(rule)); } /** @@ -364,16 +310,11 @@ public abstract class RuleTst { * defined in test-data.xsd. */ public void runTests(Rule rule, String testsFileName) { - runTests(extractTestsFromXml(rule, testsFileName)); + runTests(parseTestCollection(rule, testsFileName)); } - /** - * Run a set of tests of a certain sourceType. - */ - @InternalApi - @Deprecated - public void runTests(TestDescriptor[] tests) { - for (TestDescriptor test : tests) { + private void runTests(RuleTestCollection tests) { + for (RuleTestDescriptor test : tests.getTests()) { runTest(test); } } @@ -384,34 +325,30 @@ public abstract class RuleTst { final List rules = new ArrayList<>(getRules()); rules.sort(Comparator.comparing(Rule::getName)); - List tests = new ArrayList<>(); + List tests = new ArrayList<>(); for (Rule r : rules) { RuleTestCollection ruleTests = parseTestCollection(r); RuleTestDescriptor focused = ruleTests.getFocusedTestOrNull(); for (RuleTestDescriptor t : ruleTests.getTests()) { - TestDescriptor td = new TestDescriptor(t, ruleTests.getAbsoluteUriToTestXmlFile()); if (focused != null && !focused.equals(t)) { - td.setRegressionTest(false); // disable it + t.setDisabled(true); // disable it } - tests.add(td); + tests.add(toDynamicTest(ruleTests, t)); } } - - return tests.stream().map(this::toDynamicTest).collect(Collectors.toList()); + return tests; } - private DynamicTest toDynamicTest(TestDescriptor testDescriptor) { - if (isIgnored(testDescriptor)) { - return DynamicTest.dynamicTest("[IGNORED] " + testDescriptor.getTestMethodName(), - testDescriptor.getTestSourceUri(), - () -> {}); + private DynamicTest toDynamicTest(RuleTestCollection collection, RuleTestDescriptor testDescriptor) { + URI testSourceUri = URI.create( + collection.getAbsoluteUriToTestXmlFile() + "?line=" + testDescriptor.getLineNumber()); + if (testDescriptor.isDisabled()) { + return DynamicTest.dynamicTest("[IGNORED] " + testDescriptor.getDescription(), + testSourceUri, + () -> { }); } - return DynamicTest.dynamicTest(testDescriptor.getTestMethodName(), - testDescriptor.getTestSourceUri(), - () -> runTest(testDescriptor)); - } - - private static boolean isIgnored(TestDescriptor testDescriptor) { - return TestDescriptor.inRegressionTestMode() && !testDescriptor.isRegressionTest(); + return DynamicTest.dynamicTest(testDescriptor.getDescription(), + testSourceUri, + () -> runTest(testDescriptor)); } } diff --git a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/TestDescriptor.java b/pmd-test/src/main/java/net/sourceforge/pmd/testframework/TestDescriptor.java deleted file mode 100644 index 3982199f89..0000000000 --- a/pmd-test/src/main/java/net/sourceforge/pmd/testframework/TestDescriptor.java +++ /dev/null @@ -1,197 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.testframework; - -import java.net.URI; -import java.util.ArrayList; -import java.util.List; -import java.util.Properties; - -import org.junit.Ignore; - -import net.sourceforge.pmd.Rule; -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.test.schema.RuleTestDescriptor; - -/** - * Stores the information required to run a complete test. - * - * @deprecated Use {@link RuleTestDescriptor} instead - */ -@Ignore("this is not a unit test") -@Deprecated -public class TestDescriptor { - private Rule rule; - private Properties properties; - private String description; - private int numberOfProblemsExpected; - private List expectedMessages = new ArrayList<>(); - private List expectedLineNumbers = new ArrayList<>(); - private String code; - private LanguageVersion languageVersion; - // default, avoids unintentional mixing of state between test cases - private boolean reinitializeRule = true; - private boolean isRegressionTest = true; - private boolean useAuxClasspath = true; - private int numberInDocument = -1; - - private URI testSourceUri; - - public TestDescriptor() { - // Empty default descriptor added to please mvn surefire plugin - } - - public TestDescriptor(String code, String description, int numberOfProblemsExpected, Rule rule) { - this(code, description, numberOfProblemsExpected, rule, rule.getLanguage().getDefaultVersion()); - } - - public TestDescriptor(String code, String description, int numberOfProblemsExpected, Rule rule, - LanguageVersion languageVersion) { - this.rule = rule; - this.code = code; - this.description = description; - this.numberOfProblemsExpected = numberOfProblemsExpected; - this.languageVersion = languageVersion; - } - - // for compatibility - TestDescriptor(RuleTestDescriptor td, String absoluteUriToTestXmlFile) { - this.rule = td.getRule(); - this.code = td.getCode(); - this.description = td.getDescription(); - this.numberOfProblemsExpected = td.getExpectedProblems(); - this.expectedLineNumbers = td.getExpectedLineNumbers(); - this.expectedMessages = td.getExpectedMessages(); - this.isRegressionTest = !td.isDisabled(); - this.numberInDocument = td.getIndex(); - this.properties = td.getProperties(); - this.languageVersion = td.getLanguageVersion(); - this.numberInDocument = td.getIndex(); - this.setTestSourceUri(absoluteUriToTestXmlFile, td.getLineNumber()); - } - - public int getNumberInDocument() { - return numberInDocument; - } - - public void setNumberInDocument(int numberInDocument) { - this.numberInDocument = numberInDocument; - } - - public void setExpectedMessages(List messages) { - expectedMessages.clear(); - expectedMessages.addAll(messages); - } - - public List getExpectedMessages() { - return expectedMessages; - } - - public void setExpectedLineNumbers(List expectedLineNumbers) { - this.expectedLineNumbers.clear(); - this.expectedLineNumbers.addAll(expectedLineNumbers); - } - - public List getExpectedLineNumbers() { - return expectedLineNumbers; - } - - public void setProperties(Properties properties) { - this.properties = properties; - } - - public Properties getProperties() { - return properties; - } - - public String getCode() { - return code; - } - - public LanguageVersion getLanguageVersion() { - return languageVersion; - } - - public String getDescription() { - return description; - } - - public int getNumberOfProblemsExpected() { - return numberOfProblemsExpected; - } - - public Rule getRule() { - return rule; - } - - public boolean getReinitializeRule() { - return reinitializeRule; - } - - public void setReinitializeRule(boolean reinitializeRule) { - this.reinitializeRule = reinitializeRule; - } - - /** - * Checks whether we are testing for regression problems only. Return value - * is based on the system property "pmd.regress". - * - * @return false if system property "pmd.regress" is set to - * false, true otherwise - */ - public static boolean inRegressionTestMode() { - boolean inRegressionMode = true; // default - try { - // get the "pmd.regress" System property - String property = System.getProperty("pmd.regress"); - if (property != null) { - inRegressionMode = Boolean.parseBoolean(property); - } - } catch (IllegalArgumentException e) { - throw new RuntimeException("Invalid system property 'pmd.regress'", e); - } - - return inRegressionMode; - } - - public boolean isRegressionTest() { - return isRegressionTest; - } - - public void setRegressionTest(boolean isRegressionTest) { - this.isRegressionTest = isRegressionTest; - } - - public void setUseAuxClasspath(boolean useAuxClasspath) { - this.useAuxClasspath = useAuxClasspath; - } - - public boolean isUseAuxClasspath() { - return useAuxClasspath; - } - - @Override - public String toString() { - return description + "\n\n" + code; - } - - public String getTestMethodName() { - return getRule().getName() + "_" - + getNumberInDocument() - + "_" - + getDescription() - .replaceAll("\n|\r", "_") - .replaceAll("[^\\w\\d_$]", "_") - .replaceAll("\\s+", "_"); - } - - public void setTestSourceUri(String absoluteUri, int line) { - this.testSourceUri = URI.create(absoluteUri + "?line=" + line); - } - - public URI getTestSourceUri() { - return testSourceUri; - } -} diff --git a/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java b/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java index ed2d903ad7..ec4f67197b 100644 --- a/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java +++ b/pmd-test/src/test/java/net/sourceforge/pmd/testframework/RuleTstTest.java @@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.Arrays; +import java.util.Collections; import org.junit.jupiter.api.Test; import org.mockito.Mockito; @@ -24,8 +25,9 @@ import net.sourceforge.pmd.lang.document.TextRegion; import net.sourceforge.pmd.lang.rule.RuleTargetSelector; import net.sourceforge.pmd.test.lang.DummyLanguageModule; import net.sourceforge.pmd.test.lang.DummyLanguageModule.DummyRootNode; +import net.sourceforge.pmd.test.schema.RuleTestDescriptor; -public class RuleTstTest { +class RuleTstTest { private LanguageVersion dummyLanguage = DummyLanguageModule.getInstance().getDefaultVersion(); private Rule rule = mock(Rule.class); @@ -38,13 +40,13 @@ public class RuleTstTest { }; @Test - public void shouldCallStartAndEnd() { + void shouldCallStartAndEnd() { when(rule.getLanguage()).thenReturn(dummyLanguage.getLanguage()); when(rule.getName()).thenReturn("test rule"); when(rule.getTargetSelector()).thenReturn(RuleTargetSelector.forRootOnly()); when(rule.deepCopy()).thenReturn(rule); - ruleTester.runTestFromString("the code", rule, dummyLanguage, false); + ruleTester.runTestFromString("the code", rule, dummyLanguage); verify(rule).initialize(any(LanguageProcessor.class)); verify(rule).start(any(RuleContext.class)); @@ -59,7 +61,7 @@ public class RuleTstTest { } @Test - public void shouldAssertLinenumbersSorted() { + void shouldAssertLinenumbersSorted() { when(rule.getLanguage()).thenReturn(dummyLanguage.getLanguage()); when(rule.getName()).thenReturn("test rule"); when(rule.getMessage()).thenReturn("test rule"); @@ -79,9 +81,11 @@ public class RuleTstTest { return null; }).when(rule).apply(any(Node.class), Mockito.any(RuleContext.class)); - TestDescriptor testDescriptor = new TestDescriptor(code, "sample test", 2, rule, dummyLanguage); - testDescriptor.setReinitializeRule(false); - testDescriptor.setExpectedLineNumbers(Arrays.asList(1, 2)); + RuleTestDescriptor testDescriptor = new RuleTestDescriptor(0, rule); + testDescriptor.setLanguageVersion(dummyLanguage); + testDescriptor.setCode(code); + testDescriptor.setDescription("sample test"); + testDescriptor.recordExpectedViolations(2, Arrays.asList(1, 2), Collections.emptyList()); ruleTester.runTest(testDescriptor); } diff --git a/pmd-test/src/test/java/net/sourceforge/pmd/testframework/TestDescriptorTest.java b/pmd-test/src/test/java/net/sourceforge/pmd/testframework/TestDescriptorTest.java deleted file mode 100644 index d28756274c..0000000000 --- a/pmd-test/src/test/java/net/sourceforge/pmd/testframework/TestDescriptorTest.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd.testframework; - -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.Test; - -import net.sourceforge.pmd.RuleContext; -import net.sourceforge.pmd.lang.Language; -import net.sourceforge.pmd.lang.PlainTextLanguage; -import net.sourceforge.pmd.lang.ast.Node; -import net.sourceforge.pmd.lang.rule.AbstractRule; - -public class TestDescriptorTest { - @Test - public void testMethodName() { - Assertions.assertEquals("MockRule_1_Name", create("Name")); - Assertions.assertEquals("MockRule_1_Tests_xyz", create("Tests xyz")); - Assertions.assertEquals("MockRule_1_Tests_xyz__false_positive_", create("Tests xyz (false positive)")); - Assertions.assertEquals("MockRule_1_Tests_xyz__123", create("Tests xyz #123")); - } - - private String create(String description) { - TestDescriptor descriptor = new TestDescriptor("foo", description, 0, - new MockRule()); - descriptor.setNumberInDocument(1); - return descriptor.getTestMethodName(); - } - - private static final class MockRule extends AbstractRule { - @Override - public Language getLanguage() { - return PlainTextLanguage.getInstance(); - } - - @Override - public String getName() { - return "MockRule"; - } - - @Override - public void apply(Node target, RuleContext ctx) { - } - } -} diff --git a/pmd-visualforce/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-visualforce/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index 571a6ecb7b..0000000000 --- a/pmd-visualforce/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.vf.VfLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { { VfLanguageModule.NAME, VfLanguageModule.TERSE_NAME, "", - getLanguage(VfLanguageModule.NAME).getDefaultVersion(), }, }); - } -} diff --git a/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/LanguageVersionTest.java b/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/LanguageVersionTest.java new file mode 100644 index 0000000000..141d62ed8c --- /dev/null +++ b/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.vf; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(VfLanguageModule.NAME, VfLanguageModule.TERSE_NAME, "", + getLanguage(VfLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/RuleSetFactoryTest.java b/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/RuleSetFactoryTest.java index 3ffadc6a4a..0caab8239d 100644 --- a/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/RuleSetFactoryTest.java +++ b/pmd-visualforce/src/test/java/net/sourceforge/pmd/lang/vf/RuleSetFactoryTest.java @@ -7,8 +7,10 @@ package net.sourceforge.pmd.lang.vf; import net.sourceforge.pmd.AbstractRuleSetFactoryTest; import net.sourceforge.pmd.lang.apex.ApexLanguageModule; -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { - public RuleSetFactoryTest() { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { + RuleSetFactoryTest() { super(ApexLanguageModule.TERSE_NAME); } + + // no additional tests yet } diff --git a/pmd-vm/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-vm/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index 3b98787be2..0000000000 --- a/pmd-vm/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.vm.VmLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { { VmLanguageModule.NAME, VmLanguageModule.TERSE_NAME, "", - getLanguage(VmLanguageModule.NAME).getDefaultVersion(), }, }); - } -} diff --git a/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/LanguageVersionTest.java b/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/LanguageVersionTest.java new file mode 100644 index 0000000000..2e5645fc11 --- /dev/null +++ b/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/LanguageVersionTest.java @@ -0,0 +1,18 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.vm; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList(new TestDescriptor(VmLanguageModule.NAME, VmLanguageModule.TERSE_NAME, "", + getLanguage(VmLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-vm/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/RuleSetFactoryTest.java similarity index 50% rename from pmd-vm/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java rename to pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/RuleSetFactoryTest.java index e0ae0ae307..75037cd663 100644 --- a/pmd-vm/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ b/pmd-vm/src/test/java/net/sourceforge/pmd/lang/vm/RuleSetFactoryTest.java @@ -2,11 +2,13 @@ * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ -package net.sourceforge.pmd; +package net.sourceforge.pmd.lang.vm; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; /** * Test velocity's rulesets. */ -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { // no additional tests yet } diff --git a/pmd-xml/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java b/pmd-xml/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java deleted file mode 100644 index f81d9dfc05..0000000000 --- a/pmd-xml/src/test/java/net/sourceforge/pmd/LanguageVersionTest.java +++ /dev/null @@ -1,36 +0,0 @@ -/** - * BSD-style license; for more info see http://pmd.sourceforge.net/license.html - */ - -package net.sourceforge.pmd; - -import java.util.Arrays; -import java.util.Collection; - -import org.junit.runners.Parameterized.Parameters; - -import net.sourceforge.pmd.lang.LanguageVersion; -import net.sourceforge.pmd.lang.pom.PomLanguageModule; -import net.sourceforge.pmd.lang.wsdl.WsdlLanguageModule; -import net.sourceforge.pmd.lang.xml.XmlLanguageModule; -import net.sourceforge.pmd.lang.xsl.XslLanguageModule; - -public class LanguageVersionTest extends AbstractLanguageVersionTest { - - public LanguageVersionTest(String name, String terseName, String version, LanguageVersion expected) { - super(name, terseName, version, expected); - } - - @Parameters - public static Collection data() { - return Arrays.asList(new Object[][] { - { XmlLanguageModule.NAME, XmlLanguageModule.TERSE_NAME, "", - getLanguage(XmlLanguageModule.NAME).getDefaultVersion(), }, - { XslLanguageModule.NAME, XslLanguageModule.TERSE_NAME, "", - getLanguage(XslLanguageModule.NAME).getDefaultVersion(), }, - { WsdlLanguageModule.NAME, WsdlLanguageModule.TERSE_NAME, "", - getLanguage(WsdlLanguageModule.NAME).getDefaultVersion(), }, - { PomLanguageModule.NAME, PomLanguageModule.TERSE_NAME, "", - getLanguage(PomLanguageModule.NAME).getDefaultVersion(), }, }); - } -} diff --git a/pmd-xml/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java b/pmd-xml/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java index 15955b0565..3f185454c6 100644 --- a/pmd-xml/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java +++ b/pmd-xml/src/test/java/net/sourceforge/pmd/ant/PMDTaskTest.java @@ -4,16 +4,16 @@ package net.sourceforge.pmd.ant; -import org.junit.Test; +import org.junit.jupiter.api.Test; -public class PMDTaskTest extends AbstractAntTestHelper { +class PMDTaskTest extends AbstractAntTestHelper { - public PMDTaskTest() { + PMDTaskTest() { super.antTestScriptFilename = "pmdtasktest.xml"; } @Test - public void testXML() { + void testXML() { executeTarget("testXML"); assertOutputContaining("Potentially mistyped CDATA section with extra [ at beginning or ] at the end."); } diff --git a/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/LanguageVersionTest.java b/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/LanguageVersionTest.java new file mode 100644 index 0000000000..4e4816f7fb --- /dev/null +++ b/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/LanguageVersionTest.java @@ -0,0 +1,28 @@ +/** + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.lang.xml; + +import java.util.Arrays; +import java.util.Collection; + +import net.sourceforge.pmd.AbstractLanguageVersionTest; +import net.sourceforge.pmd.lang.pom.PomLanguageModule; +import net.sourceforge.pmd.lang.wsdl.WsdlLanguageModule; +import net.sourceforge.pmd.lang.xsl.XslLanguageModule; + +class LanguageVersionTest extends AbstractLanguageVersionTest { + + static Collection data() { + return Arrays.asList( + new TestDescriptor(XmlLanguageModule.NAME, XmlLanguageModule.TERSE_NAME, "", + getLanguage(XmlLanguageModule.NAME).getDefaultVersion()), + new TestDescriptor(XslLanguageModule.NAME, XslLanguageModule.TERSE_NAME, "", + getLanguage(XslLanguageModule.NAME).getDefaultVersion()), + new TestDescriptor(WsdlLanguageModule.NAME, WsdlLanguageModule.TERSE_NAME, "", + getLanguage(WsdlLanguageModule.NAME).getDefaultVersion()), + new TestDescriptor(PomLanguageModule.NAME, PomLanguageModule.TERSE_NAME, "", + getLanguage(PomLanguageModule.NAME).getDefaultVersion())); + } +} diff --git a/pmd-xml/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java b/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/RuleSetFactoryTest.java similarity index 51% rename from pmd-xml/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java rename to pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/RuleSetFactoryTest.java index 06fb8eccbc..b2c4b70e68 100644 --- a/pmd-xml/src/test/java/net/sourceforge/pmd/RuleSetFactoryTest.java +++ b/pmd-xml/src/test/java/net/sourceforge/pmd/lang/xml/RuleSetFactoryTest.java @@ -2,11 +2,13 @@ * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ -package net.sourceforge.pmd; +package net.sourceforge.pmd.lang.xml; + +import net.sourceforge.pmd.AbstractRuleSetFactoryTest; /** * Test xml's and xslt's rulesets */ -public class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { +class RuleSetFactoryTest extends AbstractRuleSetFactoryTest { // no additional tests yet } diff --git a/pom.xml b/pom.xml index f5d32ea8d8..578017d023 100644 --- a/pom.xml +++ b/pom.xml @@ -297,24 +297,6 @@ - - - org.junit.vintage - junit-vintage-engine - ${junit5.version} - - - - org.junit.jupiter - junit-jupiter-engine - ${junit5.version} - - - - io.kotest - kotest-runner-junit5-jvm - ${kotest.version} - net.sourceforge.pmd pmd-build-tools-config @@ -415,12 +397,28 @@ ${pmd.plugin.version} + pmd-main verify check cpd-check + + pmd-test + verify + + pmd + check + + + ${project.build.directory}/pmdTest/ + true + + /net/sourceforge/pmd/pmd-test-dogfood-config.xml + + + true @@ -719,11 +717,6 @@ ant ${ant.version} - - org.apache.ant - ant-testutil - ${ant.version} - com.beust jcommander @@ -904,12 +897,6 @@ - - pl.pragmatists - JUnitParams - 1.1.1 - test - org.mockito @@ -962,12 +949,24 @@ kotlin-test-junit ${kotlin.version} test + + + junit + junit + + io.kotest kotest-runner-junit5-jvm ${kotest.version} test + + + junit + junit + + io.kotest