1   
2    package test.net.sourceforge.pmd;
3    
4    import static org.junit.Assert.assertEquals;
5   import static org.junit.Assert.assertTrue;
6   import net.sourceforge.pmd.PMD;
7   import net.sourceforge.pmd.Report;
8   import net.sourceforge.pmd.Rule;
9   import net.sourceforge.pmd.RuleContext;
10  import net.sourceforge.pmd.RuleSet;
11  import net.sourceforge.pmd.RuleSets;
12  import net.sourceforge.pmd.SourceTypeToRuleLanguageMapper;
13  
14  import org.junit.Before;
15  import org.junit.Test;
16  
17  import test.net.sourceforge.pmd.testframework.RuleTst;
18  import test.net.sourceforge.pmd.testframework.TestDescriptor;
19  
20  import java.io.StringReader;
21  
22  import junit.framework.JUnit4TestAdapter;
23  
24   public class ExcludeLinesTest extends RuleTst {
25       private Rule rule;
26   
27       @Before 
28       public void setUp() {
29           rule = findRule("unusedcode", "UnusedLocalVariable");
30       }
31   
32       @Test
33       public void testAcceptance() {
34           runTest(new TestDescriptor(TEST1, "NOPMD should work", 0, rule));
35           runTest(new TestDescriptor(TEST2, "Should fail without exclude marker", 1, rule));
36       }
37   
38       @Test
39       public void testAlternateMarker() throws Throwable {
40           PMD p = new PMD();
41           p.setExcludeMarker("FOOBAR");
42           RuleContext ctx = new RuleContext();
43           Report r = new Report();
44           ctx.setReport(r);
45           ctx.setSourceCodeFilename("n/a");
46           RuleSet rules = new RuleSet();
47           rules.addRule(rule);
48           rules.setLanguage(SourceTypeToRuleLanguageMapper.getMappedLanguage(DEFAULT_SOURCE_TYPE));
49           p.processFile(new StringReader(TEST3), new RuleSets(rules), ctx, DEFAULT_SOURCE_TYPE);
50           assertTrue(r.isEmpty());
51           assertEquals(r.getSuppressedRuleViolations().size(), 1);
52       }
53   
54       private static final String TEST1 =
55               "public class Foo {" + PMD.EOL +
56               " void foo() {" + PMD.EOL +
57               "  int x; //NOPMD " + PMD.EOL +
58               " } " + PMD.EOL +
59               "}";
60   
61       private static final String TEST2 =
62               "public class Foo {" + PMD.EOL +
63               " void foo() {" + PMD.EOL +
64               "  int x;" + PMD.EOL +
65               " } " + PMD.EOL +
66               "}";
67   
68       private static final String TEST3 =
69               "public class Foo {" + PMD.EOL +
70               " void foo() {" + PMD.EOL +
71               "  int x; // FOOBAR" + PMD.EOL +
72               " } " + PMD.EOL +
73               "}";
74  
75      public static junit.framework.Test suite() {
76          return new JUnit4TestAdapter(ExcludeLinesTest.class);
77      }
78  }