1 21 22 package net.percederberg.grammatica.test; 23 24 import java.io.StringReader ; 25 26 import net.percederberg.grammatica.parser.ParseException; 27 import net.percederberg.grammatica.parser.Parser; 28 import net.percederberg.grammatica.parser.ParserCreationException; 29 30 36 public class TestArithmeticParser extends ParserTestCase { 37 38 41 private static final String VALID_INPUT = 42 "1 + 2*a\n" + 43 " + 345"; 44 45 48 private static final String VALID_OUTPUT = 49 "Expression(2001)\n" + 50 " Term(2003)\n" + 51 " Factor(2005)\n" + 52 " Atom(2006)\n" + 53 " NUMBER(1007): \"1\", line: 1, col: 1\n" + 54 " ExpressionRest(2002)\n" + 55 " ADD(1001): \"+\", line: 1, col: 3\n" + 56 " Expression(2001)\n" + 57 " Term(2003)\n" + 58 " Factor(2005)\n" + 59 " Atom(2006)\n" + 60 " NUMBER(1007): \"2\", line: 1, col: 5\n" + 61 " TermRest(2004)\n" + 62 " MUL(1003): \"*\", line: 1, col: 6\n" + 63 " Term(2003)\n" + 64 " Factor(2005)\n" + 65 " Atom(2006)\n" + 66 " IDENTIFIER(1008): \"a\", line: 1, col: 7\n" + 67 " ExpressionRest(2002)\n" + 68 " ADD(1001): \"+\", line: 2, col: 2\n" + 69 " Expression(2001)\n" + 70 " Term(2003)\n" + 71 " Factor(2005)\n" + 72 " Atom(2006)\n" + 73 " NUMBER(1007): \"345\", line: 2, col: 4\n"; 74 75 78 private static final String UNEXPECTED_EOF_INPUT = "1 *\t \n"; 79 80 83 private static final String UNEXPECTED_CHAR_INPUT = "1\n # 4"; 84 85 88 private static final String UNEXPECTED_TOKEN_INPUT = "1 + 2 3"; 89 90 95 public TestArithmeticParser(String name) { 96 super(name); 97 } 98 99 102 public void testValidInput() { 103 parse(createParser(VALID_INPUT), VALID_OUTPUT); 104 } 105 106 109 public void testUnexpectedEOF() { 110 failParse(createParser(UNEXPECTED_EOF_INPUT), 111 ParseException.UNEXPECTED_EOF_ERROR, 112 2, 113 1); 114 } 115 116 119 public void testUnexpectedChar() { 120 failParse(createParser(UNEXPECTED_CHAR_INPUT), 121 ParseException.UNEXPECTED_CHAR_ERROR, 122 2, 123 2); 124 } 125 126 129 public void testUnexpectedToken() { 130 failParse(createParser(UNEXPECTED_TOKEN_INPUT), 131 ParseException.UNEXPECTED_TOKEN_ERROR, 132 1, 133 7); 134 } 135 136 139 public void testParserReusage() { 140 Parser p; 141 142 p = createParser(VALID_INPUT); 143 parse(p, VALID_OUTPUT); 144 p.getTokenizer().reset(new StringReader (UNEXPECTED_CHAR_INPUT)); 145 failParse(p, ParseException.UNEXPECTED_CHAR_ERROR, 2, 2); 146 p.getTokenizer().reset(new StringReader (VALID_INPUT)); 147 parse(p, VALID_OUTPUT); 148 } 149 150 157 private Parser createParser(String input) { 158 Parser parser = null; 159 160 try { 161 parser = new ArithmeticParser(new StringReader (input)); 162 parser.prepare(); 163 } catch (ParserCreationException e) { 164 fail(e.getMessage()); 165 } 166 return parser; 167 } 168 } 169 | Popular Tags |