1import antlr3 2import testbase 3import unittest 4 5class t015calc(testbase.ANTLRTest): 6 def setUp(self): 7 self.compileGrammar() 8 9 10 def _evaluate(self, expr, expected, errors=[]): 11 cStream = antlr3.StringStream(expr) 12 lexer = self.getLexer(cStream) 13 tStream = antlr3.CommonTokenStream(lexer) 14 parser = self.getParser(tStream) 15 result = parser.evaluate() 16 self.assertEqual(result, expected) 17 self.assertEqual(len(parser.reportedErrors), len(errors), 18 parser.reportedErrors) 19 20 21 def testValid01(self): 22 self._evaluate("1 + 2", 3) 23 24 25 def testValid02(self): 26 self._evaluate("1 + 2 * 3", 7) 27 28 29 def testValid03(self): 30 self._evaluate("10 / 2", 5) 31 32 33 def testValid04(self): 34 self._evaluate("6 + 2*(3+1) - 4", 10) 35 36 37 def testMalformedInput(self): 38 self._evaluate("6 - (2*1", 4, ["mismatched token at pos 8"]) 39 40 # FIXME: most parse errors result in TypeErrors in action code, because 41 # rules return None, which is then added/multiplied... to integers. 42 # evaluate("6 - foo 2", 4, ["some error"]) 43 44 45if __name__ == '__main__': 46 unittest.main() 47 48