Debian Codegraph @

test/test_nodes.py

raw symbols SCIP
1 #! /usr/bin/env python3
2 # $Id: test_nodes.py 10299 2026-02-06 09:09:19Z milde $
3 # Author: David Goodger <[email protected]>
4 # Copyright: This module has been placed in the public domain.
5
6 """
7 Test module for nodes.py.
8 """
9
10 from pathlib import Path
11 import sys
12 import unittest
13
14 if __name__ == '__main__':
15 # prepend the "docutils root" to the Python library path
16 # so we import the local `docutils` package.
17 sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
18
19 from docutils import nodes, utils
20
21 debug = False
22
23
24 class NodeTests(unittest.TestCase):
25
26 def not_in_testlist(self, x):
27 # function to use in `condition` argument in findall() and next_node()
28 return x not in self.testlist
29
30 def test_findall(self):
31 # `findall()` is defined in class Node,
32 # we test with a tree of Element instances (simpler setup)
33 e = nodes.Element()
34 e += nodes.Element()
35 e[0] += nodes.Element()
36 e[0] += nodes.TextElement()
37 e[0][1] += nodes.Text('some text')
38 e += nodes.Element()
39 e += nodes.Element()
40 self.assertEqual(list(e.findall()),
41 [e, e[0], e[0][0], e[0][1], e[0][1][0], e[1], e[2]])
42 self.assertEqual(list(e.findall(include_self=False)),
43 [e[0], e[0][0], e[0][1], e[0][1][0], e[1], e[2]])
44 self.assertEqual(list(e.findall(descend=False)),
45 [e])
46 self.assertEqual(list(e[0].findall(descend=False, ascend=True)),
47 [e[0], e[1], e[2]])
48 self.assertEqual(list(e[0][0].findall(descend=False, ascend=True)),
49 [e[0][0], e[0][1], e[1], e[2]])
50 self.assertEqual(list(e[0][0].findall(descend=False, siblings=True)),
51 [e[0][0], e[0][1]])
52 self.testlist = e[0:2]
53 self.assertEqual(list(e.findall(condition=self.not_in_testlist)),
54 [e, e[0][0], e[0][1], e[0][1][0], e[2]])
55 # Return siblings despite siblings=False because ascend is true.
56 self.assertEqual(list(e[1].findall(ascend=True, siblings=False)),
57 [e[1], e[2]])
58 self.assertEqual(list(e[0].findall()),
59 [e[0], e[0][0], e[0][1], e[0][1][0]])
60 self.testlist = [e[0][0], e[0][1]]
61 # Condition is function returning a boolean, class or tuple of classes:
62 self.assertEqual(list(e[0].findall(condition=self.not_in_testlist)),
63 [e[0], e[0][1][0]])
64 self.testlist.append(e[0][1][0])
65 self.assertEqual(list(e[0].findall(condition=self.not_in_testlist)),
66 [e[0]])
67 self.assertEqual(list(e.findall(nodes.TextElement)), [e[0][1]])
68 self.assertEqual(list(e.findall((nodes.TextElement, nodes.Text))),
69 [e[0][1], e[0][1][0]])
70
71 def test_findall_duplicate_texts(self):
72 e = nodes.Element()
73 e += nodes.TextElement()
74 e[0] += nodes.Text('one') # e[0][0]
75 e[0] += nodes.Text('two') # e[0][1]
76 e[0] += nodes.Text('three') # e[0][2]
77 e[0] += nodes.Text('two') # e[0][3] same value as e[0][1]
78 e[0] += nodes.Text('five') # e[0][4]
79 full_list = list(e[0][0].findall(siblings=True))
80 self.assertEqual(len(full_list), 5)
81 for i in range(5):
82 self.assertIs(full_list[i], e[0][i])
83
84 partial_list = list(e[0][3].findall(siblings=True))
85 self.assertEqual(len(partial_list), 2)
86 self.assertIs(partial_list[0], e[0][3])
87 self.assertIs(partial_list[1], e[0][4])
88
89 def test_next_node(self):
90 e = nodes.Element()
91 e += nodes.Element()
92 e[0] += nodes.Element()
93 e[0] += nodes.TextElement()
94 e[0][1] += nodes.Text('some text')
95 e += nodes.Element()
96 e += nodes.Element()
97 self.testlist = [e[0], e[0][1], e[1]]
98 compare = [(e, e[0][0]),
99 (e[0], e[0][0]),
100 (e[0][0], e[0][1][0]),
101 (e[0][1], e[0][1][0]),
102 (e[0][1][0], e[2]),
103 (e[1], e[2]),
104 (e[2], None)]
105 for node, next_node in compare:
106 self.assertEqual(node.next_node(self.not_in_testlist, ascend=True),
107 next_node)
108 self.assertEqual(e[0][0].next_node(ascend=True), e[0][1])
109 self.assertEqual(e[2].next_node(), None)
110
111
112 class TextTests(unittest.TestCase):
113
114 text = nodes.Text('Line 1.\n\x00rad två.')
115 longtext = nodes.Text('Mary had a little lamb '
116 'whose fleece was white as snow '
117 'and everwhere that Mary went '
118 'the lamb was sure to go.')
119
120 def test_value_type_check(self):
121 # data must by `str` instance, no `bytes` allowed
122 with self.assertRaises(TypeError):
123 nodes.Text(b'hol')
124
125 def test_Text_rawsource_deprection_warning(self):
126 with self.assertWarnsRegex(DeprecationWarning,
127 '"rawsource" is ignored'):
128 nodes.Text('content', rawsource='content')
129
130 def test_str(self):
131 self.assertEqual(str(self.text), 'Line 1.\n\x00rad två.')
132
133 def test_repr(self):
134 self.assertEqual(repr(self.text), r"<#text: 'Line 1.\n\x00rad två.'>")
135 self.assertEqual(self.text.shortrepr(),
136 r"<#text: 'Line 1.\n\x00rad två.'>")
137
138 def test_repr_long_text(self):
139 self.assertEqual(repr(self.longtext), r"<#text: 'Mary had a "
140 r"little lamb whose fleece was white as snow "
141 r"and everwh ...'>")
142 self.assertEqual(self.longtext.shortrepr(),
143 r"<#text: 'Mary had a lit ...'>")
144
145 def test_astext(self):
146 self.assertEqual(self.text.astext(), 'Line 1.\nrad två.')
147
148 def test_pformat(self):
149 self.assertTrue(isinstance(self.text.pformat(), str))
150 self.assertEqual(self.text.pformat(), 'Line 1.\nrad två.\n')
151
152 def test_strip(self):
153 text = nodes.Text(' was noch ')
154 stripped = text.lstrip().rstrip()
155 stripped2 = text.lstrip(' wahn').rstrip(' wahn')
156 self.assertEqual(stripped, 'was noch')
157 self.assertEqual(stripped2, 's noc')
158
159 def test_comparison(self):
160 # Text nodes are compared by value
161 self.assertEqual(self.text, nodes.Text('Line 1.\n\x00rad två.'))
162
163
164 class ElementTests(unittest.TestCase):
165
166 def test_empty(self):
167 element = nodes.Element()
168 self.assertEqual(repr(element), '<Element: >')
169 self.assertEqual(str(element), '<Element/>')
170 dom = element.asdom()
171 self.assertEqual(dom.toxml(), '<Element/>')
172 dom.unlink()
173 element['attr'] = '1'
174 self.assertEqual(repr(element), '<Element: >')
175 self.assertEqual(str(element), '<Element attr="1"/>')
176 dom = element.asdom()
177 self.assertEqual(dom.toxml(), '<Element attr="1"/>')
178 dom.unlink()
179 self.assertEqual(element.pformat(), '<Element attr="1">\n')
180 del element['attr']
181 element['mark'] = '\u2022'
182 self.assertEqual(repr(element), '<Element: >')
183 self.assertEqual(str(element), '<Element mark="\u2022"/>')
184 dom = element.asdom()
185 self.assertEqual(dom.toxml(), '<Element mark="\u2022"/>')
186 dom.unlink()
187 element['names'] = ['nobody', 'имя', 'näs']
188 self.assertEqual(repr(element), '<Element "nobody; имя; näs": >')
189 self.assertTrue(isinstance(repr(element), str))
190
191 def test_withtext(self):
192 element = nodes.Element('text\nmore', nodes.Text('text\nmore'))
193 uelement = nodes.Element('grün', nodes.Text('grün'))
194 self.assertEqual(repr(element), r"<Element: <#text: 'text\nmore'>>")
195 self.assertEqual(repr(uelement), "<Element: <#text: 'grün'>>")
196 self.assertTrue(isinstance(repr(uelement), str))
197 self.assertEqual(str(element), '<Element>text\nmore</Element>')
198 self.assertEqual(str(uelement), '<Element>gr\xfcn</Element>')
199 dom = element.asdom()
200 self.assertEqual(dom.toxml(), '<Element>text\nmore</Element>')
201 dom.unlink()
202 element['attr'] = '1'
203 self.assertEqual(repr(element), r"<Element: <#text: 'text\nmore'>>")
204 self.assertEqual(str(element),
205 '<Element attr="1">text\nmore</Element>')
206 dom = element.asdom()
207 self.assertEqual(dom.toxml(),
208 '<Element attr="1">text\nmore</Element>')
209 dom.unlink()
210 self.assertEqual(element.pformat(),
211 '<Element attr="1">\n text\n more\n')
212
213 def test_index(self):
214 # Element.index() behaves like list.index() on the element's children
215 e = nodes.Element()
216 e += nodes.Element()
217 e += nodes.Text('sample')
218 e += nodes.Element()
219 e += nodes.Text('other sample')
220 e += nodes.Text('sample')
221 # return element's index for the first four children:
222 for i in range(4):
223 self.assertEqual(e.index(e[i]), i)
224 # Caution: mismatches are possible for Text nodes
225 # as they are compared by value (like `str` instances)
226 self.assertEqual(e.index(e[4]), 1)
227 self.assertEqual(e.index(e[4], start=2), 4)
228
229 def test_previous_sibling(self):
230 e = nodes.Element()
231 c1 = nodes.Element()
232 c2 = nodes.Element()
233 e += [c1, c2]
234 # print(c1 == c2)
235 self.assertEqual(e.previous_sibling(), None)
236 self.assertEqual(c1.previous_sibling(), None)
237 self.assertEqual(c2.previous_sibling(), c1)
238
239 def test_section_hierarchy(self):
240 p = nodes.paragraph()
241 a = nodes.admonition('', p)
242 self.assertEqual(p.section_hierarchy(), [])
243 s2_1 = nodes.section('', a)
244 self.assertEqual(p.section_hierarchy(), [])
245 s2_2 = nodes.section()
246 s1 = nodes.section()
247 s2 = nodes.section('', s2_1, s2_2)
248 self.assertEqual(p.section_hierarchy(), [s2_1])
249 d = utils.new_document('test data')
250 d += [nodes.paragraph(), s1, s2]
251 self.assertEqual(d.section_hierarchy(), [])
252 self.assertEqual(d[0].section_hierarchy(), [])
253 self.assertEqual(s2.section_hierarchy(), [s2])
254 self.assertEqual(s2_1.section_hierarchy(), [s2, s2_1])
255 self.assertEqual(a.section_hierarchy(), [s2, s2_1])
256 self.assertEqual(p.section_hierarchy(), [s2, s2_1])
257
258 def test_clear(self):
259 element = nodes.Element()
260 element += nodes.Element()
261 self.assertTrue(len(element))
262 element.clear()
263 self.assertTrue(not len(element))
264
265 def test_get_language_code(self):
266 # Return language tag from node or parents
267 parent = nodes.Element(classes=['parental', 'language-pt-BR'])
268 self.assertEqual(parent.get_language_code('en'), 'pt-BR')
269 child = nodes.Element(classes=['small'])
270 self.assertEqual(child.get_language_code('en'), 'en')
271 parent.append(child)
272 self.assertEqual(child.get_language_code('en'), 'pt-BR')
273
274 def test_normal_attributes(self):
275 element = nodes.Element()
276 self.assertTrue('foo' not in element)
277 self.assertRaises(KeyError, element.__getitem__, 'foo')
278 element['foo'] = 'sometext'
279 self.assertEqual(element['foo'], 'sometext')
280 del element['foo']
281 self.assertRaises(KeyError, element.__getitem__, 'foo')
282
283 def test_default_attributes(self):
284 element = nodes.Element()
285 self.assertEqual(element['ids'], [])
286 self.assertEqual(element.non_default_attributes(), {})
287 self.assertTrue(not element.is_not_default('ids'))
288 self.assertTrue(element['ids'] is not nodes.Element()['ids'])
289 element['ids'].append('someid')
290 self.assertEqual(element['ids'], ['someid'])
291 self.assertEqual(element.non_default_attributes(),
292 {'ids': ['someid']})
293 self.assertTrue(element.is_not_default('ids'))
294
295 def test_update_basic_atts(self):
296 element1 = nodes.Element(ids=['foo', 'bar'], test=['test1'])
297 element2 = nodes.Element(ids=['baz', 'qux'], test=['test2'])
298 element1.update_basic_atts(element2)
299 # 'ids' are appended because 'ids' is a basic attribute.
300 self.assertEqual(element1['ids'], ['foo', 'bar', 'baz', 'qux'])
301 # 'test' is not overwritten because it is not a basic attribute.
302 self.assertEqual(element1['test'], ['test1'])
303
304 def test_update_all_atts(self):
305 # Note: Also tests is_not_list_attribute and is_not_known_attribute
306 # and various helpers
307 # Test for full attribute replacement
308 element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent',
309 all_nodes='mom')
310 element2 = nodes.Element(ids=['baz', 'qux'], child_only='child',
311 all_nodes='dad', source='source')
312
313 # Test for when same fields are replaced as well as source...
314 element1.update_all_atts_consistantly(element2, True, True)
315 # 'ids' are appended because 'ids' is a basic attribute.
316 self.assertEqual(element1['ids'], ['foo', 'bar', 'baz', 'qux'])
317 # 'parent_only' should remain unaffected.
318 self.assertEqual(element1['parent_only'], 'parent')
319 # 'all_nodes' is overwritten due to the second parameter == True.
320 self.assertEqual(element1['all_nodes'], 'dad')
321 # 'child_only' should have been added.
322 self.assertEqual(element1['child_only'], 'child')
323 # 'source' is also overwritten due to the third parameter == True.
324 self.assertEqual(element1['source'], 'source')
325
326 # Test for when same fields are replaced but not source...
327 element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent',
328 all_nodes='mom')
329 element1.update_all_atts_consistantly(element2)
330 # 'ids' are appended because 'ids' is a basic attribute.
331 self.assertEqual(element1['ids'], ['foo', 'bar', 'baz', 'qux'])
332 # 'parent_only' should remain unaffected.
333 self.assertEqual(element1['parent_only'], 'parent')
334 # 'all_nodes' is overwritten due to the second parameter default True.
335 self.assertEqual(element1['all_nodes'], 'dad')
336 # 'child_only' should have been added.
337 self.assertEqual(element1['child_only'], 'child')
338 # 'source' remains unset due to the third parameter default of False.
339 self.assertEqual(element1.get('source'), None)
340
341 # Test for when fields are NOT replaced but source is...
342 element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent',
343 all_nodes='mom')
344 element1.update_all_atts_consistantly(element2, False, True)
345 # 'ids' are appended because 'ids' is a basic attribute.
346 self.assertEqual(element1['ids'], ['foo', 'bar', 'baz', 'qux'])
347 # 'parent_only' should remain unaffected.
348 self.assertEqual(element1['parent_only'], 'parent')
349 # 'all_nodes' is preserved due to the second parameter == False.
350 self.assertEqual(element1['all_nodes'], 'mom')
351 # 'child_only' should have been added.
352 self.assertEqual(element1['child_only'], 'child')
353 # 'source' is added due to the third parameter == True.
354 self.assertEqual(element1['source'], 'source')
355 element1 = nodes.Element(source='destination')
356 element1.update_all_atts_consistantly(element2, False, True)
357 # 'source' remains unchanged due to the second parameter == False.
358 self.assertEqual(element1['source'], 'destination')
359
360 # Test for when same fields are replaced but not source...
361 element1 = nodes.Element(ids=['foo', 'bar'], parent_only='parent',
362 all_nodes='mom')
363 element1.update_all_atts_consistantly(element2, False)
364 # 'ids' are appended because 'ids' is a basic attribute.
365 self.assertEqual(element1['ids'], ['foo', 'bar', 'baz', 'qux'])
366 # 'parent_only' should remain unaffected.
367 self.assertEqual(element1['parent_only'], 'parent')
368 # 'all_nodes' is preserved due to the second parameter == False.
369 self.assertEqual(element1['all_nodes'], 'mom')
370 # 'child_only' should have been added.
371 self.assertEqual(element1['child_only'], 'child')
372 # 'source' remains unset due to the third parameter default of False.
373 self.assertEqual(element1.get('source'), None)
374
375 # Test for List attribute merging
376 # Attribute Concatination
377 element1 = nodes.Element(ss='a', sl='1', ls=['I'], ll=['A'])
378 element2 = nodes.Element(ss='b', sl=['2'], ls='II', ll=['B'])
379 element1.update_all_atts_concatenating(element2)
380 # 'ss' is replaced because non-list
381 self.assertEqual(element1['ss'], 'b')
382 # 'sl' is replaced because they are both not lists
383 self.assertEqual(element1['sl'], ['2'])
384 # 'ls' is replaced because they are both not lists
385 self.assertEqual(element1['ls'], 'II')
386 # 'll' is extended because they are both lists
387 self.assertEqual(element1['ll'], ['A', 'B'])
388
389 # Attribute Coercion
390 element1 = nodes.Element(ss='a', sl='1', ls=['I'], ll=['A'])
391 element2 = nodes.Element(ss='b', sl=['2'], ls='II', ll=['B'])
392 element1.update_all_atts_coercion(element2)
393 # 'ss' is replaced because non-list
394 self.assertEqual(element1['ss'], 'b')
395 # 'sl' is converted to a list and appended because element2 has a list
396 self.assertEqual(element1['sl'], ['1', '2'])
397 # 'ls' has element2's value appended to the list
398 self.assertEqual(element1['ls'], ['I', 'II'])
399 # 'll' is extended because they are both lists
400 self.assertEqual(element1['ll'], ['A', 'B'])
401
402 # Attribute Conversion
403 element1 = nodes.Element(ss='a', sl='1', ls=['I'], ll=['A'])
404 element2 = nodes.Element(ss='b', sl=['2'], ls='II', ll=['B'])
405 element1.update_all_atts_convert(element2)
406 # 'ss' is converted to a list with the values from each element
407 self.assertEqual(element1['ss'], ['a', 'b'])
408 # 'sl' is converted to a list and appended
409 self.assertEqual(element1['sl'], ['1', '2'])
410 # 'ls' has element2's value appended to the list
411 self.assertEqual(element1['ls'], ['I', 'II'])
412 # 'll' is extended
413 self.assertEqual(element1['ll'], ['A', 'B'])
414
415 def test_copy(self):
416 # Shallow copy:
417 grandchild = nodes.Text('grandchild text')
418 child = nodes.emphasis('childtext', grandchild, att='child')
419 e = nodes.Element('raw text', child, att='e')
420 e_copy = e.copy()
421 self.assertTrue(e is not e_copy)
422 # Internal attributes (like `rawsource`) are also copied.
423 self.assertEqual(e.rawsource, 'raw text')
424 self.assertEqual(e_copy.rawsource, e.rawsource)
425 self.assertEqual(e_copy['att'], 'e')
426 self.assertEqual(e_copy.document, e.document)
427 self.assertEqual(e_copy.source, e.source)
428 self.assertEqual(e_copy.line, e.line)
429 # Children are not copied.
430 self.assertEqual(len(e_copy), 0)
431
432 def test_deepcopy(self):
433 # Deep copy:
434 grandchild = nodes.Text('grandchild text')
435 child = nodes.emphasis('childtext', grandchild, att='child')
436 e = nodes.Element('raw text', child, att='e')
437 e_deepcopy = e.deepcopy()
438 self.assertEqual(e_deepcopy.rawsource, e.rawsource)
439 self.assertEqual(e_deepcopy['att'], 'e')
440 # Children are copied recursively.
441 self.assertEqual(e_deepcopy[0][0], grandchild)
442 self.assertTrue(e_deepcopy[0][0] is not grandchild)
443 self.assertEqual(e_deepcopy[0]['att'], 'child')
444
445 def test_system_message_copy(self):
446 e = nodes.system_message('mytext', att='e', rawsource='raw text')
447 # Shallow copy:
448 e_copy = e.copy()
449 self.assertTrue(e is not e_copy)
450 # Internal attributes (like `rawsource`) are also copied.
451 self.assertEqual(e.rawsource, 'raw text')
452 self.assertEqual(e_copy.rawsource, e.rawsource)
453 self.assertEqual(e_copy['att'], 'e')
454
455 def test_replace_self(self):
456 parent = nodes.Element(ids=['parent'])
457 child1 = nodes.Element(ids=['child1'])
458 grandchild = nodes.Element(ids=['grandchild'])
459 child1 += grandchild
460 child2 = nodes.Element(ids=['child2'])
461 twins = [nodes.Element(ids=['twin%s' % i]) for i in (1, 2)]
462 child2 += twins
463 child3 = nodes.Element(ids=['child3'])
464 child4 = nodes.Element(ids=['child4'])
465 parent += [child1, child2, child3, child4]
466 self.assertEqual(parent.pformat(), """\
467 <Element ids="parent">
468 <Element ids="child1">
469 <Element ids="grandchild">
470 <Element ids="child2">
471 <Element ids="twin1">
472 <Element ids="twin2">
473 <Element ids="child3">
474 <Element ids="child4">
475 """)
476 # Replace child1 with the grandchild.
477 child1.replace_self(child1[0])
478 self.assertEqual(parent[0], grandchild)
479 # Assert that 'ids' have been updated.
480 self.assertEqual(grandchild['ids'], ['grandchild', 'child1'])
481 # Replace child2 with its children.
482 child2.replace_self(child2[:])
483 self.assertEqual(parent[1:3], twins)
484 # Assert that 'ids' have been propagated to first child.
485 self.assertEqual(twins[0]['ids'], ['twin1', 'child2'])
486 self.assertEqual(twins[1]['ids'], ['twin2'])
487 # Replace child3 with new child.
488 newchild = nodes.Element(ids=['newchild'])
489 child3.replace_self(newchild)
490 self.assertEqual(parent[3], newchild)
491 self.assertEqual(newchild['ids'], ['newchild', 'child3'])
492 # Crazy but possible case: Substitute child4 for itself.
493 child4.replace_self(child4)
494 # Make sure the 'child4' ID hasn't been duplicated.
495 self.assertEqual(child4['ids'], ['child4'])
496 self.assertEqual(len(parent), 5)
497
498
499 class ColspecTests(unittest.TestCase):
500
501 def test_propwidth(self):
502 # Return colwidth attribute value if it is a proportional measure.
503 colspec = nodes.colspec()
504 colspec['colwidth'] = '8.2*' # value + '*'
505 self.assertEqual(colspec.propwidth(), 8.2)
506 colspec['colwidth'] = '2' # in Docutils < 2.0, default unit is '*'
507 self.assertEqual(colspec.propwidth(), 2)
508 colspec['colwidth'] = '20%' # percentual values not supported
509 with self.assertRaisesRegex(ValueError, '"20%" is no proportional me'):
510 colspec.propwidth()
511 colspec['colwidth'] = '2em' # fixed values not supported
512 with self.assertRaisesRegex(ValueError, '"2em" is no proportional me'):
513 colspec.propwidth()
514 colspec['colwidth'] = '0*' # value must be positive
515 with self.assertRaisesRegex(ValueError, r'"0\*" is no proportional '):
516 colspec.propwidth()
517 # for backwards compatibility, numerical values are accepted
518 colspec['colwidth'] = 8.2
519 self.assertEqual(colspec.propwidth(), 8.2)
520 colspec['colwidth'] = 2
521 self.assertEqual(colspec.propwidth(), 2)
522
523
524 class ElementValidationTests(unittest.TestCase):
525
526 def test_validate(self):
527 """Valid node: validation should simply pass."""
528 node = nodes.paragraph('', 'plain text', classes='my test classes')
529 node.append(nodes.emphasis('', 'emphasised text', ids='emphtext'))
530 node.validate()
531
532 def test_validate_invalid_descendent(self):
533 paragraph = nodes.paragraph('', 'plain text')
534 tip = nodes.tip('', paragraph)
535 paragraph.append(nodes.strong('doll', id='missing-es'))
536 tip.validate(recursive=False)
537 with self.assertRaisesRegex(nodes.ValidationError,
538 'Element <strong id=.*> invalid:\n'
539 ' Attribute "id" not one of "ids", '):
540 tip.validate()
541
542 def test_validate_attributes(self):
543 # Convert to expected data-type, normalize values,
544 # cf. AttributeTypeTests below for attribute validating function tests.
545 node = nodes.image(classes='my test-classes',
546 names='My teST\n\\ \xA0classes',
547 width='30 mm')
548 node.validate_attributes()
549 self.assertEqual(node['classes'], ['my', 'test-classes'])
550 self.assertEqual(node['names'], ['My', 'teST classes'])
551 self.assertEqual(node['width'], '30mm')
552
553 def test_validate_wrong_attribute(self):
554 node = nodes.paragraph('', 'text', id='test-paragraph')
555 with self.assertRaisesRegex(nodes.ValidationError,
556 'Element <paragraph id=.*> invalid:\n'
557 ' Attribute "id" not one of "ids", '):
558 node.validate()
559
560 def test_validate_wrong_attribute_value(self):
561 node = nodes.image(uri='test.png', width='1in 3pt')
562 with self.assertRaisesRegex(nodes.ValidationError,
563 'Element <image.*> invalid:\n'
564 '.*"width" has invalid value "1in 3pt".'):
565 node.validate()
566
567 def test_validate_spurious_element(self):
568 label = nodes.label('', '*')
569 label.append(nodes.strong())
570 with self.assertRaisesRegex(nodes.ValidationError,
571 'Element <label> invalid:\n'
572 ' Child element <strong> not allowed '):
573 label.validate()
574
575 def test_validate_content(self):
576 """Check, whether an element's children fit into its content model.
577
578 Return empty lists for valid elements,
579 lists with warnings and spurious children if children don't match.
580 """
581 # sample elements
582 inline = nodes.inline() # inline element
583 text = nodes.Text('explanation') # <#text>
584 hint = nodes.hint() # body element
585
586 # empty element: (EMPTY)
587 image = nodes.image('')
588 self.assertEqual(image.validate_content(), [])
589 image.append(text)
590 self.assertEqual(image.validate_content(), [text])
591 # ValueError, "Spurious Element <#text: 'explanation'>"):
592
593 # TextElement: (#PCDATA | %inline.elements;)*
594 paragraph = nodes.paragraph() # empty element
595 self.assertEqual(paragraph.validate_content(), [])
596 paragraph = nodes.paragraph('', 'text') # just text
597 self.assertEqual(paragraph.validate_content(), [])
598 paragraph.extend([inline, nodes.Text('text 2'), nodes.math()])
599 self.assertEqual(paragraph.validate_content(), [])
600 paragraph.append(hint) # body element (sic!)
601 paragraph.append(text)
602 self.assertEqual(paragraph.validate_content(), [hint, text])
603 # validate() reports "relics" as ValueError:
604 with self.assertRaisesRegex(nodes.ValidationError,
605 '<paragraph> invalid:\n'
606 ' Child element <hint> not allowed '):
607 paragraph.validate()
608
609 # PureTextElement: (#PCDATA)
610 label = nodes.label() # empty element
611 self.assertEqual(label.validate_content(), [])
612 label = nodes.label('', '†')
613 self.assertEqual(label.validate_content(), [])
614 label.append(inline) # sic!
615 self.assertEqual(label.validate_content(), [inline])
616
617 # docinfo: (%bibliographic.elements;)+
618 docinfo = nodes.docinfo() # empty element (sic!)
619 with self.assertRaisesRegex(nodes.ValidationError,
620 'Missing child of type <Bibliographic>.'):
621 docinfo.validate_content()
622 docinfo.append(nodes.paragraph())
623 with self.assertRaisesRegex(nodes.ValidationError,
624 'Expecting .* <Bibliographic>, not '):
625 docinfo.validate_content()
626 docinfo = nodes.docinfo('', nodes.authors(), nodes.contact())
627 self.assertEqual(docinfo.validate_content(), [])
628 docinfo.append(hint) # sic!
629 self.assertEqual(docinfo.validate_content(), [hint])
630
631 # decoration: (header?, footer?)
632 decoration = nodes.decoration() # empty element
633 self.assertEqual(decoration.validate_content(), [])
634 decoration = nodes.decoration('', nodes.header(), nodes.footer())
635 self.assertEqual(decoration.validate_content(), [])
636 header = nodes.header()
637 decoration.append(header) # 3rd element (sic!)
638 self.assertEqual(decoration.validate_content(), [header])
639 decoration = nodes.decoration('', nodes.footer())
640 self.assertEqual(decoration.validate_content(), [])
641 decoration.append(header) # wrong order!
642 self.assertEqual(decoration.validate_content(), [header])
643
644 # Body elements have a range of different content models.
645
646 # container: (%body.elements;)+
647 container = nodes.container() # empty (sic!)
648 with self.assertRaisesRegex(nodes.ValidationError,
649 'Missing child of type <Body>.'):
650 container.validate_content()
651 container.append(inline) # sic!
652 with self.assertRaisesRegex(nodes.ValidationError,
653 'Expecting child of type <Body>, not <in'):
654 container.validate_content()
655 container = nodes.container('', nodes.paragraph()) # one body element
656 self.assertEqual(container.validate_content(), []) # valid
657 container.append(nodes.tip()) # more body elements
658 self.assertEqual(container.validate_content(), []) # valid
659 container.append(inline) # sic!
660 self.assertEqual(container.validate_content(), [inline])
661
662 # block_quote: ((%body.elements;)+, attribution?)
663 block_quote = nodes.block_quote('', hint, nodes.table())
664 self.assertEqual(block_quote.validate_content(), [])
665 block_quote.append(nodes.attribution())
666 self.assertEqual(block_quote.validate_content(), [])
667 block_quote.append(hint) # element after attribution (sic!)
668 self.assertEqual(block_quote.validate_content(), [hint])
669
670 # list item (%body.elements;)*
671 list_item = nodes.list_item() # empty list item is valid
672 self.assertEqual(list_item.validate_content(), [])
673 list_item.append(nodes.bullet_list()) # lists may be nested
674 list_item.append(paragraph)
675 self.assertEqual(list_item.validate_content(), [])
676 list_item.append(inline) # sic!
677 self.assertEqual(list_item.validate_content(), [inline])
678
679 # bullet_list, enumerated_list: (list_item+)
680 bullet_list = nodes.bullet_list() # empty (sic!)
681 with self.assertRaisesRegex(nodes.ValidationError,
682 'Missing child of type <list_item>.'):
683 bullet_list.validate_content()
684 bullet_list.extend([list_item, list_item, list_item])
685 self.assertEqual(bullet_list.validate_content(), [])
686 bullet_list.append(hint) # must nest in <list_item>
687 self.assertEqual(bullet_list.validate_content(), [hint])
688
689 # definition_list_item: (term, classifier*, definition)
690 definition_list_item = nodes.definition_list_item()
691 with self.assertRaisesRegex(nodes.ValidationError,
692 'Element <definition_list_item> invalid:\n'
693 ' Missing child of type <term>.'):
694 definition_list_item.validate_content(),
695 definition_list_item.append(nodes.term())
696 definition_list_item.append(nodes.definition())
697 self.assertEqual(definition_list_item.validate_content(), [])
698 definition_list_item.children.insert(1, nodes.classifier())
699 definition_list_item.children.insert(1, nodes.classifier())
700 self.assertEqual(definition_list_item.validate_content(), [])
701
702 # field: (field_name, field_body)
703 field = nodes.field()
704 with self.assertRaisesRegex(nodes.ValidationError,
705 'Missing child of type <field_name>.'):
706 field.validate_content()
707 field.extend([nodes.field_name(), nodes.field_body()])
708 self.assertEqual(field.validate_content(), [])
709 field = nodes.field('', nodes.field_body(), nodes.field_name())
710 # wrong order!
711 with self.assertRaisesRegex(nodes.ValidationError,
712 'Expecting child of type <field_name>,'
713 ' not <field_body>.'):
714 field.validate_content()
715
716 # option: (option_string, option_argument*)
717 option = nodes.option()
718 with self.assertRaisesRegex(nodes.ValidationError,
719 'Missing child of type <option_string>.'):
720 option.validate_content()
721 option.append(nodes.paragraph()) # sic!
722 with self.assertRaisesRegex(nodes.ValidationError,
723 'Expecting child of type <option_string>,'
724 ' not <paragraph>.'):
725 option.validate_content()
726 option = nodes.option('', nodes.option_string())
727 self.assertEqual(option.validate_content(), [])
728 option.append(nodes.option_argument())
729 self.assertEqual(option.validate_content(), [])
730
731 # line_block: (line | line_block)+
732 line_block = nodes.line_block() # sic!
733 with self.assertRaisesRegex(nodes.ValidationError,
734 ' child of type <line> or <line_block>.'):
735 line_block.validate_content()
736 line_block.append(nodes.line_block())
737 self.assertEqual(line_block.validate_content(), [])
738 line_block = nodes.line_block('', nodes.paragraph(), nodes.line())
739 with self.assertRaisesRegex(nodes.ValidationError,
740 'Expecting child of type <line> or '
741 '<line_block>, not <paragraph>.'):
742 line_block.validate_content()
743
744 # admonition: (title, (%body.elements;)+)
745 admonition = nodes.admonition('', nodes.paragraph())
746 with self.assertRaisesRegex(nodes.ValidationError,
747 'Expecting child of type <title>,'
748 ' not <paragraph>.'):
749 admonition.validate_content()
750 admonition = nodes.admonition('', nodes.title(), nodes.paragraph())
751 self.assertEqual(admonition.validate_content(), [])
752
753 # specific admonitions: (%body.elements;)+
754 note = nodes.note()
755 with self.assertRaisesRegex(nodes.ValidationError,
756 'Missing child of type <Body>.'):
757 note.validate_content()
758 note.append(nodes.enumerated_list())
759 self.assertEqual(note.validate_content(), [])
760
761 # footnote: (label?, (%body.elements;)+)
762 # TODO: use case for footnote without label (make it required?)
763 # rST parser can generate footnotes without body elements!
764 footnote = nodes.footnote('', hint)
765 self.assertEqual(footnote.validate_content(), [])
766
767 # citation: (label, (%body.elements;)+)
768 # TODO: rST parser allows empty citation
769 # (see test_rst/test_citations.py). Is this sensible?
770 citation = nodes.citation('', hint)
771 with self.assertRaisesRegex(nodes.ValidationError,
772 'Expecting child of type <label>,'
773 ' not <hint>.'):
774 citation.validate_content()
775
776 # Table group: (colspec*, thead?, tbody)
777 tgroup = nodes.tgroup() # empty (sic!)
778 with self.assertRaisesRegex(nodes.ValidationError,
779 'Missing child of type <tbody>.'):
780 tgroup.validate_content()
781 tgroup = nodes.tgroup('', nodes.colspec(), nodes.colspec(),
782 nodes.thead(), nodes.tbody())
783 self.assertEqual(tgroup.validate_content(), [])
784 thead = nodes.thead()
785 tgroup = nodes.tgroup('', nodes.tbody(), thead) # wrong order!
786 self.assertEqual(tgroup.validate_content(), [thead])
787
788 def test_validate_content_authors(self):
789 """Return empty list for valid elements, raise ValidationError else.
790
791 Specific method for `authors` instances: complex content model
792 requires repeated application of `authors.content_model`.
793 """
794 authors = nodes.authors()
795 with self.assertRaisesRegex(nodes.ValidationError,
796 'Missing child of type <author>.'):
797 authors.validate_content()
798 authors.extend([nodes.author(), nodes.address(), nodes.contact()])
799 self.assertEqual(authors.validate_content(), [])
800 authors.append(nodes.hint())
801 with self.assertRaisesRegex(nodes.ValidationError,
802 ' child of type <author>, not <hint>.'):
803 authors.validate_content()
804 authors.extend([nodes.author(), nodes.tip(), nodes.contact()])
805 with self.assertRaisesRegex(nodes.ValidationError,
806 ' child of type <author>, not <hint>.'):
807 authors.validate_content()
808
809 def test_validate_content_subtitle(self):
810 """<subtitle> must follow a <title>.
811 """
812 subtitle = nodes.subtitle()
813 paragraph = nodes.paragraph()
814 sidebar = nodes.sidebar('', subtitle, paragraph)
815 with self.assertRaisesRegex(nodes.ValidationError,
816 '<subtitle> only allowed after <title>.'):
817 sidebar.validate_content()
818
819 def test_validate_content_transition(self):
820 """Test additional constraints on <transition> placement:
821 Not at begin or end of section or document text,
822 not after another transition.
823 """
824 transition = nodes.transition()
825 comment = nodes.comment()
826 paragraph = nodes.paragraph()
827 subdef = nodes.substitution_definition()
828 target = nodes.target()
829 title = nodes.title()
830
831 section = nodes.section('', title, comment, transition, paragraph)
832 self.assertEqual(section.validate_content(), [])
833 section = nodes.section('', title, subdef, transition, target, subdef)
834 with self.assertRaisesRegex(nodes.ValidationError,
835 '<transition> may not begin a section .*\n'
836 ' <transition> may not end a section '):
837 self.assertEqual(section.validate_content(), [])
838 section = nodes.section('', title, paragraph, transition,
839 nodes.transition(), paragraph)
840 with self.assertRaisesRegex(nodes.ValidationError,
841 'Element <section> invalid:\n'
842 ' <transition> may not directly follow'):
843 self.assertEqual(section.validate_content(), [])
844
845 document = utils.new_document('test')
846 document.extend([nodes.decoration(), transition, nodes.meta()])
847 with self.assertRaisesRegex(nodes.ValidationError,
848 '<transition> may not begin a section .*\n'
849 ' <transition> may not end a section '):
850 self.assertEqual(section.validate_content(), [])
851
852
853 class MiscTests(unittest.TestCase):
854
855 def test_node_class_names(self):
856 node_class_names = []
857 for x in dir(nodes):
858 c = getattr(nodes, x)
859 if (isinstance(c, type)
860 and issubclass(c, nodes.Node)
861 and len(c.__bases__) > 1):
862 node_class_names.append(x)
863 node_class_names.sort()
864 nodes.node_class_names.sort()
865 self.assertEqual(node_class_names, nodes.node_class_names)
866
867
868 class TreeCopyVisitorTests(unittest.TestCase):
869
870 def setUp(self):
871 document = utils.new_document('test data')
872 document += nodes.paragraph('', 'Paragraph 1.')
873 blist = nodes.bullet_list()
874 for i in range(1, 6):
875 item = nodes.list_item()
876 for j in range(1, 4):
877 item += nodes.paragraph('', 'Item %s, paragraph %s.' % (i, j))
878 blist += item
879 document += blist
880 self.document = document
881
882 def compare_trees(self, one, two):
883 self.assertEqual(one.__class__, two.__class__)
884 self.assertNotEqual(id(one), id(two))
885 self.assertEqual(len(one.children), len(two.children))
886 for i in range(len(one.children)):
887 self.compare_trees(one.children[i], two.children[i])
888
889 def test_copy_whole(self):
890 visitor = nodes.TreeCopyVisitor(self.document)
891 self.document.walkabout(visitor)
892 newtree = visitor.get_tree_copy()
893 self.assertEqual(self.document.pformat(), newtree.pformat())
894 self.compare_trees(self.document, newtree)
895
896
897 class SetIdTests(unittest.TestCase):
898
899 def setUp(self):
900 self.document = utils.new_document('test')
901 self.elements = [nodes.Element(names=['test']),
902 nodes.section(), # Name empty
903 nodes.section(names=['Test']), # duplicate id
904 nodes.footnote(names=['2019-10-30']), # id empty
905 ]
906
907 def test_set_id_default(self):
908 # Default prefixes.
909 for element in self.elements:
910 self.document.set_id(element)
911 ids = [element['ids'] for element in self.elements]
912 self.assertEqual(ids, [['test'], ['section-1'],
913 ['test-1'], ['footnote-1']])
914
915 def test_set_id_custom(self):
916 # Custom prefixes.
917
918 # Change settings.
919 self.document.settings.id_prefix = 'P-'
920 self.document.settings.auto_id_prefix = 'auto'
921
922 for element in self.elements:
923 self.document.set_id(element)
924 ids = [element['ids'] for element in self.elements]
925 self.assertEqual(ids, [['P-test'],
926 ['P-auto1'],
927 ['P-auto2'],
928 ['P-2019-10-30']])
929
930 def test_set_id_descriptive_auto_id(self):
931 # Use name or tag-name for auto-id.
932
933 # Change setting.
934 self.document.settings.auto_id_prefix = '%'
935
936 for element in self.elements:
937 self.document.set_id(element)
938 ids = [element['ids'] for element in self.elements]
939 self.assertEqual(ids, [['test'],
940 ['section-1'],
941 ['test-1'],
942 ['footnote-1']])
943
944 def test_set_id_custom_descriptive_auto_id(self):
945 # Custom prefixes and name or tag-name for auto-id.
946
947 # Change settings.
948 self.document.settings.id_prefix = 'P:'
949 self.document.settings.auto_id_prefix = 'a-%'
950
951 for element in self.elements:
952 self.document.set_id(element)
953 ids = [element['ids'] for element in self.elements]
954 self.assertEqual(ids, [['P:test'],
955 ['P:a-section-1'],
956 ['P:test-1'],
957 ['P:2019-10-30']])
958
959
960 class NodeVisitorTests(unittest.TestCase):
961 def setUp(self):
962 self.document = utils.new_document('test')
963 self.element = nodes.Element()
964 self.visitor = nodes.NodeVisitor(self.document)
965
966 def test_dispatch_visit_unknown(self):
967 # raise exception if no visit/depart methods are defined for node class
968 with self.assertRaises(NotImplementedError):
969 self.visitor.dispatch_visit(self.element)
970
971 def test_dispatch_visit_optional(self):
972 # silently skip nodes of a class in tuple nodes.NodeVisitor.optional
973 rv = self.visitor.dispatch_visit(nodes.meta())
974 self.assertIsNone(rv)
975
976
977 class MiscFunctionTests(unittest.TestCase):
978
979 ids = [('a', 'a'), ('A', 'a'), ('', ''), ('a b \n c', 'a-b-c'),
980 ('a.b.c', 'a-b-c'), (' - a - b - c - ', 'a-b-c'), (' - ', ''),
981 ('\u2020\u2066', ''), ('a \xa7 b \u2020 c', 'a-b-c'),
982 ('1', ''), ('1abc', 'abc'),
983 ]
984
985 ids_unicode_all = [
986 ('\u00f8 o with stroke', 'o-o-with-stroke'),
987 ('\u0111 d with stroke', 'd-d-with-stroke'),
988 ('\u0127 h with stroke', 'h-h-with-stroke'),
989 ('\u0131 dotless i', 'i-dotless-i'),
990 ('\u0142 l with stroke', 'l-l-with-stroke'),
991 ('\u0167 t with stroke', 't-t-with-stroke'),
992 # From Latin Extended-B
993 ('\u0180 b with stroke', 'b-b-with-stroke'),
994 ('\u0183 b with topbar', 'b-b-with-topbar'),
995 ('\u0188 c with hook', 'c-c-with-hook'),
996 ('\u018c d with topbar', 'd-d-with-topbar'),
997 ('\u0192 f with hook', 'f-f-with-hook'),
998 ('\u0199 k with hook', 'k-k-with-hook'),
999 ('\u019a l with bar', 'l-l-with-bar'),
1000 ('\u019e n with long right leg', 'n-n-with-long-right-leg'),
1001 ('\u01a5 p with hook', 'p-p-with-hook'),
1002 ('\u01ab t with palatal hook', 't-t-with-palatal-hook'),
1003 ('\u01ad t with hook', 't-t-with-hook'),
1004 ('\u01b4 y with hook', 'y-y-with-hook'),
1005 ('\u01b6 z with stroke', 'z-z-with-stroke'),
1006 ('\u01e5 g with stroke', 'g-g-with-stroke'),
1007 ('\u0225 z with hook', 'z-z-with-hook'),
1008 ('\u0234 l with curl', 'l-l-with-curl'),
1009 ('\u0235 n with curl', 'n-n-with-curl'),
1010 ('\u0236 t with curl', 't-t-with-curl'),
1011 ('\u0237 dotless j', 'j-dotless-j'),
1012 ('\u023c c with stroke', 'c-c-with-stroke'),
1013 ('\u023f s with swash tail', 's-s-with-swash-tail'),
1014 ('\u0240 z with swash tail', 'z-z-with-swash-tail'),
1015 ('\u0247 e with stroke', 'e-e-with-stroke'),
1016 ('\u0249 j with stroke', 'j-j-with-stroke'),
1017 ('\u024b q with hook tail', 'q-q-with-hook-tail'),
1018 ('\u024d r with stroke', 'r-r-with-stroke'),
1019 ('\u024f y with stroke', 'y-y-with-stroke'),
1020 # From Latin-1 Supplements
1021 ('\u00e0: a with grave', 'a-a-with-grave'),
1022 ('\u00e1 a with acute', 'a-a-with-acute'),
1023 ('\u00e2 a with circumflex', 'a-a-with-circumflex'),
1024 ('\u00e3 a with tilde', 'a-a-with-tilde'),
1025 ('\u00e4 a with diaeresis', 'a-a-with-diaeresis'),
1026 ('\u00e5 a with ring above', 'a-a-with-ring-above'),
1027 ('\u00e7 c with cedilla', 'c-c-with-cedilla'),
1028 ('\u00e8 e with grave', 'e-e-with-grave'),
1029 ('\u00e9 e with acute', 'e-e-with-acute'),
1030 ('\u00ea e with circumflex', 'e-e-with-circumflex'),
1031 ('\u00eb e with diaeresis', 'e-e-with-diaeresis'),
1032 ('\u00ec i with grave', 'i-i-with-grave'),
1033 ('\u00ed i with acute', 'i-i-with-acute'),
1034 ('\u00ee i with circumflex', 'i-i-with-circumflex'),
1035 ('\u00ef i with diaeresis', 'i-i-with-diaeresis'),
1036 ('\u00f1 n with tilde', 'n-n-with-tilde'),
1037 ('\u00f2 o with grave', 'o-o-with-grave'),
1038 ('\u00f3 o with acute', 'o-o-with-acute'),
1039 ('\u00f4 o with circumflex', 'o-o-with-circumflex'),
1040 ('\u00f5 o with tilde', 'o-o-with-tilde'),
1041 ('\u00f6 o with diaeresis', 'o-o-with-diaeresis'),
1042 ('\u00f9 u with grave', 'u-u-with-grave'),
1043 ('\u00fa u with acute', 'u-u-with-acute'),
1044 ('\u00fb u with circumflex', 'u-u-with-circumflex'),
1045 ('\u00fc u with diaeresis', 'u-u-with-diaeresis'),
1046 ('\u00fd y with acute', 'y-y-with-acute'),
1047 ('\u00ff y with diaeresis', 'y-y-with-diaeresis'),
1048 # From Latin Extended-A
1049 ('\u0101 a with macron', 'a-a-with-macron'),
1050 ('\u0103 a with breve', 'a-a-with-breve'),
1051 ('\u0105 a with ogonek', 'a-a-with-ogonek'),
1052 ('\u0107 c with acute', 'c-c-with-acute'),
1053 ('\u0109 c with circumflex', 'c-c-with-circumflex'),
1054 ('\u010b c with dot above', 'c-c-with-dot-above'),
1055 ('\u010d c with caron', 'c-c-with-caron'),
1056 ('\u010f d with caron', 'd-d-with-caron'),
1057 ('\u0113 e with macron', 'e-e-with-macron'),
1058 ('\u0115 e with breve', 'e-e-with-breve'),
1059 ('\u0117 e with dot above', 'e-e-with-dot-above'),
1060 ('\u0119 e with ogonek', 'e-e-with-ogonek'),
1061 ('\u011b e with caron', 'e-e-with-caron'),
1062 ('\u011d g with circumflex', 'g-g-with-circumflex'),
1063 ('\u011f g with breve', 'g-g-with-breve'),
1064 ('\u0121 g with dot above', 'g-g-with-dot-above'),
1065 ('\u0123 g with cedilla', 'g-g-with-cedilla'),
1066 ('\u0125 h with circumflex', 'h-h-with-circumflex'),
1067 ('\u0129 i with tilde', 'i-i-with-tilde'),
1068 ('\u012b i with macron', 'i-i-with-macron'),
1069 ('\u012d i with breve', 'i-i-with-breve'),
1070 ('\u012f i with ogonek', 'i-i-with-ogonek'),
1071 ('\u0133 ligature ij', 'ij-ligature-ij'),
1072 ('\u0135 j with circumflex', 'j-j-with-circumflex'),
1073 ('\u0137 k with cedilla', 'k-k-with-cedilla'),
1074 ('\u013a l with acute', 'l-l-with-acute'),
1075 ('\u013c l with cedilla', 'l-l-with-cedilla'),
1076 ('\u013e l with caron', 'l-l-with-caron'),
1077 ('\u0140 l with middle dot', 'l-l-with-middle-dot'),
1078 ('\u0144 n with acute', 'n-n-with-acute'),
1079 ('\u0146 n with cedilla', 'n-n-with-cedilla'),
1080 ('\u0148 n with caron', 'n-n-with-caron'),
1081 ('\u014d o with macron', 'o-o-with-macron'),
1082 ('\u014f o with breve', 'o-o-with-breve'),
1083 ('\u0151 o with double acute', 'o-o-with-double-acute'),
1084 ('\u0155 r with acute', 'r-r-with-acute'),
1085 ('\u0157 r with cedilla', 'r-r-with-cedilla'),
1086 ('\u0159 r with caron', 'r-r-with-caron'),
1087 ('\u015b s with acute', 's-s-with-acute'),
1088 ('\u015d s with circumflex', 's-s-with-circumflex'),
1089 ('\u015f s with cedilla', 's-s-with-cedilla'),
1090 ('\u0161 s with caron', 's-s-with-caron'),
1091 ('\u0163 t with cedilla', 't-t-with-cedilla'),
1092 ('\u0165 t with caron', 't-t-with-caron'),
1093 ('\u0169 u with tilde', 'u-u-with-tilde'),
1094 ('\u016b u with macron', 'u-u-with-macron'),
1095 ('\u016d u with breve', 'u-u-with-breve'),
1096 ('\u016f u with ring above', 'u-u-with-ring-above'),
1097 ('\u0171 u with double acute', 'u-u-with-double-acute'),
1098 ('\u0173 u with ogonek', 'u-u-with-ogonek'),
1099 ('\u0175 w with circumflex', 'w-w-with-circumflex'),
1100 ('\u0177 y with circumflex', 'y-y-with-circumflex'),
1101 ('\u017a z with acute', 'z-z-with-acute'),
1102 ('\u017c z with dot above', 'z-z-with-dot-above'),
1103 ('\u017e z with caron', 'z-z-with-caron'),
1104 # From Latin Extended-B
1105 ('\u01a1 o with horn', 'o-o-with-horn'),
1106 ('\u01b0 u with horn', 'u-u-with-horn'),
1107 ('\u01c6 dz with caron', 'dz-dz-with-caron'),
1108 ('\u01c9 lj', 'lj-lj'),
1109 ('\u01cc nj', 'nj-nj'),
1110 ('\u01ce a with caron', 'a-a-with-caron'),
1111 ('\u01d0 i with caron', 'i-i-with-caron'),
1112 ('\u01d2 o with caron', 'o-o-with-caron'),
1113 ('\u01d4 u with caron', 'u-u-with-caron'),
1114 ('\u01e7 g with caron', 'g-g-with-caron'),
1115 ('\u01e9 k with caron', 'k-k-with-caron'),
1116 ('\u01eb o with ogonek', 'o-o-with-ogonek'),
1117 ('\u01ed o with ogonek and macron', 'o-o-with-ogonek-and-macron'),
1118 ('\u01f0 j with caron', 'j-j-with-caron'),
1119 ('\u01f3 dz', 'dz-dz'),
1120 ('\u01f5 g with acute', 'g-g-with-acute'),
1121 ('\u01f9 n with grave', 'n-n-with-grave'),
1122 ('\u0201 a with double grave', 'a-a-with-double-grave'),
1123 ('\u0203 a with inverted breve', 'a-a-with-inverted-breve'),
1124 ('\u0205 e with double grave', 'e-e-with-double-grave'),
1125 ('\u0207 e with inverted breve', 'e-e-with-inverted-breve'),
1126 ('\u0209 i with double grave', 'i-i-with-double-grave'),
1127 ('\u020b i with inverted breve', 'i-i-with-inverted-breve'),
1128 ('\u020d o with double grave', 'o-o-with-double-grave'),
1129 ('\u020f o with inverted breve', 'o-o-with-inverted-breve'),
1130 ('\u0211 r with double grave', 'r-r-with-double-grave'),
1131 ('\u0213 r with inverted breve', 'r-r-with-inverted-breve'),
1132 ('\u0215 u with double grave', 'u-u-with-double-grave'),
1133 ('\u0217 u with inverted breve', 'u-u-with-inverted-breve'),
1134 ('\u0219 s with comma below', 's-s-with-comma-below'),
1135 ('\u021b t with comma below', 't-t-with-comma-below'),
1136 ('\u021f h with caron', 'h-h-with-caron'),
1137 ('\u0227 a with dot above', 'a-a-with-dot-above'),
1138 ('\u0229 e with cedilla', 'e-e-with-cedilla'),
1139 ('\u022f o with dot above', 'o-o-with-dot-above'),
1140 ('\u0233 y with macron', 'y-y-with-macron'),
1141 # digraphs From Latin-1 Supplements
1142 ('\u00df: ligature sz', 'sz-ligature-sz'),
1143 ('\u00e6 ae', 'ae-ae'),
1144 ('\u0153 ligature oe', 'oe-ligature-oe'),
1145 ('\u0238 db digraph', 'db-db-digraph'),
1146 ('\u0239 qp digraph', 'qp-qp-digraph'),
1147 ]
1148
1149 def test_make_id(self):
1150 failures = []
1151 tests = self.ids + self.ids_unicode_all
1152 for input_, expect in tests:
1153 output = nodes.make_id(input_)
1154 if expect != output:
1155 failures.append("'%s' != '%s'" % (expect, output))
1156 if failures:
1157 self.fail(f'{len(failures)} failures in {len(self.ids)} ids\n'
1158 + "\n".join(failures))
1159
1160 names = [ # sample, whitespace_normalized, fully_normalized
1161 ('a', 'a', 'a'),
1162 ('A', 'A', 'a'),
1163 ('A a A ', 'A a A', 'a a a'),
1164 ('A a A a', 'A a A a', 'a a a a'),
1165 (' AaA\n\r\naAa\tAaA\t\t', 'AaA aAa AaA', 'aaa aaa aaa')
1166 ]
1167
1168 def test_whitespace_normalize_name(self):
1169 for (sample, ws, full) in self.names:
1170 result = nodes.whitespace_normalize_name(sample)
1171 self.assertEqual(result, ws)
1172
1173 def test_fully_normalize_name(self):
1174 for (sample, ws, fully) in self.names:
1175 result = nodes.fully_normalize_name(sample)
1176 self.assertEqual(result, fully)
1177
1178 def test_split_name_list(self):
1179 self.assertEqual(nodes.split_name_list(r'a\ n\ame two\\ n\\ames'),
1180 ['a name', 'two\\', r'n\ames'])
1181
1182 def test_parse_measure(self):
1183 # measure is number + unit
1184 # By default, a run of ASCII letters or µ, a single percent sign,
1185 # or the empty string are recognized as unit.
1186 self.assertEqual(nodes.parse_measure('8ex'), (8, 'ex'))
1187 self.assertEqual(nodes.parse_measure('2.5'), (2.5, ''))
1188 self.assertEqual(nodes.parse_measure('-2s'), (-2, 's'))
1189 # Spaces between number and unit are tolerated, case is preserved:
1190 self.assertEqual(nodes.parse_measure('2 µF'), (2, 'µF'))
1191 self.assertEqual(nodes.parse_measure('10 EUR'), (10, 'EUR'))
1192 self.assertEqual(nodes.parse_measure('.5 %'), (.5, '%'))
1193 # Only a single percent sign is allowed:
1194 with self.assertRaisesRegex(ValueError, '"2%%" is no valid measure'):
1195 nodes.parse_measure('2%%')
1196 # Scientific notation is not supported:
1197 with self.assertRaisesRegex(ValueError, '"3e-4 mm" is no valid '):
1198 nodes.parse_measure('3e-4 mm')
1199 # Units must follow the number:
1200 with self.assertRaisesRegex(ValueError, '"EUR 23" is no valid '):
1201 nodes.parse_measure('EUR 23')
1202 # Supported units can be configured with a "unit regexp pattern":
1203 self.assertEqual(nodes.parse_measure('10 EUR', 'EUR|€'), (10, 'EUR'))
1204 self.assertEqual(nodes.parse_measure('10 €', 'EUR|€'), (10, '€'))
1205 with self.assertRaisesRegex(ValueError, '"20 DM" is no valid measure'):
1206 nodes.parse_measure('20 DM', 'EUR|€')
1207 # Measures without unit are only supported, if the pattern says so:
1208 with self.assertRaisesRegex(ValueError, '"20" is no valid measure'):
1209 nodes.parse_measure('20', 'EUR|€')
1210
1211
1212 class AttributeTypeTests(unittest.TestCase):
1213 """Test validator functions for the supported `attribute data types`__
1214
1215 See also test_parsers/test_docutils_xml/test_parse_element.py.
1216
1217 __ https://docutils.sourceforge.io/docs/ref/doctree.html#attribute-types
1218 """
1219
1220 def test_create_keyword_validator(self):
1221 # function factory for "choice validators"
1222 food = nodes.create_keyword_validator('ham', 'spam')
1223 self.assertEqual(food('ham'), 'ham')
1224 with self.assertRaisesRegex(ValueError,
1225 '"bacon" is not one of "ham", "spam".'):
1226 food('bacon')
1227
1228 def test_validate_identifier(self):
1229 # Identifiers must start with an ASCII letter and may contain
1230 # letters, digits and the hyphen
1231 # https://docutils.sourceforge.io/docs/ref/doctree.html#idref-type
1232 self.assertEqual(nodes.validate_identifier('mo-8b'), 'mo-8b')
1233 with self.assertRaisesRegex(ValueError, '"8b-mo" is no valid id'):
1234 nodes.validate_identifier('8b-mo')
1235
1236 def test_validate_identifier_list(self):
1237 # list of identifiers (cf. above)
1238 # or a `str` of space-separated identifiers.
1239 l1 = ['m8-b', 'm8-c']
1240 s1 = 'm8-b m8-c'
1241 self.assertEqual(nodes.validate_identifier_list(l1), l1)
1242 self.assertEqual(nodes.validate_identifier_list(s1), l1)
1243 l2 = ['m8-b', 'm8_c']
1244 s2 = 'm8-b #8c'
1245 with self.assertRaises(ValueError):
1246 nodes.validate_identifier_list(l2)
1247 with self.assertRaises(ValueError):
1248 nodes.validate_identifier_list(s2)
1249
1250 def test_validate_measure(self):
1251 # measure == number (int or decimal fraction) + optional unit
1252 # internal whitespace is removed
1253 self.assertEqual(nodes.validate_measure('8 ex'), '8ex')
1254 self.assertEqual(nodes.validate_measure('2'), '2')
1255 # unit is "%" or a run of ASCII letters plus "µ"; case is preserved
1256 self.assertEqual(nodes.validate_measure('3.5 %'), '3.5%')
1257 self.assertEqual(nodes.validate_measure('300 µm'), '300µm')
1258 self.assertEqual(nodes.validate_measure('4 kHz'), '4kHz')
1259 # other characters and whitespace are not allowed in a unit identifier
1260 with self.assertRaisesRegex(ValueError, 'no valid measure'):
1261 nodes.validate_measure('3 micro-farads')
1262 with self.assertRaisesRegex(ValueError, 'no valid measure'):
1263 nodes.validate_measure('3 micro farads')
1264 # a number is required
1265 with self.assertRaisesRegex(ValueError, '"ex" is no valid measure'):
1266 nodes.validate_measure('ex')
1267 # padding whitespace is not valid
1268 with self.assertRaisesRegex(ValueError, '"8ex " is no valid measure'):
1269 nodes.validate_measure('8ex ')
1270 # Negative numbers:
1271 # * ``doctree.txt`` does not mention negative numbers,
1272 # * in rST, negative numbers are not valid.
1273 # Provisional: currently valid but may become invalid!
1274 # self.assertEqual(nodes.validate_measure('-2'), '-2')
1275
1276 def test_validate_NMTOKEN(self):
1277 # str with ASCII-letters, digits, hyphen, underscore, and full-stop.
1278 self.assertEqual(nodes.validate_NMTOKEN('-8x_.'), '-8x_.')
1279 # internal space is not allowed
1280 with self.assertRaises(ValueError):
1281 nodes.validate_NMTOKEN('why me')
1282
1283 def test_validate_NMTOKENS(self):
1284 # list of NMTOKENS or string with space-separated NMTOKENS
1285 l1 = ['8_b', '8.c']
1286 s1 = '8_b 8.c'
1287 l2 = ['8_b', '8/c']
1288 s2 = '8_b #8'
1289 self.assertEqual(nodes.validate_NMTOKENS(l1), l1)
1290 self.assertEqual(nodes.validate_NMTOKENS(s1), l1)
1291 with self.assertRaises(ValueError):
1292 nodes.validate_NMTOKENS(l2)
1293 with self.assertRaises(ValueError):
1294 nodes.validate_NMTOKENS(s2)
1295
1296 def test_validate_refname_list(self):
1297 # list or string of "reference names".
1298 l1 = ['*:@', r'"more"\ & \x!']
1299 s1 = r'*:@ \"more"\\\ &\ \\x!' # unescaped backslash is ignored
1300 self.assertEqual(nodes.validate_refname_list(l1), l1)
1301 self.assertEqual(nodes.validate_refname_list(s1), l1)
1302 # whitspace is normalized, case is not normalized
1303 l2 = ['LARGE', 'a\t \tc']
1304 s2 = r'LARGE a\ \ \c'
1305 normalized = ['LARGE', 'a c']
1306
1307 self.assertEqual(nodes.validate_refname_list(l2), normalized)
1308 self.assertEqual(nodes.validate_refname_list(s2), normalized)
1309
1310 def test_validate_yesorno(self):
1311 # False if '0', else bool
1312 # TODO: The docs say '0' is false:
1313 # * Also return `True` for values that evaluate to `False`?
1314 # Even for `False` and `None`?
1315 # * Also return `False` for 'false', 'off', 'no'
1316 # like boolean config settings?
1317 self.assertFalse(nodes.validate_yesorno('0'))
1318 self.assertFalse(nodes.validate_yesorno(0))
1319 self.assertTrue(nodes.validate_yesorno('*'))
1320 self.assertTrue(nodes.validate_yesorno(1))
1321 # self.assertFalse(nodes.validate_yesorno('no'))
1322
1323
1324 if __name__ == '__main__':
1325 unittest.main()