Applied patch 1583167 - Better test code management from Wouter

Made one small change - initial patch had resources in the same directory. Changed to look in current directory + xml. So, core rules are test.net.sf.pmd.rules.xml

If anyone disagrees with this I'm not 100% set on this decision - it made it cleaner to me


git-svn-id: https://pmd.svn.sourceforge.net/svnroot/pmd/trunk@4757 51baf565-9d33-0410-a72c-fc3788e3496d
This commit is contained in:
Allan Caplan
2006-10-27 02:01:25 +00:00
parent 523da8ab31
commit da00dd2a2b
7 changed files with 148 additions and 45 deletions

View File

@ -17,6 +17,7 @@ Fixed bug 1581123 - False +: UnnecessaryWrapperObjectCreation.
Applied patch 1551189 - SingularField false + for initialization blocks
Applied patch 1573981 - false + in CloneMethodMustImplementCloneable
Applied patch 1574988 - false + in OverrideBothEqualsAndHashcode
Applied patch 1583167 - Better test code management. Internal JUnits can now be written in XML's
Implemented RFE 1566313 - Command Line now takes minimumpriority attribute to filter out rulesets
PMD now requires JDK 1.4 to run. Note that, however, PMD will still analyze code from earlier JDKs.
SummaryHTML Report changes from Brent Fisher - now contains linePrefix to support source output from javadoc using "linksource"

View File

@ -1,43 +1,16 @@
package test.net.sourceforge.pmd.rules;
import net.sourceforge.pmd.PMD;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.RuleSetNotFoundException;
import test.net.sourceforge.pmd.testframework.SimpleAggregatorTst;
import test.net.sourceforge.pmd.testframework.TestDescriptor;
public class BrokenNullCheckTest extends SimpleAggregatorTst {
private Rule rule;
public void setUp() throws RuleSetNotFoundException {
public void setUp() {
rule = findRule("basic", "BrokenNullCheck");
}
public void testAll() {
runTests(new TestDescriptor[]{
new TestDescriptor(TEST1, "should be ||", 1, rule),
new TestDescriptor(TEST2, "should be &&", 1, rule),
});
runTests(rule);
}
private static final String TEST1 =
"public class Foo {" + PMD.EOL +
" List bar(List list) {" + PMD.EOL +
" if (list != null || !list.equals(buz)) {" + PMD.EOL +
" return list;" + PMD.EOL +
" }" + PMD.EOL +
" }" + PMD.EOL +
"}";
private static final String TEST2 =
"public class Foo {" + PMD.EOL +
" List bar(List list) {" + PMD.EOL +
" if (list == null && list.equals(buz)) {" + PMD.EOL +
" return list;" + PMD.EOL +
" }" + PMD.EOL +
" }" + PMD.EOL +
"}";
}

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<test-data>
<test-code>
<description><![CDATA[
should be ||
]]></description>
<expected-problems>1</expected-problems>
<code><![CDATA[
public class Foo {
List bar(List list) {
if (list != null || !list.equals(buz)) {
return list;
}
}
}]]> </code>
</test-code>
<test-code>
<description><![CDATA[
should be &&
]]></description>
<expected-problems>1</expected-problems>
<code><![CDATA[
public class Foo {
List bar(List list) {
if (list == null && list.equals(buz)) {
return list;
}
}
}]]> </code>
</test-code>
</test-data>

View File

@ -3,6 +3,15 @@
*/
package test.net.sourceforge.pmd.testframework;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import junit.framework.TestCase;
import net.sourceforge.pmd.PMD;
import net.sourceforge.pmd.Report;
@ -16,13 +25,25 @@ import net.sourceforge.pmd.SimpleRuleSetNameMapper;
import net.sourceforge.pmd.SourceType;
import net.sourceforge.pmd.SourceTypeToRuleLanguageMapper;
import java.io.StringReader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class RuleTst extends TestCase {
public static final SourceType DEFAULT_SOURCE_TYPE = SourceType.JAVA_14;
public void runTestFromString(String code, int expectedResults, Rule rule) throws Throwable {
runTestFromString(code, expectedResults, rule, DEFAULT_SOURCE_TYPE);
public void runTestFromString(TestDescriptor test) throws Throwable {
runTestFromString(test, DEFAULT_SOURCE_TYPE);
}
/**
* @deprecated use runTestFromString(TestDescriptor test)
*/
public void runTestFromString(String code, int numberOfProblemsExpected, Rule rule) throws Throwable {
TestDescriptor test = new TestDescriptor(code, "", numberOfProblemsExpected, rule);
runTestFromString(test, DEFAULT_SOURCE_TYPE);
}
public Rule findRule(String rs, String r) {
@ -48,11 +69,11 @@ public class RuleTst extends TestCase {
* @param rule
* @throws Throwable
*/
public void runTestFromString(String code, int expectedResults, Rule rule,
public void runTestFromString(TestDescriptor test,
SourceType sourceType) throws Throwable {
int res = processUsingStringReader(code, rule, sourceType).size();
assertEquals("Expected " + expectedResults + " failures, got " + res + ".",
expectedResults, res);
int res = processUsingStringReader(test.getCode(), test.getRule(), sourceType).size();
assertEquals("\"" + test.getDescription() + "\" test resulted in wrong amount of failures,",
test.getNumberOfProblemsExpected(), res);
}
private Report processUsingStringReader(String code, Rule rule,
@ -82,6 +103,63 @@ public class RuleTst extends TestCase {
p.processFile(new StringReader(code), new RuleSets(rules), ctx, sourceType);
}
public TestDescriptor[] extractTestsFromXml(Rule rule) {
String testXmlFileName = "xml/" + rule.getName() + ".xml";
InputStream inputStream = getClass().getResourceAsStream(testXmlFileName);
Document doc;
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
doc = builder.parse(inputStream);
} catch (ParserConfigurationException pce) {
pce.printStackTrace();
throw new RuntimeException("Couldn't find " + testXmlFileName + ", due to: " + pce.getMessage());
} catch (FactoryConfigurationError fce) {
fce.printStackTrace();
throw new RuntimeException("Couldn't find " + testXmlFileName + ", due to: " + fce.getMessage());
} catch (IOException ioe) {
ioe.printStackTrace();
throw new RuntimeException("Couldn't find " + testXmlFileName + ", due to: " + ioe.getMessage());
} catch (SAXException se) {
se.printStackTrace();
throw new RuntimeException("Couldn't find " + testXmlFileName + ", due to: " + se.getMessage());
}
Element root = doc.getDocumentElement();
NodeList testCodes = root.getElementsByTagName("test-code");
TestDescriptor[] tests = new TestDescriptor[testCodes.getLength()];
for (int i = 0; i < testCodes.getLength(); i++) {
Element testCode = (Element)testCodes.item(i);
int expectedProblems = Integer.parseInt(getNodeValue(testCode, "expected-problems"));
String description = getNodeValue(testCode, "description");
String code = getNodeValue(testCode, "code");
tests[i] = new TestDescriptor(code, description, expectedProblems, rule);
}
return tests;
}
private String getNodeValue(Element parentElm, String nodeName) {
NodeList nodes = parentElm.getElementsByTagName(nodeName);
if (nodes == null || nodes.getLength() == 0) {
throw new RuntimeException("Required tag is missing from the test-xml: " + nodeName);
}
Node node = nodes.item(0);
String value = parseTextNode(node);
return value.trim();
}
private static String parseTextNode(Node exampleNode) {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < exampleNode.getChildNodes().getLength(); i++) {
Node node = exampleNode.getChildNodes().item(i);
if (node.getNodeType() == Node.CDATA_SECTION_NODE
|| node.getNodeType() == Node.TEXT_NODE) {
buffer.append(node.getNodeValue());
}
}
return buffer.toString();
}
public void runTestFromString(String code, Rule rule, Report report) throws Throwable {
runTestFromString(code, rule, report, DEFAULT_SOURCE_TYPE);

View File

@ -3,9 +3,14 @@
*/
package test.net.sourceforge.pmd.testframework;
import net.sourceforge.pmd.Rule;
import net.sourceforge.pmd.SourceType;
public class SimpleAggregatorTst extends RuleTst {
public void runTests(Rule rule) {
runTests(extractTestsFromXml(rule));
}
public void runTests(TestDescriptor[] tests) {
runTests(tests, DEFAULT_SOURCE_TYPE);
@ -19,11 +24,10 @@ public class SimpleAggregatorTst extends RuleTst {
public void runTests(TestDescriptor[] tests, SourceType sourceType) {
for (int i = 0; i < tests.length; i++) {
try {
runTestFromString(tests[i].code, tests[i].numberOfProblemsExpected,
tests[i].rule, sourceType);
runTestFromString(tests[i], sourceType);
} catch (Throwable t) {
t.printStackTrace();
throw new RuntimeException("Test \"" + tests[i].description + "\" failed");
throw new RuntimeException("Test \"" + tests[i].getDescription() + "\" failed");
}
}
}

View File

@ -7,10 +7,10 @@ import net.sourceforge.pmd.Rule;
public class TestDescriptor {
public String code;
public String description;
public int numberOfProblemsExpected;
public Rule rule;
private String code;
private String description;
private int numberOfProblemsExpected;
private Rule rule;
public TestDescriptor(String code, String description, int numberOfProblemsExpected, Rule rule) {
this.rule = rule;
@ -18,4 +18,20 @@ public class TestDescriptor {
this.description = description;
this.numberOfProblemsExpected = numberOfProblemsExpected;
}
public String getCode() {
return code;
}
public String getDescription() {
return description;
}
public int getNumberOfProblemsExpected() {
return numberOfProblemsExpected;
}
public Rule getRule() {
return rule;
}
}

View File

@ -56,7 +56,7 @@
<li><a href="http://www.livejournal.com/users/insac/">Fabio Insaccanebbia</a> - Improvement for UseArraysAsList, UnusedNullCheckInEquals, MisplacedNullCheck, UselessOperationOnImmutable, AvoidArrayLoops, UseArraysAsList, AvoidConstantsInterface, AvoidDecimalLiteralsInBigDecimalConstructor, ClassCastExceptionWithToArray, BigIntegerInstantiation_1.4, BigIntegerInstantiation_1.5</li>
<li>Ryan Gustafson - Patch to fix bug in AvoidDecimalLiteralsInBigDecimalConstructor, patch to add "ref" overrides to RuleSetFactory, patch to fix JDK 1.3 incompatibilities in PMD 2.0</li>
<li>Stefan Seidel - Reported JDK 1.5 parsing bug</li>
<li>Wouter Zelle - Fixed bug in OverrideBothEqualsAndHashcode, wrote BrokenNullCheck rule, fixed a false positive in InefficientStringBuffering, fixed a false positive in NonThreadSafeSingleton, a nice patch to clean up some of the Ant task properties and fix a TextRenderer bug, rewrote PositionLiteralsFirstInComparisons in XPath, Renderer improvement suggestions, wrote NonThreadSafeSingleton rule, wrote DefaultPackage rule, worked thru ASTMethodDeclaration.isSyntacticallyX design, reported docs bug 1292689 for UnnecessaryLocalBeforeReturn, reported leftover ExceptionTypeChecking source file, rewrote UselessOverridingMethod in Java, UselessOverridingMethod rule, ProperLogger rule, nifty code to allow variables in XPath rules, externalInfoUrl data for all rules in basic and unusedcode rulesets, some very nifty XSLT, improvements to UseCorrectExceptionLogging, designed and implemented the "externalInfoUrl" feature in the rule definitions, fixed a devious bug in RuleSetFactory, AvoidPrintStackTrace, initial implementation of SimplifyConditional</li>
<li>Wouter Zelle - Fixed bug in OverrideBothEqualsAndHashcode, wrote BrokenNullCheck rule, fixed a false positive in InefficientStringBuffering, fixed a false positive in NonThreadSafeSingleton, a nice patch to clean up some of the Ant task properties and fix a TextRenderer bug, rewrote PositionLiteralsFirstInComparisons in XPath, Renderer improvement suggestions, wrote NonThreadSafeSingleton rule, wrote DefaultPackage rule, worked thru ASTMethodDeclaration.isSyntacticallyX design, reported docs bug 1292689 for UnnecessaryLocalBeforeReturn, reported leftover ExceptionTypeChecking source file, rewrote UselessOverridingMethod in Java, UselessOverridingMethod rule, ProperLogger rule, nifty code to allow variables in XPath rules, externalInfoUrl data for all rules in basic and unusedcode rulesets, some very nifty XSLT, improvements to UseCorrectExceptionLogging, designed and implemented the "externalInfoUrl" feature in the rule definitions, fixed a devious bug in RuleSetFactory, AvoidPrintStackTrace, initial implementation of SimplifyConditional, Implemented JUnit XML framework</li>
<li>Aaron Optimizer Digulla - Tweaks to pmd.bat</li>
<li>Peter Van de Voorde - Rewrote the 'create rule XML' functionality in the designer utility</li>
<li>Josh Devins - Reported bug with annotation parsing</li>