aboutsummaryrefslogtreecommitdiff
path: root/runtime/Python/tests/t012lexerXML.py
blob: 3e8f8b4e7ec4f6dcfb4ba2fc64b925baaadca304 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import antlr3
import testbase
import unittest
import os
import sys
from cStringIO import StringIO
import difflib
import textwrap

class t012lexerXML(testbase.ANTLRTest):
    def setUp(self):
        self.compileGrammar('t012lexerXMLLexer.g')
        
        
    def lexerClass(self, base):
        class TLexer(base):
            def emitErrorMessage(self, msg):
                # report errors to /dev/null
                pass

            def reportError(self, re):
                # no error recovery yet, just crash!
                raise re

        return TLexer
    
        
    def testValid(self):
        inputPath = os.path.splitext(__file__)[0] + '.input'
        stream = antlr3.StringStream(unicode(open(inputPath).read(), 'utf-8'))
        lexer = self.getLexer(stream)

        while True:
            token = lexer.nextToken()
            if token.type == self.lexerModule.EOF:
                break


        output = unicode(lexer.outbuf.getvalue(), 'utf-8')

        outputPath = os.path.splitext(__file__)[0] + '.output'
        testOutput = unicode(open(outputPath).read(), 'utf-8')

        success = (output == testOutput)
        if not success:
            d = difflib.Differ()
            r = d.compare(output.splitlines(1), testOutput.splitlines(1))
            self.fail(
                ''.join([l.encode('ascii', 'backslashreplace') for l in r])
                )


    def testMalformedInput1(self):
        input = textwrap.dedent("""\
        <?xml version='1.0'?>
        <document d>
        </document>
        """)

        stream = antlr3.StringStream(input)
        lexer = self.getLexer(stream)

        try:
            while True:
                token = lexer.nextToken()
                if token.type == antlr3.EOF:
                    break

            raise AssertionError

        except antlr3.NoViableAltException, exc:
            assert exc.unexpectedType == '>', repr(exc.unexpectedType)
            assert exc.charPositionInLine == 11, repr(exc.charPositionInLine)
            assert exc.line == 2, repr(exc.line)


    def testMalformedInput2(self):
        input = textwrap.dedent("""\
        <?tml version='1.0'?>
        <document>
        </document>
        """)

        stream = antlr3.StringStream(input)
        lexer = self.getLexer(stream)

        try:
            while True:
                token = lexer.nextToken()
                if token.type == antlr3.EOF:
                    break

            raise AssertionError

        except antlr3.MismatchedSetException, exc:
            assert exc.unexpectedType == 't', repr(exc.unexpectedType)
            assert exc.charPositionInLine == 2, repr(exc.charPositionInLine)
            assert exc.line == 1, repr(exc.line)


    def testMalformedInput3(self):
        input = textwrap.dedent("""\
        <?xml version='1.0'?>
        <docu ment attr="foo">
        </document>
        """)

        stream = antlr3.StringStream(input)
        lexer = self.getLexer(stream)

        try:
            while True:
                token = lexer.nextToken()
                if token.type == antlr3.EOF:
                    break

            raise AssertionError

        except antlr3.NoViableAltException, exc:
            assert exc.unexpectedType == 'a', repr(exc.unexpectedType)
            assert exc.charPositionInLine == 11, repr(exc.charPositionInLine)
            assert exc.line == 2, repr(exc.line)

            

if __name__ == '__main__':
    unittest.main()


## # run an infinite loop with randomly mangled input
## while True:
##     print "ping"

##     input = """\
## <?xml version='1.0'?>
## <!DOCTYPE component [
## <!ELEMENT component (PCDATA|sub)*>
## <!ATTLIST component
##           attr CDATA #IMPLIED
##           attr2 CDATA #IMPLIED
## >
## <!ELMENT sub EMPTY>

## ]>
## <component attr="val'ue" attr2='val"ue'>
## <!-- This is a comment -->
## Text
## <![CDATA[huhu]]>
## &amp;
## &lt;
## <?xtal cursor='11'?>
## <sub/>
## <sub></sub>
## </component>
## """

##     import random
##     input = list(input) # make it mutable
##     for _ in range(3):
##         p1 = random.randrange(len(input))
##         p2 = random.randrange(len(input))

##         c1 = input[p1]
##         input[p1] = input[p2]
##         input[p2] = c1
##     input = ''.join(input) # back to string
        
##     stream = antlr3.StringStream(input)
##     lexer = Lexer(stream)

##     try:
##         while True:
##             token = lexer.nextToken()
##             if token.type == EOF:
##                 break

##     except antlr3.RecognitionException, exc:
##         print exc
##         for l in input.splitlines()[0:exc.line]:
##             print l
##         print ' '*exc.charPositionInLine + '^'

##     except BaseException, exc:
##         print '\n'.join(['%02d: %s' % (idx+1, l) for idx, l in enumerate(input.splitlines())])
##         print "%s at %d:%d" % (exc, stream.line, stream.charPositionInLine)
##         print
        
##         raise