1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3   */
4   package test.net.sourceforge.pmd.testframework;
5   
6   import junit.framework.TestCase;
7   import net.sourceforge.pmd.PMD;
8   import net.sourceforge.pmd.Report;
9   import net.sourceforge.pmd.Rule;
10  import net.sourceforge.pmd.RuleContext;
11  import net.sourceforge.pmd.RuleSet;
12  import net.sourceforge.pmd.RuleSetFactory;
13  import net.sourceforge.pmd.RuleSetNotFoundException;
14  import net.sourceforge.pmd.SimpleRuleSetNameMapper;
15  import net.sourceforge.pmd.TargetJDK1_4;
16  import net.sourceforge.pmd.TargetJDK1_5;
17  import net.sourceforge.pmd.TargetJDKVersion;
18  
19  import java.io.StringReader;
20  
21  public class RuleTst extends TestCase {
22  
23      public void runTestFromString(String code, int expectedResults, Rule rule) throws Throwable {
24          int res = processUsingStringReader(code, rule).size();
25          assertEquals("Expected " + expectedResults + " failures, got " + res + ".", expectedResults, res);
26      }
27  
28      public Rule findRule(String rs, String r) {
29          try {
30  			Rule rule = new RuleSetFactory().createRuleSet(new SimpleRuleSetNameMapper(rs).getRuleSets()).getRuleByName(r);
31              if (rule == null){
32                  fail("Rule "+r+" not found in ruleset "+rs);
33              }
34              return rule;
35  		} catch (RuleSetNotFoundException e) {
36  			e.printStackTrace();
37  			fail("Couldn't find ruleset "+rs);
38  			return null;
39  		}
40      }
41  
42      public void runTestFromString(String code, Rule rule, Report report) throws Throwable {
43          runTestFromString(code, rule, report, new TargetJDK1_4());
44      }
45  
46      public void runTestFromString15(String code, Rule rule, Report report) throws Throwable {
47          runTestFromString(code, rule, report, new TargetJDK1_5());
48      }
49  
50      public void runTestFromString(String code, Rule rule, Report report, TargetJDKVersion jdk) throws Throwable {
51          PMD p = new PMD(jdk);
52          RuleContext ctx = new RuleContext();
53          ctx.setReport(report);
54          ctx.setSourceCodeFilename("n/a");
55          RuleSet rules = new RuleSet();
56          rules.addRule(rule);
57          p.processFile(new StringReader(code), rules, ctx);
58      }
59  
60      private Report processUsingStringReader(String code, Rule rule) throws Throwable {
61          Report report = new Report();
62          runTestFromString(code, rule, report);
63          return report;
64      }
65  }