Merge branch 'pmd7-junit5' into 7.0.x

This commit is contained in:
Clément Fournier committed 2022-07-16 17:08:15 +02:00
commit 942c8f045d
129 files changed
+3060 -2886

No files matched your search

+5
View File
@@ -77,6 +77,11 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-rules</artifactId>
+13 -8
View File
@@ -130,7 +130,7 @@
</dependency>
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock</artifactId>
<artifactId>wiremock-jre8</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -139,8 +139,13 @@
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.platform</groupId>
<artifactId>junit-platform-suite</artifactId>
<scope>test</scope>
</dependency>
<dependency>
@@ -148,11 +153,6 @@
<artifactId>JUnitParams</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-testutil</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
@@ -163,6 +163,11 @@
<artifactId>system-rules</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.github.stefanbirkner</groupId>
<artifactId>system-lambda</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>me.tongfei</groupId>
<artifactId>progressbar</artifactId>
@@ -9,9 +9,11 @@ import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.DESCRIPTION;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.EXCLUDE;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.EXCLUDE_PATTERN;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.INCLUDE_PATTERN;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.NAME;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.PRIORITY;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.REF;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.RULE;
import static net.sourceforge.pmd.util.internal.xml.SchemaConstants.RULESET;
import java.io.IOException;
import java.io.InputStream;
@@ -38,6 +40,7 @@ import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
@@ -47,10 +50,10 @@ import net.sourceforge.pmd.rules.RuleFactory;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.StringUtil;
import net.sourceforge.pmd.util.internal.xml.PmdXmlReporter;
import net.sourceforge.pmd.util.internal.xml.SchemaConstants;
import net.sourceforge.pmd.util.internal.xml.XmlErrorMessages;
import net.sourceforge.pmd.util.internal.xml.XmlUtil;
import net.sourceforge.pmd.util.log.MessageReporter;
import net.sourceforge.pmd.util.log.internal.NoopReporter;
import com.github.oowekyala.ooxml.DomUtils;
import com.github.oowekyala.ooxml.messages.NiceXmlMessageSpec;
@@ -242,7 +245,7 @@ final class RuleSetFactory {
} else {
err.at(node).error(XmlErrorMessages.ERR__UNEXPECTED_ELEMENT_IN,
node.getTagName(),
SchemaConstants.RULESET);
RULESET);
}
}
@@ -322,9 +325,9 @@ final class RuleSetFactory {
boolean withDeprecatedRuleReferences,
Set<String> rulesetReferences,
PmdXmlReporter err) {
if (ruleNode.hasAttribute("ref")) {
String ref = ruleNode.getAttribute("ref");
RuleSetReferenceId refId = parseReferenceAndWarn(ruleSetBuilder, ref);
if (REF.hasAttribute(ruleNode)) {
String ref = REF.getAttributeOrThrow(ruleNode, err);
RuleSetReferenceId refId = parseReferenceAndWarn(ref, REF.getAttributeNode(ruleNode), err);
if (refId != null) {
if (refId.isAllRules()) {
parseRuleSetReferenceNode(ruleSetBuilder, ruleNode, ref, refId, rulesetReferences, err);
@@ -362,7 +365,7 @@ final class RuleSetFactory {
if (EXCLUDE.matchesElt(child)) {
String excludedRuleName;
try {
excludedRuleName = SchemaConstants.NAME.getAttributeOrThrow(child, err);
excludedRuleName = NAME.getAttributeOrThrow(child, err);
} catch (XmlException ignored) {
// has been reported
continue;
@@ -431,19 +434,23 @@ final class RuleSetFactory {
rulesetReferences.add(ref);
}
private RuleSetReferenceId parseReferenceAndWarn(RuleSetBuilder ruleSetBuilder, String ref) {
private RuleSetReferenceId parseReferenceAndWarn(String ref,
Node xmlPlace,
PmdXmlReporter err) {
ref = compatibilityFilter.applyRef(ref, this.warnDeprecated);
if (ref == null) {
LOG.debug("Rule ref {} references a deleted rule, ignoring", ref);
err.at(xmlPlace).warn("Rule reference references a deleted rule, ignoring");
return null; // deleted rule
}
// only emit a warning if we check for deprecated syntax
MessageReporter subReporter = warnDeprecated ? err.at(xmlPlace) : new NoopReporter();
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(ref, warnDeprecated);
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(ref, subReporter);
if (references.size() > 1 && warnDeprecated) {
LOG.warn("Using a comma separated list as a ref attribute is deprecated. "
+ "All references but the first are ignored. Reference: '{}'", ref);
err.at(xmlPlace).warn("Using a comma separated list as a ref attribute is deprecated. "
+ "All references but the first are ignored.");
} else if (references.isEmpty()) {
LOG.warn("Empty ref attribute in ruleset '{}'", ruleSetBuilder.getName());
err.at(xmlPlace).warn("Empty ref attribute");
return null;
}
return references.get(0);
@@ -518,11 +525,11 @@ final class RuleSetFactory {
boolean isSameRuleSet = false;
if (!otherRuleSetReferenceId.isExternal()
&& containsRule(ruleSetReferenceId, otherRuleSetReferenceId.getRuleName())) {
otherRuleSetReferenceId = new RuleSetReferenceId(ref, ruleSetReferenceId);
otherRuleSetReferenceId = new RuleSetReferenceId(ref, ruleSetReferenceId, err.at(REF.getAttributeNode(ruleNode)));
isSameRuleSet = true;
} else if (otherRuleSetReferenceId.isExternal()
&& otherRuleSetReferenceId.getRuleSetFileName().equals(ruleSetReferenceId.getRuleSetFileName())) {
otherRuleSetReferenceId = new RuleSetReferenceId(otherRuleSetReferenceId.getRuleName(), ruleSetReferenceId);
otherRuleSetReferenceId = new RuleSetReferenceId(otherRuleSetReferenceId.getRuleName(), ruleSetReferenceId, err.at(REF.getAttributeNode(ruleNode)));
isSameRuleSet = true;
}
// do not ignore deprecated rule references
@@ -16,6 +16,7 @@ import java.util.Properties;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -144,6 +145,9 @@ public final class RuleSetLoader {
);
}
private @Nullable MessageReporter filteredReporter() {
return warnDeprecated ? reporter : null;
}
/**
* Parses and returns a ruleset from its location. The location may
@@ -154,7 +158,7 @@ public final class RuleSetLoader {
* @throws RuleSetLoadException If any error occurs (eg, invalid syntax, or resource not found)
*/
public RuleSet loadFromResource(String rulesetPath) {
return loadFromResource(new RuleSetReferenceId(rulesetPath, null, warnDeprecated));
return loadFromResource(new RuleSetReferenceId(rulesetPath, null, filteredReporter()));
}
/**
@@ -166,7 +170,7 @@ public final class RuleSetLoader {
* @throws RuleSetLoadException If any error occurs (eg, invalid syntax)
*/
public RuleSet loadFromString(String filename, final String rulesetXmlContent) {
return loadFromResource(new RuleSetReferenceId(filename, null, warnDeprecated) {
return loadFromResource(new RuleSetReferenceId(filename, null, filteredReporter()) {
@Override
public InputStream getInputStream(ResourceLoader rl) {
return new ByteArrayInputStream(rulesetXmlContent.getBytes(StandardCharsets.UTF_8));
@@ -16,11 +16,10 @@ import java.util.Objects;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import net.sourceforge.pmd.annotation.InternalApi;
import net.sourceforge.pmd.util.ResourceLoader;
import net.sourceforge.pmd.util.log.MessageReporter;
/**
* This class is used to parse a RuleSet reference value. Most commonly used for
@@ -84,9 +83,6 @@ public class RuleSetReferenceId {
// todo this class has issues... What is even an "external" ruleset?
// terminology and API should be clarified.
// use the logger of RuleSetFactory, because the warnings conceptually come from there.
private static final Logger LOG = LoggerFactory.getLogger(RuleSetFactory.class);
private final boolean external;
private final String ruleSetFileName;
private final boolean allRules;
@@ -105,7 +101,7 @@ public class RuleSetReferenceId {
*/
public RuleSetReferenceId(final String id) {
this(id, null);
this(id, null, null);
}
private RuleSetReferenceId(final String ruleSetFileName, boolean external, String ruleName, RuleSetReferenceId externalRuleSetReferenceId) {
@@ -132,7 +128,7 @@ public class RuleSetReferenceId {
* RuleSetReferenceId.
*/
public RuleSetReferenceId(final String id, final RuleSetReferenceId externalRuleSetReferenceId) {
this(id, externalRuleSetReferenceId, false);
this(id, externalRuleSetReferenceId, null);
}
/**
@@ -149,7 +145,9 @@ public class RuleSetReferenceId {
* @throws IllegalArgumentException If the ID is not Rule reference when there is an external
* RuleSetReferenceId.
*/
RuleSetReferenceId(final String id, final RuleSetReferenceId externalRuleSetReferenceId, boolean warnDeprecated) {
RuleSetReferenceId(final String id,
final RuleSetReferenceId externalRuleSetReferenceId,
final @Nullable MessageReporter err) {
this.originalRef = id;
if (externalRuleSetReferenceId != null && !externalRuleSetReferenceId.isExternal()) {
@@ -179,7 +177,7 @@ public class RuleSetReferenceId {
} else {
String tempRuleName = getRuleName(id);
String tempRuleSetFileName = tempRuleName != null && id != null
? id.substring(0, id.length() - tempRuleName.length() - 1) : id;
? id.substring(0, id.length() - tempRuleName.length() - 1) : id;
if (isValidUrl(tempRuleSetFileName)) {
// remaining part is a xml ruleset file, so the tempRuleName is
@@ -208,9 +206,9 @@ public class RuleSetReferenceId {
String expandedRuleset = resolveDeprecatedBuiltInRulesetShorthand(tempRuleSetFileName);
String builtinRuleSet = expandedRuleset == null ? tempRuleSetFileName : expandedRuleset;
if (checkRulesetExists(builtinRuleSet)) {
if (expandedRuleset != null && warnDeprecated) {
LOG.warn(
"Ruleset reference '{}' uses a deprecated form, use '{}' instead",
if (expandedRuleset != null && err != null) {
err.warn(
"Ruleset reference ''{0}'' uses a deprecated form, use ''{1}'' instead",
tempRuleSetFileName, builtinRuleSet
);
}
@@ -376,27 +374,21 @@ public class RuleSetReferenceId {
*
* @return The corresponding List of RuleSetReferenceId instances.
*/
// TODO deprecate and remove
public static List<RuleSetReferenceId> parse(String referenceString) {
return parse(referenceString, false);
return parse(referenceString, null);
}
/**
* Parse a String comma separated list of RuleSet reference IDs into a List
* of RuleReferenceId instances.
*
* @param referenceString A comma separated list of RuleSet reference IDs.
*
* @return The corresponding List of RuleSetReferenceId instances.
*/
public static List<RuleSetReferenceId> parse(String referenceString, boolean warnDeprecated) {
static List<RuleSetReferenceId> parse(String referenceString,
MessageReporter err) {
List<RuleSetReferenceId> references = new ArrayList<>();
if (referenceString != null && referenceString.trim().length() > 0) {
if (referenceString.indexOf(',') == -1) {
references.add(new RuleSetReferenceId(referenceString, null, warnDeprecated));
references.add(new RuleSetReferenceId(referenceString, null, err));
} else {
for (String name : referenceString.split(",")) {
references.add(new RuleSetReferenceId(name.trim(), null, warnDeprecated));
references.add(new RuleSetReferenceId(name.trim(), null, err));
}
}
}
@@ -407,7 +399,7 @@ public class RuleSetReferenceId {
* Is this an external RuleSet reference?
*
* @return <code>true</code> if this is an external reference,
* <code>false</code> otherwise.
* <code>false</code> otherwise.
*/
public boolean isExternal() {
return external;
@@ -5,13 +5,13 @@
package net.sourceforge.pmd;
import static net.sourceforge.pmd.properties.constraints.NumericConstraints.inRange;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Collections;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.Report.SuppressedViolation;
import net.sourceforge.pmd.lang.ast.DummyNode;
@@ -67,33 +67,33 @@ public class AbstractRuleTest {
}
@Test
public void testCreateRV() {
void testCreateRV() {
MyRule r = new MyRule();
r.setRuleSetName("foo");
DummyNode s = new DummyRootNode().withFileName("filename");
s.setCoords(5, 5, 5, 10);
RuleViolation rv = new ParametricRuleViolation<>(r, s, r.getMessage());
assertEquals("Line number mismatch!", 5, rv.getBeginLine());
assertEquals("Filename mismatch!", "filename", rv.getFilename());
assertEquals("Rule object mismatch!", r, rv.getRule());
assertEquals("Rule msg mismatch!", "my rule msg", rv.getDescription());
assertEquals("RuleSet name mismatch!", "foo", rv.getRule().getRuleSetName());
assertEquals(5, rv.getBeginLine(), "Line number mismatch!");
assertEquals("filename", rv.getFilename(), "Filename mismatch!");
assertEquals(r, rv.getRule(), "Rule object mismatch!");
assertEquals("my rule msg", rv.getDescription(), "Rule msg mismatch!");
assertEquals("foo", rv.getRule().getRuleSetName(), "RuleSet name mismatch!");
}
@Test
public void testCreateRV2() {
void testCreateRV2() {
MyRule r = new MyRule();
DummyNode s = new DummyRootNode().withFileName("filename");
s.setCoords(5, 5, 5, 10);
RuleViolation rv = new ParametricRuleViolation<>(r, s, "specificdescription");
assertEquals("Line number mismatch!", 5, rv.getBeginLine());
assertEquals("Filename mismatch!", "filename", rv.getFilename());
assertEquals("Rule object mismatch!", r, rv.getRule());
assertEquals("Rule description mismatch!", "specificdescription", rv.getDescription());
assertEquals(5, rv.getBeginLine(), "Line number mismatch!");
assertEquals("filename", rv.getFilename(), "Filename mismatch!");
assertEquals(r, rv.getRule(), "Rule object mismatch!");
assertEquals("specificdescription", rv.getDescription(), "Rule description mismatch!");
}
@Test
public void testRuleWithVariableInMessage() throws Exception {
void testRuleWithVariableInMessage() throws Exception {
MyRule r = new MyRule() {
@Override
public void apply(Node target, RuleContext ctx) {
@@ -112,7 +112,7 @@ public class AbstractRuleTest {
}
@Test
public void testRuleSuppress() {
void testRuleSuppress() {
DummyRootNode n = new DummyRootNode().withNoPmdComments(Collections.singletonMap(5, ""));
n.setCoords(5, 1, 6, 1);
RuleViolation violation = DefaultRuleViolationFactory.defaultInstance().createViolation(new MyRule(), n, "specificdescription");
@@ -122,82 +122,82 @@ public class AbstractRuleTest {
}
@Test
public void testEquals1() {
void testEquals1() {
MyRule r = new MyRule();
assertFalse("A rule is never equals to null!", r.equals(null));
assertFalse(r.equals(null), "A rule is never equals to null!");
}
@Test
public void testEquals2() {
void testEquals2() {
MyRule r = new MyRule();
assertEquals("A rule must be equals to itself", r, r);
assertEquals(r, r, "A rule must be equals to itself");
}
@Test
public void testEquals3() {
void testEquals3() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
assertEquals("Two instances of the same rule are equal", r1, r2);
assertEquals("Hashcode for two instances of the same rule must be equal", r1.hashCode(), r2.hashCode());
assertEquals(r1, r2, "Two instances of the same rule are equal");
assertEquals(r1.hashCode(), r2.hashCode(), "Hashcode for two instances of the same rule must be equal");
}
@Test
public void testEquals4() {
void testEquals4() {
MyRule myRule = new MyRule();
assertFalse("A rule cannot be equal to an object of another class", myRule.equals("MyRule"));
assertFalse(myRule.equals("MyRule"), "A rule cannot be equal to an object of another class");
}
@Test
public void testEquals5() {
void testEquals5() {
MyRule myRule = new MyRule();
MyOtherRule myOtherRule = new MyOtherRule();
assertFalse("Two rules from different classes cannot be equal", myRule.equals(myOtherRule));
assertFalse(myRule.equals(myOtherRule), "Two rules from different classes cannot be equal");
}
@Test
public void testEquals6() {
void testEquals6() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setName("MyRule2");
assertFalse("Rules with different names cannot be equal", r1.equals(r2));
assertFalse(r1.equals(r2), "Rules with different names cannot be equal");
}
@Test
public void testEquals7() {
void testEquals7() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setPriority(RulePriority.HIGH);
assertFalse("Rules with different priority levels cannot be equal", r1.equals(r2));
assertFalse(r1.equals(r2), "Rules with different priority levels cannot be equal");
}
@Test
public void testEquals8() {
void testEquals8() {
MyRule r1 = new MyRule();
r1.setProperty(MyRule.XPATH_PROPERTY, "something");
MyRule r2 = new MyRule();
r2.setProperty(MyRule.XPATH_PROPERTY, "something else");
assertFalse("Rules with different properties values cannot be equal", r1.equals(r2));
assertFalse(r1.equals(r2), "Rules with different properties values cannot be equal");
}
@Test
public void testEquals9() {
void testEquals9() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setProperty(MyRule.XPATH_PROPERTY, "something else");
assertFalse("Rules with different properties cannot be equal", r1.equals(r2));
assertFalse(r1.equals(r2), "Rules with different properties cannot be equal");
}
@Test
public void testEquals10() {
void testEquals10() {
MyRule r1 = new MyRule();
MyRule r2 = new MyRule();
r2.setMessage("another message");
assertEquals("Rules with different messages are still equal", r1, r2);
assertEquals("Rules that are equal must have the an equal hashcode", r1.hashCode(), r2.hashCode());
assertEquals(r1, r2, "Rules with different messages are still equal");
assertEquals(r1.hashCode(), r2.hashCode(), "Rules that are equal must have the an equal hashcode");
}
@Test
public void testDeepCopyRule() {
void testDeepCopyRule() {
MyRule r1 = new MyRule();
MyRule r2 = (MyRule) r1.deepCopy();
assertEquals(r1.getDescription(), r2.getDescription());
@@ -4,11 +4,11 @@
package net.sourceforge.pmd;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.io.File;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.lang.LanguageFilenameFilter;
@@ -19,47 +19,47 @@ import net.sourceforge.pmd.lang.LanguageRegistry;
*
* @author pieter_van_raemdonck - Application Engineers NV/SA - www.ae.be
*/
public class FileSelectorTest {
class FileSelectorTest {
/**
* Test wanted selection of a source file.
*/
@Test
public void testWantedFile() {
void testWantedFile() {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(
LanguageRegistry.getLanguage(DummyLanguageModule.NAME));
File javaFile = new File("/path/to/myFile.dummy");
boolean selected = fileSelector.accept(javaFile.getParentFile(), javaFile.getName());
assertEquals("This file should be selected !", true, selected);
assertEquals(true, selected, "This file should be selected !");
}
/**
* Test unwanted selection of a non source file.
*/
@Test
public void testUnwantedFile() {
void testUnwantedFile() {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(
LanguageRegistry.getLanguage(DummyLanguageModule.NAME));
File javaFile = new File("/path/to/myFile.txt");
boolean selected = fileSelector.accept(javaFile.getParentFile(), javaFile.getName());
assertEquals("Not-source file must not be selected!", false, selected);
assertEquals(false, selected, "Not-source file must not be selected!");
}
/**
* Test unwanted selection of a java file.
*/
@Test
public void testUnwantedJavaFile() {
void testUnwantedJavaFile() {
LanguageFilenameFilter fileSelector = new LanguageFilenameFilter(
LanguageRegistry.getLanguage(DummyLanguageModule.NAME));
File javaFile = new File("/path/to/MyClass.java");
boolean selected = fileSelector.accept(javaFile.getParentFile(), javaFile.getName());
assertEquals("Unwanted java file must not be selected!", false, selected);
assertEquals(false, selected, "Unwanted java file must not be selected!");
}
}
@@ -16,7 +16,7 @@ import static org.mockito.Mockito.verify;
import java.io.IOException;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentMatchers;
import net.sourceforge.pmd.RuleSetTest.MockRule;
@@ -27,10 +27,10 @@ import net.sourceforge.pmd.reporting.ReportStats;
/**
* @author Clément Fournier
*/
public class PmdAnalysisTest {
class PmdAnalysisTest {
@Test
public void testPmdAnalysisWithEmptyConfig() {
void testPmdAnalysisWithEmptyConfig() {
PMDConfiguration config = new PMDConfiguration();
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
assertThat(pmd.files().getCollectedFiles(), empty());
@@ -40,7 +40,7 @@ public class PmdAnalysisTest {
}
@Test
public void testRendererInteractions() throws IOException {
void testRendererInteractions() throws IOException {
PMDConfiguration config = new PMDConfiguration();
config.setInputPaths("sample-source/dummy");
Renderer renderer = spy(Renderer.class);
@@ -57,7 +57,7 @@ public class PmdAnalysisTest {
}
@Test
public void testRulesetLoading() {
void testRulesetLoading() {
PMDConfiguration config = new PMDConfiguration();
config.addRuleSet("rulesets/dummy/basic.xml");
try (PmdAnalysis pmd = PmdAnalysis.create(config)) {
@@ -66,7 +66,7 @@ public class PmdAnalysisTest {
}
@Test
public void testRulesetWhenSomeoneHasAnError() {
void testRulesetWhenSomeoneHasAnError() {
PMDConfiguration config = new PMDConfiguration();
config.addRuleSet("rulesets/dummy/basic.xml");
config.addRuleSet("rulesets/xxxe/notaruleset.xml");
File diff suppressed because it is too large. Load diff
@@ -4,14 +4,14 @@
package net.sourceforge.pmd;
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.io.IOException;
import java.io.StringWriter;
import java.util.function.Consumer;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
@@ -28,7 +28,7 @@ public class ReportTest {
// Files are grouped together now.
@Test
public void testSortedReportFile() throws IOException {
void testSortedReportFile() throws IOException {
Renderer rend = new XMLRenderer();
String result = render(rend, r -> {
Node s = getNode(10, 5, "foo");
@@ -38,11 +38,11 @@ public class ReportTest {
Rule rule2 = new MockRule("name", "desc", "msg", "rulesetname");
r.onRuleViolation(new ParametricRuleViolation<>(rule2, s1, rule2.getMessage()));
});
assertTrue("sort order wrong", result.indexOf("bar") < result.indexOf("foo"));
assertTrue(result.indexOf("bar") < result.indexOf("foo"), "sort order wrong");
}
@Test
public void testSortedReportLine() throws IOException {
void testSortedReportLine() throws IOException {
Renderer rend = new XMLRenderer();
String result = render(rend, r -> {
Node node1 = getNode(20, 5, "foo1"); // line 20: after rule2 violation
@@ -53,11 +53,11 @@ public class ReportTest {
Rule rule2 = new MockRule("rule2", "rule2", "msg", "rulesetname");
r.onRuleViolation(new ParametricRuleViolation<>(rule2, node2, rule2.getMessage())); // same file!!
});
assertTrue("sort order wrong", result.indexOf("rule2") < result.indexOf("rule1"));
assertTrue(result.indexOf("rule2") < result.indexOf("rule1"), "sort order wrong");
}
@Test
public void testIterator() {
void testIterator() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Node node1 = getNode(5, 5, true, "file1");
Node node2 = getNode(5, 6, true, "file1");
@@ -80,7 +80,7 @@ public class ReportTest {
}
@Test
public void testFilterViolations() {
void testFilterViolations() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Node node1 = getNode(5, 5, true, "file1");
Node node2 = getNode(5, 6, true, "file1");
@@ -96,7 +96,7 @@ public class ReportTest {
}
@Test
public void testUnion() {
void testUnion() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Node node1 = getNode(1, 2, true, "file1");
Report report1 = Report.buildReport(it -> {
@@ -4,10 +4,11 @@
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.function.BiConsumer;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.ast.RootNode;
@@ -15,7 +16,7 @@ import net.sourceforge.pmd.lang.ast.impl.DummyTreeUtil;
public class RuleContextTest {
public static Report getReport(Rule rule, BiConsumer<Rule, RuleContext> sideEffects) {
static Report getReport(Rule rule, BiConsumer<Rule, RuleContext> sideEffects) {
return Report.buildReport(listener -> sideEffects.accept(rule, RuleContext.create(listener, rule)));
}
@@ -23,29 +24,29 @@ public class RuleContextTest {
return getReport(rule, (r, ctx) -> r.apply(node, ctx));
}
public static Report getReportForRuleSetApply(RuleSet ruleset, RootNode node) {
static Report getReportForRuleSetApply(RuleSet ruleset, RootNode node) {
return Report.buildReport(listener -> new RuleSets(ruleset).apply(node, listener));
}
@Test
public void testMessage() throws Exception {
void testMessage() throws Exception {
Report report = getReport(new FooRule(), (r, ctx) -> ctx.addViolationWithMessage(DummyTreeUtil.tree(DummyTreeUtil::root), "message with \"'{'\""));
Assert.assertEquals("message with \"{\"", report.getViolations().get(0).getDescription());
assertEquals("message with \"{\"", report.getViolations().get(0).getDescription());
}
@Test
public void testMessageEscaping() throws Exception {
void testMessageEscaping() throws Exception {
RuleViolation violation = makeViolation("message with \"'{'\"");
Assert.assertEquals("message with \"{\"", violation.getDescription());
assertEquals("message with \"{\"", violation.getDescription());
}
@Test
public void testMessageEscaping2() throws Exception {
void testMessageEscaping2() throws Exception {
RuleViolation violation = makeViolation("message with ${ohio}");
Assert.assertEquals("message with ${ohio}", violation.getDescription());
assertEquals("message with ${ohio}", violation.getDescription());
}
private RuleViolation makeViolation(String unescapedMessage, Object... args) throws Exception {
@@ -4,13 +4,13 @@
package net.sourceforge.pmd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.Dummy2LanguageModule;
import net.sourceforge.pmd.lang.DummyLanguageModule;
@@ -21,18 +21,18 @@ import net.sourceforge.pmd.lang.rule.RuleReference;
import net.sourceforge.pmd.properties.PropertyDescriptor;
import net.sourceforge.pmd.properties.PropertyFactory;
public class RuleReferenceTest {
class RuleReferenceTest {
@Test
public void testRuleSetReference() {
void testRuleSetReference() {
RuleReference ruleReference = new RuleReference();
RuleSetReference ruleSetReference = new RuleSetReference("somename");
ruleReference.setRuleSetReference(ruleSetReference);
assertEquals("Not same rule set reference", ruleSetReference, ruleReference.getRuleSetReference());
assertEquals(ruleSetReference, ruleReference.getRuleSetReference(), "Not same rule set reference");
}
@Test
public void testOverride() {
void testOverride() {
final PropertyDescriptor<String> PROPERTY1_DESCRIPTOR = PropertyFactory.stringProperty("property1").desc("Test property").defaultValue("").build();
MockRule rule = new MockRule();
rule.definePropertyDescriptor(PROPERTY1_DESCRIPTOR);
@@ -66,7 +66,7 @@ public class RuleReferenceTest {
}
@Test
public void testLanguageOverrideDisallowed() {
void testLanguageOverrideDisallowed() {
MockRule rule = new MockRule();
Language dummyLang = LanguageRegistry.getLanguage(DummyLanguageModule.NAME);
rule.setLanguage(dummyLang);
@@ -74,16 +74,16 @@ public class RuleReferenceTest {
RuleReference ruleReference = new RuleReference();
ruleReference.setRule(rule);
Assert.assertThrows(UnsupportedOperationException.class, () -> ruleReference.setLanguage(LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME)));
Assert.assertEquals(dummyLang, ruleReference.getLanguage());
Assert.assertThrows(IllegalArgumentException.class, () -> ruleReference.setMaximumLanguageVersion(LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME).getVersion("1.0")));
Assert.assertEquals(rule.getMaximumLanguageVersion(), ruleReference.getOverriddenMaximumLanguageVersion());
Assert.assertThrows(IllegalArgumentException.class, () -> ruleReference.setMinimumLanguageVersion(LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME).getVersion("1.0")));
Assert.assertEquals(rule.getMinimumLanguageVersion(), ruleReference.getMinimumLanguageVersion());
assertThrows(UnsupportedOperationException.class, () -> ruleReference.setLanguage(LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME)));
assertEquals(dummyLang, ruleReference.getLanguage());
assertThrows(IllegalArgumentException.class, () -> ruleReference.setMaximumLanguageVersion(LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME).getVersion("1.0")));
assertEquals(rule.getMaximumLanguageVersion(), ruleReference.getOverriddenMaximumLanguageVersion());
assertThrows(IllegalArgumentException.class, () -> ruleReference.setMinimumLanguageVersion(LanguageRegistry.getLanguage(Dummy2LanguageModule.NAME).getVersion("1.0")));
assertEquals(rule.getMinimumLanguageVersion(), ruleReference.getMinimumLanguageVersion());
}
@Test
public void testDeepCopyOverride() {
void testDeepCopyOverride() {
final PropertyDescriptor<String> PROPERTY1_DESCRIPTOR = PropertyFactory.stringProperty("property1").desc("Test property").defaultValue("").build();
MockRule rule = new MockRule();
rule.definePropertyDescriptor(PROPERTY1_DESCRIPTOR);
@@ -119,61 +119,61 @@ public class RuleReferenceTest {
private void validateOverriddenValues(final PropertyDescriptor<String> propertyDescriptor1,
final PropertyDescriptor<String> propertyDescriptor2, RuleReference ruleReference) {
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME),
ruleReference.getLanguage());
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME), ruleReference.getLanguage(),
"Override failed");
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.3"),
ruleReference.getMinimumLanguageVersion());
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.3"),
ruleReference.getOverriddenMinimumLanguageVersion());
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.3"), ruleReference.getMinimumLanguageVersion(),
"Override failed");
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.3"), ruleReference.getOverriddenMinimumLanguageVersion(),
"Override failed");
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"),
ruleReference.getMaximumLanguageVersion());
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"),
ruleReference.getOverriddenMaximumLanguageVersion());
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"), ruleReference.getMaximumLanguageVersion(),
"Override failed");
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"), ruleReference.getOverriddenMaximumLanguageVersion(),
"Override failed");
assertEquals("Override failed", false, ruleReference.getRule().isDeprecated());
assertEquals("Override failed", true, ruleReference.isDeprecated());
assertEquals("Override failed", true, ruleReference.isOverriddenDeprecated());
assertEquals(false, ruleReference.getRule().isDeprecated(), "Override failed");
assertEquals(true, ruleReference.isDeprecated(), "Override failed");
assertEquals(true, ruleReference.isOverriddenDeprecated(), "Override failed");
assertEquals("Override failed", "name2", ruleReference.getName());
assertEquals("Override failed", "name2", ruleReference.getOverriddenName());
assertEquals("name2", ruleReference.getName(), "Override failed");
assertEquals("name2", ruleReference.getOverriddenName(), "Override failed");
assertEquals("Override failed", "value2", ruleReference.getProperty(propertyDescriptor1));
assertEquals("Override failed", "value3", ruleReference.getProperty(propertyDescriptor2));
assertTrue("Override failed", ruleReference.getPropertyDescriptors().contains(propertyDescriptor1));
assertTrue("Override failed", ruleReference.getPropertyDescriptors().contains(propertyDescriptor2));
assertFalse("Override failed", ruleReference.getOverriddenPropertyDescriptors().contains(propertyDescriptor1));
assertTrue("Override failed", ruleReference.getOverriddenPropertyDescriptors().contains(propertyDescriptor2));
assertTrue("Override failed",
ruleReference.getPropertiesByPropertyDescriptor().containsKey(propertyDescriptor1));
assertTrue("Override failed",
ruleReference.getPropertiesByPropertyDescriptor().containsKey(propertyDescriptor2));
assertTrue("Override failed",
ruleReference.getOverriddenPropertiesByPropertyDescriptor().containsKey(propertyDescriptor1));
assertTrue("Override failed",
ruleReference.getOverriddenPropertiesByPropertyDescriptor().containsKey(propertyDescriptor2));
assertEquals("value2", ruleReference.getProperty(propertyDescriptor1), "Override failed");
assertEquals("value3", ruleReference.getProperty(propertyDescriptor2), "Override failed");
assertTrue(ruleReference.getPropertyDescriptors().contains(propertyDescriptor1), "Override failed");
assertTrue(ruleReference.getPropertyDescriptors().contains(propertyDescriptor2), "Override failed");
assertFalse(ruleReference.getOverriddenPropertyDescriptors().contains(propertyDescriptor1), "Override failed");
assertTrue(ruleReference.getOverriddenPropertyDescriptors().contains(propertyDescriptor2), "Override failed");
assertTrue(ruleReference.getPropertiesByPropertyDescriptor().containsKey(propertyDescriptor1),
"Override failed");
assertTrue(ruleReference.getPropertiesByPropertyDescriptor().containsKey(propertyDescriptor2),
"Override failed");
assertTrue(ruleReference.getOverriddenPropertiesByPropertyDescriptor().containsKey(propertyDescriptor1),
"Override failed");
assertTrue(ruleReference.getOverriddenPropertiesByPropertyDescriptor().containsKey(propertyDescriptor2),
"Override failed");
assertEquals("Override failed", "message2", ruleReference.getMessage());
assertEquals("Override failed", "message2", ruleReference.getOverriddenMessage());
assertEquals("message2", ruleReference.getMessage(), "Override failed");
assertEquals("message2", ruleReference.getOverriddenMessage(), "Override failed");
assertEquals("Override failed", "description2", ruleReference.getDescription());
assertEquals("Override failed", "description2", ruleReference.getOverriddenDescription());
assertEquals("description2", ruleReference.getDescription(), "Override failed");
assertEquals("description2", ruleReference.getOverriddenDescription(), "Override failed");
assertEquals("Override failed", 2, ruleReference.getExamples().size());
assertEquals("Override failed", "example1", ruleReference.getExamples().get(0));
assertEquals("Override failed", "example2", ruleReference.getExamples().get(1));
assertEquals("Override failed", "example2", ruleReference.getOverriddenExamples().get(0));
assertEquals(2, ruleReference.getExamples().size(), "Override failed");
assertEquals("example1", ruleReference.getExamples().get(0), "Override failed");
assertEquals("example2", ruleReference.getExamples().get(1), "Override failed");
assertEquals("example2", ruleReference.getOverriddenExamples().get(0), "Override failed");
assertEquals("Override failed", "externalInfoUrl2", ruleReference.getExternalInfoUrl());
assertEquals("Override failed", "externalInfoUrl2", ruleReference.getOverriddenExternalInfoUrl());
assertEquals("externalInfoUrl2", ruleReference.getExternalInfoUrl(), "Override failed");
assertEquals("externalInfoUrl2", ruleReference.getOverriddenExternalInfoUrl(), "Override failed");
assertEquals("Override failed", RulePriority.MEDIUM_HIGH, ruleReference.getPriority());
assertEquals("Override failed", RulePriority.MEDIUM_HIGH, ruleReference.getOverriddenPriority());
assertEquals(RulePriority.MEDIUM_HIGH, ruleReference.getPriority(), "Override failed");
assertEquals(RulePriority.MEDIUM_HIGH, ruleReference.getOverriddenPriority(), "Override failed");
}
@Test
public void testNotOverride() {
void testNotOverride() {
final PropertyDescriptor<String> PROPERTY1_DESCRIPTOR = PropertyFactory.stringProperty("property1").desc("Test property").defaultValue("").build();
MockRule rule = new MockRule();
rule.definePropertyDescriptor(PROPERTY1_DESCRIPTOR);
@@ -204,36 +204,36 @@ public class RuleReferenceTest {
ruleReference.setPriority(RulePriority.HIGH);
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.3"),
ruleReference.getMinimumLanguageVersion());
assertNull("Override failed", ruleReference.getOverriddenMinimumLanguageVersion());
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.3"), ruleReference.getMinimumLanguageVersion(),
"Override failed");
assertNull(ruleReference.getOverriddenMinimumLanguageVersion(), "Override failed");
assertEquals("Override failed", LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"),
ruleReference.getMaximumLanguageVersion());
assertNull("Override failed", ruleReference.getOverriddenMaximumLanguageVersion());
assertEquals(LanguageRegistry.getLanguage(DummyLanguageModule.NAME).getVersion("1.7"), ruleReference.getMaximumLanguageVersion(),
"Override failed");
assertNull(ruleReference.getOverriddenMaximumLanguageVersion(), "Override failed");
assertEquals("Override failed", false, ruleReference.isDeprecated());
assertNull("Override failed", ruleReference.isOverriddenDeprecated());
assertEquals(false, ruleReference.isDeprecated(), "Override failed");
assertNull(ruleReference.isOverriddenDeprecated(), "Override failed");
assertEquals("Override failed", "name1", ruleReference.getName());
assertNull("Override failed", ruleReference.getOverriddenName());
assertEquals("name1", ruleReference.getName(), "Override failed");
assertNull(ruleReference.getOverriddenName(), "Override failed");
assertEquals("Override failed", "value1", ruleReference.getProperty(PROPERTY1_DESCRIPTOR));
assertEquals("value1", ruleReference.getProperty(PROPERTY1_DESCRIPTOR), "Override failed");
assertEquals("Override failed", "message1", ruleReference.getMessage());
assertNull("Override failed", ruleReference.getOverriddenMessage());
assertEquals("message1", ruleReference.getMessage(), "Override failed");
assertNull(ruleReference.getOverriddenMessage(), "Override failed");
assertEquals("Override failed", "description1", ruleReference.getDescription());
assertNull("Override failed", ruleReference.getOverriddenDescription());
assertEquals("description1", ruleReference.getDescription(), "Override failed");
assertNull(ruleReference.getOverriddenDescription(), "Override failed");
assertEquals("Override failed", 1, ruleReference.getExamples().size());
assertEquals("Override failed", "example1", ruleReference.getExamples().get(0));
assertNull("Override failed", ruleReference.getOverriddenExamples());
assertEquals(1, ruleReference.getExamples().size(), "Override failed");
assertEquals("example1", ruleReference.getExamples().get(0), "Override failed");
assertNull(ruleReference.getOverriddenExamples(), "Override failed");
assertEquals("Override failed", "externalInfoUrl1", ruleReference.getExternalInfoUrl());
assertNull("Override failed", ruleReference.getOverriddenExternalInfoUrl());
assertEquals("externalInfoUrl1", ruleReference.getExternalInfoUrl(), "Override failed");
assertNull(ruleReference.getOverriddenExternalInfoUrl(), "Override failed");
assertEquals("Override failed", RulePriority.HIGH, ruleReference.getPriority());
assertNull("Override failed", ruleReference.getOverriddenPriority());
assertEquals(RulePriority.HIGH, ruleReference.getPriority(), "Override failed");
assertNull(ruleReference.getOverriddenPriority(), "Override failed");
}
}
@@ -4,13 +4,16 @@
package net.sourceforge.pmd;
import org.junit.Assert;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
public class RuleSetFactoryCompatibilityTest {
import org.junit.jupiter.api.Test;
class RuleSetFactoryCompatibilityTest {
@Test
public void testCorrectOldReference() throws Exception {
void testCorrectOldReference() throws Exception {
final String ruleset = "<?xml version=\"1.0\"?>\n" + "\n" + "<ruleset name=\"Test\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
@@ -25,11 +28,11 @@ public class RuleSetFactoryCompatibilityTest {
RuleSetLoader rulesetLoader = new RuleSetLoader().setCompatibility(compat);
RuleSet createdRuleSet = rulesetLoader.loadFromString("dummy.xml", ruleset);
Assert.assertNotNull(createdRuleSet.getRuleByName("DummyBasicMockRule"));
assertNotNull(createdRuleSet.getRuleByName("DummyBasicMockRule"));
}
@Test
public void testCorrectMovedAndRename() {
void testCorrectMovedAndRename() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleMoved("dummy", "notexisting", "basic", "OldDummyBasicMockRule");
@@ -37,11 +40,11 @@ public class RuleSetFactoryCompatibilityTest {
String out = rsfc.applyRef("rulesets/dummy/notexisting.xml/OldDummyBasicMockRule");
Assert.assertEquals("rulesets/dummy/basic.xml/NewNameForDummyBasicMockRule", out);
assertEquals("rulesets/dummy/basic.xml/NewNameForDummyBasicMockRule", out);
}
@Test
public void testExclusion() {
void testExclusion() {
final String ruleset = "<?xml version=\"1.0\"?>\n" + "\n" + "<ruleset name=\"Test\"\n"
+ " xmlns=\"http://pmd.sourceforge.net/ruleset/2.0.0\"\n"
+ " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
@@ -55,12 +58,12 @@ public class RuleSetFactoryCompatibilityTest {
RuleSetLoader rulesetLoader = new RuleSetLoader().setCompatibility(compat);
RuleSet createdRuleSet = rulesetLoader.loadFromString("dummy.xml", ruleset);
Assert.assertNotNull(createdRuleSet.getRuleByName("DummyBasicMockRule"));
Assert.assertNull(createdRuleSet.getRuleByName("SampleXPathRule"));
assertNotNull(createdRuleSet.getRuleByName("DummyBasicMockRule"));
assertNull(createdRuleSet.getRuleByName("SampleXPathRule"));
}
@Test
public void testExclusionRenamedAndMoved() {
void testExclusionRenamedAndMoved() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleMovedAndRenamed("dummy", "oldbasic", "OldDummyBasicMockRule", "basic", "NewNameForDummyBasicMockRule");
@@ -68,33 +71,33 @@ public class RuleSetFactoryCompatibilityTest {
String in = "rulesets/dummy/oldbasic.xml";
String out = rsfc.applyRef(in);
Assert.assertEquals(in, out);
assertEquals(in, out);
}
@Test
public void testFilter() {
void testFilter() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleMoved("dummy", "notexisting", "basic", "DummyBasicMockRule");
rsfc.addFilterRuleRemoved("dummy", "basic", "DeletedRule");
rsfc.addFilterRuleRenamed("dummy", "basic", "OldNameOfBasicMockRule", "NewNameOfBasicMockRule");
Assert.assertEquals("rulesets/dummy/basic.xml/DummyBasicMockRule",
assertEquals("rulesets/dummy/basic.xml/DummyBasicMockRule",
rsfc.applyRef("rulesets/dummy/notexisting.xml/DummyBasicMockRule"));
Assert.assertEquals("rulesets/dummy/basic.xml/NewNameOfBasicMockRule",
assertEquals("rulesets/dummy/basic.xml/NewNameOfBasicMockRule",
rsfc.applyRef("rulesets/dummy/basic.xml/OldNameOfBasicMockRule"));
Assert.assertNull(rsfc.applyRef("rulesets/dummy/basic.xml/DeletedRule"));
assertNull(rsfc.applyRef("rulesets/dummy/basic.xml/DeletedRule"));
}
@Test
public void testExclusionFilter() {
void testExclusionFilter() {
RuleSetFactoryCompatibility rsfc = new RuleSetFactoryCompatibility();
rsfc.addFilterRuleRenamed("dummy", "basic", "AnotherOldNameOfBasicMockRule", "NewNameOfBasicMockRule");
String out = rsfc.applyExclude("rulesets/dummy/basic.xml", "AnotherOldNameOfBasicMockRule", false);
Assert.assertEquals("NewNameOfBasicMockRule", out);
assertEquals("NewNameOfBasicMockRule", out);
}
}
@@ -4,70 +4,75 @@
package net.sourceforge.pmd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Assert;
import org.junit.Test;
import org.junit.jupiter.api.Test;
public class RuleSetFactoryDuplicatedRuleLoggingTest extends RulesetFactoryTestBase {
import com.github.stefanbirkner.systemlambda.SystemLambda;
protected RuleSet loadMyRuleSet(String ruleSetFilename) {
return loadRuleSetInDir("net/sourceforge/pmd/rulesets/duplicatedRuleLoggingTest", ruleSetFilename);
}
class RuleSetFactoryDuplicatedRuleLoggingTest extends RulesetFactoryTestBase {
private static final String DIR = "net/sourceforge/pmd/rulesets/duplicatedRuleLoggingTest";
@Test
public void duplicatedRuleReferenceShouldWarn() {
RuleSet ruleset = loadMyRuleSet("duplicatedRuleReference.xml");
void duplicatedRuleReferenceShouldWarn() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "duplicatedRuleReference.xml");
assertEquals(1, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
Assert.assertEquals(RulePriority.MEDIUM, mockRule.getPriority());
verifyFoundAWarningWithMessage(containing(
assertEquals(1, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.MEDIUM, mockRule.getPriority());
});
assertThat(log, containsString(
"The rule DummyBasicMockRule is referenced multiple times in ruleset 'Custom Rules'. "
+ "Only the last rule configuration is used."
));
+ "Only the last rule configuration is used"));
}
@Test
public void duplicatedRuleReferenceWithOverrideShouldNotWarn() {
RuleSet ruleset = loadMyRuleSet("duplicatedRuleReferenceWithOverride.xml");
void duplicatedRuleReferenceWithOverrideShouldNotWarn() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "duplicatedRuleReferenceWithOverride.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
verifyNoWarnings();
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
});
assertTrue(log.isEmpty());
}
@Test
public void duplicatedRuleReferenceWithOverrideBeforeShouldNotWarn() {
RuleSet ruleset = loadMyRuleSet("duplicatedRuleReferenceWithOverrideBefore.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
verifyNoWarnings();
void duplicatedRuleReferenceWithOverrideBeforeShouldNotWarn() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "duplicatedRuleReferenceWithOverrideBefore.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
});
assertTrue(log.isEmpty());
}
@Test
public void multipleDuplicates() {
RuleSet ruleset = loadMyRuleSet("multipleDuplicates.xml");
void multipleDuplicates() throws Exception {
String log = SystemLambda.tapSystemErr(() -> {
RuleSet ruleset = loadRuleSetInDir(DIR, "multipleDuplicates.xml");
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.MEDIUM_HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
verifyFoundAWarningWithMessage(containing(
"The rule DummyBasicMockRule is referenced multiple times in ruleset 'Custom Rules'. "
+ "Only the last rule configuration is used."));
verifyFoundAWarningWithMessage(containing(
"The ruleset rulesets/dummy/basic.xml is referenced multiple times in ruleset 'Custom Rules'"));
assertEquals(2, ruleset.getRules().size());
Rule mockRule = ruleset.getRuleByName("DummyBasicMockRule");
assertNotNull(mockRule);
assertEquals(RulePriority.MEDIUM_HIGH, mockRule.getPriority());
assertNotNull(ruleset.getRuleByName("SampleXPathRule"));
});
assertThat(log, containsString("The rule DummyBasicMockRule is referenced multiple times in ruleset 'Custom Rules'. Only the last rule configuration is used."));
assertThat(log, containsString("The ruleset rulesets/dummy/basic.xml is referenced multiple times in ruleset 'Custom Rules'"));
}
}
@@ -7,21 +7,22 @@ package net.sourceforge.pmd;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import com.github.stefanbirkner.systemlambda.SystemLambda;
public class RuleSetFactoryMessagesTest extends RulesetFactoryTestBase {
@Test
public void testFullMessage() {
assertCannotParse(
public void testFullMessage() throws Exception {
String log = SystemLambda.tapSystemErr(() -> assertCannotParse(
rulesetXml(
dummyRule(
priority("not a priority")
)
)
);
));
String log = systemErrRule.getLog();
assertThat(log, containsString(
"Error at dummyRuleset.xml:9:1\n"
+ " 7| \n"
File diff suppressed because it is too large. Load diff
@@ -14,68 +14,68 @@ import static com.github.tomakehurst.wiremock.client.WireMock.stubFor;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching;
import static com.github.tomakehurst.wiremock.client.WireMock.verify;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.util.IOUtil;
import net.sourceforge.pmd.util.ResourceLoader;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo;
import com.github.tomakehurst.wiremock.junit5.WireMockTest;
public class RuleSetReferenceIdTest {
@WireMockTest
class RuleSetReferenceIdTest {
private static void assertRuleSetReferenceId(final boolean expectedExternal, final String expectedRuleSetFileName,
final boolean expectedAllRules, final String expectedRuleName, final String expectedToString,
final RuleSetReferenceId reference) {
assertEquals("Wrong external", expectedExternal, reference.isExternal());
assertEquals("Wrong RuleSet file name", expectedRuleSetFileName, reference.getRuleSetFileName());
assertEquals("Wrong all Rule reference", expectedAllRules, reference.isAllRules());
assertEquals("Wrong Rule name", expectedRuleName, reference.getRuleName());
assertEquals("Wrong toString()", expectedToString, reference.toString());
}
@Test(expected = IllegalArgumentException.class)
public void testCommaInSingleId() {
new RuleSetReferenceId("bad,id");
}
@Test(expected = IllegalArgumentException.class)
public void testInternalWithInternal() {
new RuleSetReferenceId("SomeRule", new RuleSetReferenceId("SomeOtherRule"));
}
@Test(expected = IllegalArgumentException.class)
public void testExternalWithExternal() {
new RuleSetReferenceId("someruleset.xml/SomeRule", new RuleSetReferenceId("someruleset.xml/SomeOtherRule"));
}
@Test(expected = IllegalArgumentException.class)
public void testExternalWithInternal() {
new RuleSetReferenceId("someruleset.xml/SomeRule", new RuleSetReferenceId("SomeOtherRule"));
assertEquals(expectedExternal, reference.isExternal(), "Wrong external");
assertEquals(expectedRuleSetFileName, reference.getRuleSetFileName(), "Wrong RuleSet file name");
assertEquals(expectedAllRules, reference.isAllRules(), "Wrong all Rule reference");
assertEquals(expectedRuleName, reference.getRuleName(), "Wrong Rule name");
assertEquals(expectedToString, reference.toString(), "Wrong toString()");
}
@Test
public void testInteralWithExternal() {
void testCommaInSingleId() {
assertThrows(IllegalArgumentException.class, () -> new RuleSetReferenceId("bad,id"));
}
@Test
void testInternalWithInternal() {
assertThrows(IllegalArgumentException.class, () ->
new RuleSetReferenceId("SomeRule", new RuleSetReferenceId("SomeOtherRule")));
}
@Test
void testExternalWithExternal() {
assertThrows(IllegalArgumentException.class, () ->
new RuleSetReferenceId("someruleset.xml/SomeRule", new RuleSetReferenceId("someruleset.xml/SomeOtherRule")));
}
@Test
void testExternalWithInternal() {
assertThrows(IllegalArgumentException.class, () ->
new RuleSetReferenceId("someruleset.xml/SomeRule", new RuleSetReferenceId("SomeOtherRule")));
}
@Test
void testInteralWithExternal() {
// This is okay
new RuleSetReferenceId("SomeRule", new RuleSetReferenceId("someruleset.xml/SomeOtherRule"));
}
@Test
public void testEmptyRuleSet() {
void testEmptyRuleSet() {
// This is representative of how the Test framework creates
// RuleSetReferenceId from static RuleSet XMLs
RuleSetReferenceId reference = new RuleSetReferenceId(null);
@@ -83,8 +83,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testInternalWithExternalRuleSet() {
void testInternalWithExternalRuleSet() {
// This is representative of how the RuleSetFactory temporarily pairs an
// internal reference
// with an external reference.
@@ -100,7 +99,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testConstructorGivenHttpUrlIdSucceedsAndProcessesIdCorrectly() {
void testConstructorGivenHttpUrlIdSucceedsAndProcessesIdCorrectly() {
final String sonarRulesetUrlId = "http://localhost:54321/profiles/export?format=pmd&language=java&name=Sonar%2520way";
@@ -108,13 +107,10 @@ public class RuleSetReferenceIdTest {
assertRuleSetReferenceId(true, sonarRulesetUrlId, true, null, sonarRulesetUrlId, ruleSetReferenceId);
}
@org.junit.Rule
public WireMockRule wireMockRule = new WireMockRule(0);
@Test
public void testConstructorGivenHttpUrlInputStream() throws Exception {
void testConstructorGivenHttpUrlInputStream(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {
String path = "/profiles/export?format=pmd&language=java&name=Sonar%2520way";
String rulesetUrl = "http://localhost:" + wireMockRule.port() + path;
String rulesetUrl = "http://localhost:" + wmRuntimeInfo.getHttpPort() + path;
stubFor(head(urlEqualTo(path)).willReturn(aResponse().withStatus(200)));
stubFor(get(urlEqualTo(path))
.willReturn(aResponse().withStatus(200).withHeader("Content-type", "text/xml").withBody("xyz")));
@@ -135,10 +131,10 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testConstructorGivenHttpUrlSingleRuleInputStream() throws Exception {
void testConstructorGivenHttpUrlSingleRuleInputStream(WireMockRuntimeInfo wmRuntimeInfo) throws Exception {
String path = "/profiles/export?format=pmd&language=java&name=Sonar%2520way";
String completePath = path + "/DummyBasicMockRule";
String hostpart = "http://localhost:" + wireMockRule.port();
String hostpart = "http://localhost:" + wmRuntimeInfo.getHttpPort();
String basicRuleSet = IOUtil
.readToString(RuleSetReferenceId.class.getResourceAsStream("/rulesets/dummy/basic.xml"), StandardCharsets.UTF_8);
@@ -165,7 +161,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testOneSimpleRuleSet() {
void testOneSimpleRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic");
assertEquals(1, references.size());
@@ -174,7 +170,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testMultipleSimpleRuleSet() {
void testMultipleSimpleRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-unusedcode,dummy-basic");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/unusedcode.xml", true, null, "rulesets/dummy/unusedcode.xml",
@@ -187,7 +183,7 @@ public class RuleSetReferenceIdTest {
* See https://sourceforge.net/p/pmd/bugs/1201/
*/
@Test
public void testMultipleRulesWithSpaces() {
void testMultipleRulesWithSpaces() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic, dummy-unusedcode, dummy2-basic");
assertEquals(3, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", true, null, "rulesets/dummy/basic.xml",
@@ -199,7 +195,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testOneReleaseRuleSet() {
void testOneReleaseRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("50");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/releases/50.xml", true, null, "rulesets/releases/50.xml",
@@ -207,7 +203,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testOneFullRuleSet() {
void testOneFullRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("rulesets/java/unusedcode.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/java/unusedcode.xml", true, null, "rulesets/java/unusedcode.xml",
@@ -215,7 +211,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testOneFullRuleSetURL() {
void testOneFullRuleSetURL() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("file://somepath/rulesets/java/unusedcode.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "file://somepath/rulesets/java/unusedcode.xml", true, null,
@@ -223,7 +219,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testMultipleFullRuleSet() {
void testMultipleFullRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId
.parse("rulesets/java/unusedcode.xml,rulesets/java/basic.xml");
assertEquals(2, references.size());
@@ -234,7 +230,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testMixRuleSet() {
void testMixRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("rulesets/dummy/unusedcode.xml,dummy2-basic");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/unusedcode.xml", true, null, "rulesets/dummy/unusedcode.xml",
@@ -244,14 +240,14 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testUnknownRuleSet() {
void testUnknownRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("nonexistant.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "nonexistant.xml", true, null, "nonexistant.xml", references.get(0));
}
@Test
public void testUnknownAndSimpleRuleSet() {
void testUnknownAndSimpleRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic,nonexistant.xml");
assertEquals(2, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", true, null, "rulesets/dummy/basic.xml",
@@ -260,7 +256,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testSimpleRuleSetAndRule() {
void testSimpleRuleSetAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("dummy-basic/DummyBasicMockRule");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/dummy/basic.xml", false, "DummyBasicMockRule",
@@ -268,7 +264,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testFullRuleSetAndRule() {
void testFullRuleSetAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("rulesets/java/basic.xml/EmptyCatchBlock");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "rulesets/java/basic.xml", false, "EmptyCatchBlock",
@@ -276,7 +272,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testFullRuleSetURLAndRule() {
void testFullRuleSetURLAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId
.parse("file://somepath/rulesets/java/unusedcode.xml/EmptyCatchBlock");
assertEquals(1, references.size());
@@ -285,21 +281,21 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testInternalRuleSetAndRule() {
void testInternalRuleSetAndRule() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("EmptyCatchBlock");
assertEquals(1, references.size());
assertRuleSetReferenceId(false, null, false, "EmptyCatchBlock", "EmptyCatchBlock", references.get(0));
}
@Test
public void testRelativePathRuleSet() {
void testRelativePathRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("pmd/pmd-ruleset.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "pmd/pmd-ruleset.xml", true, null, "pmd/pmd-ruleset.xml", references.get(0));
}
@Test
public void testAbsolutePathRuleSet() {
void testAbsolutePathRuleSet() {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse("/home/foo/pmd/pmd-ruleset.xml");
assertEquals(1, references.size());
assertRuleSetReferenceId(true, "/home/foo/pmd/pmd-ruleset.xml", true, null, "/home/foo/pmd/pmd-ruleset.xml",
@@ -307,7 +303,7 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testFooRules() throws Exception {
void testFooRules() throws Exception {
String fooRulesFile = new File("./src/test/resources/net/sourceforge/pmd/rulesets/foo-project/foo-rules")
.getCanonicalPath();
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(fooRulesFile);
@@ -316,12 +312,8 @@ public class RuleSetReferenceIdTest {
}
@Test
public void testNullRulesetString() throws Exception {
void testNullRulesetString() throws Exception {
List<RuleSetReferenceId> references = RuleSetReferenceId.parse(null);
assertTrue(references.isEmpty());
}
public static junit.framework.Test suite() {
return new junit.framework.JUnit4TestAdapter(RuleSetReferenceIdTest.class);
}
}
@@ -4,9 +4,9 @@
package net.sourceforge.pmd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
@@ -24,8 +24,8 @@ import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.xml.sax.EntityResolver;
@@ -34,18 +34,18 @@ import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
public class RuleSetSchemaTest {
class RuleSetSchemaTest {
private CollectingErrorHandler errorHandler;
@Before
public void setUp() {
@BeforeEach
void setUp() {
Locale.setDefault(Locale.ROOT);
errorHandler = new CollectingErrorHandler();
}
@Test
public void verifyVersion2() throws Exception {
void verifyVersion2() throws Exception {
String ruleset = generateRuleSet("2.0.0");
Document doc = parseWithVersion2(ruleset);
assertNotNull(doc);
@@ -56,7 +56,7 @@ public class RuleSetSchemaTest {
}
@Test
public void validateOnly() throws Exception {
void validateOnly() throws Exception {
Validator validator = PMDRuleSetEntityResolver.getSchemaVersion2().newValidator();
validator.setErrorHandler(errorHandler);
validator.validate(new StreamSource(new ByteArrayInputStream(generateRuleSet("2.0.0").getBytes(StandardCharsets.UTF_8))));
File diff suppressed because it is too large. Load diff
@@ -4,13 +4,14 @@
package net.sourceforge.pmd;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.ByteArrayOutputStream;
import java.util.Random;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.RuleSet.RuleSetBuilder;
import net.sourceforge.pmd.lang.rule.RuleReference;
@@ -19,7 +20,7 @@ import net.sourceforge.pmd.lang.rule.RuleReference;
* Unit test for {@link RuleSetWriter}.
*
*/
public class RuleSetWriterTest {
class RuleSetWriterTest {
private ByteArrayOutputStream out;
private RuleSetWriter writer;
@@ -27,8 +28,8 @@ public class RuleSetWriterTest {
/**
* Prepare the output stream.
*/
@Before
public void setupOutputStream() {
@BeforeEach
void setupOutputStream() {
out = new ByteArrayOutputStream();
writer = new RuleSetWriter(out);
}
@@ -36,8 +37,8 @@ public class RuleSetWriterTest {
/**
* Closes the output stream at the end.
*/
@After
public void cleanupStream() {
@AfterEach
void cleanupStream() {
if (writer != null) {
writer.close();
}
@@ -50,7 +51,7 @@ public class RuleSetWriterTest {
* any error
*/
@Test
public void testWrite() throws Exception {
void testWrite() throws Exception {
RuleSet braces = new RuleSetLoader().loadFromResource("net/sourceforge/pmd/TestRuleset1.xml");
RuleSet ruleSet = new RuleSetBuilder(new Random().nextLong())
.withName("ruleset")
@@ -61,7 +62,7 @@ public class RuleSetWriterTest {
writer.write(ruleSet);
String written = out.toString("UTF-8");
Assert.assertTrue(written.contains("<exclude name=\"MockRule2\""));
assertTrue(written.contains("<exclude name=\"MockRule2\""));
}
/**
@@ -71,7 +72,7 @@ public class RuleSetWriterTest {
* any error
*/
@Test
public void testRuleReferenceOverriddenName() throws Exception {
void testRuleReferenceOverriddenName() throws Exception {
RuleSet rs = new RuleSetLoader().loadFromResource("rulesets/dummy/basic.xml");
RuleReference ruleRef = new RuleReference();
@@ -84,6 +85,6 @@ public class RuleSetWriterTest {
writer.write(ruleSet);
String written = out.toString("UTF-8");
Assert.assertTrue(written.contains("ref=\"rulesets/dummy/basic.xml/DummyBasicMockRule\""));
assertTrue(written.contains("ref=\"rulesets/dummy/basic.xml/DummyBasicMockRule\""));
}
}
@@ -4,8 +4,8 @@
package net.sourceforge.pmd;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertSame;
import java.util.ArrayList;
import java.util.Arrays;
@@ -13,7 +13,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
@@ -21,10 +21,10 @@ import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
public class RuleViolationComparatorTest {
class RuleViolationComparatorTest {
@Test
public void testComparator() {
void testComparator() {
Rule rule1 = new MockRule("name1", "desc", "msg", "rulesetname1");
Rule rule2 = new MockRule("name2", "desc", "msg", "rulesetname2");
@@ -64,9 +64,9 @@ public class RuleViolationComparatorTest {
int count = 0;
for (int i = 0; i < expectedOrder.length; i++) {
count++;
assertSame("Wrong RuleViolation " + i + ", used seed: " + seed, expectedOrder[i], ruleViolations.get(i));
assertSame(expectedOrder[i], ruleViolations.get(i), "Wrong RuleViolation " + i + ", used seed: " + seed);
}
assertEquals("Missing assertion for every RuleViolation", expectedOrder.length, count);
assertEquals(expectedOrder.length, count, "Missing assertion for every RuleViolation");
}
private RuleViolation createJavaRuleViolation(Rule rule, String fileName, int beginLine, String description,
@@ -4,13 +4,13 @@
package net.sourceforge.pmd;
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.Comparator;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.lang.ast.DummyNode;
import net.sourceforge.pmd.lang.ast.DummyNode.DummyRootNode;
@@ -18,35 +18,33 @@ import net.sourceforge.pmd.lang.ast.Node;
import net.sourceforge.pmd.lang.rule.MockRule;
import net.sourceforge.pmd.lang.rule.ParametricRuleViolation;
import junit.framework.JUnit4TestAdapter;
public class RuleViolationTest {
class RuleViolationTest {
@Test
public void testConstructor1() {
void testConstructor1() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
DummyNode s = new DummyRootNode().withFileName("filename");
s.setCoords(2, 1, 2, 3);
RuleViolation r = new ParametricRuleViolation<Node>(rule, s, rule.getMessage());
assertEquals("object mismatch", rule, r.getRule());
assertEquals("line number is wrong", 2, r.getBeginLine());
assertEquals("filename is wrong", "filename", r.getFilename());
assertEquals(rule, r.getRule(), "object mismatch");
assertEquals(2, r.getBeginLine(), "line number is wrong");
assertEquals("filename", r.getFilename(), "filename is wrong");
}
@Test
public void testConstructor2() {
void testConstructor2() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
DummyNode s = new DummyRootNode().withFileName("filename");
s.setCoords(2, 1, 2, 3);
RuleViolation r = new ParametricRuleViolation<Node>(rule, s, "description");
assertEquals("object mismatch", rule, r.getRule());
assertEquals("line number is wrong", 2, r.getBeginLine());
assertEquals("filename is wrong", "filename", r.getFilename());
assertEquals("description is wrong", "description", r.getDescription());
assertEquals(rule, r.getRule(), "object mismatch");
assertEquals(2, r.getBeginLine(), "line number is wrong");
assertEquals("filename", r.getFilename(), "filename is wrong");
assertEquals("description", r.getDescription(), "description is wrong");
}
@Test
public void testComparatorWithDifferentFilenames() {
void testComparatorWithDifferentFilenames() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Comparator<RuleViolation> comp = RuleViolation.DEFAULT_COMPARATOR;
DummyNode s = new DummyRootNode().withFileName("filename1");
@@ -60,7 +58,7 @@ public class RuleViolationTest {
}
@Test
public void testComparatorWithSameFileDifferentLines() {
void testComparatorWithSameFileDifferentLines() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Comparator<RuleViolation> comp = RuleViolation.DEFAULT_COMPARATOR;
DummyNode s = new DummyRootNode().withFileName("filename1");
@@ -73,9 +71,9 @@ public class RuleViolationTest {
assertTrue(comp.compare(r2, r1) > 0);
}
@Ignore
@Disabled
@Test
public void testComparatorWithSameFileSameLines() {
void testComparatorWithSameFileSameLines() {
Rule rule = new MockRule("name", "desc", "msg", "rulesetname");
Comparator<RuleViolation> comp = RuleViolation.DEFAULT_COMPARATOR;
DummyRootNode rootNode = new DummyRootNode();
@@ -94,8 +92,4 @@ public class RuleViolationTest {
assertEquals(1, comp.compare(r1, r2));
assertEquals(1, comp.compare(r2, r1));
}
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(RuleViolationTest.class);
}
}
@@ -21,13 +21,11 @@ import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.junit.Before;
import org.junit.contrib.java.lang.system.SystemErrRule;
import org.junit.jupiter.api.BeforeEach;
import org.mockito.verification.VerificationMode;
import org.slf4j.LoggerFactory;
import org.slf4j.event.Level;
import net.sourceforge.pmd.junit.LocaleRule;
import net.sourceforge.pmd.lang.DummyLanguageModule;
import net.sourceforge.pmd.util.internal.xml.SchemaConstant;
import net.sourceforge.pmd.util.internal.xml.SchemaConstants;
@@ -36,15 +34,9 @@ import net.sourceforge.pmd.util.log.internal.SimpleMessageReporter;
public class RulesetFactoryTestBase {
@org.junit.Rule
public LocaleRule localeRule = LocaleRule.en();
@org.junit.Rule
public SystemErrRule systemErrRule = new SystemErrRule().enableLog().muteForSuccessfulTests();
protected MessageReporter mockReporter;
@Before
@BeforeEach
public void setup() {
SimpleMessageReporter reporter = new SimpleMessageReporter(LoggerFactory.getLogger(RulesetFactoryTestBase.class));
mockReporter = spy(reporter);
@@ -0,0 +1,122 @@
/*
* BSD-style license; for more info see http://pmd.sourceforge.net/license.html
*/
package net.sourceforge.pmd.ant;
import static com.github.stefanbirkner.systemlambda.SystemLambda.restoreSystemProperties;
import java.io.File;
import java.io.PrintStream;
import java.io.StringWriter;
import java.nio.charset.Charset;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildListener;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;
import org.junit.jupiter.api.AfterAll;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import net.sourceforge.pmd.util.IOUtil;
class AbstractAntTest {
protected Project project;
protected StringBuilder log;
protected StringWriter out;
protected StringWriter err;
protected void configureProject(String filename) {
project = new Project();
project.init();
project.addBuildListener(new AntBuildListener(Project.MSG_INFO));
File antFile = new File(filename);
ProjectHelper.configureProject(project, antFile);
}
@AfterAll
static void resetLogging() {
Slf4jSimpleConfiguration.reconfigureDefaultLogLevel(null);
}
protected void executeTarget(String targetName) {
// restoring system properties: PMDTask might change logging properties
// See Slf4jSimpleConfigurationForAnt and resetLogging
try {
restoreSystemProperties(() -> {
executeTargetImpl(targetName);
});
} catch (BuildException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void executeTargetImpl(String targetName) {
log = new StringBuilder();
out = new StringWriter();
err = new StringWriter();
PrintStream outStream = new PrintStream(IOUtil.fromWriter(out, Charset.defaultCharset().name()));
PrintStream errStream = new PrintStream(IOUtil.fromWriter(err, Charset.defaultCharset().name()));
synchronized (System.out) {
PrintStream originalOut = System.out;
PrintStream originalErr = System.err;
originalOut.flush();
originalErr.flush();
try {
System.setOut(outStream);
System.setErr(errStream);
project.executeTarget(targetName);
} finally {
System.setOut(originalOut);
System.setErr(originalErr);
}
}
}
private class AntBuildListener implements BuildListener {
private final int logLevel;
private AntBuildListener(int logLevel) {
this.logLevel = logLevel;
}
@Override
public void buildStarted(BuildEvent event) {
}
@Override
public void buildFinished(BuildEvent event) {
}
@Override
public void targetStarted(BuildEvent event) {
}
@Override
public void targetFinished(BuildEvent event) {
}
@Override
public void taskStarted(BuildEvent event) {
}
@Override
public void taskFinished(BuildEvent event) {
}
@Override
public void messageLogged(BuildEvent event) {
if (event.getPriority() > logLevel) {
return;
}
log.append(event.getMessage());
}
}
}
@@ -4,33 +4,28 @@
package net.sourceforge.pmd.ant;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.io.File;
import org.apache.tools.ant.BuildFileRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
*
* @author Romain Pelisse &lt;belaran@gmail.com&gt;
*
*/
public class CPDTaskTest {
class CPDTaskTest extends AbstractAntTest {
@Rule
public final BuildFileRule buildRule = new BuildFileRule();
@Before
public void setUp() {
buildRule.configureProject("src/test/resources/net/sourceforge/pmd/ant/xml/cpdtasktest.xml");
@BeforeEach
void setUp() {
configureProject("src/test/resources/net/sourceforge/pmd/ant/xml/cpdtasktest.xml");
}
@Test
public void testBasic() {
buildRule.executeTarget("testBasic");
void testBasic() {
executeTarget("testBasic");
// FIXME: This clearly needs to be improved - but I don't like to write
// test, so feel free to contribute :)
assertTrue(new File("target/cpd.ant.tests").exists());
@@ -4,23 +4,23 @@
package net.sourceforge.pmd.ant;
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.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.File;
import org.junit.Test;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.renderers.CSVRenderer;
import net.sourceforge.pmd.renderers.HTMLRenderer;
import net.sourceforge.pmd.renderers.TextRenderer;
import net.sourceforge.pmd.renderers.XMLRenderer;
public class FormatterTest {
class FormatterTest {
@Test
public void testType() {
void testType() {
Formatter f = new Formatter();
f.setType("xml");
assertTrue(f.createRenderer() instanceof XMLRenderer);
@@ -40,10 +40,10 @@ public class FormatterTest {
}
@Test
public void testNull() {
void testNull() {
Formatter f = new Formatter();
assertTrue("Formatter toFile should start off null!", f.isNoOutputSupplied());
assertTrue(f.isNoOutputSupplied(), "Formatter toFile should start off null!");
f.setToFile(new File("foo"));
assertFalse("Formatter toFile should not be null!", f.isNoOutputSupplied());
assertFalse(f.isNoOutputSupplied(), "Formatter toFile should not be null!");
}
}
@@ -4,7 +4,8 @@
package net.sourceforge.pmd.ant;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.fail;
import java.io.FileInputStream;
import java.io.IOException;
@@ -12,93 +13,73 @@ import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileRule;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import net.sourceforge.pmd.internal.Slf4jSimpleConfiguration;
import net.sourceforge.pmd.util.IOUtil;
public class PMDTaskTest {
class PMDTaskTest extends AbstractAntTest {
@Rule
public final BuildFileRule buildRule = new BuildFileRule();
// 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);
}
@Before
public void setUp() {
buildRule.configureProject("src/test/resources/net/sourceforge/pmd/ant/xml/pmdtasktest.xml");
@BeforeEach
void setUp() {
configureProject("src/test/resources/net/sourceforge/pmd/ant/xml/pmdtasktest.xml");
}
@Test
public void testFormatterWithNoToFileAttribute() {
void testFormatterWithNoToFileAttribute() {
try {
buildRule.executeTarget("testFormatterWithNoToFileAttribute");
executeTarget("testFormatterWithNoToFileAttribute");
fail("This should throw an exception");
} catch (BuildException ex) {
Assert.assertEquals("toFile or toConsole needs to be specified in Formatter", ex.getMessage());
assertEquals("toFile or toConsole needs to be specified in Formatter", ex.getMessage());
}
}
@Test
public void testNoRuleSets() {
void testNoRuleSets() {
try {
buildRule.executeTarget("testNoRuleSets");
executeTarget("testNoRuleSets");
fail("This should throw an exception");
} catch (BuildException ex) {
Assert.assertEquals("No rulesets specified", ex.getMessage());
assertEquals("No rulesets specified", ex.getMessage());
}
}
@Test
public void testBasic() {
buildRule.executeTarget("testBasic");
void testBasic() {
executeTarget("testBasic");
}
@Test
public void testInvalidLanguageVersion() {
void testInvalidLanguageVersion() {
try {
buildRule.executeTarget("testInvalidLanguageVersion");
Assert.assertEquals(
executeTarget("testInvalidLanguageVersion");
assertEquals(
"The following language is not supported:<sourceLanguage name=\"java\" version=\"42\" />.",
buildRule.getLog());
log.toString());
fail("This should throw an exception");
} catch (BuildException ex) {
Assert.assertEquals(
assertEquals(
"The following language is not supported:<sourceLanguage name=\"java\" version=\"42\" />.",
ex.getMessage());
}
}
@Test
public void testWithShortFilenames() throws IOException {
buildRule.executeTarget("testWithShortFilenames");
void testWithShortFilenames() throws IOException {
executeTarget("testWithShortFilenames");
try (InputStream in = new FileInputStream("target/pmd-ant-test.txt")) {
String actual = IOUtil.readToString(in, StandardCharsets.UTF_8);
// remove any trailing newline
actual = actual.trim();
Assert.assertEquals("sample.dummy:1:\tSampleXPathRule:\tTest Rule 2", actual);
assertEquals("sample.dummy:1:\tSampleXPathRule:\tTest Rule 2", actual);
}
}
@Test
public void testXmlFormatter() throws IOException {
buildRule.executeTarget("testXmlFormatter");
void testXmlFormatter() throws IOException {
executeTarget("testXmlFormatter");
try (InputStream in = new FileInputStream("target/pmd-ant-xml.xml");
InputStream expectedStream = PMDTaskTest.class.getResourceAsStream("xml/expected-pmd-ant-xml.xml")) {
@@ -116,7 +97,7 @@ public class PMDTaskTest {
expected = expected.replaceFirst("endcolumn=\"109\"", "endcolumn=\"110\"");
}
Assert.assertEquals(expected, actual);
assertEquals(expected, actual);
}
}
}
File diff suppressed because it is too large. Load diff
@@ -4,33 +4,36 @@
package net.sourceforge.pmd.cache.internal;
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.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import junitparams.JUnitParamsRunner;
import junitparams.Parameters;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
abstract class AbstractClasspathEntryFingerprinterTest {
@RunWith(JUnitParamsRunner.class)
public abstract class AbstractClasspathEntryFingerprinterTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
@TempDir
Path tempDir;
protected ClasspathEntryFingerprinter fingerprinter = newFingerPrinter();
protected Checksum checksum = new Adler32();
@Before
public void setUp() {
@BeforeEach
void setUp() {
checksum.reset();
}
@@ -43,37 +46,37 @@ public abstract class AbstractClasspathEntryFingerprinterTest {
protected abstract File createValidNonEmptyFile() throws IOException;
@Test
public void appliesToNullIsSafe() {
void appliesToNullIsSafe() {
fingerprinter.appliesTo(null);
}
@Parameters(method = "getValidFileExtensions")
@Test
public void appliesToValidFile(final String extension) {
Assert.assertTrue(fingerprinter.appliesTo(extension));
@ParameterizedTest
@MethodSource("getValidFileExtensions")
void appliesToValidFile(final String extension) {
assertTrue(fingerprinter.appliesTo(extension));
}
@Parameters(method = "getInvalidFileExtensions")
@Test
public void doesNotApplyToInvalidFile(final String extension) {
Assert.assertFalse(fingerprinter.appliesTo(extension));
@ParameterizedTest
@MethodSource("getInvalidFileExtensions")
void doesNotApplyToInvalidFile(final String extension) {
assertFalse(fingerprinter.appliesTo(extension));
}
@Test
public void fingerprintNonExistingFile() throws MalformedURLException, IOException {
void fingerprintNonExistingFile() throws MalformedURLException, IOException {
final long prevValue = checksum.getValue();
fingerprinter.fingerprint(new File("non-existing").toURI().toURL(), checksum);
Assert.assertEquals(prevValue, checksum.getValue());
assertEquals(prevValue, checksum.getValue());
}
@Test
public void fingerprintExistingValidFile() throws IOException {
void fingerprintExistingValidFile() throws IOException {
final long prevValue = checksum.getValue();
final File file = createValidNonEmptyFile();
Assert.assertNotEquals(prevValue, updateFingerprint(file));
assertNotEquals(prevValue, updateFingerprint(file));
}
protected long updateFingerprint(final File file) throws MalformedURLException, IOException {
@@ -10,7 +10,7 @@ import java.nio.charset.StandardCharsets;
import com.google.common.io.Files;
public class RawFileFingerprinterTest extends AbstractClasspathEntryFingerprinterTest {
class RawFileFingerprinterTest extends AbstractClasspathEntryFingerprinterTest {
@Override
protected ClasspathEntryFingerprinter newFingerPrinter() {
@@ -29,7 +29,7 @@ public class RawFileFingerprinterTest extends AbstractClasspathEntryFingerprinte
@Override
protected File createValidNonEmptyFile() throws IOException {
final File file = tempFolder.newFile("Foo.class");
File file = tempDir.resolve("Foo.class").toFile();
Files.write("some content", file, StandardCharsets.UTF_8);
return file;
Loaded 30 of 129 files, more files were not shown because too many files have changed in this diff. Show more