Debian Codegraph @

test/test_writers/test_html5_polyglot.py

raw symbols SCIP
1 #! /usr/bin/env python3
2
3 # $Id: test_html5_polyglot.py 10135 2025-05-20 15:07:28Z milde $
4 # Author: reggie dugard <[email protected]>
5 # Maintainer: [email protected]
6 # Copyright: This module has been placed in the public domain.
7
8 """Test HTML5 writer output ("fragment"/"body" part).
9
10 This is the document body (not HTML <body>).
11 """
12
13 from pathlib import Path
14 import sys
15 import unittest
16
17 if __name__ == '__main__':
18 # prepend the "docutils root" to the Python library path
19 # so we import the local `docutils` package.
20 sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
21
22 import docutils
23 import docutils.core
24 from docutils.parsers.rst.directives.images import PIL
25 from docutils.utils.code_analyzer import with_pygments
26 from docutils.writers import html5_polyglot
27
28 if with_pygments:
29 import pygments
30
31 if tuple(map(int, pygments.__version__.split('.')[:2])) < (2, 14):
32 # pygments output changed in version 2.14
33 with_pygments = False
34
35 # TEST_ROOT is ./test/ from the docutils root
36 TEST_ROOT = Path(__file__).parents[1]
37 DATA_ROOT = TEST_ROOT / 'data'
38 ROOT_PREFIX = (TEST_ROOT / 'functional/input').as_posix()
39
40 # Pillow/PIL is optional:
41 if PIL:
42 REQUIRES_PIL = ''
43 ONLY_LOCAL = 'Cannot get file path corresponding to https://dummy.png.'
44 # Pillow versions vary in their error output (cf. bugs: #485 and #500)
45 try:
46 PIL.Image.open(Path('dummy.png'))
47 except OSError as err:
48 DUMMY_PNG_NOT_FOUND = str(err)
49 HEIGHT_ATTR = 'height="32" '
50 WIDTH_ATTR = 'width="32" '
51 NO_PIL_SYSTEM_MESSAGE = ''
52 else:
53 REQUIRES_PIL = '\n Requires Python Imaging Library.'
54 ONLY_LOCAL = 'Requires Python Imaging Library.'
55 DUMMY_PNG_NOT_FOUND = 'Requires Python Imaging Library.'
56 HEIGHT_ATTR = ''
57 WIDTH_ATTR = ''
58 NO_PIL_SYSTEM_MESSAGE = (
59 '<aside class="system-message">\n'
60 '<p class="system-message-title">System Message:'
61 ' WARNING/2 (<span class="docutils literal">'
62 '&lt;string&gt;</span>, line 1)</p>\n'
63 '<p>Cannot scale image!\n'
64 ' Could not get size from &quot;/data/blue%20square.png&quot;:\n'
65 ' Requires Python Imaging Library.</p>\n'
66 '</aside>\n')
67
68
69 class Html5WriterPublishPartsTestCase(unittest.TestCase):
70 """Test case for HTML5 writer via the publish_parts() interface."""
71
72 maxDiff = None
73
74 def test_publish(self):
75 for name, (settings_overrides, cases) in totest.items():
76 for casenum, (case_input, case_expected) in enumerate(cases):
77 with self.subTest(id=f'totest[{name!r}][{casenum}]'):
78 if name == 'syntax_highlight' and not with_pygments:
79 self.skipTest('syntax highlight requires pygments')
80 parts = docutils.core.publish_parts(
81 source=case_input,
82 writer=html5_polyglot.Writer(),
83 settings_overrides={
84 '_disable_config': True,
85 'strict_visitor': True,
86 'stylesheet_path': '',
87 'section_self_link': True,
88 **settings_overrides,
89 }
90 )
91 self.assertEqual(case_expected, parts['body'])
92
93
94 totest = {} # expected samples contain only the "body" part of the HMTL output
95
96 totest['standard'] = ({}, [
97 ["""\
98 Simple String
99 """,
100 '<p>Simple String</p>\n',
101 ],
102 ["""\
103 Simple String with *markup*
104 """,
105 '<p>Simple String with <em>markup</em></p>\n',
106 ],
107 ["""\
108 Simple String with an even simpler ``inline literal``
109 """,
110 '<p>Simple String with an even simpler <span class="docutils literal">inline literal</span></p>\n',
111 ],
112 ["""\
113 A simple `anonymous reference`__
114
115 __ http://www.test.com/test_url
116 """,
117 '<p>A simple <a class="reference external" href="http://www.test.com/test_url">anonymous reference</a></p>\n',
118 ],
119 ["""\
120 One paragraph.
121
122 Two paragraphs.
123 """,
124 """\
125 <p>One paragraph.</p>
126 <p>Two paragraphs.</p>
127 """,
128 ],
129 ["""\
130 A simple `named reference`_ with stuff in between the
131 reference and the target.
132
133 .. _`named reference`: http://www.test.com/test_url
134 """,
135 """\
136 <p>A simple <a class="reference external" href="http://www.test.com/test_url">named reference</a> with stuff in between the
137 reference and the target.</p>
138 """,
139 ],
140 ["""\
141 .. [CIT2022] A citation.
142 """,
143 """\
144 <div role="list" class="citation-list">
145 <div class="citation" id="cit2022" role="doc-biblioentry">
146 <span class="label"><span class="fn-bracket">[</span>CIT2022<span class="fn-bracket">]</span></span>
147 <p>A citation.</p>
148 </div>
149 </div>
150 """,
151 ],
152 [f"""\
153 .. image:: {DATA_ROOT.as_uri()}/circle.svg
154 :loading: embed
155 :width: 50%
156 :height: 30
157 :align: left
158 """,
159 """\
160 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 10 10" style="width: 50%;" height="30" class="align-left">
161 <circle cx="5" cy="5" r="4" fill="lightblue" />
162 </svg>
163 """],
164 ])
165
166
167 totest['no_title_promotion'] = ({'doctitle_xform': False}, [
168 ["""\
169 +++++
170 Title
171 +++++
172
173 Not A Subtitle
174 ==============
175
176 Some stuff
177
178 Section
179 -------
180
181 Some more stuff
182
183 Another Section
184 ...............
185
186 And even more stuff
187 """,
188 """\
189 <section id="title">
190 <h2>Title<a class="self-link" title="link to this section" href="#title"></a></h2>
191 <section id="not-a-subtitle">
192 <h3>Not A Subtitle<a class="self-link" title="link to this section" href="#not-a-subtitle"></a></h3>
193 <p>Some stuff</p>
194 <section id="section">
195 <h4>Section<a class="self-link" title="link to this section" href="#section"></a></h4>
196 <p>Some more stuff</p>
197 <section id="another-section">
198 <h5>Another Section<a class="self-link" title="link to this section" href="#another-section"></a></h5>
199 <p>And even more stuff</p>
200 </section>
201 </section>
202 </section>
203 </section>
204 """,
205 ],
206 ["""\
207 * bullet
208 * list
209 """,
210 """\
211 <ul class="simple">
212 <li><p>bullet</p></li>
213 <li><p>list</p></li>
214 </ul>
215 """,
216 ],
217 ["""\
218 .. table::
219 :align: right
220 :width: 320
221
222 +-----+-----+
223 | 1 | 2 |
224 +-----+-----+
225 | 3 | 4 |
226 +-----+-----+
227 """,
228 """\
229 <table class="align-right" style="width: 320px;">
230 <tbody>
231 <tr><td><p>1</p></td>
232 <td><p>2</p></td>
233 </tr>
234 <tr><td><p>3</p></td>
235 <td><p>4</p></td>
236 </tr>
237 </tbody>
238 </table>
239 """,
240 ],
241 ["""\
242 Not a docinfo.
243
244 :This: .. _target:
245
246 is
247 :a:
248 :simple:
249 :field: list
250 """,
251 """\
252 <p>Not a docinfo.</p>
253 <dl class="field-list simple">
254 <dt>This<span class="colon">:</span></dt>
255 <dd><p id="target">is</p>
256 </dd>
257 <dt>a<span class="colon">:</span></dt>
258 <dd><p></p></dd>
259 <dt>simple<span class="colon">:</span></dt>
260 <dd><p></p></dd>
261 <dt>field<span class="colon">:</span></dt>
262 <dd><p>list</p>
263 </dd>
264 </dl>
265 """,
266 ],
267 ["""\
268 Not a docinfo.
269
270 :This is: a
271 :simple field list with loooong field: names
272 """,
273 """\
274 <p>Not a docinfo.</p>
275 <dl class="field-list simple">
276 <dt>This is<span class="colon">:</span></dt>
277 <dd><p>a</p>
278 </dd>
279 <dt>simple field list with loooong field<span class="colon">:</span></dt>
280 <dd><p>names</p>
281 </dd>
282 </dl>
283 """,
284 ],
285 ["""\
286 Not a docinfo.
287
288 .. class:: field-indent-200
289
290 :This: is a
291 :simple: field list with custom indent.
292 """,
293 """\
294 <p>Not a docinfo.</p>
295 <dl class="field-list simple" style="--field-indent: 200px;">
296 <dt>This<span class="colon">:</span></dt>
297 <dd><p>is a</p>
298 </dd>
299 <dt>simple<span class="colon">:</span></dt>
300 <dd><p>field list with custom indent.</p>
301 </dd>
302 </dl>
303 """,
304 ],
305 ["""\
306 Not a docinfo.
307
308 .. class:: field-indent-200uf
309
310 :This: is a
311 :simple: field list without custom indent,
312 because the unit "uf" is invalid.
313 """,
314 """\
315 <p>Not a docinfo.</p>
316 <dl class="field-indent-200uf field-list simple">
317 <dt>This<span class="colon">:</span></dt>
318 <dd><p>is a</p>
319 </dd>
320 <dt>simple<span class="colon">:</span></dt>
321 <dd><p>field list without custom indent,
322 because the unit &quot;uf&quot; is invalid.</p>
323 </dd>
324 </dl>
325 """,
326 ],
327 ["""\
328 .. figure:: dummy.png
329 :figname: fig:dummy
330
331 The figure's caption.
332
333 A legend.
334
335 The legend's second paragraph.
336 """,
337 """\
338 <figure id="fig-dummy">
339 <img alt="dummy.png" src="dummy.png" />
340 <figcaption>
341 <p>The figure's caption.</p>
342 <div class="legend">
343 <p>A legend.</p>
344 <p>The legend's second paragraph.</p>
345 </div>
346 </figcaption>
347 </figure>
348 """,
349 ],
350 ["""\
351 .. figure:: dummy.png
352
353 The figure's caption, no legend.
354 """,
355 """\
356 <figure>
357 <img alt="dummy.png" src="dummy.png" />
358 <figcaption>
359 <p>The figure's caption, no legend.</p>
360 </figcaption>
361 </figure>
362 """,
363 ],
364 ["""\
365 .. figure:: dummy.png
366
367 ..
368
369 A legend without caption.
370 """,
371 """\
372 <figure>
373 <img alt="dummy.png" src="dummy.png" />
374 <figcaption>
375 <div class="legend">
376 <p>A legend without caption.</p>
377 </div>
378 </figcaption>
379 </figure>
380 """,
381 ],
382 ["""\
383 .. figure:: dummy.png
384
385 No caption nor legend.
386 """,
387 """\
388 <figure>
389 <img alt="dummy.png" src="dummy.png" />
390 </figure>
391 <p>No caption nor legend.</p>
392 """,
393 ],
394 [f"""\
395 .. include:: {DATA_ROOT}/multiple-term-definition.xml
396 :parser: xml
397 """,
398 """\
399 <dl>
400 <dt>New in Docutils 0.22</dt>
401 <dd><p>A definition list item may contain several
402 terms with optional classifier(s).</p>
403 <p>However, there is currently no corresponding
404 reStructuredText syntax.</p>
405 </dd>
406 <dt>term 2a</dt>
407 <dt>term 2b</dt>
408 <dd><p>definition 2</p>
409 </dd>
410 <dt>term 3a<span class="classifier">classifier 3a</span><span class="classifier">classifier 3aa</span><dt>term 3b<span class="classifier">classifier 3b</span></dt>
411 <dd><p>definition 3</p>
412 </dd>
413 </dl>
414 """,
415 ],
416 ])
417
418
419 totest['lazy_loading'] = ({'image_loading': 'lazy',
420 'report_level': 4}, [
421 ["""\
422 Lazy loading by default, overridden by :loading: option
423 ("cannot embed" warning ignored).
424
425 .. image:: dummy.png
426 .. image:: dummy.png
427 :loading: link
428 .. figure:: dummy.png
429 .. figure:: dummy.png
430 :loading: embed
431 """,
432 """\
433 <p>Lazy loading by default, overridden by :loading: option
434 (&quot;cannot embed&quot; warning ignored).</p>
435 <img alt="dummy.png" loading="lazy" src="dummy.png" />
436 <img alt="dummy.png" src="dummy.png" />
437 <figure>
438 <img alt="dummy.png" loading="lazy" src="dummy.png" />
439 </figure>
440 <figure>
441 <img alt="dummy.png" src="dummy.png" />
442 </figure>
443 """,
444 ],
445 ])
446
447
448 totest['root_prefix'] = ({'root_prefix': ROOT_PREFIX,
449 'image_loading': 'embed',
450 'warning_stream': '',
451 }, [
452 ["""\
453 .. image:: /data/blue%20square.png
454 :scale: 100%
455 .. figure:: /data/blue%20square.png
456 """,
457 f'<img alt="/data/blue%20square.png" {HEIGHT_ATTR}src="data:image/png;base64,'
458 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAALElEQVR4nO3NMQ'
459 'EAMAjAsDFjvIhHFCbgSwU0kdXvsn96BwAAAAAAAAAAAIsNnEwBk52VRuMAAAAA'
460 'SUVORK5CYII="'
461 f' {WIDTH_ATTR}/>\n{NO_PIL_SYSTEM_MESSAGE}'
462 '<figure>\n'
463 '<img alt="/data/blue%20square.png" src="data:image/png;base64,'
464 'iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAIAAAD8GO2jAAAALElEQVR4nO3NMQ'
465 'EAMAjAsDFjvIhHFCbgSwU0kdXvsn96BwAAAAAAAAAAAIsNnEwBk52VRuMAAAAA'
466 'SUVORK5CYII=" />\n'
467 '</figure>\n',
468 ],
469 ])
470
471
472 totest['no_backlinks'] = ({'footnote_backlinks': False}, [
473
474 ["""\
475 Two footnotes [#f1]_ [#f2]_ and two citations [once]_ [twice]_.
476
477 The latter are referenced a second time [#f2]_ [twice]_.
478
479 .. [#f1] referenced once
480 .. [#f2] referenced twice
481 .. [once] citation referenced once
482 .. [twice] citation referenced twice
483 """,
484 """\
485 <p>Two footnotes <a class="brackets" href="#f1" id="footnote-reference-1" role="doc-noteref"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></a> <a class="brackets" href="#f2" id="footnote-reference-2" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a> and two citations <a class="citation-reference" href="#once" id="citation-reference-1" role="doc-biblioref">[once]</a> <a class="citation-reference" href="#twice" id="citation-reference-2" role="doc-biblioref">[twice]</a>.</p>
486 <p>The latter are referenced a second time <a class="brackets" href="#f2" id="footnote-reference-3" role="doc-noteref"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></a> <a class="citation-reference" href="#twice" id="citation-reference-3" role="doc-biblioref">[twice]</a>.</p>
487 <aside class="footnote-list brackets">
488 <aside class="footnote brackets" id="f1" role="doc-footnote">
489 <span class="label"><span class="fn-bracket">[</span>1<span class="fn-bracket">]</span></span>
490 <p>referenced once</p>
491 </aside>
492 <aside class="footnote brackets" id="f2" role="doc-footnote">
493 <span class="label"><span class="fn-bracket">[</span>2<span class="fn-bracket">]</span></span>
494 <p>referenced twice</p>
495 </aside>
496 </aside>
497 <div role="list" class="citation-list">
498 <div class="citation" id="once" role="doc-biblioentry">
499 <span class="label"><span class="fn-bracket">[</span>once<span class="fn-bracket">]</span></span>
500 <p>citation referenced once</p>
501 </div>
502 <div class="citation" id="twice" role="doc-biblioentry">
503 <span class="label"><span class="fn-bracket">[</span>twice<span class="fn-bracket">]</span></span>
504 <p>citation referenced twice</p>
505 </div>
506 </div>
507 """,
508 ],
509 ])
510
511
512 totest['syntax_highlight'] = ({'syntax_highlight': 'short',
513 }, [
514 ["""\
515 .. code:: shell
516
517 cat <<EOF
518 Hello World
519 EOF
520 """,
521 """\
522 <pre class="code shell literal-block"><code>cat<span class="w"> </span><span class="s">&lt;&lt;EOF
523 Hello World
524 EOF</span></code></pre>
525 """,
526 ],
527 ["""\
528 .. role:: shell(code)
529 :language: shell
530
531 :shell:`cat <<EOF Hello World EOF`
532 """,
533 """\
534 <p><code class="shell">cat<span class="w"> </span><span class="s">&lt;&lt;EOF Hello World EOF</span></code></p>
535 """,
536 ],
537 ])
538
539
540 totest['system_messages'] = ({'math_output': 'mathml',
541 'warning_stream': '',
542 }, [
543 ["""\
544 .. image:: https://dummy.png
545 :loading: embed
546 """,
547 """\
548 <img alt="https://dummy.png" src="https://dummy.png" />
549 <aside class="system-message">
550 <p class="system-message-title">System Message: ERROR/3 \
551 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
552 <p>Cannot embed image &quot;https://dummy.png&quot;:
553 Cannot get file path corresponding to https://dummy.png.</p>
554 </aside>
555 """,
556 ],
557 [f"""\
558 .. image:: {DATA_ROOT.as_uri()}/circle-broken.svg
559 :loading: embed
560 """,
561 f"""\
562 <svg xmlns="http://www.w3.org/2000/svg"
563 viewBox="0 0 10 10">
564 <circle cx="5" cy="5" r="4" fill="lightblue" x/>
565 </svg>
566
567 <aside class="system-message">
568 <p class="system-message-title">System Message: ERROR/3 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
569 <p>Cannot parse SVG image &quot;{DATA_ROOT.as_uri()}/circle-broken.svg&quot;:
570 not well-formed (invalid token): line 3, column 48</p>
571 </aside>
572 """
573 ],
574 [r"""Broken :math:`\sin \my`.
575 """,
576 """\
577 <p>Broken <span class="math problematic">\\sin \\my</span>.</p>
578 <aside class="system-message">
579 <p class="system-message-title">System Message: WARNING/2 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
580 <p>Unknown LaTeX command &quot;\\my&quot;.</p>
581 </aside>
582 """],
583 ])
584
585 totest['system_messages-PIL'] = ({'math_output': 'mathml',
586 'warning_stream': '',
587 }, [
588 ["""\
589 .. image:: dummy.png
590 :scale: 100%
591 :loading: embed
592 """,
593 f"""\
594 <img alt="dummy.png" src="dummy.png" />
595 <aside class="system-message">
596 <p class="system-message-title">System Message: WARNING/2 \
597 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
598 <p>Cannot scale image!
599 Could not get size from &quot;dummy.png&quot;:
600 {DUMMY_PNG_NOT_FOUND}</p>
601 </aside>
602 <aside class="system-message">
603 <p class="system-message-title">System Message: ERROR/3 \
604 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
605 <p>Cannot embed image &quot;dummy.png&quot;:
606 [Errno 2] No such file or directory: 'dummy.png'</p>
607 </aside>
608 """,
609 ],
610 ["""\
611 .. image:: dummy.mp4
612 :scale: 100%
613 """,
614 f"""\
615 <video src="dummy.mp4" title="dummy.mp4">
616 <a href="dummy.mp4">dummy.mp4</a>
617 </video>
618 <aside class="system-message">
619 <p class="system-message-title">System Message: WARNING/2 \
620 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
621 <p>Cannot scale image!
622 Could not get size from &quot;dummy.mp4&quot;:{REQUIRES_PIL}
623 PIL cannot read video images.</p>
624 </aside>
625 """,
626 ],
627 ["""\
628 .. image:: https://dummy.png
629 :scale: 100%
630 :loading: embed
631 """,
632 f"""\
633 <img alt="https://dummy.png" src="https://dummy.png" />
634 <aside class="system-message">
635 <p class="system-message-title">System Message: WARNING/2 \
636 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
637 <p>Cannot scale image!
638 Could not get size from &quot;https://dummy.png&quot;:
639 {ONLY_LOCAL}</p>
640 </aside>
641 <aside class="system-message">
642 <p class="system-message-title">System Message: ERROR/3 \
643 (<span class="docutils literal">&lt;string&gt;</span>, line 1)</p>
644 <p>Cannot embed image &quot;https://dummy.png&quot;:
645 Cannot get file path corresponding to https://dummy.png.</p>
646 </aside>
647 """,
648 ],
649 ])
650
651 totest['no_system_messages'] = ({'math_output': 'mathml',
652 'report_level': 4,
653 'warning_stream': '',
654 }, [
655 ["""\
656 .. image:: dummy.png
657 :scale: 100%
658 :loading: embed
659
660 .. image:: dummy.mp4
661 :scale: 100%
662 """,
663 """\
664 <img alt="dummy.png" src="dummy.png" />
665 <video src="dummy.mp4" title="dummy.mp4">
666 <a href="dummy.mp4">dummy.mp4</a>
667 </video>
668 """,
669 ],
670 [f"""\
671 .. image:: {DATA_ROOT.as_uri()}/circle-broken.svg
672 :loading: embed
673 """,
674 """\
675 <svg xmlns="http://www.w3.org/2000/svg"
676 viewBox="0 0 10 10">
677 <circle cx="5" cy="5" r="4" fill="lightblue" x/>
678 </svg>
679
680 """],
681 [r'Broken :math:`\sin \my`.',
682 '<p>Broken <tt class="math">\\sin \\my</tt>.</p>\n'
683 ],
684 ])
685
686
687 if __name__ == '__main__':
688 unittest.main()