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