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        assert result == expected, "%r != %r" % (result, expected)
17        assert len(parser.reportedErrors) == len(errors), parser.reportedErrors
18
19
20    def testValid01(self):
21        self._evaluate("1 + 2", 3)
22
23
24    def testValid02(self):
25        self._evaluate("1 + 2 * 3", 7)
26
27
28    def testValid03(self):
29        self._evaluate("10 / 2", 5)
30
31
32    def testValid04(self):
33        self._evaluate("6 + 2*(3+1) - 4", 10)
34
35
36    def testMalformedInput(self):
37        self._evaluate("6 - (2*1", 4, ["mismatched token at pos 8"])
38
39    # FIXME: most parse errors result in TypeErrors in action code, because
40    # rules return None, which is then added/multiplied... to integers.
41    # evaluate("6 - foo 2", 4, ["some error"])
42
43
44if __name__ == '__main__':
45    unittest.main()
46
47