1 package test.net.sourceforge.pmd.rules; 2 3 import static org.junit.Assert.assertEquals; 4 import net.sourceforge.pmd.PMD; 5 import net.sourceforge.pmd.Report; 6 import net.sourceforge.pmd.Rule; 7 import net.sourceforge.pmd.RuleContext; 8 import net.sourceforge.pmd.RuleSet; 9 import net.sourceforge.pmd.RuleViolation; 10 import net.sourceforge.pmd.rules.XPathRule; 11 12 import org.junit.Before; 13 import org.junit.Test; 14 15 import test.net.sourceforge.pmd.testframework.RuleTst; 16 17 import java.io.StringReader; 18 /** 19 * @author daniels 20 */ 21 public class XPathRuleTest extends RuleTst { 22 23 XPathRule rule; 24 25 @Before 26 public void setUp() { 27 rule = new XPathRule(); 28 rule.setMessage("XPath Rule Failed"); 29 } 30 31 @Test 32 public void testPluginname() throws Throwable { 33 Rule rule = new XPathRule(); 34 rule.addProperty("xpath", "//VariableDeclaratorId[string-length(@Image) < 3]"); 35 rule.setMessage("{0}"); 36 rule.addProperty("pluginname", "true"); 37 PMD p = new PMD(); 38 RuleContext ctx = new RuleContext(); 39 Report report = new Report(); 40 ctx.setReport(report); 41 ctx.setSourceCodeFilename("n/a"); 42 RuleSet rules = new RuleSet(); 43 rules.addRule(rule); 44 p.processFile(new StringReader(TEST1), rules, ctx); 45 RuleViolation rv = (RuleViolation) report.iterator().next(); 46 assertEquals("a", rv.getDescription()); 47 } 48 49 @Test 50 public void testVariables() throws Throwable { 51 Rule rule = new XPathRule(); 52 rule.addProperty("xpath", "//VariableDeclaratorId[@Image=$var]"); 53 rule.setMessage("Avoid vars"); 54 rule.addProperty("var", "fiddle"); 55 PMD p = new PMD(); 56 RuleContext ctx = new RuleContext(); 57 Report report = new Report(); 58 ctx.setReport(report); 59 ctx.setSourceCodeFilename("n/a"); 60 RuleSet rules = new RuleSet(); 61 rules.addRule(rule); 62 p.processFile(new StringReader(TEST2), rules, ctx); 63 RuleViolation rv = (RuleViolation) report.iterator().next(); 64 assertEquals(3, rv.getBeginLine()); 65 } 66 67 private static final String TEST1 = 68 "public class Foo {" + PMD.EOL + 69 " int a;" + PMD.EOL + 70 "}"; 71 72 private static final String TEST2 = 73 "public class Foo {" + PMD.EOL + 74 " int faddle;" + PMD.EOL + 75 " int fiddle;" + PMD.EOL + 76 "}"; 77 78 public static junit.framework.Test suite() { 79 return new junit.framework.JUnit4TestAdapter(XPathRuleTest.class); 80 } 81 }