Debian Codegraph @

test/test_parsers/test_docutils_xml/test_parse_element.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 # :Copyright: © 2024 Günter Milde.
3 # :License: Released under the terms of the `2-Clause BSD license`_, in short:
4 #
5 # Copying and distribution of this file, with or without modification,
6 # are permitted in any medium without royalty provided the copyright
7 # notice and this notice are preserved.
8 # This file is offered as-is, without any warranty.
9 #
10 # .. _2-Clause BSD license: https://opensource.org/licenses/BSD-2-Clause
11
12 """Tests for parsers/docutils_xml.py."""
13
14 from pathlib import Path
15 import sys
16 import unittest
17 import xml.etree.ElementTree as ET
18
19 if __name__ == '__main__':
20 # prepend the "docutils root" to the Python library path
21 # so we import the local `docutils` package.
22 sys.path.insert(0, str(Path(__file__).resolve().parents[3]))
23
24 from docutils import frontend, utils
25 from docutils.parsers import docutils_xml
26
27
28 class ParseElementTestCase(unittest.TestCase):
29 """Test the `docutils.xml.parse_element()` function."""
30 maxDiff = None
31
32 # supress warnings when passing `document` to `parse_element()`
33 settings = frontend.get_default_settings(docutils_xml.Parser)
34 settings.warning_stream = '' # comment out to see warnings
35 document = utils.new_document('xml input', settings)
36
37 def test_element_with_child_with_text(self):
38 xml = '<tip><paragraph>some text</paragraph></tip>'
39 node = docutils_xml.parse_element(xml)
40 self.assertEqual(xml, str(node))
41
42 def test_tailing_text_after_root(self):
43 """etree.ElementTree does not accept tailing text in the input.
44 """
45 xml = '<strong>text</strong>tailing text'
46 with self.assertRaisesRegex(ET.ParseError, 'junk after document '):
47 docutils_xml.parse_element(xml)
48 # If a document is provided, report via a "loose" error system message
49 # comment out ``settings.warning_stream = ''`` above to see it).
50 node = docutils_xml.parse_element(xml, self.document)
51 self.assertEqual('<strong>text</strong>', str(node))
52
53 def test_nothing_but_junk_text(self):
54 xml = 'just text'
55 node = docutils_xml.parse_element(xml, self.document)
56 self.assertEqual(node.astext(), 'No XML element found.')
57
58 def test_nonexistent_element_type(self):
59 xml = '<tip><p>some text</p></tip>'
60 node = docutils_xml.parse_element(xml, self.document)
61 self.assertEqual(xml, str(node))
62 # see test_misc.py for the warning
63
64 def test_junk_text(self):
65 # insert text also in nodes that are not TextElement instances
66 xml = '<tip>some text</tip>'
67 node = docutils_xml.parse_element(xml)
68 self.assertEqual(xml, str(node))
69 with self.assertRaisesRegex(ValueError,
70 'Expecting child of type <Body>,'
71 ' not text data "some text"'):
72 node.validate()
73
74 def test_tailing_junk_text(self):
75 # insert text also in nodes that are not TextElement instances
76 xml = '<tip><paragraph>some text</paragraph>tailing text</tip>'
77 node = docutils_xml.parse_element(xml)
78 self.assertEqual(xml, str(node))
79 with self.assertRaisesRegex(
80 ValueError, 'Spurious text: "tailing text"'):
81 node.validate()
82
83 def test_element_with_attributes(self):
84 xml = ('<image align="left" alt="a barking dog" height="3ex"'
85 ' loading="embed" scale="3" uri="dog.jpg" width="4.50 cm"/>')
86 node = docutils_xml.parse_element(xml)
87 # attribute values are normalized:
88 self.assertEqual(xml.replace('4.50 cm', '4.5cm'), str(node))
89
90 def test_element_with_invalid_attributes(self):
91 """Silently accept invalid attribute names and values.
92
93 Validation reports problems.
94 """
95 xml = ('<image breadth="3 cm" height="three inch"/>')
96 node = docutils_xml.parse_element(xml)
97 self.assertEqual(xml, str(node))
98 with self.assertRaisesRegex(
99 ValueError,
100 'Element <image .*> invalid:\n'
101 ' Attribute "breadth" not one of "ids", .*, "loading".\n'
102 ' Attribute "height" has invalid value "three inch".\n'
103 ' "three inch" is no valid measure.'):
104 node.validate()
105
106
107 class XmlAttributesTestCase(unittest.TestCase):
108 """
109 Test correct parsing of the `supported element attributes`_.
110
111 See also `AttributeTypeTests` in ../../test_nodes.py.
112
113 __ https://docutils.sourceforge.io/
114 docs/ref/doctree.html#attribute-reference
115 """
116 common_attributes = {'classes': [],
117 'dupnames': [],
118 'ids': [],
119 'names': []}
120
121 def test_alt(self): # CDATA (str)
122 xml = ('<image alt="a barking dog" align="left" height="3 ex"'
123 ' loading="embed" scale="3" uri="dog.jpg" width="4 cm"/>')
124 expected = {'alt': 'a barking dog',
125 'align': 'left',
126 'height': '3ex',
127 'loading': 'embed',
128 'scale': 3,
129 'uri': 'dog.jpg',
130 'width': '4cm'}
131 node = docutils_xml.parse_element(xml)
132 self.assertEqual(node.attributes, self.common_attributes | expected)
133
134 # 'align': CDATA (str) → test_alt
135
136 def test_anonymous(self): # yesorno (int)
137 xml = '<target anonymous="1" ids="target-1" refuri="example.html" />'
138 expected = {'anonymous': 1,
139 'ids': ['target-1'],
140 'refuri': 'example.html'}
141 node = docutils_xml.parse_element(xml)
142 self.assertEqual(node.attributes, self.common_attributes | expected)
143
144 def test_auto(self): # CDATA (str)
145 # also encodes footnote label type: '1': numbered, '*': symbols
146 xml = '<footnote auto="*" backrefs="footnote-reference-2" />'
147 expected = {'auto': '*',
148 'backrefs': ['footnote-reference-2']}
149 node = docutils_xml.parse_element(xml)
150 self.assertEqual(node.attributes, self.common_attributes | expected)
151
152 # 'backrefs': idrefs.type (list[str]) → test_auto
153
154 def test_bullet(self): # CDATA (str)
155 xml = '<bullet_list bullet="*" classes="first x-2nd" />'
156 expected = {'bullet': '*',
157 'classes': ['first', 'x-2nd']}
158 node = docutils_xml.parse_element(xml)
159 self.assertEqual(node.attributes, self.common_attributes | expected)
160
161 # 'classes': classnames.type (list[str]) → test_bullet
162
163 def test_colwidth(self): # CDATA (int)
164 # Provisional. Currently, Docutils handles "colwidth" differently
165 # from the Exchange Table Model. This will eventually change
166 # (see https://docutils.sourceforge.io/docs/ref/doctree.html#colwidth).
167 xml = '<colspec colwidth="33*" stub="1" />'
168 expected = {'colwidth': 33, 'stub': 1}
169 node = docutils_xml.parse_element(xml)
170 self.assertEqual(node.attributes, self.common_attributes | expected)
171 # Note: the upstream default unit is "pt", not "*".
172 xml = '<colspec colwidth="33" stub="1" />'
173 expected = {'colwidth': 33, 'stub': 1}
174 node = docutils_xml.parse_element(xml)
175 self.assertEqual(node.attributes, self.common_attributes | expected)
176
177 def test_delimiter(self): # CDATA (str)
178 xml = '<option_argument delimiter="=">FILE</option_argument>'
179 expected = {'delimiter': '='}
180 node = docutils_xml.parse_element(xml)
181 self.assertEqual(node.attributes, self.common_attributes | expected)
182
183 def test_dupnames(self): # refnames.type (list[str]).
184 xml = r'<section dupnames="title\ 1" ids="title-1" />'
185 expected = {'dupnames': ['title 1'],
186 'ids': ['title-1']}
187 node = docutils_xml.parse_element(xml)
188 self.assertEqual(node.attributes, self.common_attributes | expected)
189
190 def test_enumtype(self): # EnumeratedType (str)
191 xml = ('<enumerated_list enumtype="upperroman"'
192 ' prefix="(" start="2" suffix=")" />')
193 expected = {'enumtype': 'upperroman',
194 'prefix': '(',
195 'start': 2,
196 'suffix': ')'}
197 node = docutils_xml.parse_element(xml)
198 self.assertEqual(node.attributes, self.common_attributes | expected)
199
200 def test_format(self): # NMTOKENS (str) (space-delimited list of keywords)
201 xml = '<raw format="html latex" xml:space="preserve" />'
202 expected = {'format': 'html latex',
203 'xml:space': 'preserve'}
204 node = docutils_xml.parse_element(xml)
205 self.assertEqual(node.attributes, self.common_attributes | expected)
206
207 # 'height': measure (str) → test_alt
208 # 'ids': ids.type (list[str]) → test_names
209
210 def test_level(self): # level (int)
211 xml = ('<system_message level="3" line="21" source="string"'
212 ' type="ERROR" />')
213 expected = {'backrefs': [],
214 'level': 3,
215 'line': 21,
216 'source': 'string',
217 'type': 'ERROR'}
218 node = docutils_xml.parse_element(xml)
219 self.assertEqual(node.attributes, self.common_attributes | expected)
220
221 def test_ltrim(self): # yesorno (int)
222 xml = '<substitution_definition ltrim="1" names="nbsp" />'
223 expected = {'ltrim': 1, 'names': ['nbsp']}
224 node = docutils_xml.parse_element(xml)
225 self.assertEqual(node.attributes, self.common_attributes | expected)
226
227 # 'loading': EnumeratedType (str) → test_alt
228
229 def test_morecols(self): # number (int)
230 xml = '<entry morecols="1" />'
231 expected = {'morecols': 1}
232 node = docutils_xml.parse_element(xml)
233 self.assertEqual(node.attributes, self.common_attributes | expected)
234
235 def test_names(self): # refnames.type (list[str])
236 # internal whitespace in XML escaped
237 xml = r'<section ids="title-2 title-1" names="title\ 2\\ title\ 1" />'
238 expected = {'ids': ['title-2', 'title-1'],
239 'names': ['title 2\\', 'title 1']}
240 node = docutils_xml.parse_element(xml)
241 self.assertEqual(node.attributes, self.common_attributes | expected)
242
243 # 'prefix': CDATA (str) → test_enumtype
244
245 def test_refid(self): # idref.type (str)
246 xml = '<target refid="title-1-1"></target>'
247 expected = {'refid': 'title-1-1'}
248 node = docutils_xml.parse_element(xml)
249 self.assertEqual(node.attributes, self.common_attributes | expected)
250
251 def test_refname(self): # refname.type (str)
252 xml = '<target refname="title 2"></target>'
253 expected = {'refname': 'title 2'}
254 node = docutils_xml.parse_element(xml)
255 self.assertEqual(node.attributes, self.common_attributes | expected)
256
257 # 'refuri: CDATA (str) → test_anonymous
258
259 def test_rtrim(self): # yesorno (int)
260 xml = '<substitution_definition ltrim="1" names="nbsp" />'
261 expected = {'ltrim': 1,
262 'names': ['nbsp']}
263 node = docutils_xml.parse_element(xml)
264 self.assertEqual(node.attributes, self.common_attributes | expected)
265
266 # 'scale': number (int) → test_alt
267 # 'source': CDATA (str) → test_title
268 # 'start': number (int) → test_enumtype
269 # 'stub': yesorno (int) → test_colwidth
270 # 'suffix': CDATA (str) → test_enumtype
271
272 def test_title(self): # CDATA (str)
273 xml = (r'<document ids="test-document" names="test\ document"'
274 r' source="/tmp/foo.rst" title="Test Document" />')
275 expected = {'ids': ['test-document'],
276 'names': ['test document'],
277 'source': '/tmp/foo.rst',
278 'title': 'Test Document'}
279 node = docutils_xml.parse_element(xml)
280 self.assertEqual(node.attributes, self.common_attributes | expected)
281
282 # 'uri': CDATA (str) → test_alt
283 # 'width' measure (str) → test_alt
284 # 'xml:space' EnumeratedType (str) → test_format
285
286
287 if __name__ == '__main__':
288 unittest.main()