1   /***
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3   */
4   package test.net.sourceforge.pmd.symboltable;
5   
6   import junit.framework.TestCase;
7   import net.sourceforge.pmd.ast.ASTVariableDeclaratorId;
8   import net.sourceforge.pmd.ast.SimpleNode;
9   import net.sourceforge.pmd.symboltable.AbstractScope;
10  import net.sourceforge.pmd.symboltable.ClassScope;
11  import net.sourceforge.pmd.symboltable.NameDeclaration;
12  import net.sourceforge.pmd.symboltable.NameOccurrence;
13  import net.sourceforge.pmd.symboltable.Scope;
14  import net.sourceforge.pmd.symboltable.VariableNameDeclaration;
15  
16  import java.util.Iterator;
17  
18  public class AbstractScopeTest extends TestCase {
19  
20      // A helper class to stub out AbstractScope's abstract stuff
21      private class MyScope extends AbstractScope {
22          protected NameDeclaration findVariableHere(NameOccurrence occ) {
23              for (Iterator i = variableNames.keySet().iterator(); i.hasNext();) {
24                  NameDeclaration decl = (NameDeclaration) i.next();
25                  if (decl.getImage().equals(occ.getImage())) {
26                      return decl;
27                  }
28              }
29              return null;
30          }
31      }
32  
33      // Another helper class to test the search for a class scope behavior
34      private class IsEnclosingClassScope extends ClassScope {
35  
36          public IsEnclosingClassScope(String name) {
37              super(name);
38          }
39  
40          protected NameDeclaration findVariableHere(NameOccurrence occ) {
41              return null;
42          }
43  
44          public ClassScope getEnclosingClassScope() {
45              return this;
46          }
47      }
48  
49      public void testAccessors() {
50          Scope scope = new MyScope();
51          MyScope parent = new MyScope();
52          scope.setParent(parent);
53          assertEquals(parent, scope.getParent());
54  
55          assertTrue(!scope.getVariableDeclarations(false).keySet().iterator().hasNext());
56          assertTrue(scope.getVariableDeclarations(true).isEmpty());
57      }
58  
59      public void testEnclClassScopeGetsDelegatedRight() {
60          Scope scope = new MyScope();
61          Scope isEncl = new IsEnclosingClassScope("Foo");
62          scope.setParent(isEncl);
63          assertEquals(isEncl, scope.getEnclosingClassScope());
64      }
65  
66      public void testAdd() {
67          Scope scope = new MyScope();
68          ASTVariableDeclaratorId node = new ASTVariableDeclaratorId(1);
69          node.setImage("foo");
70          VariableNameDeclaration decl = new VariableNameDeclaration(node);
71          scope.addDeclaration(decl);
72          assertTrue(scope.contains(new NameOccurrence(new SimpleNode(1), "foo")));
73      }
74  }