summaryrefslogtreecommitdiff
path: root/sandbox/docutils_xml/test/test_parsers/test_XmlParser.py
blob: bab79e189f3e5d2c71d4eaf345cce78bedad2974 (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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# -*- coding: utf-8 -*-

# Copyright (C) 2013 Stefan Merten

# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; either version 2 of the License,
# or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.

"""
Test XmlParser.
"""

import unittest
import docutils.frontend
from docutils.nodes import Text

from __init__ import DocutilsTestSupport

from docutils_xml.parsers.xml import Uri2Prefixes, XmlVisitor, XmlParser, SomeChildren

###############################################################################

class XmlVisitorMock(XmlVisitor):
    """
    Mock class recording calls in document.
    """

    depth = 0
    """
    :type: int

    Current indentation depth.
    """

    indent = u"  "
    """
    :type: unicode

    Indentation to use for one step.
    """

    currentPrefix = None
    """
    :type: str

    The prefix of the current call.
    """

    currentTag = None
    """
    :type: str

    The tag of the current call.
    """

    def __recordVisit(self, elem):
        ( pfx, nm ) = self.uri2Prefixes.elem2PrefixName(elem)
        attrs = ""
        for attr in sorted(elem.keys()):
            attrs += " %s=%r" % ( attr, elem.get(attr) )
        self.document += Text("%s{ %s:%s%s\n"
                              % ( self.depth * self.indent,
                                  self.currentPrefix, self.currentTag,
                                  attrs))
        self.depth += 1
        control = elem.get('control', None)
        if control in ( 'SkipNode', 'SkipDeparture', 'SkipSiblings',
                        'SkipChildren', 'StopTraversal' ):
            e = eval("docutils.nodes.%s()" % ( control, ))
            try:
                raise e
            except ( docutils.nodes.SkipNode, docutils.nodes.SkipSiblings ):
                self.depth -= 1
                raise
        elif control == 'SomeChildren':
            tags = [ child.split(':', 1)
                     for child in elem.get('controlSomeChildren', '').split() ]
            raise SomeChildren(tags)
        return None

    def __recordDepart(self, elem):
        ( pfx, nm ) = self.uri2Prefixes.elem2PrefixName(elem)
        self.depth -= 1
        self.document += Text("%s} %s:%s\n"
                              % ( self.depth * self.indent,
                                  self.currentPrefix, self.currentTag ))
        return None

    def __getattr__(self, name):
        ( currentType, self.currentPrefix,
          self.currentTag ) = name.split('_', 2)
        if currentType == 'visit':
            return self.__recordVisit
        else:
            return self.__recordDepart

###############################################################################

class XmlParserMock(XmlParser):
    """
    Mock class recording visited nodes in the output document.
    """

    uri2Prefixes = Uri2Prefixes((
            ( 'urn:example', 'ex', 'alias', 'int' ),
            # ( 'urn:empty', u'' ), # Empty tag is not accepted by lxml
            ( 'urn:other', 'ot' ),
            ))

    visitorClass = XmlVisitorMock

###############################################################################

class XmlParserTestCase(DocutilsTestSupport.ParserTestCase):
    """
    Output checker for XmlParser.

    Supports additional settings on input and exceptions on output as
    `XsltParserTestCase` does.
    """

    parser = XmlParserMock()
    """Parser shared by all XmlParserTestCases."""

    option_parser = docutils.frontend.OptionParser(components=(
            XmlParserMock, ))

    def test_parser(self):
        if self.run_in_debugger:
            pdb.set_trace()
        if isinstance(self.input, ( list, tuple )):
            ( case_settings, input ) = self.input
        else:
            ( case_settings, input ) = ( { }, self.input )
        settings = self.settings.copy()
        settings.__dict__.update(self.suite_settings)
        settings.__dict__.update(case_settings)
        document = docutils.utils.new_document('test data', settings)
        if (isinstance(self.expected, type)
            and issubclass(self.expected, Exception)):
            with self.assertRaises(self.expected):
                self.parser.parse(input, document)
        else:
            self.parser.parse(input, document)
            output = document.pformat()
            self.compare_output(input, output, self.expected)

###############################################################################

class XmlParserTestSuite(DocutilsTestSupport.ParserTestSuite):

    test_case_class = XmlParserTestCase

###############################################################################

totest = {}

totest['simple'] = (
    ( u"""<?xml version="1.0"?>
<rootOnly/>
""",
  """<document source="test data">
    { :rootOnly
    } :rootOnly
""" ),
    ( u"""<?xml version="1.0"?>
<root>
  <embedded/>
</root>
""",
      """<document source="test data">
    { :root
      { :embedded
      } :embedded
    } :root
""" ),
    ( u"""<?xml version="1.0"?>
<root>
  <one/>
  <two/>
</root>
""",
      """<document source="test data">
    { :root
      { :one
      } :one
      { :two
      } :two
    } :root
""" ),
    ( u"""<?xml version="1.0"?>
<rootOnly otherAttr='moreContent' attribute="content"/>
""",
  """<document source="test data">
    { :rootOnly attribute='content' otherAttr='moreContent'
    } :rootOnly
""" ),
    )

totest['nonAscii'] = (
    ( u"""<?xml version="1.0"?>
<rootÜmlaut/>
""",
  """<document source="test data">
    { :rootmlaut
    } :rootmlaut
""" ),
    )

totest['encoding'] = (
    ( """<?xml version="1.0"?>
<rootOnly/>
""",
  """<document source="test data">
    { :rootOnly
    } :rootOnly
""" ),
    ( """<?xml version="1.0" encoding="ascii"?>
<rootOnly/>
""",
  """<document source="test data">
    { :rootOnly
    } :rootOnly
""" ),
    ( u"""<?xml version="1.0" encoding="ascii"?>
<rootOnly/>
""",
  """<document source="test data">
    { :rootOnly
    } :rootOnly
""" ),
    ( """<?xml version="1.0" encoding="utf-8"?>
<rootOnly/>
""",
  """<document source="test data">
    { :rootOnly
    } :rootOnly
""" ),
    ( u"""<?xml version="1.0" encoding="utf-8"?>
<rootOnly/>
""",
  """<document source="test data">
    { :rootOnly
    } :rootOnly
""" ),
    ( """<?xml version="1.0" encoding="utf-8"?>
<root\xC3\x9Cmlaut/>
""",
  u"""<document source="test data">
    { :rootmlaut
    } :rootmlaut
""" ),
    ( u"""<?xml version="1.0" encoding="utf-8"?>
<rootÜmlaut/>
""",
  u"""<document source="test data">
    { :rootmlaut
    } :rootmlaut
""" ),
    ( u"""<?xml version="1.0" encoding="bla"?>
<rootÜmlaut/>
""",
    LookupError ),
    ( u"""<?xml version="1.0" encoding="iso-8859-1"?>
<root€mlaut/>
""",
    UnicodeError ),
    )

totest['namespace'] = (
    ( u"""<?xml version="1.0"?>
<root
    xmlns:int="urn:example"
    xmlns:alias="urn:example"
    xmlns:ot="urn:other">
  <int:one/>
  <alias:two/>
  <ot:three/>
</root>
""",
      """<document source="test data">
    { :root
      { ex:one
      } ex:one
      { ex:two
      } ex:two
      { ot:three
      } ot:three
    } :root
""" ),
    )

totest['SkipNode'] = (
    ( u"""<?xml version="1.0"?>
<root control='SkipNode'>
  <one/>
  <two/>
</root>
""",
      """<document source="test data">
    { :root control='SkipNode'
""" ),
    )

totest['SkipDeparture'] = (
    ( u"""<?xml version="1.0"?>
<root control='SkipDeparture'>
  <one/>
  <two/>
</root>
""",
      """<document source="test data">
    { :root control='SkipDeparture'
      { :one
      } :one
      { :two
      } :two
""" ),
    )

totest['SkipSiblings'] = (
    ( u"""<?xml version="1.0"?>
<root>
  <one control='SkipSiblings'/>
  <two/>
</root>
""",
      """<document source="test data">
    { :root
      { :one control='SkipSiblings'
    } :root
""" ),
    )

totest['SkipChildren'] = (
    ( u"""<?xml version="1.0"?>
<root control='SkipChildren'>
  <one/>
  <two/>
</root>
""",
      """<document source="test data">
    { :root control='SkipChildren'
    } :root
""" ),
    )

totest['StopTraversal'] = (
    ( u"""<?xml version="1.0"?>
<root>
  <one control='StopTraversal'/>
  <two/>
</root>
""",
      """<document source="test data">
    { :root
      { :one control='StopTraversal'
      } :one
    } :root
""" ),
    )

totest['SomeChildren'] = (
    # Take care to use namespaced children
    ( u"""<?xml version="1.0"?>
<root xmlns:int="urn:example"
      control='SomeChildren'>
  <int:one/>
  <int:two/>
</root>
""",
      """<document source="test data">
    { :root control='SomeChildren'
    } :root
""" ),
    ( u"""<?xml version="1.0"?>
<root xmlns:int="urn:example"
      control='SomeChildren' controlSomeChildren='ex:one'>
  <int:one/>
  <int:two/>
</root>
""",
      """<document source="test data">
    { :root control='SomeChildren' controlSomeChildren='ex:one'
      { ex:one
      } ex:one
    } :root
""" ),
    ( u"""<?xml version="1.0"?>
<root xmlns:int="urn:example"
      control='SomeChildren' controlSomeChildren='ex:one ex:two ex:three'>
  <int:one/>
  <int:two/>
</root>
""",
      """<document source="test data">
    { :root control='SomeChildren' controlSomeChildren='ex:one ex:two ex:three'
      { ex:one
      } ex:one
      { ex:two
      } ex:two
    } :root
""" ),
    )

###############################################################################

def suite():
    s = XmlParserTestSuite()
    s.generateTests(totest)
    return s

###############################################################################

if __name__ == '__main__':
    import unittest
    unittest.main(defaultTest='suite')