View Javadoc

1   /**
2    * BSD-style license; for more info see http://pmd.sourceforge.net/license.html
3    */
4   package net.sourceforge.pmd.lang.ecmascript.ast;
5   
6   import java.util.List;
7   
8   import org.junit.Assert;
9   import org.junit.Test;
10  import org.mozilla.javascript.ast.AstRoot;
11  
12  /**
13   * See the following bugs:
14   * #1141 ECMAScript: getFinallyBlock() is buggy. 
15   * #1142 ECMAScript: getCatchClause() is buggy 
16   */
17  public class ASTTryStatementTest extends EcmascriptParserTestBase {
18  
19      private ASTTryStatement getTryStmt(String js) {
20          EcmascriptNode<AstRoot> node = parse(js);
21          List<ASTTryStatement> trys = node.findDescendantsOfType(ASTTryStatement.class);
22          Assert.assertEquals(1, trys.size());
23          ASTTryStatement tryStmt = trys.get(0);
24          return tryStmt;
25      }
26  
27      @Test
28      public void testFinallyBlockOnly() {
29          ASTTryStatement tryStmt = getTryStmt("function() { try { } finally { } }");
30          Assert.assertNull(tryStmt.getCatchClause(0));
31          Assert.assertFalse(tryStmt.hasCatch());
32          Assert.assertEquals(0, tryStmt.getNumCatchClause());
33          Assert.assertNotNull(tryStmt.getFinallyBlock());
34          Assert.assertTrue(tryStmt.hasFinally());
35      }
36  
37      @Test
38      public void testCatchBlockOnly() {
39          ASTTryStatement tryStmt = getTryStmt("function() { try { } catch (error) { } }");
40          Assert.assertNotNull(tryStmt.getCatchClause(0));
41          Assert.assertTrue(tryStmt.hasCatch());
42          Assert.assertEquals(1, tryStmt.getNumCatchClause());
43          Assert.assertNull(tryStmt.getFinallyBlock());
44          Assert.assertFalse(tryStmt.hasFinally());
45      }
46  
47      @Test
48      public void testCatchAndFinallyBlock() {
49          ASTTryStatement tryStmt = getTryStmt("function() { try { } catch (error) { } finally { } }");
50          Assert.assertNotNull(tryStmt.getCatchClause(0));
51          Assert.assertTrue(tryStmt.hasCatch());
52          Assert.assertEquals(1, tryStmt.getNumCatchClause());
53          Assert.assertNotNull(tryStmt.getFinallyBlock());
54          Assert.assertTrue(tryStmt.hasFinally());
55      }
56  
57      @Test
58      public void testMultipleCatchAndFinallyBlock() {
59          ASTTryStatement tryStmt = getTryStmt("function() { "
60                  + "try { } "
61                  + "catch (error if error instanceof BadError) { } "
62                  + "catch (error2 if error2 instanceof OtherError) { } "
63                  + "finally { } }");
64          Assert.assertNotNull(tryStmt.getCatchClause(0));
65          Assert.assertNotNull(tryStmt.getCatchClause(1));
66          Assert.assertTrue(tryStmt.hasCatch());
67          Assert.assertEquals(2, tryStmt.getNumCatchClause());
68          Assert.assertNotNull(tryStmt.getFinallyBlock());
69          Assert.assertTrue(tryStmt.hasFinally());
70      }
71  }