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