• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import antlr3
2import testbase
3import unittest
4
5class t005lexer(testbase.ANTLRTest):
6    def setUp(self):
7        self.compileGrammar()
8
9
10    def lexerClass(self, base):
11        class TLexer(base):
12            def emitErrorMessage(self, msg):
13                # report errors to /dev/null
14                pass
15
16            def reportError(self, re):
17                # no error recovery yet, just crash!
18                raise re
19
20        return TLexer
21
22
23    def testValid(self):
24        stream = antlr3.StringStream('fofoofooo')
25        lexer = self.getLexer(stream)
26
27        token = lexer.nextToken()
28        assert token.type == self.lexerModule.FOO
29        assert token.start == 0, token.start
30        assert token.stop == 1, token.stop
31        assert token.text == 'fo', token.text
32
33        token = lexer.nextToken()
34        assert token.type == self.lexerModule.FOO
35        assert token.start == 2, token.start
36        assert token.stop == 4, token.stop
37        assert token.text == 'foo', token.text
38
39        token = lexer.nextToken()
40        assert token.type == self.lexerModule.FOO
41        assert token.start == 5, token.start
42        assert token.stop == 8, token.stop
43        assert token.text == 'fooo', token.text
44
45        token = lexer.nextToken()
46        assert token.type == self.lexerModule.EOF
47
48
49    def testMalformedInput1(self):
50        stream = antlr3.StringStream('2')
51        lexer = self.getLexer(stream)
52
53        try:
54            token = lexer.nextToken()
55            raise AssertionError
56
57        except antlr3.MismatchedTokenException, exc:
58            assert exc.expecting == 'f', repr(exc.expecting)
59            assert exc.unexpectedType == '2', repr(exc.unexpectedType)
60
61
62    def testMalformedInput2(self):
63        stream = antlr3.StringStream('f')
64        lexer = self.getLexer(stream)
65
66        try:
67            token = lexer.nextToken()
68            raise AssertionError
69
70        except antlr3.EarlyExitException, exc:
71            assert exc.unexpectedType == antlr3.EOF, repr(exc.unexpectedType)
72
73
74if __name__ == '__main__':
75    unittest.main()
76