Debian Codegraph @

tests/test_builders/test_build_html.py

raw
1 """Test the HTML builder and check output against XPath."""
2
3 from __future__ import annotations
4
5 import os
6 import posixpath
7 import re
8 from typing import TYPE_CHECKING
9
10 import pytest
11 from docutils import nodes
12 from docutils.parsers import rst
13 from docutils.readers import standalone
14 from docutils.writers import html5_polyglot
15
16 from sphinx import addnodes
17 from sphinx._cli.util.errors import strip_escape_sequences
18 from sphinx.builders.html import (
19 StandaloneHTMLBuilder,
20 validate_html_extra_path,
21 validate_html_static_path,
22 )
23 from sphinx.errors import ConfigError
24 from sphinx.testing.util import etree_parse
25 from sphinx.util.docutils import _get_settings, new_document
26 from sphinx.util.inventory import InventoryFile, _InventoryItem
27 from sphinx.writers.html5 import HTML5Translator
28
29 from tests.test_builders.xpath_data import FIGURE_CAPTION
30 from tests.test_builders.xpath_util import check_xpath
31
32 if TYPE_CHECKING:
33 from collections.abc import Callable, Sequence
34 from pathlib import Path
35 from typing import Any
36 from xml.etree.ElementTree import Element, ElementTree
37
38 from sphinx.testing.util import SphinxTestApp
39
40
41 def test_html_sidebars_error(
42 make_app: Callable[..., SphinxTestApp], tmp_path: Path
43 ) -> None:
44 (tmp_path / 'conf.py').touch()
45 with pytest.raises(
46 ConfigError,
47 match="Values in 'html_sidebars' must be a list of strings. "
48 "At least one pattern has a string value: 'index'. "
49 r"Change to `html_sidebars = \{'index': \['searchbox.html'\]\}`.",
50 ):
51 make_app(
52 'html',
53 srcdir=tmp_path,
54 confoverrides={'html_sidebars': {'index': 'searchbox.html'}},
55 )
56
57
58 def test_html4_error(make_app: Callable[..., SphinxTestApp], tmp_path: Path) -> None:
59 (tmp_path / 'conf.py').touch()
60 with pytest.raises(
61 ConfigError,
62 match='HTML 4 is no longer supported by Sphinx',
63 ):
64 make_app(
65 'html',
66 srcdir=tmp_path,
67 confoverrides={'html4_writer': True},
68 )
69
70
71 @pytest.mark.parametrize(
72 ('fname', 'path', 'check'),
73 [
74 ('index.html', ".//div[@class='citation']/span", r'Ref1'),
75 ('index.html', ".//div[@class='citation']/span", r'Ref_1'),
76 (
77 'footnote.html',
78 ".//a[@class='footnote-reference brackets'][@href='#id9'][@id='id1']",
79 r'1',
80 ),
81 (
82 'footnote.html',
83 ".//a[@class='footnote-reference brackets'][@href='#id10'][@id='id2']",
84 r'2',
85 ),
86 (
87 'footnote.html',
88 ".//a[@class='footnote-reference brackets'][@href='#foo'][@id='id3']",
89 r'3',
90 ),
91 (
92 'footnote.html',
93 ".//a[@class='reference internal'][@href='#bar'][@id='id4']/span",
94 r'\[bar\]',
95 ),
96 (
97 'footnote.html',
98 ".//a[@class='reference internal'][@href='#baz-qux'][@id='id5']/span",
99 r'\[baz_qux\]',
100 ),
101 (
102 'footnote.html',
103 ".//a[@class='footnote-reference brackets'][@href='#id11'][@id='id6']",
104 r'4',
105 ),
106 (
107 'footnote.html',
108 ".//a[@class='footnote-reference brackets'][@href='#id12'][@id='id7']",
109 r'5',
110 ),
111 (
112 'footnote.html',
113 ".//aside[@class='footnote brackets']/span/a[@href='#id1']",
114 r'1',
115 ),
116 (
117 'footnote.html',
118 ".//aside[@class='footnote brackets']/span/a[@href='#id2']",
119 r'2',
120 ),
121 (
122 'footnote.html',
123 ".//aside[@class='footnote brackets']/span/a[@href='#id3']",
124 r'3',
125 ),
126 ('footnote.html', ".//div[@class='citation']/span/a[@href='#id4']", r'bar'),
127 ('footnote.html', ".//div[@class='citation']/span/a[@href='#id5']", r'baz_qux'),
128 (
129 'footnote.html',
130 ".//aside[@class='footnote brackets']/span/a[@href='#id6']",
131 r'4',
132 ),
133 (
134 'footnote.html',
135 ".//aside[@class='footnote brackets']/span/a[@href='#id7']",
136 r'5',
137 ),
138 (
139 'footnote.html',
140 ".//aside[@class='footnote brackets']/span/a[@href='#id8']",
141 r'6',
142 ),
143 ],
144 )
145 @pytest.mark.sphinx('html', testroot='root')
146 @pytest.mark.test_params(shared_result='test_build_html_output_docutils18')
147 def test_docutils_output(
148 app: SphinxTestApp,
149 cached_etree_parse: Callable[[Path], ElementTree],
150 fname: str,
151 path: str,
152 check: str,
153 ) -> None:
154 app.build()
155 check_xpath(cached_etree_parse(app.outdir / fname), fname, path, check)
156
157
158 @pytest.mark.sphinx(
159 'html',
160 testroot='root',
161 parallel=2,
162 )
163 def test_html_parallel(app: SphinxTestApp) -> None:
164 app.build()
165
166
167 class ConfHTMLTranslator(HTML5Translator):
168 depart_with_node = 0
169
170 def depart_admonition(self, node: nodes.Element | None = None) -> None:
171 if node is not None:
172 self.depart_with_node += 1
173 super().depart_admonition(node)
174
175
176 @pytest.mark.sphinx('html', testroot='_blank')
177 def test_html_translator(app: SphinxTestApp) -> None:
178 settings = _get_settings(
179 standalone.Reader, rst.Parser, html5_polyglot.Writer, defaults={}
180 )
181 doctree = new_document(__file__, settings)
182 doctree.append(addnodes.seealso('test', nodes.Text('test')))
183 doctree.append(nodes.note('test', nodes.Text('test')))
184 doctree.append(nodes.warning('test', nodes.Text('test')))
185 doctree.append(nodes.attention('test', nodes.Text('test')))
186 doctree.append(nodes.caution('test', nodes.Text('test')))
187 doctree.append(nodes.danger('test', nodes.Text('test')))
188 doctree.append(nodes.error('test', nodes.Text('test')))
189 doctree.append(nodes.hint('test', nodes.Text('test')))
190 doctree.append(nodes.important('test', nodes.Text('test')))
191 doctree.append(nodes.tip('test', nodes.Text('test')))
192
193 visitor = ConfHTMLTranslator(doctree, app.builder)
194 assert isinstance(visitor, ConfHTMLTranslator)
195 assert isinstance(visitor, HTML5Translator)
196 doctree.walkabout(visitor)
197
198 assert visitor.depart_with_node == 10
199
200
201 @pytest.mark.parametrize(
202 ('path', 'check', 'be_found'),
203 [
204 (FIGURE_CAPTION + "//span[@class='caption-number']", 'Fig. 1', True),
205 (FIGURE_CAPTION + "//span[@class='caption-number']", 'Fig. 2', True),
206 (FIGURE_CAPTION + "//span[@class='caption-number']", 'Fig. 3', True),
207 (".//div//span[@class='caption-number']", 'No.1 ', True),
208 (".//div//span[@class='caption-number']", 'No.2 ', True),
209 ('.//li/p/a/span', 'Fig. 1', True),
210 ('.//li/p/a/span', 'Fig. 2', True),
211 ('.//li/p/a/span', 'Fig. 3', True),
212 ('.//li/p/a/span', 'No.1', True),
213 ('.//li/p/a/span', 'No.2', True),
214 ],
215 )
216 @pytest.mark.sphinx(
217 'html',
218 testroot='add_enumerable_node',
219 srcdir='test_enumerable_node',
220 )
221 def test_enumerable_node(
222 app: SphinxTestApp,
223 cached_etree_parse: Callable[[Path], ElementTree],
224 path: str,
225 check: str,
226 be_found: bool,
227 ) -> None:
228 app.build()
229 check_xpath(
230 cached_etree_parse(app.outdir / 'index.html'),
231 'index.html',
232 path,
233 check,
234 be_found,
235 )
236
237
238 @pytest.mark.sphinx(
239 'html',
240 testroot='basic',
241 confoverrides={'html_copy_source': False},
242 )
243 def test_html_copy_source(app: SphinxTestApp) -> None:
244 app.build(force_all=True)
245 assert not (app.outdir / '_sources' / 'index.rst.txt').exists()
246
247
248 @pytest.mark.sphinx(
249 'html',
250 testroot='basic',
251 confoverrides={'html_sourcelink_suffix': '.txt'},
252 )
253 def test_html_sourcelink_suffix(app: SphinxTestApp) -> None:
254 app.build(force_all=True)
255 assert (app.outdir / '_sources' / 'index.rst.txt').exists()
256
257
258 @pytest.mark.sphinx(
259 'html',
260 testroot='basic',
261 confoverrides={'html_sourcelink_suffix': '.rst'},
262 )
263 def test_html_sourcelink_suffix_same(app: SphinxTestApp) -> None:
264 app.build(force_all=True)
265 assert (app.outdir / '_sources' / 'index.rst').exists()
266
267
268 @pytest.mark.sphinx(
269 'html',
270 testroot='basic',
271 confoverrides={'html_sourcelink_suffix': ''},
272 )
273 def test_html_sourcelink_suffix_empty(app: SphinxTestApp) -> None:
274 app.build(force_all=True)
275 assert (app.outdir / '_sources' / 'index.rst').exists()
276
277
278 @pytest.mark.sphinx('html', testroot='html_entity')
279 def test_html_entity(app: SphinxTestApp) -> None:
280 app.build(force_all=True)
281 valid_entities = {'amp', 'lt', 'gt', 'quot', 'apos'}
282 content = (app.outdir / 'index.html').read_text(encoding='utf8')
283 for entity in re.findall(r'&([a-z]+);', content, re.MULTILINE):
284 assert entity not in valid_entities
285
286
287 @pytest.mark.sphinx('html', testroot='basic')
288 def test_html_inventory(app: SphinxTestApp) -> None:
289 app.build(force_all=True)
290
291 with app.outdir.joinpath('objects.inv').open('rb') as f:
292 invdata = InventoryFile.load(f, 'https://www.google.com', posixpath.join)
293
294 assert set(invdata.keys()) == {'std:label', 'std:doc'}
295 assert set(invdata['std:label'].keys()) == {
296 'modindex',
297 'py-modindex',
298 'genindex',
299 'search',
300 }
301 assert invdata['std:label']['modindex'] == _InventoryItem(
302 project_name='Project name not set',
303 project_version='',
304 uri='https://www.google.com/py-modindex.html',
305 display_name='Module Index',
306 )
307 assert invdata['std:label']['py-modindex'] == _InventoryItem(
308 project_name='Project name not set',
309 project_version='',
310 uri='https://www.google.com/py-modindex.html',
311 display_name='Python Module Index',
312 )
313 assert invdata['std:label']['genindex'] == _InventoryItem(
314 project_name='Project name not set',
315 project_version='',
316 uri='https://www.google.com/genindex.html',
317 display_name='Index',
318 )
319 assert invdata['std:label']['search'] == _InventoryItem(
320 project_name='Project name not set',
321 project_version='',
322 uri='https://www.google.com/search.html',
323 display_name='Search Page',
324 )
325 assert set(invdata['std:doc'].keys()) == {'index'}
326 assert invdata['std:doc']['index'] == _InventoryItem(
327 project_name='Project name not set',
328 project_version='',
329 uri='https://www.google.com/index.html',
330 display_name='The basic Sphinx documentation for testing',
331 )
332
333
334 @pytest.mark.usefixtures('_http_teapot')
335 @pytest.mark.sphinx(
336 'html',
337 testroot='images',
338 confoverrides={'html_sourcelink_suffix': ''},
339 )
340 def test_html_anchor_for_figure(app: SphinxTestApp) -> None:
341 app.build(force_all=True)
342 content = (app.outdir / 'index.html').read_text(encoding='utf8')
343 assert (
344 '<figcaption>\n<p><span class="caption-text">The caption of pic</span>'
345 '<a class="headerlink" href="#id1" title="Link to this image">¶</a></p>\n</figcaption>'
346 ) in content
347
348
349 @pytest.mark.sphinx('html', testroot='directives-raw')
350 def test_html_raw_directive(app: SphinxTestApp) -> None:
351 app.build(force_all=True)
352 result = (app.outdir / 'index.html').read_text(encoding='utf8')
353
354 # standard case
355 assert 'standalone raw directive (HTML)' in result
356 assert 'standalone raw directive (LaTeX)' not in result
357
358 # with substitution
359 assert '<p>HTML: abc def ghi</p>' in result
360 assert '<p>LaTeX: abc ghi</p>' in result
361
362
363 @pytest.mark.parametrize(
364 ('path', 'check', 'be_found'),
365 [
366 (".//link[@href='_static/persistent.css'][@rel='stylesheet']", '', True),
367 (
368 ".//link[@href='_static/default.css'][@rel='stylesheet'][@title='Default']",
369 '',
370 True,
371 ),
372 (
373 ".//link[@href='_static/alternate1.css']"
374 "[@rel='alternate stylesheet']"
375 "[@title='Alternate']",
376 '',
377 True,
378 ),
379 (
380 ".//link[@href='_static/alternate2.css'][@rel='alternate stylesheet']",
381 '',
382 True,
383 ),
384 (
385 ".//link[@href='_static/more_persistent.css'][@rel='stylesheet']",
386 '',
387 True,
388 ),
389 (
390 ".//link[@href='_static/more_default.css']"
391 "[@rel='stylesheet']"
392 "[@title='Default']",
393 '',
394 True,
395 ),
396 (
397 ".//link[@href='_static/more_alternate1.css']"
398 "[@rel='alternate stylesheet']"
399 "[@title='Alternate']",
400 '',
401 True,
402 ),
403 (
404 ".//link[@href='_static/more_alternate2.css'][@rel='alternate stylesheet']",
405 '',
406 True,
407 ),
408 ],
409 )
410 @pytest.mark.sphinx('html', testroot='stylesheets')
411 def test_alternate_stylesheets(
412 app: SphinxTestApp,
413 cached_etree_parse: Callable[[Path], ElementTree],
414 path: str,
415 check: str,
416 be_found: bool,
417 ) -> None:
418 app.build()
419 check_xpath(
420 cached_etree_parse(app.outdir / 'index.html'),
421 'index.html',
422 path,
423 check,
424 be_found,
425 )
426
427
428 @pytest.mark.sphinx('html', testroot='html_style')
429 def test_html_style(app: SphinxTestApp) -> None:
430 app.build()
431 result = (app.outdir / 'index.html').read_text(encoding='utf8')
432 assert (
433 '<link rel="stylesheet" type="text/css" href="_static/default.css" />'
434 ) in result
435 assert (
436 '<link rel="stylesheet" type="text/css" href="_static/alabaster.css" />'
437 ) not in result
438
439
440 @pytest.mark.sphinx(
441 'html',
442 testroot='basic',
443 confoverrides={
444 'html_sidebars': {
445 '**': [
446 'localtoc.html',
447 'searchfield.html',
448 'sourcelink.html',
449 ]
450 }
451 },
452 )
453 def test_html_sidebar(app: SphinxTestApp) -> None:
454 # default for alabaster
455 app.build(force_all=True)
456 result = (app.outdir / 'index.html').read_text(encoding='utf8')
457 # layout.html
458 assert '<div class="sphinxsidebar" role="navigation" aria-label="Main">' in result
459 assert '<h1>The basic Sphinx documentation for testing' in result
460 assert '<h3>Navigation</h3>' in result
461 # localtoc.html
462 assert '<h3><a href="#">Table of Contents</a></h3>' in result
463 # searchfield.html
464 assert '<div class="searchformwrapper">' in result
465 # sourcelink.html
466 assert '<h3>This Page</h3>' in result
467
468 assert isinstance(app.builder, StandaloneHTMLBuilder) # type-checking
469 sidebars = app.builder._get_sidebars('index')
470 assert sidebars == (
471 'localtoc.html',
472 'searchfield.html',
473 'sourcelink.html',
474 )
475
476 # only sourcelink.html
477 app.config.html_sidebars = {'**': ['sourcelink.html']}
478 app.build(force_all=True)
479 result = (app.outdir / 'index.html').read_text(encoding='utf8')
480 # layout.html
481 assert '<div class="sphinxsidebar" role="navigation" aria-label="Main">' in result
482 assert '<h1>The basic Sphinx documentation for testing' in result
483 assert '<h3>Navigation</h3>' in result
484 # localtoc.html
485 assert '<h3><a href="#">Table of Contents</a></h3>' not in result
486 # searchfield.html
487 assert '<div class="searchformwrapper">' not in result
488 # sourcelink.html
489 assert '<h3>This Page</h3>' in result
490
491 assert isinstance(app.builder, StandaloneHTMLBuilder) # type-checking
492 sidebars = app.builder._get_sidebars('index')
493 assert sidebars == ('sourcelink.html',)
494
495 # no sidebars
496 app.config.html_sidebars = {'**': []}
497 app.build(force_all=True)
498 result = (app.outdir / 'index.html').read_text(encoding='utf8')
499 # layout.html
500 assert (
501 '<div class="sphinxsidebar" role="navigation" aria-label="Main">'
502 ) not in result
503 assert '<h1>The basic Sphinx documentation for testing' in result
504 assert '<h3>Navigation</h3>' in result
505 # localtoc.html
506 assert '<h3><a href="#">Table of Contents</a></h3>' not in result
507 # searchfield.html
508 assert '<div class="searchformwrapper">' not in result
509 # sourcelink.html
510 assert '<h3>This Page</h3>' not in result
511
512 assert isinstance(app.builder, StandaloneHTMLBuilder) # type-checking
513 sidebars = app.builder._get_sidebars('index')
514 assert sidebars == ()
515
516
517 @pytest.mark.parametrize(
518 ('fname', 'path', 'check', 'be_found'),
519 [
520 ('index.html', ".//h1/em/a[@href='https://example.com/cp.1']", '', True),
521 ('index.html', ".//em/a[@href='https://example.com/man.1']", '', True),
522 ('index.html', ".//em/a[@href='https://example.com/ls.1']", '', True),
523 ('index.html', ".//em/a[@href='https://example.com/sphinx.']", '', True),
524 ],
525 )
526 @pytest.mark.sphinx(
527 'html',
528 testroot='manpage_url',
529 confoverrides={'manpages_url': 'https://example.com/{page}.{section}'},
530 )
531 @pytest.mark.test_params(shared_result='test_build_html_manpage_url')
532 def test_html_manpage(
533 app: SphinxTestApp,
534 cached_etree_parse: Callable[[Path], ElementTree],
535 fname: str,
536 path: str,
537 check: str,
538 be_found: bool,
539 ) -> None:
540 app.build()
541 check_xpath(cached_etree_parse(app.outdir / fname), fname, path, check, be_found)
542
543
544 @pytest.mark.sphinx(
545 'html',
546 testroot='toctree-glob',
547 confoverrides={'html_baseurl': 'https://example.com/'},
548 )
549 def test_html_baseurl(app: SphinxTestApp) -> None:
550 app.build()
551
552 result = (app.outdir / 'index.html').read_text(encoding='utf8')
553 assert '<link rel="canonical" href="https://example.com/index.html" />' in result
554
555 result = (app.outdir / 'qux' / 'index.html').read_text(encoding='utf8')
556 assert (
557 '<link rel="canonical" href="https://example.com/qux/index.html" />'
558 ) in result
559
560
561 @pytest.mark.sphinx(
562 'html',
563 testroot='toctree-glob',
564 confoverrides={
565 'html_baseurl': 'https://example.com/subdir',
566 'html_file_suffix': '.htm',
567 },
568 )
569 def test_html_baseurl_and_html_file_suffix(app: SphinxTestApp) -> None:
570 app.build()
571
572 result = (app.outdir / 'index.htm').read_text(encoding='utf8')
573 assert (
574 '<link rel="canonical" href="https://example.com/subdir/index.htm" />'
575 ) in result
576
577 result = (app.outdir / 'qux' / 'index.htm').read_text(encoding='utf8')
578 assert (
579 '<link rel="canonical" href="https://example.com/subdir/qux/index.htm" />'
580 ) in result
581
582
583 @pytest.mark.sphinx(
584 'html',
585 testroot='basic',
586 srcdir='validate_html_extra_path',
587 )
588 def test_validate_html_extra_path(app: SphinxTestApp) -> None:
589 (app.confdir / '_static').mkdir(parents=True, exist_ok=True)
590 app.config.html_extra_path = [
591 '/path/to/not_found', # not found
592 '_static',
593 app.outdir, # outdir
594 app.outdir / '_static', # inside outdir
595 ] # fmt: skip
596
597 validate_html_extra_path(app, app.config)
598 assert app.config.html_extra_path == ['_static']
599
600 warnings = strip_escape_sequences(app.warning.getvalue()).splitlines()
601 assert "html_extra_path entry '/path/to/not_found' does not exist" in warnings[0]
602 assert warnings[1].endswith(' is placed inside outdir')
603 assert warnings[2].endswith(' does not exist')
604 assert len(warnings) == 3
605
606
607 @pytest.mark.sphinx(
608 'html',
609 testroot='basic',
610 srcdir='validate_html_static_path',
611 )
612 def test_validate_html_static_path(app: SphinxTestApp) -> None:
613 (app.confdir / '_static').mkdir(parents=True, exist_ok=True)
614 app.config.html_static_path = [
615 '/path/to/not_found', # not found
616 '_static',
617 app.outdir, # outdir
618 app.outdir / '_static', # inside outdir
619 ] # fmt: skip
620
621 validate_html_static_path(app, app.config)
622 assert app.config.html_static_path == ['_static']
623
624 warnings = strip_escape_sequences(app.warning.getvalue()).splitlines()
625 assert "html_static_path entry '/path/to/not_found' does not exist" in warnings[0]
626 assert warnings[1].endswith(' is placed inside outdir')
627 assert warnings[2].endswith(' does not exist')
628 assert len(warnings) == 3
629
630
631 @pytest.mark.sphinx(
632 'html',
633 testroot='basic',
634 confoverrides={'html_permalinks': False},
635 )
636 def test_html_permalink_disable(app: SphinxTestApp) -> None:
637 app.build()
638 content = (app.outdir / 'index.html').read_text(encoding='utf8')
639
640 assert '<h1>The basic Sphinx documentation for testing</h1>' in content
641
642
643 @pytest.mark.sphinx(
644 'html',
645 testroot='basic',
646 confoverrides={'html_permalinks_icon': '<span>[PERMALINK]</span>'},
647 )
648 def test_html_permalink_icon(app: SphinxTestApp) -> None:
649 app.build()
650 content = (app.outdir / 'index.html').read_text(encoding='utf8')
651
652 assert (
653 '<h1>The basic Sphinx documentation for testing<a class="headerlink" '
654 'href="#the-basic-sphinx-documentation-for-testing" '
655 'title="Link to this heading"><span>[PERMALINK]</span></a></h1>'
656 ) in content
657
658
659 @pytest.mark.sphinx('html', testroot='html_signaturereturn_icon')
660 def test_html_signaturereturn_icon(app: SphinxTestApp) -> None:
661 app.build()
662 content = (app.outdir / 'index.html').read_text(encoding='utf8')
663
664 assert '<span class="sig-return-icon">&#x2192;</span>' in content
665
666
667 @pytest.mark.sphinx(
668 'html',
669 testroot='root',
670 srcdir=os.urandom(4).hex(),
671 )
672 def test_html_remove_sources_before_write_gh_issue_10786(app: SphinxTestApp) -> None:
673 # See: https://github.com/sphinx-doc/sphinx/issues/10786
674 target = app.srcdir / 'img.png'
675
676 def handler(app: SphinxTestApp) -> list[tuple[str, dict[str, Any], str]]:
677 assert target.exists()
678 target.unlink()
679 return []
680
681 app.connect('html-collect-pages', handler)
682 assert target.exists()
683 app.build()
684 assert not target.exists()
685
686 ws = strip_escape_sequences(app.warning.getvalue()).splitlines()
687 assert len(ws) >= 1
688
689 file = os.fsdecode(target)
690 assert f"WARNING: cannot copy image file '{file}': {file} does not exist" == ws[-1]
691
692
693 @pytest.mark.sphinx(
694 'html',
695 testroot='domain-py-python_maximum_signature_line_length',
696 confoverrides={'python_maximum_signature_line_length': 1},
697 )
698 def test_html_pep_695_one_type_per_line(
699 app: SphinxTestApp, cached_etree_parse: Callable[[Path], ElementTree]
700 ) -> None:
701 app.build()
702 fname = app.outdir / 'index.html'
703 etree = cached_etree_parse(fname)
704
705 class chk:
706 def __init__(self, expect: str) -> None:
707 self.expect = expect
708
709 def __call__(self, nodes: Sequence[Element]) -> None:
710 assert len(nodes) == 1, nodes
711 objnode = ''.join(nodes[0].itertext()).replace('\n\n', '')
712 objnode = objnode.rstrip(chr(182)) # remove '¶' symbol
713 objnode = objnode.strip('\n') # remove surrounding new lines
714 assert objnode == self.expect
715
716 # each signature has a dangling ',' at the end of its parameters lists
717 check_xpath(
718 etree,
719 fname,
720 r'.//dt[@id="generic_foo"][1]',
721 chk('generic_foo[\nT,\n]()'),
722 )
723 check_xpath(
724 etree,
725 fname,
726 r'.//dt[@id="generic_bar"][1]',
727 chk('generic_bar[\nT,\n](\nx: list[T],\n)'),
728 )
729 check_xpath(
730 etree,
731 fname,
732 r'.//dt[@id="generic_ret"][1]',
733 chk('generic_ret[\nR,\n]() → R'),
734 )
735 check_xpath(
736 etree,
737 fname,
738 r'.//dt[@id="MyGenericClass"][1]',
739 chk('class MyGenericClass[\nX,\n]'),
740 )
741 check_xpath(
742 etree,
743 fname,
744 r'.//dt[@id="MyList"][1]',
745 chk('class MyList[\nT,\n](list[T])'),
746 )
747
748
749 @pytest.mark.sphinx(
750 'html',
751 testroot='domain-py-python_maximum_signature_line_length',
752 confoverrides={
753 'python_maximum_signature_line_length': 1,
754 'python_trailing_comma_in_multi_line_signatures': False,
755 },
756 )
757 def test_html_pep_695_trailing_comma_in_multi_line_signatures(
758 app: SphinxTestApp,
759 ) -> None:
760 app.build()
761 fname = app.outdir / 'index.html'
762 etree = etree_parse(fname)
763
764 class chk:
765 def __init__(self, expect: str) -> None:
766 self.expect = expect
767
768 def __call__(self, nodes: Sequence[Element]) -> None:
769 assert len(nodes) == 1, nodes
770 objnode = ''.join(nodes[0].itertext()).replace('\n\n', '')
771 objnode = objnode.rstrip(chr(182)) # remove '¶' symbol
772 objnode = objnode.strip('\n') # remove surrounding new lines
773 assert objnode == self.expect
774
775 # each signature has a dangling ',' at the end of its parameters lists
776 check_xpath(
777 etree,
778 fname,
779 r'.//dt[@id="generic_foo"][1]',
780 chk('generic_foo[\nT\n]()'),
781 )
782 check_xpath(
783 etree,
784 fname,
785 r'.//dt[@id="generic_bar"][1]',
786 chk('generic_bar[\nT\n](\nx: list[T]\n)'),
787 )
788 check_xpath(
789 etree,
790 fname,
791 r'.//dt[@id="generic_ret"][1]',
792 chk('generic_ret[\nR\n]() → R'),
793 )
794 check_xpath(
795 etree,
796 fname,
797 r'.//dt[@id="MyGenericClass"][1]',
798 chk('class MyGenericClass[\nX\n]'),
799 )
800 check_xpath(
801 etree,
802 fname,
803 r'.//dt[@id="MyList"][1]',
804 chk('class MyList[\nT\n](list[T])'),
805 )
806
807
808 @pytest.mark.sphinx('html', testroot='directives-admonition-collapse')
809 def test_html_admonition_collapse(app: SphinxTestApp) -> None:
810 app.build()
811 fname = app.outdir / 'index.html'
812 etree = etree_parse(fname)
813
814 def _create_check(text: str, open: bool) -> Callable[[Sequence[Element]], None]:
815 def _check(els: Sequence[Element]) -> None:
816 assert len(els) == 1
817 el = els[0]
818 if open:
819 assert el.attrib['open'] == 'open'
820 else:
821 assert 'open' not in el.attrib
822 p = el.find('p')
823 assert p is not None
824 assert p.text == text
825
826 return _check
827
828 check_xpath(
829 etree,
830 fname,
831 r'.//div[@class="standard admonition note"]//p',
832 'This is a standard note.',
833 )
834 check_xpath(
835 etree,
836 fname,
837 r'.//details[@class="admonition note"]',
838 _create_check('This note is collapsible, and initially open by default.', True),
839 )
840 check_xpath(
841 etree,
842 fname,
843 r'.//details[@class="admonition-example admonition"]',
844 _create_check('This example is collapsible, and initially open.', True),
845 )
846 check_xpath(
847 etree,
848 fname,
849 r'.//details[@class="admonition hint"]',
850 _create_check('This hint is collapsible, but initially closed.', False),
851 )