Debian Codegraph @

test/test_utils/test_math/test_mathml_elements.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
13 """
14 Test module for utils/__init__.py.
15 """
16
17 from pathlib import Path
18 import sys
19 import unittest
20
21 if __name__ == '__main__':
22 # prepend the "docutils root" to the Python library path
23 # so we import the local `docutils` package.
24 sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
25
26 import docutils.utils.math.mathml_elements as mml
27
28 TEST_ROOT = Path(__file__).parent # ./test/ from the docutils root
29
30 # The index of MathML elements
31 # on https://developer.mozilla.org/en-US/docs/Web/MathML/Element
32 # for Nr. of children see https://www.w3.org/TR/mathml4/#presm_reqarg_table
33 # (Elements with 1* show 1 or * depending on the corresponding TeX macro.)
34 # Element Nr. of children Description comment
35 mathml_elements = """
36 <maction> * Bound actions to sub-expressions DEPRECATED
37 <annotation> 0 Data annotations NOT IMPLEMENTED
38 <annotation-xml> * XML annotations NOT IMPLEMENTED
39 <math> * Top-level element
40 <menclose> 1 Enclosed contents (non-standard) deprecated
41 <merror> * Enclosed syntax error messages
42 <mfenced> * Parentheses (non-standard) DEPRECATED
43 <mfrac> 2 Fraction
44 <mi> 0 Identifier
45 <mmultiscripts> * Prescripts and tensor indices NOT IMPLEMENTED
46 <mn> 0 Number
47 <mo> 0 Operator (and similar)
48 <mover> 2 Overscript
49 <mpadded> * Extra padding
50 <mphantom> 1 Invisible content reserving space
51 <mroot> 2 Radical with specified index
52 <mrow> * Grouped sub-expressions
53 <ms> 0 String literal NOT IMPLEMENTED
54 <mspace> 0 Space
55 <msqrt> 1 Square root without an index
56 <mstyle> * Style change (for compatibility)
57 <msub> 2 Subscript
58 <msup> 2 Superscrip
59 <msubsup> 3 Subscript-superscript pair
60 <mtable> * Table or matrix
61 <mtd> * Cell in a table or a matrix
62 <mtext> 0 Text
63 <mtr> * Row in a table or a matrix
64 <munder> 2 Underscript
65 <munderover> 3 Underscript-overscript pair
66 <semantics> * annotations (e.g. text source) NOT IMPLEMENTED
67 """
68
69
70 class MathElementTests(unittest.TestCase):
71 """Test the <MathElement> base class."""
72
73 prettyXML = """\
74 <math id="root">
75 <math id="c1"></math>
76 <math id="c2">
77 <math id="cc1"></math>
78 </math>
79 </math>"""
80
81 def test__init__(self):
82 """Instantiate a MathElement object and test its properties."""
83
84 # No arguments required, the class name is used as XML tag:
85 e1 = mml.MathElement()
86 self.assertEqual(e1.tag, 'MathElement')
87
88 # Positional arguments are stored as children,
89 # named arguments are stored as element attributes:
90 # * argument names are downcased,
91 # * attribute values must be `str`, `boolean`, or numerical
92 # and are stored as `str` (cf. test_a_str() below).
93 e0 = mml.MathElement(e1, CLASS='root', scriptlevel=1)
94 # len() returns the number of children
95 self.assertEqual(len(e0), 1)
96 # Attributes can be accessed using get(), set(), items(), and keys().
97 self.assertEqual(e0.get('class'), 'root')
98 e0.set('scriptlevel', 2)
99 e0.set('displaystyle', True)
100 self.assertEqual(e0.attrib, {'class': 'root',
101 'scriptlevel': '2',
102 'displaystyle': 'true'})
103
104 def test_children(self):
105 # positional arguments are stored as children.
106 e4 = mml.MathElement(id='e4')
107 e3 = mml.MathElement(id='e3')
108 e2 = mml.MathElement(e3, e4, id='e2')
109 e1 = mml.MathElement(id='e1')
110 e0 = mml.MathElement(e1, e2, id='e0')
111 # xml.etree uses list syntax to access them
112 self.assertEqual(e0[0], e1)
113 self.assertEqual(e0[1][-1], e4)
114 self.assertEqual(e0[:], [e1, e2]) # list of e0's children
115 # The default iterator yields the immediate children
116 self.assertEqual(tuple(e0), (e1, e2))
117 # The `iter()` method returns `self` and all descendants
118 self.assertEqual(tuple(e0.iter()), (e0, e1, e2, e3, e4))
119
120 # more list-like functions are tested below...
121
122 def test_a_str(self):
123 # test the XML attribute normalisation
124 #
125 # Values are converted to `str`:
126 self.assertEqual(mml.MathElement.a_str(-2), '-2')
127 self.assertEqual(mml.MathElement.a_str(1), '1')
128 self.assertEqual(mml.MathElement.a_str(0), '0')
129 # Booleans are downcased:
130 self.assertEqual(mml.MathElement.a_str(True), 'true')
131 self.assertEqual(mml.MathElement.a_str(False), 'false')
132 # Strings are left as-is:
133 self.assertEqual(mml.MathElement.a_str('+1'), '+1')
134 self.assertEqual(mml.MathElement.a_str('True'), 'True')
135 self.assertEqual(mml.MathElement.a_str(''), '')
136
137 def test__repr__(self):
138 """The representation should match the code to instantiate."""
139 # Watch the idempotent normalisation:
140 # * attribute names are downcased,
141 # * XML attribute values are converted to strings
142 e1 = mml.MathElement(mml.MathElement(level=2), CLASS='root')
143 self.assertEqual(repr(e1),
144 "MathElement(MathElement(level='2'), class='root')")
145 # Also report non-default number of children: (as `int`, not `str`)
146 e1[0].nchildren = 1
147 self.assertEqual(repr(e1[0]), "MathElement(nchildren=1, level='2')")
148
149 def test__str__(self):
150 """Informal string representation for debugging and error reports."""
151 e1 = mml.MathElement(mml.MathElement(level=2), CLASS='root')
152 self.assertEqual(str(e1), 'MathElement(MathElement())')
153
154 def test__setitem__(self):
155 """Setting an item also sets the `parent` attribute on the child."""
156 e1 = mml.MathElement()
157 e1[:] = (mml.MathElement(id=1), mml.MathElement(id=2))
158 self.assertEqual(e1[0].parent, e1)
159 self.assertEqual(e1[0].get('id'), '1')
160 self.assertEqual(e1[1].get('id'), '2')
161 e1[0] = mml.MathElement(id=3)
162 self.assertEqual(e1[0].get('id'), '3')
163 self.assertEqual(e1[0].parent, e1)
164 e1[2:] = (mml.MathElement(id=4), mml.MathElement(id=5))
165 e1[1:] = []
166 e1.nchildren = 2
167 with self.assertRaises(TypeError) as cm:
168 e1[:] = (mml.MathElement(id=6), mml.MathElement(id=7))
169 self.assertIn('takes only 2 children', str(cm.exception))
170
171 def test_is_full(self):
172 # A node is "full", if the number of children equals or exceeds
173 # the number of accepted children given in the "nchildren" attribute.
174 e1 = mml.MathElement()
175 self.assertTrue(e1.nchildren is None) # no limit to number of children
176 self.assertFalse(e1.is_full())
177 e1.nchildren = 1 # element expects/accepts one child.
178 self.assertFalse(e1.is_full())
179 e1.nchildren = 0 # element expects/accepts no children.
180 self.assertTrue(e1.is_full())
181
182 def test_close(self):
183 """Closing an element returns first non-closed anchestor or None."""
184 e1 = mml.MathElement(mml.MathElement())
185 self.assertEqual(e1[0].close(), e1)
186 self.assertTrue(e1.close() is None)
187 # When all anchestors are closed, return None as well
188 self.assertTrue(e1[0].close() is None)
189
190 def test_append(self):
191 """Test special features of the "append()" method."""
192 e1 = mml.MathElement()
193 e1.nchildren = 2 # element expects/accepts two children.
194
195 # Appending to an element sets the internal "parent" attribute ...
196 result = e1.append(mml.MathElement(id='c1'))
197 self.assertEqual(e1[0].parent, e1)
198 # ... which is hidden in XML ...
199 self.assertEqual(e1[0].toxml(), '<MathElement id="c1"></MathElement>')
200 # ... and returns the new "insertion point".
201 # If more children may be appended, return self
202 self.assertEqual(result, e1)
203 # If the element is "full" after appending the child,
204 # a non-full anchestor or None is returned:
205 result = e1.append(mml.MathElement(id='c2'))
206 self.assertTrue(result is None)
207
208 # Trying to append to an element that is "full" returns an error:
209 with self.assertRaises(TypeError) as cm:
210 result = e1.append(mml.MathElement())
211 self.assertEqual(str(cm.exception),
212 'Element "MathElement(MathElement(), MathElement())"'
213 ' takes only 2 children.')
214
215 def test_extend(self):
216 e1 = mml.MathElement()
217 c1 = mml.MathElement(id='c1')
218 c2 = mml.MathElement(id='c2')
219 e1.extend([c1, c2])
220 self.assertEqual([*e1], [c1, c2])
221
222 def test_pop(self):
223 c1 = mml.MathElement(id='c1')
224 c2 = mml.MathElement(id='c2')
225 e1 = mml.MathElement(c1, c2)
226 last_element = e1.pop()
227 self.assertEqual(last_element, c2)
228 self.assertEqual([*e1], [c1])
229 first_element = e1.pop(0)
230 self.assertEqual(first_element, c1)
231 with self.assertRaises(IndexError):
232 e1.pop()
233
234 def test_in_block(self):
235 # Return True, if `self` or an anchestor is a block-level element:
236 e1 = mml.math(display='block')
237 e2 = mml.math(mml.math(id='e3'), id='e2')
238 self.assertTrue(e1.in_block())
239 self.assertFalse(e2.in_block())
240 self.assertFalse(e2[0].in_block())
241 e1.append(e2)
242 self.assertTrue(e2.in_block())
243 self.assertTrue(e2[0].in_block())
244
245 def test_indent_xml(self):
246 """Modify `text` and `tail` to get indented XML output."""
247 c1 = mml.math(id='c1')
248 cc1 = mml.math(id='cc1')
249 c2 = mml.math(cc1, id='c2')
250 root = mml.math(c1, c2, id='root')
251 self.assertTrue('\n' not in str(root))
252 root.indent_xml()
253 self.assertEqual(root.toxml(), self.prettyXML)
254 # You can easily remove the indentation (but not the newlines):
255 root.indent_xml(space='')
256 self.assertEqual(c2.toxml(),
257 '<math id="c2">\n<math id="cc1"></math>\n</math>\n')
258 # Reverting `indent_xml()` requires iterating over all descendants
259 root.unindent_xml()
260 self.assertEqual(c2.toxml(),
261 '<math id="c2"><math id="cc1"></math></math>')
262
263 def test_unindent_xml(self):
264 # see also last assertion in `test_indent_xml()`
265 e1 = mml.math(mml.mtext('Hallo welt!\n'))
266 e1.indent_xml()
267 self.assertEqual(e1.toxml(),
268 '<math>\n <mtext>Hallo welt!\n</mtext>\n</math>')
269 # don't strip whitespace from MathToken's text attributes:
270 e1.unindent_xml()
271 self.assertEqual(e1.toxml(),
272 '<math><mtext>Hallo welt!\n</mtext></math>')
273
274 def test_toxml(self):
275 """XML representation of the element/subtree as `str`."""
276 e1 = mml.math(mml.math(level=2), CLASS='root')
277 self.assertEqual(e1.toxml(),
278 '<math class="root"><math level="2"></math></math>')
279
280
281 class MathSchemaTests(unittest.TestCase):
282 """Test `MathSchema` and derived element classes."""
283
284 def test__init__(self):
285 # the optional `switch` argument is stored as internal attribute
286 ms1 = mml.MathSchema(switch=True, id='ms1')
287 self.assertEqual(repr(ms1), "MathSchema(switch=True, id='ms1')")
288 # internal attributes are not exported to XML.
289 self.assertEqual(ms1.toxml(),
290 '<MathSchema id="ms1"></MathSchema>')
291 # the default value is dropped from ``repr()``
292 ms1.switch = False
293 self.assertEqual(repr(ms1), "MathSchema(id='ms1')")
294
295 def test__init__full(self):
296 # when initialized with `nchildren` children and `switch` True,
297 # the children are switched and `switch` is reset:
298 ms2 = mml.MathSchema(mml.mn(1), mml.mn(2), switch=True)
299 self.assertEqual(repr(ms2), "MathSchema(mn('2'), mn('1'))")
300 self.assertEqual(ms2.toxml(),
301 '<MathSchema><mn>2</mn><mn>1</mn></MathSchema>')
302
303 def test_append(self):
304 # appending normalizes the order before switching
305 ms1 = mml.MathSchema(mml.mn(1), switch=True)
306 ms1.append(mml.mn(2))
307 self.assertEqual(repr(ms1), "MathSchema(mn('2'), mn('1'))")
308 # appending to a closed element raises TypeError
309 with self.assertRaises(TypeError) as cm:
310 ms1.append(mml.mn(3))
311 self.assertIn('takes only 2 children', str(cm.exception))
312
313
314 class MathTokenTests(unittest.TestCase):
315 """Test MathToken and derived element classes."""
316
317 def test__init__(self):
318 # requires one argument `text` that is stored as the element's text
319 self.assertEqual(repr(mml.mi('x')), "mi('x')")
320 # the argument is converted to a `str`
321 self.assertEqual(repr(mml.mn(42)), "mn('42')")
322 # only one positional argument allowed:
323 with self.assertRaises(TypeError):
324 mml.mo('[', 'stretchy')
325 # text must be `str` or numerical value:
326 with self.assertRaises(ValueError) as cm:
327 mml.mi(mml.mtext('out'))
328 self.assertIn('MathToken element expects `str` or number',
329 str(cm.exception))
330
331 # optional named arguments become XML attributes
332 e1 = mml.mo('[', stretchy=False)
333 self.assertEqual(e1.toxml(), '<mo stretchy="false">[</mo>')
334
335 def test_append(self):
336 # MathTokens don't take child elements.
337 # Appending to MathTokens raises an exception.
338 e1 = mml.mo('[')
339 self.assertEqual(e1.nchildren, 0)
340 with self.assertRaises(TypeError) as cm:
341 e1.append(mml.mi('x'))
342 self.assertEqual(str(cm.exception),
343 'Element "mo(\'[\')" does not take children.')
344 with self.assertRaises(TypeError) as cm:
345 e1[:] = [mml.mn(3)]
346 self.assertEqual(str(cm.exception),
347 'Element "mo(\'[\')" does not take children.')
348
349
350 class mrowTests(unittest.TestCase):
351 """Test the `mrow` element class."""
352
353 def test_transfer_attributes(self):
354 e1 = mml.mrow(level=1, CLASS='cls1', style='rule1;')
355 e2 = mml.mrow(level=2, CLASS='cls2')
356 e3 = mml.mrow(level=3, style='rule3')
357 # e1.attrib -> e2.attrib
358 e1.transfer_attributes(e2)
359 self.assertEqual(e2.get('level'), '1')
360 self.assertEqual(e2.get('class'), 'cls2 cls1')
361 self.assertEqual(e2.get('style'), 'rule1;')
362 # e3.attrib -> e1.attrib
363 e3.transfer_attributes(e1)
364 self.assertEqual(e1.get('level'), '3')
365 self.assertEqual(e1.get('class'), 'cls1')
366 self.assertEqual(e1.get('style'), 'rule1; rule3')
367
368 def test_close_only_child(self):
369 # Remove <mrow> if it has a parent and only one child element.
370 # NOTE: this feature may be removed.
371 c1 = mml.math(CLASS='c1')
372 row1 = mml.mrow(c1, CLASS='row1')
373 # if possible, attach child to parent
374 row1.close() # no parent, no removal
375 self.assertEqual(c1.parent, row1)
376
377 root = mml.math(row1) # provide a parent
378 row1.close() # try again
379 self.assertEqual(c1.parent, root)
380 self.assertEqual(root.toxml(),
381 '<math><math class="c1 row1"></math></math>')
382
383
384 class MathMLElementTests(unittest.TestCase):
385 """Test classes for "MathML Core" elements."""
386
387 def test_mathml_elements(self):
388 for line in mathml_elements.strip().splitlines():
389 element, nchildren, description = line.split(maxsplit=2)
390 element = element.strip('<>')
391 if 'DEPRECATED' in description or 'NOT IMPLEMENTED' in description:
392 continue
393 cls = getattr(mml, element)
394 if issubclass(cls, mml.MathToken):
395 e = cls('x')
396 self.assertEqual(e.toxml(), f'<{element}>x</{element}>')
397 else:
398 e = cls()
399 self.assertEqual(e.toxml(), f'<{element}></{element}>')
400 if nchildren == '*':
401 self.assertTrue(e.nchildren is None,
402 f'{element}.nchildren == {e.nchildren}')
403 else:
404 self.assertEqual(e.nchildren, int(nchildren),
405 f'{element}.nchildren == {e.nchildren}')
406
407
408 if __name__ == '__main__':
409 unittest.main()