View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.xml.rule;
5   
6   import static org.junit.Assert.assertEquals;
7   
8   import java.io.StringReader;
9   import java.util.ArrayList;
10  import java.util.List;
11  
12  import net.sourceforge.pmd.RuleContext;
13  import net.sourceforge.pmd.lang.Language;
14  import net.sourceforge.pmd.lang.Parser;
15  import net.sourceforge.pmd.lang.ast.Node;
16  import net.sourceforge.pmd.lang.xml.XmlParserOptions;
17  import net.sourceforge.pmd.lang.xml.ast.XmlNode;
18  
19  import org.junit.Test;
20  
21  public class AbstractXmlRuleTest {
22  
23      @Test
24      public void testVisit() throws Exception {
25  	String source = "<?xml version=\"1.0\"?><foo abc=\"abc\"><bar/></foo>";
26  	XmlParserOptions parserOptions = new XmlParserOptions();
27  	Parser parser = Language.XML.getDefaultVersion().getLanguageVersionHandler().getParser(parserOptions);
28  	XmlNode xmlNode = (XmlNode) parser.parse(null, new StringReader(source));
29  	List<XmlNode> nodes = new ArrayList<XmlNode>();
30  	nodes.add(xmlNode);
31  
32  	MyRule rule = new MyRule();
33  	rule.apply(nodes, null);
34  
35  	assertEquals(3, rule.visitedNodes.size());
36  	assertEquals("document", rule.visitedNodes.get(0).toString());
37  	assertEquals("foo", rule.visitedNodes.get(1).toString());
38  	assertEquals("bar", rule.visitedNodes.get(2).toString());
39      }
40  
41      private static class MyRule extends AbstractXmlRule {
42  	final List<XmlNode> visitedNodes = new ArrayList<XmlNode>();
43  
44  	public MyRule() {
45  	}
46  
47  	@Override
48  	public void apply(List<? extends Node> nodes, RuleContext ctx) {
49  	    visitedNodes.clear();
50  	    super.apply(nodes, ctx);
51  	}
52  
53  	@Override
54  	protected void visit(XmlNode node, RuleContext ctx) {
55  	    visitedNodes.add(node);
56  	    super.visit(node, ctx);
57  	}
58      }
59  
60      public static junit.framework.Test suite() {
61  	return new junit.framework.JUnit4TestAdapter(AbstractXmlRuleTest.class);
62      }
63  }