Debian Codegraph @

tests/test_intl/test_intl.py

raw
1 """Test message patching for internationalization purposes.
2
3 Runs the text builder in the test root.
4 """
5
6 from __future__ import annotations
7
8 import os
9 import re
10 import shutil
11 import time
12 from typing import TYPE_CHECKING
13
14 import pygments
15 import pytest
16 from babel.messages import mofile, pofile
17 from babel.messages.catalog import Catalog
18 from docutils import nodes
19
20 from sphinx import locale
21 from sphinx._cli.util.errors import strip_escape_sequences
22 from sphinx.testing.util import assert_node, etree_parse
23 from sphinx.util.nodes import NodeMatcher
24
25 from tests.utils import extract_element, extract_node
26
27 if TYPE_CHECKING:
28 import xml.etree.ElementTree as ET
29 from collections.abc import Callable, Iterator
30 from io import StringIO
31 from pathlib import Path
32
33 from sphinx.testing.fixtures import _app_params
34 from sphinx.testing.util import SphinxTestApp
35
36 _CATALOG_LOCALE = 'xx'
37
38 sphinx_intl = pytest.mark.sphinx(
39 confoverrides={
40 'language': _CATALOG_LOCALE,
41 'locale_dirs': ['.'],
42 'gettext_compact': False,
43 'html_sidebars': {'**': ['globaltoc.html']}, # for test_html_meta
44 },
45 )
46
47
48 def read_po(pathname: Path) -> Catalog:
49 with open(pathname, encoding='utf-8') as f:
50 return pofile.read_po(f)
51
52
53 def write_mo(pathname: Path, po: Catalog) -> None:
54 with open(pathname, 'wb') as f:
55 mofile.write_mo(f, po)
56
57
58 def _set_mtime_ns(target: Path, value: int) -> int:
59 os.utime(target, ns=(value, value))
60 return target.stat().st_mtime_ns
61
62
63 def _get_bom_intl_path(srcdir: Path) -> tuple[Path, Path]:
64 basedir = srcdir / _CATALOG_LOCALE / 'LC_MESSAGES'
65 return basedir / 'bom.po', basedir / 'bom.mo'
66
67
68 def _get_update_targets(app: SphinxTestApp) -> tuple[set[str], set[str], set[str]]:
69 app.env.find_files(app.config, app.builder)
70 added, changed, removed = app.env.get_outdated_files(config_changed=False)
71 return added, changed, removed
72
73
74 @pytest.fixture(autouse=True)
75 def _info(app: SphinxTestApp) -> Iterator[None]:
76 yield
77 print(f'# language: {app.config.language}')
78 print(f'# locale_dirs: {app.config.locale_dirs}')
79
80
81 def elem_gettexts(elem: ET.Element) -> list[str]:
82 return list(filter(None, map(str.strip, elem.itertext())))
83
84
85 def elem_getref(elem: ET.Element) -> str | None:
86 return elem.attrib.get('refid') or elem.attrib.get('refuri')
87
88
89 def assert_elem(
90 elem: ET.Element,
91 *,
92 texts: list[str] | None = None,
93 refs: list[str] | None = None,
94 names: list[str] | None = None,
95 ) -> None:
96 if texts is not None:
97 _texts = elem_gettexts(elem)
98 assert _texts == texts
99 if refs is not None:
100 _refs = [elem_getref(x) for x in elem.findall('reference')]
101 assert _refs == refs
102 if names is not None:
103 _names = elem.attrib['names'].split()
104 assert _names == names
105
106
107 def assert_count(expected_expr: str, result: str, count: int) -> None:
108 find_pair = (expected_expr, result)
109 assert len(re.findall(*find_pair)) == count, find_pair
110
111
112 @sphinx_intl
113 @pytest.mark.sphinx('text', testroot='intl')
114 @pytest.mark.test_params(shared_result='test_intl_basic')
115 def test_text_emit_warnings(app: SphinxTestApp) -> None:
116 app.build()
117 # test warnings in translation
118 warnings = getwarning(app.warning)
119 warning_expr = (
120 '.*/warnings.txt:4:<translated>:1: '
121 'WARNING: Inline literal start-string without end-string. \\[docutils\\]\n'
122 )
123 assert re.search(warning_expr, warnings), (
124 f'{warning_expr!r} did not match {warnings!r}'
125 )
126
127
128 @sphinx_intl
129 @pytest.mark.sphinx('text', testroot='intl')
130 @pytest.mark.test_params(shared_result='test_intl_basic')
131 def test_text_warning_node(app: SphinxTestApp) -> None:
132 app.build()
133 # test warnings in translation
134 result = (app.outdir / 'warnings.txt').read_text(encoding='utf8')
135 expect = (
136 '3. I18N WITH REST WARNINGS'
137 '\n**************************\n'
138 '\nLINE OF >>``<<BROKEN LITERAL MARKUP.\n'
139 )
140 assert result == expect
141
142
143 @sphinx_intl
144 @pytest.mark.sphinx('text', testroot='intl')
145 @pytest.mark.test_params(shared_result='test_intl_basic')
146 def test_text_title_underline(app: SphinxTestApp) -> None:
147 app.build()
148 # --- simple translation; check title underlines
149 result = (app.outdir / 'bom.txt').read_text(encoding='utf8')
150 expect = (
151 '2. Datei mit UTF-8'
152 '\n******************\n' # underline matches new translation
153 '\nThis file has umlauts: äöü.\n'
154 )
155 assert result == expect
156
157
158 @sphinx_intl
159 @pytest.mark.sphinx('text', testroot='intl')
160 @pytest.mark.test_params(shared_result='test_intl_basic')
161 def test_text_subdirs(app: SphinxTestApp) -> None:
162 app.build()
163 # --- check translation in subdirs
164 result = (app.outdir / 'subdir' / 'index.txt').read_text(encoding='utf8')
165 assert result.startswith('1. subdir contents\n******************\n')
166
167
168 @sphinx_intl
169 @pytest.mark.sphinx('text', testroot='intl')
170 @pytest.mark.test_params(shared_result='test_intl_basic')
171 def test_text_inconsistency_warnings(app: SphinxTestApp) -> None:
172 app.build()
173 # --- check warnings for inconsistency in number of references
174 result = (app.outdir / 'refs_inconsistency.txt').read_text(encoding='utf8')
175 expect = (
176 '8. I18N WITH REFS INCONSISTENCY'
177 '\n*******************************\n'
178 '\n* FOR CITATION [ref3].\n'
179 '\n* reference FOR reference.\n'
180 '\n* ORPHAN REFERENCE: I18N WITH REFS INCONSISTENCY.\n'
181 '\n* the [refs] [translations] [order] is ignored.\n'
182 '\n[1] THIS IS A AUTO NUMBERED FOOTNOTE.\n'
183 '\n[ref2] THIS IS A CITATION.\n'
184 '\n[100] THIS IS A NUMBERED FOOTNOTE.\n'
185 '\n[order] order\n'
186 '\n[refs] references\n'
187 '\n[translations] translations\n'
188 )
189 assert result == expect
190
191 warnings = getwarning(app.warning)
192 warning_fmt = (
193 '.*/refs_inconsistency.txt:\\d+: '
194 'WARNING: inconsistent %(reftype)s in translated message.'
195 ' original: %(original)s, translated: %(translated)s \\[i18n.inconsistent_references\\]\n'
196 )
197 expected_warning_expr = (
198 warning_fmt
199 % {
200 'reftype': 'footnote references',
201 'original': "\\['\\[#\\]_'\\]",
202 'translated': '\\[\\]',
203 }
204 + warning_fmt
205 % {
206 'reftype': 'footnote references',
207 'original': "\\['\\[100\\]_'\\]",
208 'translated': '\\[\\]',
209 }
210 + warning_fmt
211 % {
212 'reftype': 'citation references',
213 'original': "\\['\\[ref2\\]_'\\]",
214 'translated': "\\['\\[ref3\\]_'\\]",
215 }
216 + warning_fmt
217 % {
218 'reftype': 'references',
219 'original': "\\['reference_'\\]",
220 'translated': "\\['reference_', 'reference_'\\]",
221 }
222 + warning_fmt
223 % {
224 'reftype': 'references',
225 'original': '\\[\\]',
226 'translated': "\\['`I18N WITH REFS INCONSISTENCY`_'\\]",
227 }
228 )
229 assert re.search(expected_warning_expr, warnings), (
230 f'{expected_warning_expr!r} did not match {warnings!r}'
231 )
232
233 expected_citation_ref_warning_expr = '.*/refs_inconsistency.txt:\\d+: WARNING: Citation \\[ref2\\] is not referenced.'
234 assert re.search(expected_citation_ref_warning_expr, warnings), (
235 f'{expected_citation_ref_warning_expr!r} did not match {warnings!r}'
236 )
237
238 expected_citation_warning_expr = (
239 '.*/refs_inconsistency.txt:\\d+: WARNING: citation not found: ref3'
240 )
241 assert re.search(expected_citation_warning_expr, warnings), (
242 f'{expected_citation_warning_expr!r} did not match {warnings!r}'
243 )
244
245
246 @sphinx_intl
247 @pytest.mark.sphinx('text', testroot='intl')
248 @pytest.mark.test_params(shared_result='test_intl_basic')
249 def test_noqa(app: SphinxTestApp) -> None:
250 app.build()
251 result = (app.outdir / 'noqa.txt').read_text(encoding='utf8')
252 expect = r"""FIRST SECTION
253 *************
254
255 TRANSLATED TEXT WITHOUT REFERENCE.
256
257 TEST noqa WHITESPACE INSENSITIVITY.
258
259 "#noqa" IS ESCAPED AT THE END OF THIS STRING. #noqa
260
261
262 NEXT SECTION WITH PARAGRAPH TO TEST BARE noqa
263 *********************************************
264
265 Some text, again referring to the section: NEXT SECTION WITH PARAGRAPH
266 TO TEST BARE noqa.
267 """
268 assert result == expect
269 assert 'next-section' not in getwarning(app.warning)
270
271
272 @sphinx_intl
273 @pytest.mark.sphinx('text', testroot='intl')
274 @pytest.mark.test_params(shared_result='test_intl_basic')
275 def test_text_literalblock_warnings(app: SphinxTestApp) -> None:
276 app.build()
277 # --- check warning for literal block
278 result = (app.outdir / 'literalblock.txt').read_text(encoding='utf8')
279 expect = (
280 '9. I18N WITH LITERAL BLOCK'
281 '\n**************************\n'
282 '\nCORRECT LITERAL BLOCK:\n'
283 '\n this is'
284 '\n literal block\n'
285 '\nMISSING LITERAL BLOCK:\n'
286 '\n<SYSTEM MESSAGE:'
287 )
288 assert result.startswith(expect)
289
290 warnings = getwarning(app.warning)
291 expected_warning_expr = (
292 '.*/literalblock.txt:\\d+: WARNING: Literal block expected; none found.'
293 )
294 assert re.search(expected_warning_expr, warnings), (
295 f'{expected_warning_expr!r} did not match {warnings!r}'
296 )
297
298
299 @sphinx_intl
300 @pytest.mark.sphinx('text', testroot='intl')
301 @pytest.mark.test_params(shared_result='test_intl_basic')
302 def test_text_definition_terms(app: SphinxTestApp) -> None:
303 app.build()
304 # --- definition terms: regression test for
305 # https://github.com/sphinx-doc/sphinx/issues/975,
306 # https://github.com/sphinx-doc/sphinx/issues/2198, and
307 # https://github.com/sphinx-doc/sphinx/issues/2205
308 result = (app.outdir / 'definition_terms.txt').read_text(encoding='utf8')
309 expect = (
310 '13. I18N WITH DEFINITION TERMS'
311 '\n******************************\n'
312 '\nSOME TERM'
313 '\n THE CORRESPONDING DEFINITION\n'
314 '\nSOME *TERM* WITH LINK'
315 '\n THE CORRESPONDING DEFINITION #2\n'
316 '\nSOME **TERM** WITH : CLASSIFIER1 : CLASSIFIER2'
317 '\n THE CORRESPONDING DEFINITION\n'
318 '\nSOME TERM WITH : CLASSIFIER[]'
319 '\n THE CORRESPONDING DEFINITION\n'
320 )
321 assert result == expect
322
323
324 @sphinx_intl
325 @pytest.mark.sphinx('text', testroot='intl')
326 @pytest.mark.test_params(shared_result='test_intl_basic')
327 def test_text_glossary_term(app: SphinxTestApp) -> None:
328 app.build()
329 # --- glossary terms: regression test for
330 # https://github.com/sphinx-doc/sphinx/issues/1090
331 result = (app.outdir / 'glossary_terms.txt').read_text(encoding='utf8')
332 expect = r"""18. I18N WITH GLOSSARY TERMS
333 ****************************
334
335 SOME NEW TERM
336 THE CORRESPONDING GLOSSARY
337
338 SOME OTHER NEW TERM
339 THE CORRESPONDING GLOSSARY #2
340
341 LINK TO *SOME NEW TERM*.
342
343 TRANSLATED GLOSSARY SHOULD BE SORTED BY TRANSLATED TERMS:
344
345 TRANSLATED TERM XXX
346 DEFINE XXX
347
348 TRANSLATED TERM YYY
349 DEFINE YYY
350
351 TRANSLATED TERM ZZZ
352 VVV
353 DEFINE ZZZ
354 """
355 assert result == expect
356 warnings = getwarning(app.warning)
357 assert warnings.count('term not in glossary') == 1
358
359
360 @sphinx_intl
361 @pytest.mark.sphinx('text', testroot='intl')
362 @pytest.mark.test_params(shared_result='test_intl_basic')
363 def test_text_glossary_term_inconsistencies(app: SphinxTestApp) -> None:
364 app.build()
365 # --- glossary term inconsistencies: regression test for
366 # https://github.com/sphinx-doc/sphinx/issues/1090
367 result = (app.outdir / 'glossary_terms_inconsistency.txt').read_text(
368 encoding='utf8'
369 )
370 expect = (
371 '19. I18N WITH GLOSSARY TERMS INCONSISTENCY'
372 '\n******************************************\n'
373 '\n1. LINK TO *SOME NEW TERM*.\n'
374 '\n2. LINK TO *TERM NOT IN GLOSSARY*.\n'
375 )
376 assert result == expect
377
378 warnings = getwarning(app.warning)
379 expected_warning_expr = (
380 '.*/glossary_terms_inconsistency.txt:\\d+: '
381 'WARNING: inconsistent term references in translated message.'
382 " original: \\[':term:`Some term`', ':term:`Some other term`'\\],"
383 " translated: \\[':term:`SOME NEW TERM`'\\] \\[i18n.inconsistent_references\\]\n"
384 )
385 assert re.search(expected_warning_expr, warnings), (
386 f'{expected_warning_expr!r} did not match {warnings!r}'
387 )
388 expected_warning_expr = (
389 '.*/glossary_terms_inconsistency.txt:\\d+:<translated>:1: '
390 "WARNING: term not in glossary: 'TERM NOT IN GLOSSARY'"
391 )
392 assert re.search(expected_warning_expr, warnings), (
393 f'{expected_warning_expr!r} did not match {warnings!r}'
394 )
395
396
397 @sphinx_intl
398 @pytest.mark.sphinx('text', testroot='intl')
399 @pytest.mark.test_params(shared_result='test_intl_basic')
400 def test_text_refs_reordered_no_warning(app: SphinxTestApp) -> None:
401 app.build()
402 # --- refs_reordered: verify no inconsistency warnings
403 result = (app.outdir / 'refs_reordered.txt').read_text(encoding='utf8')
404 # Verify the translation was applied
405 assert 'MULTIPLE REFS REORDERED' in result
406 assert 'SINGLE REF WITH TRANSLATED DISPLAY TEXT' in result
407
408 warnings = getwarning(app.warning)
409 # Should NOT have any inconsistent_references warnings for refs_reordered.txt
410 unexpected_warning_expr = '.*/refs_reordered.txt.*inconsistent.*references'
411 assert not re.search(unexpected_warning_expr, warnings), (
412 f'Unexpected warning found: {warnings!r}'
413 )
414
415
416 @sphinx_intl
417 @pytest.mark.sphinx('gettext', testroot='intl')
418 @pytest.mark.test_params(shared_result='test_intl_gettext')
419 def test_gettext_section(app: SphinxTestApp) -> None:
420 app.build()
421 # --- section
422 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'section.po')
423 actual = read_po(app.outdir / 'section.pot')
424 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
425 for expect_msg in (msg for msg in expect if msg.id):
426 assert expect_msg.id in actual_msg_ids
427
428
429 @sphinx_intl
430 @pytest.mark.sphinx('text', testroot='intl')
431 @pytest.mark.test_params(shared_result='test_intl_basic')
432 def test_text_section(app: SphinxTestApp) -> None:
433 app.build()
434 # --- section
435 result = (app.outdir / 'section.txt').read_text(encoding='utf8')
436 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'section.po')
437 for expect_msg in expect:
438 if not expect_msg.id:
439 continue
440 assert isinstance(expect_msg.string, str)
441 assert expect_msg.string in result
442
443
444 @sphinx_intl
445 @pytest.mark.sphinx('text', testroot='intl')
446 @pytest.mark.test_params(shared_result='test_intl_basic')
447 def test_text_seealso(app: SphinxTestApp) -> None:
448 app.build()
449 # --- seealso
450 result = (app.outdir / 'seealso.txt').read_text(encoding='utf8')
451 expect = (
452 '12. I18N WITH SEEALSO'
453 '\n*********************\n'
454 '\nSee also: SHORT TEXT 1\n'
455 '\nSee also: LONG TEXT 1\n'
456 '\nSee also:\n'
457 '\n SHORT TEXT 2\n'
458 '\n LONG TEXT 2\n'
459 )
460 assert result == expect
461
462
463 @sphinx_intl
464 @pytest.mark.sphinx('text', testroot='intl')
465 @pytest.mark.test_params(shared_result='test_intl_basic')
466 def test_text_figure_captions(app: SphinxTestApp) -> None:
467 app.build()
468 # --- figure captions: regression test for
469 # https://github.com/sphinx-doc/sphinx/issues/940
470 result = (app.outdir / 'figure.txt').read_text(encoding='utf8')
471 expect = (
472 '14. I18N WITH FIGURE CAPTION'
473 '\n****************************\n'
474 '\n [image]MY CAPTION OF THE FIGURE\n'
475 '\n MY DESCRIPTION PARAGRAPH1 OF THE FIGURE.\n'
476 '\n MY DESCRIPTION PARAGRAPH2 OF THE FIGURE.\n'
477 '\n'
478 '\n14.1. FIGURE IN THE BLOCK'
479 '\n=========================\n'
480 '\nBLOCK\n'
481 '\n [image]MY CAPTION OF THE FIGURE\n'
482 '\n MY DESCRIPTION PARAGRAPH1 OF THE FIGURE.\n'
483 '\n MY DESCRIPTION PARAGRAPH2 OF THE FIGURE.\n'
484 '\n'
485 '\n'
486 '14.2. IMAGE URL AND ALT\n'
487 '=======================\n'
488 '\n'
489 '[image: I18N -> IMG][image]\n'
490 '\n'
491 ' [image: IMG -> I18N][image]\n'
492 '\n'
493 '\n'
494 '14.3. IMAGE ON SUBSTITUTION\n'
495 '===========================\n'
496 '\n'
497 '\n'
498 '14.4. IMAGE UNDER NOTE\n'
499 '======================\n'
500 '\n'
501 'Note:\n'
502 '\n'
503 ' [image: i18n under note][image]\n'
504 '\n'
505 ' [image: img under note][image]\n'
506 )
507 assert result == expect
508
509
510 @sphinx_intl
511 @pytest.mark.sphinx('text', testroot='intl')
512 @pytest.mark.test_params(shared_result='test_intl_basic')
513 def test_text_rubric(app: SphinxTestApp) -> None:
514 app.build()
515 # --- rubric: regression test for pull request
516 # https://github.com/sphinx-doc/sphinx/issues/190
517 result = (app.outdir / 'rubric.txt').read_text(encoding='utf8')
518 expect = (
519 'I18N WITH RUBRIC'
520 '\n****************\n'
521 '\n-[ RUBRIC TITLE ]-\n'
522 '\n'
523 '\nRUBRIC IN THE BLOCK'
524 '\n===================\n'
525 '\nBLOCK\n'
526 '\n -[ RUBRIC TITLE ]-\n'
527 )
528 assert result == expect
529
530
531 @sphinx_intl
532 @pytest.mark.sphinx('text', testroot='intl')
533 @pytest.mark.test_params(shared_result='test_intl_basic')
534 def test_text_docfields(app: SphinxTestApp) -> None:
535 app.build()
536 # --- docfields
537 result = (app.outdir / 'docfields.txt').read_text(encoding='utf8')
538 expect = (
539 '21. I18N WITH DOCFIELDS'
540 '\n***********************\n'
541 '\nclass Cls1\n'
542 '\n Parameters:'
543 '\n **param** -- DESCRIPTION OF PARAMETER param\n'
544 '\nclass Cls2\n'
545 '\n Parameters:'
546 '\n * **foo** -- DESCRIPTION OF PARAMETER foo\n'
547 '\n * **bar** -- DESCRIPTION OF PARAMETER bar\n'
548 '\nclass Cls3(values)\n'
549 '\n Raises:'
550 '\n **ValueError** -- IF THE VALUES ARE OUT OF RANGE\n'
551 '\nclass Cls4(values)\n'
552 '\n Raises:'
553 '\n * **TypeError** -- IF THE VALUES ARE NOT VALID\n'
554 '\n * **ValueError** -- IF THE VALUES ARE OUT OF RANGE\n'
555 '\nclass Cls5\n'
556 '\n Returns:'
557 '\n A NEW "Cls3" INSTANCE\n'
558 )
559 assert result == expect
560
561
562 @sphinx_intl
563 @pytest.mark.sphinx('text', testroot='intl')
564 @pytest.mark.test_params(shared_result='test_intl_basic')
565 def test_text_admonitions(app: SphinxTestApp) -> None:
566 app.build()
567 # --- admonitions
568 # https://github.com/sphinx-doc/sphinx/issues/1206:
569 # gettext did not translate admonition directive's title
570 # see https://docutils.sourceforge.io/docs/ref/rst/directives.html#admonitions
571 result = (app.outdir / 'admonitions.txt').read_text(encoding='utf8')
572 directives = (
573 'attention',
574 'caution',
575 'danger',
576 'error',
577 'hint',
578 'important',
579 'note',
580 'tip',
581 'warning',
582 'admonition',
583 )
584 for d in directives:
585 assert d.upper() + ' TITLE' in result
586 assert d.upper() + ' BODY' in result
587
588 # https://github.com/sphinx-doc/sphinx/issues/4938
589 # `1. ` prefixed admonition title
590 assert '1. ADMONITION TITLE' in result
591
592
593 @sphinx_intl
594 @pytest.mark.sphinx('gettext', testroot='intl')
595 @pytest.mark.test_params(shared_result='test_intl_gettext')
596 def test_gettext_toctree(app: SphinxTestApp) -> None:
597 app.build()
598 # --- toctree (index.rst)
599 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'index.po')
600 actual = read_po(app.outdir / 'index.pot')
601 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
602 for expect_msg in (msg for msg in expect if msg.id):
603 assert expect_msg.id in actual_msg_ids
604 # --- toctree (toctree.rst)
605 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'toctree.po')
606 actual = read_po(app.outdir / 'toctree.pot')
607 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
608 for expect_msg in (msg for msg in expect if msg.id):
609 assert expect_msg.id in actual_msg_ids
610
611
612 @sphinx_intl
613 @pytest.mark.sphinx('gettext', testroot='intl')
614 @pytest.mark.test_params(shared_result='test_intl_gettext')
615 def test_gettext_table(app: SphinxTestApp) -> None:
616 app.build()
617 # --- toctree
618 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'table.po')
619 actual = read_po(app.outdir / 'table.pot')
620 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
621 for expect_msg in (msg for msg in expect if msg.id):
622 assert expect_msg.id in actual_msg_ids
623
624
625 @sphinx_intl
626 @pytest.mark.sphinx('text', testroot='intl')
627 @pytest.mark.test_params(shared_result='test_intl_basic')
628 def test_text_table(app: SphinxTestApp) -> None:
629 app.build()
630 # --- toctree
631 result = (app.outdir / 'table.txt').read_text(encoding='utf8')
632 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'table.po')
633 for expect_msg in expect:
634 if not expect_msg.id:
635 continue
636 assert isinstance(expect_msg.string, str)
637 assert expect_msg.string in result
638
639
640 @sphinx_intl
641 @pytest.mark.sphinx('text', testroot='intl')
642 @pytest.mark.test_params(shared_result='test_intl_basic')
643 def test_text_toctree(app: SphinxTestApp) -> None:
644 app.build()
645 # --- toctree (index.rst)
646 # Note: index.rst contains contents that is not shown in text.
647 result = (app.outdir / 'index.txt').read_text(encoding='utf8')
648 assert 'CONTENTS' in result
649 assert 'TABLE OF CONTENTS' in result
650 # --- toctree (toctree.rst)
651 result = (app.outdir / 'toctree.txt').read_text(encoding='utf8')
652 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'toctree.po')
653 for expect_msg in expect:
654 if not expect_msg.id:
655 continue
656 assert isinstance(expect_msg.string, str)
657 assert expect_msg.string in result
658
659
660 @sphinx_intl
661 @pytest.mark.sphinx('gettext', testroot='intl')
662 @pytest.mark.test_params(shared_result='test_intl_gettext')
663 def test_gettext_topic(app: SphinxTestApp) -> None:
664 app.build()
665 # --- topic
666 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'topic.po')
667 actual = read_po(app.outdir / 'topic.pot')
668 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
669 for expect_msg in (msg for msg in expect if msg.id):
670 assert expect_msg.id in actual_msg_ids
671
672
673 @sphinx_intl
674 @pytest.mark.sphinx('text', testroot='intl')
675 @pytest.mark.test_params(shared_result='test_intl_basic')
676 def test_text_topic(app: SphinxTestApp) -> None:
677 app.build()
678 # --- topic
679 result = (app.outdir / 'topic.txt').read_text(encoding='utf8')
680 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'topic.po')
681 for expect_msg in expect:
682 if not expect_msg.id:
683 continue
684 assert isinstance(expect_msg.string, str)
685 assert expect_msg.string in result
686
687
688 @sphinx_intl
689 @pytest.mark.sphinx('gettext', testroot='intl')
690 @pytest.mark.test_params(shared_result='test_intl_gettext')
691 def test_gettext_definition_terms(app: SphinxTestApp) -> None:
692 app.build()
693 # --- definition terms: regression test for
694 # https://github.com/sphinx-doc/sphinx/issues/2198,
695 # https://github.com/sphinx-doc/sphinx/issues/2205
696 expect = read_po(
697 app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'definition_terms.po'
698 )
699 actual = read_po(app.outdir / 'definition_terms.pot')
700 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
701 for expect_msg in (msg for msg in expect if msg.id):
702 assert expect_msg.id in actual_msg_ids
703
704
705 @sphinx_intl
706 @pytest.mark.sphinx('gettext', testroot='intl')
707 @pytest.mark.test_params(shared_result='test_intl_gettext')
708 def test_gettext_glossary_terms(app: SphinxTestApp) -> None:
709 app.build()
710 # --- glossary terms: regression test for
711 # https://github.com/sphinx-doc/sphinx/issues/1090
712 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'glossary_terms.po')
713 actual = read_po(app.outdir / 'glossary_terms.pot')
714 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
715 for expect_msg in (msg for msg in expect if msg.id):
716 assert expect_msg.id in actual_msg_ids
717 warnings = app.warning.getvalue().replace(os.sep, '/')
718 assert 'term not in glossary' not in warnings
719
720
721 @sphinx_intl
722 @pytest.mark.sphinx('gettext', testroot='intl')
723 @pytest.mark.test_params(shared_result='test_intl_gettext')
724 def test_gettext_glossary_term_inconsistencies(app: SphinxTestApp) -> None:
725 app.build()
726 # --- glossary term inconsistencies: regression test for
727 # https://github.com/sphinx-doc/sphinx/issues/1090
728 expect = read_po(
729 app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'glossary_terms_inconsistency.po'
730 )
731 actual = read_po(app.outdir / 'glossary_terms_inconsistency.pot')
732 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
733 for expect_msg in (msg for msg in expect if msg.id):
734 assert expect_msg.id in actual_msg_ids
735
736
737 @sphinx_intl
738 @pytest.mark.sphinx('gettext', testroot='intl')
739 @pytest.mark.test_params(shared_result='test_intl_gettext')
740 def test_gettext_literalblock(app: SphinxTestApp) -> None:
741 app.build()
742 # --- gettext builder always ignores ``only`` directive
743 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'literalblock.po')
744 actual = read_po(app.outdir / 'literalblock.pot')
745 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
746 for expect_msg in expect:
747 if not expect_msg.id:
748 continue
749 assert isinstance(expect_msg.id, str)
750 if len(expect_msg.id.splitlines()) == 1:
751 # compare translations only labels
752 assert expect_msg.id in actual_msg_ids
753 else:
754 pass # skip code-blocks and literalblocks
755
756
757 @sphinx_intl
758 @pytest.mark.sphinx('gettext', testroot='intl')
759 @pytest.mark.test_params(shared_result='test_intl_gettext')
760 def test_gettext_buildr_ignores_only_directive(app: SphinxTestApp) -> None:
761 app.build()
762 # --- gettext builder always ignores ``only`` directive
763 expect = read_po(app.srcdir / _CATALOG_LOCALE / 'LC_MESSAGES' / 'only.po')
764 actual = read_po(app.outdir / 'only.pot')
765 actual_msg_ids = {msg.id for msg in actual if msg.id} # pyright: ignore[reportUnhashable]
766 for expect_msg in (msg for msg in expect if msg.id):
767 assert expect_msg.id in actual_msg_ids
768
769
770 @sphinx_intl
771 @pytest.mark.sphinx('html', testroot='intl', copy_test_root=True)
772 def test_node_translated_attribute(app: SphinxTestApp) -> None:
773 app.build(filenames=[app.srcdir / 'translation_progress.txt'])
774
775 doctree = app.env.get_doctree('translation_progress')
776
777 translated_nodes = sum(1 for _ in doctree.findall(NodeMatcher(translated=True)))
778 assert translated_nodes == 10 + 1 # 10 lines + title
779
780 untranslated_nodes = sum(1 for _ in doctree.findall(NodeMatcher(translated=False)))
781 assert untranslated_nodes == 2 + 2 + 1 # 2 lines + 2 lines + substitution reference
782
783
784 @sphinx_intl
785 @pytest.mark.sphinx('html', testroot='intl', copy_test_root=True)
786 def test_translation_progress_substitution(app: SphinxTestApp) -> None:
787 app.build(filenames=[app.srcdir / 'translation_progress.txt'])
788
789 doctree = app.env.get_doctree('translation_progress')
790
791 # 11 out of 16 lines are translated
792 assert extract_node(doctree, 0, 19, 0) == '68.75%'
793
794
795 @pytest.mark.sphinx(
796 'html',
797 testroot='intl',
798 freshenv=True,
799 confoverrides={
800 'language': _CATALOG_LOCALE,
801 'locale_dirs': ['.'],
802 'gettext_compact': False,
803 'translation_progress_classes': True,
804 },
805 copy_test_root=True,
806 )
807 def test_translation_progress_classes_true(app: SphinxTestApp) -> None:
808 app.build(filenames=[app.srcdir / 'translation_progress.txt'])
809
810 doctree = app.env.get_doctree('translation_progress')
811
812 # title
813 assert 'translated' in extract_element(doctree, 0, 0)['classes']
814
815 # translated lines
816 assert 'translated' in extract_element(doctree, 0, 1)['classes']
817 assert 'translated' in extract_element(doctree, 0, 2)['classes']
818 assert 'translated' in extract_element(doctree, 0, 3)['classes']
819 assert 'translated' in extract_element(doctree, 0, 4)['classes']
820 assert 'translated' in extract_element(doctree, 0, 5)['classes']
821 assert 'translated' in extract_element(doctree, 0, 6)['classes']
822 assert 'translated' in extract_element(doctree, 0, 7)['classes']
823 assert 'translated' in extract_element(doctree, 0, 8)['classes']
824
825 assert extract_element(doctree, 0, 9)['classes'] == [] # comment node
826
827 # idempotent
828 assert 'translated' in extract_element(doctree, 0, 10)['classes']
829 assert 'translated' in extract_element(doctree, 0, 11)['classes']
830
831 assert extract_element(doctree, 0, 12)['classes'] == [] # comment node
832
833 # untranslated
834 assert 'untranslated' in extract_element(doctree, 0, 13)['classes']
835 assert 'untranslated' in extract_element(doctree, 0, 14)['classes']
836
837 assert extract_element(doctree, 0, 15)['classes'] == [] # comment node
838
839 # missing
840 assert 'untranslated' in extract_element(doctree, 0, 16)['classes']
841 assert 'untranslated' in extract_element(doctree, 0, 17)['classes']
842
843 assert extract_element(doctree, 0, 18)['classes'] == [] # comment node
844
845 # substitution reference
846 assert 'untranslated' in extract_element(doctree, 0, 19)['classes']
847
848 assert isinstance(doctree[0], nodes.Element)
849 assert len(doctree[0]) == 20
850
851
852 class _MockClock:
853 """Object for mocking :func:`time.time_ns` (if needed).
854
855 Use :meth:`sleep` to make this specific clock sleep for some time.
856 """
857
858 def time(self) -> int:
859 """Nanosecond since 'fake' epoch."""
860 raise NotImplementedError
861
862 def sleep(self, ds: float) -> None:
863 """Sleep *ds* seconds."""
864 raise NotImplementedError
865
866
867 class _MockWindowsClock(_MockClock):
868 """Object for mocking :func:`time.time_ns` on Windows platforms.
869
870 The result is in 'nanoseconds' but with a microsecond resolution
871 so that the division by 1_000 does not cause rounding issues.
872 """
873
874 def __init__(self) -> None:
875 self.us: int = 0 # current microsecond 'tick'
876
877 def time(self) -> int:
878 ret = 1_000 * self.us
879 self.us += 1
880 return ret
881
882 def sleep(self, ds: float) -> None:
883 self.us += int(ds * 1e6)
884
885
886 class _MockUnixClock(_MockClock):
887 """Object for mocking :func:`time.time_ns` on Unix platforms.
888
889 Since nothing is needed for Unix platforms, this object acts as
890 a proxy so that the API is the same as :class:`_MockWindowsClock`.
891 """
892
893 def time(self) -> int:
894 return time.time_ns()
895
896 def sleep(self, ds: float) -> None:
897 time.sleep(ds)
898
899
900 @pytest.fixture
901 def mock_time_and_i18n() -> Iterator[tuple[pytest.MonkeyPatch, _MockClock]]:
902 from sphinx.util.i18n import CatalogInfo
903
904 # save the 'original' definition
905 catalog_write_mo = CatalogInfo.write_mo
906
907 def mock_write_mo(self: CatalogInfo, locale: str, use_fuzzy: bool = False) -> None:
908 catalog_write_mo(self, locale, use_fuzzy)
909 # ensure that the .mo file being written has a correct fake timestamp
910 _set_mtime_ns(self.mo_path, time.time_ns())
911
912 # see: https://github.com/pytest-dev/pytest/issues/363
913 # see: https://github.com/astral-sh/ty/issues/1787
914 with pytest.MonkeyPatch.context() as mock: # ty: ignore[missing-argument]
915 clock: _MockClock
916 if os.name == 'posix':
917 clock = _MockUnixClock()
918 else:
919 # When using pytest.mark.parametrize() to emulate test repetition,
920 # the teardown phase on Windows fails due to an error apparently in
921 # the colorama.ansitowin32 module, so we forcibly disable colors.
922 mock.setenv('NO_COLOR', '1')
923 # apply the patch only for Windows
924 clock = _MockWindowsClock()
925 mock.setattr('time.time_ns', clock.time)
926 # Use clock.sleep() to emulate time.sleep() but do not try
927 # to mock the latter since this might break other libraries.
928 mock.setattr('sphinx.util.i18n.CatalogInfo.write_mo', mock_write_mo)
929 yield mock, clock
930
931
932 # use the same testroot as 'gettext' since the latter contains less PO files
933 @sphinx_intl
934 @pytest.mark.sphinx(
935 'dummy',
936 testroot='builder-gettext-dont-rebuild-mo',
937 freshenv=True,
938 copy_test_root=True,
939 )
940 def test_dummy_should_rebuild_mo(
941 mock_time_and_i18n: tuple[pytest.MonkeyPatch, _MockClock],
942 make_app: Callable[..., SphinxTestApp],
943 app_params: _app_params,
944 ) -> None:
945 mock, clock = mock_time_and_i18n
946 assert os.name == 'posix' or clock.time() == 0
947
948 args, kwargs = app_params
949 app = make_app(*args, **kwargs)
950 po_path, mo_path = _get_bom_intl_path(app.srcdir)
951
952 # creation time of the those files (order does not matter)
953 bom_rst = app.srcdir / 'bom.rst'
954 bom_rst_time = time.time_ns()
955
956 index_rst = app.srcdir / 'index.rst'
957 index_rst_time = time.time_ns()
958 po_time = time.time_ns()
959
960 # patch the 'creation time' of the source files
961 assert _set_mtime_ns(po_path, po_time) == po_time
962 assert _set_mtime_ns(bom_rst, bom_rst_time) == bom_rst_time
963 assert _set_mtime_ns(index_rst, index_rst_time) == index_rst_time
964
965 assert not mo_path.exists()
966 # when writing mo files, the counter is updated by calling
967 # patch_write_mo which is called to create .mo files (and
968 # thus the timestamp of the files are not those given by
969 # the OS but our fake ones)
970 app.build()
971 assert mo_path.exists()
972 # Do a real sleep on POSIX, or simulate a sleep on Windows
973 # to ensure that calls to time.time_ns() remain consistent.
974 clock.sleep(0.1 if os.name == 'posix' else 1)
975
976 # check that the source files were not modified
977 assert bom_rst.stat().st_mtime_ns == bom_rst_time
978 assert index_rst.stat().st_mtime_ns == index_rst_time
979 # check that the 'bom' document is discovered after the .mo
980 # file has been written on the disk (i.e., read_doc() is called
981 # after the creation of the .mo files)
982 assert app.env.all_docs['bom'] > mo_path.stat().st_mtime_ns // 1000
983
984 # Since it is after the build, the number of documents to be updated is 0
985 update_targets = _get_update_targets(app)
986 assert update_targets[1] == set()
987 # When rewriting the timestamp of mo file, the number of documents to be
988 # updated will be changed.
989 new_mo_time = time.time_ns()
990 assert _set_mtime_ns(mo_path, new_mo_time) == new_mo_time
991 update_targets = _get_update_targets(app)
992 assert update_targets[1] == {'bom'}
993 mock.undo() # explicit call since it's not a context
994
995 # remove all sources for the next test
996 shutil.rmtree(app.srcdir, ignore_errors=True)
997 time.sleep(0.1 if os.name == 'posix' else 0.5) # real sleep
998
999
1000 @sphinx_intl
1001 @pytest.mark.sphinx(
1002 'gettext',
1003 testroot='builder-gettext-dont-rebuild-mo',
1004 freshenv=True,
1005 copy_test_root=True,
1006 )
1007 def test_gettext_dont_rebuild_mo(
1008 mock_time_and_i18n: tuple[pytest.MonkeyPatch, _MockClock], app: SphinxTestApp
1009 ) -> None:
1010 mock, clock = mock_time_and_i18n
1011 assert os.name == 'posix' or clock.time() == 0
1012
1013 assert app.srcdir.exists()
1014
1015 # patch the 'creation time' of the source files
1016 bom_rst = app.srcdir / 'bom.rst'
1017 bom_rst_time = time.time_ns()
1018 assert _set_mtime_ns(bom_rst, bom_rst_time) == bom_rst_time
1019
1020 index_rst = app.srcdir / 'index.rst'
1021 index_rst_time = time.time_ns()
1022 assert _set_mtime_ns(index_rst, index_rst_time) == index_rst_time
1023
1024 # phase 1: create fake MO file in the src directory
1025 po_path, mo_path = _get_bom_intl_path(app.srcdir)
1026 write_mo(mo_path, read_po(po_path))
1027 po_time = time.time_ns()
1028 assert _set_mtime_ns(po_path, po_time) == po_time
1029
1030 # phase 2: build document with gettext builder.
1031 # The mo file in the srcdir directory is retained.
1032 app.build()
1033 # Do a real sleep on POSIX, or simulate a sleep on Windows
1034 # to ensure that calls to time.time_ns() remain consistent.
1035 clock.sleep(0.5 if os.name == 'posix' else 1)
1036 # Since it is after the build, the number of documents to be updated is 0
1037 update_targets = _get_update_targets(app)
1038 assert update_targets[1] == set()
1039 # Even if the timestamp of the mo file is updated, the number of documents
1040 # to be updated is 0. gettext builder does not rebuild because of mo update.
1041 new_mo_time = time.time_ns()
1042 assert _set_mtime_ns(mo_path, new_mo_time) == new_mo_time
1043 update_targets = _get_update_targets(app)
1044 assert update_targets[1] == set()
1045 mock.undo() # remove the patch
1046
1047 # remove all sources for the next test
1048 shutil.rmtree(app.srcdir, ignore_errors=True)
1049 time.sleep(0.1 if os.name == 'posix' else 0.5) # real sleep
1050
1051
1052 @sphinx_intl
1053 @pytest.mark.sphinx('html', testroot='intl')
1054 @pytest.mark.test_params(shared_result='test_intl_basic')
1055 def test_html_meta(app: SphinxTestApp) -> None:
1056 app.build()
1057 # --- test for meta
1058 result = (app.outdir / 'index.html').read_text(encoding='utf8')
1059 expected_expr = (
1060 '<meta content="TESTDATA FOR I18N" name="description" translated="True" />'
1061 )
1062 assert expected_expr in result
1063 expected_expr = (
1064 '<meta content="I18N, SPHINX, MARKUP" name="keywords" translated="True" />'
1065 )
1066 assert expected_expr in result
1067 expected_expr = '<p class="caption" role="heading"><span class="caption-text">HIDDEN TOC</span></p>'
1068 assert expected_expr in result
1069
1070
1071 @sphinx_intl
1072 @pytest.mark.sphinx('html', testroot='intl')
1073 @pytest.mark.test_params(shared_result='test_intl_basic')
1074 def test_html_footnotes(app: SphinxTestApp) -> None:
1075 app.build()
1076 # --- test for
1077 # https://github.com/sphinx-doc/sphinx/issues/955
1078 # cant-build-html-with-footnotes-when-using
1079 # expect no error by build
1080 (app.outdir / 'footnote.html').read_text(encoding='utf8')
1081
1082
1083 @sphinx_intl
1084 @pytest.mark.sphinx('html', testroot='intl')
1085 @pytest.mark.test_params(shared_result='test_intl_basic')
1086 def test_html_undefined_refs(app: SphinxTestApp) -> None:
1087 app.build()
1088 # --- links to undefined reference
1089 result = (app.outdir / 'refs_inconsistency.html').read_text(encoding='utf8')
1090
1091 expected_expr = (
1092 '<a class="reference external" href="https://www.example.com">reference</a>'
1093 )
1094 assert len(re.findall(expected_expr, result)) == 2
1095
1096 expected_expr = '<a class="reference internal" href="#reference">reference</a>'
1097 assert len(re.findall(expected_expr, result)) == 0
1098
1099 expected_expr = (
1100 '<a class="reference internal" '
1101 'href="#i18n-with-refs-inconsistency">I18N WITH '
1102 'REFS INCONSISTENCY</a>'
1103 )
1104 assert len(re.findall(expected_expr, result)) == 1
1105
1106
1107 @sphinx_intl
1108 @pytest.mark.sphinx('html', testroot='intl')
1109 @pytest.mark.test_params(shared_result='test_intl_basic')
1110 def test_html_index_entries(app: SphinxTestApp) -> None:
1111 app.build()
1112 # --- index entries: regression test for
1113 # https://github.com/sphinx-doc/sphinx/issues/976
1114 result = (app.outdir / 'genindex.html').read_text(encoding='utf8')
1115
1116 def wrap(tag: str, keyword: str) -> str:
1117 start_tag = '<%s[^>]*>' % tag
1118 end_tag = '</%s>' % tag
1119 return rf'{start_tag}\s*{keyword}\s*{end_tag}'
1120
1121 def wrap_nest(parenttag: str, childtag: str, keyword: str) -> str:
1122 start_tag1 = f'<{parenttag}[^>]*>'
1123 start_tag2 = f'<{childtag}[^>]*>'
1124 return rf'{start_tag1}\s*{keyword}\s*{start_tag2}'
1125
1126 expected_exprs = [
1127 wrap('h2', 'Symbols'),
1128 wrap('h2', 'C'),
1129 wrap('h2', 'E'),
1130 wrap('h2', 'F'),
1131 wrap('h2', 'M'),
1132 wrap('h2', 'N'),
1133 wrap('h2', 'R'),
1134 wrap('h2', 'S'),
1135 wrap('h2', 'T'),
1136 wrap('h2', 'V'),
1137 wrap('a', 'NEWSLETTER'),
1138 wrap('a', 'MAILING LIST'),
1139 wrap('a', 'RECIPIENTS LIST'),
1140 wrap('a', 'FIRST SECOND'),
1141 wrap('a', 'SECOND THIRD'),
1142 wrap('a', 'THIRD, FIRST'),
1143 wrap_nest('li', 'ul', 'ENTRY'),
1144 wrap_nest('li', 'ul', 'SEE'),
1145 ]
1146 for expr in expected_exprs:
1147 assert re.search(expr, result, re.MULTILINE), (
1148 f'{expr!r} did not match {result!r}'
1149 )
1150
1151
1152 @sphinx_intl
1153 @pytest.mark.sphinx('html', testroot='intl')
1154 @pytest.mark.test_params(shared_result='test_intl_basic')
1155 def test_html_versionchanges(app: SphinxTestApp) -> None:
1156 app.build()
1157 # --- versionchanges
1158 result = (app.outdir / 'versionchange.html').read_text(encoding='utf8')
1159
1160 def get_content(result: str, name: str) -> str:
1161 matched = re.search(rf'<div class="{name}">\n*(.*?)</div>', result, re.DOTALL)
1162 if matched:
1163 return matched.group(1)
1164 return ''
1165
1166 expect1 = (
1167 """<p><span class="versionmodified deprecated">Deprecated since version 1.0: </span>"""
1168 """THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSION-DEPRECATED.</p>\n"""
1169 """<p>THIS IS THE <em>SECOND</em> PARAGRAPH OF VERSION-DEPRECATED.</p>\n"""
1170 )
1171 matched_content = get_content(result, 'deprecated')
1172 assert matched_content == expect1
1173
1174 expect2 = (
1175 """<p><span class="versionmodified added">Added in version 1.0: </span>"""
1176 """THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSION-ADDED.</p>\n"""
1177 )
1178 matched_content = get_content(result, 'versionadded')
1179 assert matched_content == expect2
1180
1181 expect3 = (
1182 """<p><span class="versionmodified changed">Changed in version 1.0: </span>"""
1183 """THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSION-CHANGED.</p>\n"""
1184 )
1185 matched_content = get_content(result, 'versionchanged')
1186 assert matched_content == expect3
1187
1188 expect4 = (
1189 """<p><span class="versionmodified removed">Removed in version 1.0: </span>"""
1190 """THIS IS THE <em>FIRST</em> PARAGRAPH OF VERSION-REMOVED.</p>\n"""
1191 )
1192 matched_content = get_content(result, 'versionremoved')
1193 assert matched_content == expect4
1194
1195
1196 @sphinx_intl
1197 @pytest.mark.sphinx('html', testroot='intl')
1198 @pytest.mark.test_params(shared_result='test_intl_basic')
1199 def test_html_docfields(app: SphinxTestApp) -> None:
1200 app.build()
1201 # --- docfields
1202 # expect no error by build
1203 (app.outdir / 'docfields.html').read_text(encoding='utf8')
1204
1205
1206 @sphinx_intl
1207 @pytest.mark.sphinx('html', testroot='intl')
1208 @pytest.mark.test_params(shared_result='test_intl_basic')
1209 def test_html_template(app: SphinxTestApp) -> None:
1210 app.build()
1211 # --- gettext template
1212 result = (app.outdir / 'contents.html').read_text(encoding='utf8')
1213 assert 'WELCOME' in result
1214 assert 'SPHINX 2013.120' in result
1215
1216
1217 @sphinx_intl
1218 @pytest.mark.sphinx('html', testroot='intl')
1219 @pytest.mark.test_params(shared_result='test_intl_basic')
1220 def test_html_rebuild_mo(app: SphinxTestApp) -> None:
1221 app.build()
1222 # --- rebuild by .mo mtime
1223 app.build()
1224 _, updated, _ = _get_update_targets(app)
1225 assert updated == set()
1226
1227 _, bom_file = _get_bom_intl_path(app.srcdir)
1228 old_mtime = bom_file.stat().st_mtime
1229 new_mtime = old_mtime + (dt := 5)
1230 os.utime(bom_file, (new_mtime, new_mtime))
1231 assert old_mtime + dt == new_mtime, (old_mtime + dt, new_mtime)
1232 _, updated, _ = _get_update_targets(app)
1233 assert updated == {'bom'}
1234
1235
1236 @sphinx_intl
1237 @pytest.mark.sphinx('xml', testroot='intl')
1238 @pytest.mark.test_params(shared_result='test_intl_basic')
1239 def test_xml_footnotes(app: SphinxTestApp) -> None:
1240 app.build()
1241 # --- footnotes: regression test for fix
1242 # https://github.com/sphinx-doc/sphinx/issues/955,
1243 # https://github.com/sphinx-doc/sphinx/issues/1176
1244 et = etree_parse(app.outdir / 'footnote.xml')
1245 secs = et.findall('section')
1246
1247 para0 = secs[0].findall('paragraph')
1248 assert_elem(
1249 para0[0],
1250 texts=[
1251 'I18N WITH FOOTNOTE',
1252 'INCLUDE THIS CONTENTS',
1253 '2',
1254 '[ref]',
1255 '1',
1256 '100',
1257 '*',
1258 '. SECOND FOOTNOTE_REF',
1259 '100',
1260 '.',
1261 ],
1262 refs=['i18n-with-footnote', 'ref'],
1263 )
1264
1265 # check node_id for footnote_references which refer same footnote
1266 # See: https://github.com/sphinx-doc/sphinx/issues/3002
1267 assert para0[0][4].text == para0[0][6].text == '100'
1268 assert para0[0][4].attrib['ids'] != para0[0][6].attrib['ids']
1269
1270 footnote0 = secs[0].findall('footnote')
1271 assert_elem(
1272 footnote0[0],
1273 texts=['1', 'THIS IS A AUTO NUMBERED FOOTNOTE.'],
1274 refs=None,
1275 names=['1'],
1276 )
1277 assert_elem(
1278 footnote0[1],
1279 texts=['100', 'THIS IS A NUMBERED FOOTNOTE.'],
1280 refs=None,
1281 names=['100'],
1282 )
1283 assert_elem(
1284 footnote0[2],
1285 texts=['2', 'THIS IS A AUTO NUMBERED NAMED FOOTNOTE.'],
1286 refs=None,
1287 names=['named'],
1288 )
1289 assert_elem(
1290 footnote0[3],
1291 texts=['*', 'THIS IS A AUTO SYMBOL FOOTNOTE.'],
1292 refs=None,
1293 names=None,
1294 )
1295
1296 citation0 = secs[0].findall('citation')
1297 assert_elem(
1298 citation0[0],
1299 texts=['ref', 'THIS IS A NAMED FOOTNOTE.'],
1300 refs=None,
1301 names=['ref'],
1302 )
1303
1304 warnings = getwarning(app.warning)
1305 warning_expr = '.*/footnote.xml:\\d*: SEVERE: Duplicate ID: ".*".\n'
1306 assert not re.search(warning_expr, warnings), (
1307 f'{warning_expr!r} did match {warnings!r}'
1308 )
1309
1310
1311 @sphinx_intl
1312 @pytest.mark.sphinx('xml', testroot='intl')
1313 @pytest.mark.test_params(shared_result='test_intl_basic')
1314 def test_xml_footnote_backlinks(app: SphinxTestApp) -> None:
1315 app.build()
1316 # --- footnote backlinks: i18n test for
1317 # https://github.com/sphinx-doc/sphinx/issues/1058
1318 et = etree_parse(app.outdir / 'footnote.xml')
1319 secs = et.findall('section')
1320
1321 para0 = secs[0].findall('paragraph')
1322 refs0 = para0[0].findall('footnote_reference')
1323 refid2id = {r.attrib.get('refid'): r.attrib.get('ids') for r in refs0}
1324
1325 footnote0 = secs[0].findall('footnote')
1326 for footnote in footnote0:
1327 ids = footnote.attrib.get('ids')
1328 backrefs = footnote.attrib['backrefs'].split()
1329 assert refid2id[ids] in backrefs
1330
1331
1332 @sphinx_intl
1333 @pytest.mark.sphinx('xml', testroot='intl')
1334 @pytest.mark.test_params(shared_result='test_intl_basic')
1335 def test_xml_refs_in_python_domain(app: SphinxTestApp) -> None:
1336 app.build()
1337 # --- refs in the Python domain
1338 et = etree_parse(app.outdir / 'refs_python_domain.xml')
1339 secs = et.findall('section')
1340
1341 # regression test for fix
1342 # https://github.com/sphinx-doc/sphinx/issues/1363
1343 para0 = secs[0].findall('paragraph')
1344 assert_elem(
1345 para0[0],
1346 texts=['SEE THIS DECORATOR:', 'sensitive_variables()', '.'],
1347 refs=['sensitive.sensitive_variables'],
1348 )
1349
1350
1351 @sphinx_intl
1352 @pytest.mark.sphinx('xml', testroot='intl')
1353 @pytest.mark.test_params(shared_result='test_intl_basic')
1354 def test_xml_keep_external_links(app: SphinxTestApp) -> None:
1355 app.build()
1356 # --- keep external links: regression test for
1357 # https://github.com/sphinx-doc/sphinx/issues/1044
1358 et = etree_parse(app.outdir / 'external_links.xml')
1359 secs = et.findall('section')
1360
1361 para0 = secs[0].findall('paragraph')
1362 # external link check
1363 assert_elem(
1364 para0[0],
1365 texts=['EXTERNAL LINK TO', 'Python', '.'],
1366 refs=['https://python.org/index.html'],
1367 )
1368
1369 # internal link check
1370 assert_elem(
1371 para0[1],
1372 texts=['EXTERNAL LINKS', 'IS INTERNAL LINK.'],
1373 refs=['i18n-with-external-links'],
1374 )
1375
1376 # inline link check
1377 assert_elem(
1378 para0[2],
1379 texts=['INLINE LINK BY', 'THE SPHINX SITE', '.'],
1380 refs=['https://sphinx-doc.org'],
1381 )
1382
1383 # unnamed link check
1384 assert_elem(
1385 para0[3],
1386 texts=['UNNAMED', 'LINK', '.'],
1387 refs=['https://google.com'],
1388 )
1389
1390 # link target swapped translation
1391 para1 = secs[1].findall('paragraph')
1392 assert_elem(
1393 para1[0],
1394 texts=['LINK TO', 'external2', 'AND', 'external1', '.'],
1395 refs=['https://www.google.com/external2', 'https://www.google.com/external1'],
1396 )
1397 assert_elem(
1398 para1[1],
1399 texts=['LINK TO', 'THE PYTHON SITE', 'AND', 'THE SPHINX SITE', '.'],
1400 refs=['https://python.org', 'https://sphinx-doc.org'],
1401 )
1402
1403 # multiple references in the same line
1404 para2 = secs[2].findall('paragraph')
1405 assert_elem(
1406 para2[0],
1407 texts=[
1408 'LINK TO',
1409 'EXTERNAL LINKS',
1410 ',',
1411 'Python',
1412 ',',
1413 'THE SPHINX SITE',
1414 ',',
1415 'UNNAMED',
1416 'AND',
1417 'THE PYTHON SITE',
1418 '.',
1419 ],
1420 refs=[
1421 'i18n-with-external-links',
1422 'https://python.org/index.html',
1423 'https://sphinx-doc.org',
1424 'https://google.com',
1425 'https://python.org',
1426 ],
1427 )
1428
1429
1430 @sphinx_intl
1431 @pytest.mark.sphinx('xml', testroot='intl')
1432 @pytest.mark.test_params(shared_result='test_intl_basic')
1433 def test_xml_role_xref(app: SphinxTestApp) -> None:
1434 app.build()
1435 # --- role xref: regression test for
1436 # https://github.com/sphinx-doc/sphinx/issues/1090,
1437 # https://github.com/sphinx-doc/sphinx/issues/1193
1438 et = etree_parse(app.outdir / 'role_xref.xml')
1439 sec1, sec2 = et.findall('section')
1440
1441 (para1,) = sec1.findall('paragraph')
1442 assert_elem(
1443 para1,
1444 texts=[
1445 'LINK TO',
1446 "I18N ROCK'N ROLE XREF",
1447 ',',
1448 'CONTENTS',
1449 ',',
1450 'SOME NEW TERM',
1451 '.',
1452 ],
1453 refs=['i18n-role-xref', 'index', 'glossary_terms#term-Some-term'],
1454 )
1455
1456 (sec1_1,) = sec1.findall('section')
1457 (title,) = sec1_1.findall('title')
1458 assert_elem(
1459 title,
1460 texts=[
1461 'LINK TO',
1462 "I18N ROCK'N ROLE XREF",
1463 ',',
1464 'CONTENTS',
1465 ',',
1466 'SOME NEW TERM',
1467 '.',
1468 ],
1469 refs=['i18n-role-xref', 'index', 'glossary_terms#term-Some-term'],
1470 )
1471
1472 para2 = sec2.findall('paragraph')
1473 assert_elem(
1474 para2[0],
1475 texts=['LINK TO', 'SOME OTHER NEW TERM', 'AND', 'SOME NEW TERM', '.'],
1476 refs=['glossary_terms#term-Some-other-term', 'glossary_terms#term-Some-term'],
1477 )
1478 assert_elem(
1479 para2[1],
1480 texts=[
1481 'LINK TO',
1482 'LABEL',
1483 'AND',
1484 'SAME TYPE LINKS',
1485 'AND',
1486 'SAME TYPE LINKS',
1487 '.',
1488 ],
1489 refs=['i18n-role-xref', 'same-type-links', 'same-type-links'],
1490 )
1491 assert_elem(
1492 para2[2],
1493 texts=['LINK TO', 'I18N WITH GLOSSARY TERMS', 'AND', 'CONTENTS', '.'],
1494 refs=['glossary_terms', 'index'],
1495 )
1496 assert_elem(
1497 para2[3],
1498 texts=['LINK TO', '--module', 'AND', '-m', '.'],
1499 refs=['cmdoption-module', 'cmdoption-m'],
1500 )
1501 assert_elem(
1502 para2[4],
1503 texts=['LINK TO', 'env2', 'AND', 'env1', '.'],
1504 refs=['envvar-env2', 'envvar-env1'],
1505 )
1506 # TODO: how do I link token role to productionlist?
1507 assert_elem(
1508 para2[5],
1509 texts=['LINK TO', 'token2', 'AND', 'token1', '.'],
1510 refs=[],
1511 )
1512 assert_elem(
1513 para2[6],
1514 texts=['LINK TO', 'same-type-links', 'AND', 'i18n-role-xref', '.'],
1515 refs=['same-type-links', 'i18n-role-xref'],
1516 )
1517
1518
1519 @sphinx_intl
1520 @pytest.mark.sphinx('xml', testroot='intl')
1521 @pytest.mark.test_params(shared_result='test_intl_basic')
1522 def test_xml_warnings(app: SphinxTestApp) -> None:
1523 app.build()
1524 # warnings
1525 warnings = getwarning(app.warning)
1526 assert warnings.count('term not in glossary') == 1
1527 assert 'undefined label' not in warnings
1528 assert 'unknown document' not in warnings
1529
1530
1531 @sphinx_intl
1532 @pytest.mark.sphinx('xml', testroot='intl')
1533 @pytest.mark.test_params(shared_result='test_intl_basic')
1534 def test_xml_label_targets(app: SphinxTestApp) -> None:
1535 app.build()
1536 # --- label targets: regression test for
1537 # https://github.com/sphinx-doc/sphinx/issues/1193,
1538 # https://github.com/sphinx-doc/sphinx/issues/1265
1539 et = etree_parse(app.outdir / 'label_target.xml')
1540 secs = et.findall('section')
1541
1542 para0 = secs[0].findall('paragraph')
1543 assert_elem(
1544 para0[0],
1545 texts=[
1546 'X SECTION AND LABEL',
1547 'POINT TO',
1548 'implicit-target',
1549 'AND',
1550 'X SECTION AND LABEL',
1551 'POINT TO',
1552 'section-and-label',
1553 '.',
1554 ],
1555 refs=['implicit-target', 'section-and-label'],
1556 )
1557
1558 para1 = secs[1].findall('paragraph')
1559 assert_elem(
1560 para1[0],
1561 texts=[
1562 'X EXPLICIT-TARGET',
1563 'POINT TO',
1564 'explicit-target',
1565 'AND',
1566 'X EXPLICIT-TARGET',
1567 'POINT TO DUPLICATED ID LIKE',
1568 'id1',
1569 '.',
1570 ],
1571 refs=['explicit-target', 'id1'],
1572 )
1573
1574 para2 = secs[2].findall('paragraph')
1575 assert_elem(
1576 para2[0],
1577 texts=['X IMPLICIT SECTION NAME', 'POINT TO', 'implicit-section-name', '.'],
1578 refs=['implicit-section-name'],
1579 )
1580
1581 sec2 = secs[2].findall('section')
1582
1583 para2_0 = sec2[0].findall('paragraph')
1584 assert_elem(
1585 para2_0[0],
1586 texts=['`X DUPLICATED SUB SECTION`_', 'IS BROKEN LINK.'],
1587 refs=[],
1588 )
1589
1590 para3 = secs[3].findall('paragraph')
1591 assert_elem(
1592 para3[0],
1593 texts=[
1594 'X',
1595 'bridge label',
1596 'IS NOT TRANSLATABLE BUT LINKED TO TRANSLATED SECTION TITLE.',
1597 ],
1598 refs=['label-bridged-target-section'],
1599 )
1600 assert_elem(
1601 para3[1],
1602 texts=[
1603 'X',
1604 'bridge label',
1605 'POINT TO',
1606 'LABEL BRIDGED TARGET SECTION',
1607 'AND',
1608 'bridge label2',
1609 'POINT TO',
1610 'SECTION AND LABEL',
1611 '. THE SECOND APPEARED',
1612 'bridge label2',
1613 'POINT TO CORRECT TARGET.',
1614 ],
1615 refs=['label-bridged-target-section', 'section-and-label', 'section-and-label'],
1616 )
1617
1618
1619 @sphinx_intl
1620 @pytest.mark.sphinx('xml', testroot='intl')
1621 @pytest.mark.test_params(shared_result='test_intl_basic')
1622 def test_xml_strange_markup(app: SphinxTestApp) -> None:
1623 app.build()
1624 et = etree_parse(app.outdir / 'markup.xml')
1625 secs = et.findall('section')
1626
1627 (subsec1,) = secs[0].findall('section')
1628 (title1,) = subsec1.findall('title')
1629 assert_elem(title1, texts=['1. TITLE STARTING WITH 1.'])
1630
1631
1632 @sphinx_intl
1633 @pytest.mark.sphinx('html', testroot='intl')
1634 @pytest.mark.test_params(shared_result='test_intl_basic')
1635 def test_additional_targets_should_not_be_translated(app: SphinxTestApp) -> None:
1636 if tuple(map(int, pygments.__version__.split('.')[:2])) >= (2, 19):
1637 sp = '<span class="w"> </span>'
1638 else:
1639 sp = ' '
1640
1641 app.build()
1642 # [literalblock.txt]
1643 result = (app.outdir / 'literalblock.html').read_text(encoding='utf8')
1644
1645 # title should be translated
1646 expected_expr = 'CODE-BLOCKS'
1647 assert_count(expected_expr, result, 2)
1648
1649 # ruby code block should not be translated but be highlighted
1650 expected_expr = """<span class="s1">&#39;result&#39;</span>"""
1651 assert_count(expected_expr, result, 1)
1652
1653 # C code block without lang should not be translated and *ruby* highlighted
1654 expected_expr = """<span class="c1">#include &lt;stdlib.h&gt;</span>"""
1655 assert_count(expected_expr, result, 1)
1656
1657 # C code block with lang should not be translated but be *C* highlighted
1658 expected_expr = (
1659 """<span class="cp">#include</span>"""
1660 """<span class="w"> </span>"""
1661 """<span class="cpf">&lt;stdio.h&gt;</span>"""
1662 )
1663 assert_count(expected_expr, result, 1)
1664
1665 # literal block in list item should not be translated
1666 expected_expr = (
1667 """<span class="n">literal</span>"""
1668 """<span class="o">-</span>"""
1669 """<span class="n">block</span>\n"""
1670 """<span class="k">in</span>"""
1671 """<span class="w"> </span>"""
1672 """<span class="n">list</span>"""
1673 )
1674 assert_count(expected_expr, result, 1)
1675
1676 # doctest block should not be translated but be highlighted
1677 expected_expr = (
1678 """<span class="gp">&gt;&gt;&gt; </span>"""
1679 f"""<span class="kn">import</span>{sp}<span class="nn">sys</span> """
1680 """<span class="c1"># sys importing</span>"""
1681 )
1682 assert_count(expected_expr, result, 1)
1683
1684 # [raw.txt]
1685
1686 result = (app.outdir / 'raw.html').read_text(encoding='utf8')
1687
1688 # raw block should not be translated
1689 expected_expr = """<iframe src="https://sphinx-doc.org"></iframe></section>"""
1690 assert_count(expected_expr, result, 1)
1691
1692 # [figure.txt]
1693
1694 result = (app.outdir / 'figure.html').read_text(encoding='utf8')
1695
1696 # src for image block should not be translated (alt is translated)
1697 expected_expr = """<img alt="I18N -&gt; IMG" src="_images/i18n.png" />"""
1698 assert_count(expected_expr, result, 1)
1699
1700 # src for figure block should not be translated (alt is translated)
1701 expected_expr = """<img alt="IMG -&gt; I18N" src="_images/img.png" />"""
1702 assert_count(expected_expr, result, 1)
1703
1704
1705 @sphinx_intl
1706 @pytest.mark.sphinx(
1707 'html',
1708 testroot='intl',
1709 srcdir='test_additional_targets_should_be_translated',
1710 confoverrides={
1711 'language': _CATALOG_LOCALE,
1712 'locale_dirs': ['.'],
1713 'gettext_compact': False,
1714 'gettext_additional_targets': [
1715 'index',
1716 'literal-block',
1717 'doctest-block',
1718 'raw',
1719 'image',
1720 ],
1721 },
1722 )
1723 def test_additional_targets_should_be_translated(app: SphinxTestApp) -> None:
1724 if tuple(map(int, pygments.__version__.split('.')[:2])) >= (2, 19):
1725 sp = '<span class="w"> </span>'
1726 else:
1727 sp = ' '
1728
1729 app.build()
1730 # [literalblock.txt]
1731 result = (app.outdir / 'literalblock.html').read_text(encoding='utf8')
1732
1733 # basic literal block should be translated
1734 expected_expr = (
1735 '<span class="n">THIS</span> <span class="n">IS</span>\n'
1736 '<span class="n">LITERAL</span> <span class="n">BLOCK</span>'
1737 )
1738 assert_count(expected_expr, result, 1)
1739
1740 # literalinclude should be translated
1741 expected_expr = '<span class="s2">&quot;HTTPS://SPHINX-DOC.ORG&quot;</span>'
1742 assert_count(expected_expr, result, 1)
1743
1744 # title should be translated
1745 expected_expr = 'CODE-BLOCKS'
1746 assert_count(expected_expr, result, 2)
1747
1748 # ruby code block should be translated and be highlighted
1749 expected_expr = """<span class="s1">&#39;RESULT&#39;</span>"""
1750 assert_count(expected_expr, result, 1)
1751
1752 # C code block without lang should be translated and *ruby* highlighted
1753 expected_expr = """<span class="c1">#include &lt;STDLIB.H&gt;</span>"""
1754 assert_count(expected_expr, result, 1)
1755
1756 # C code block with lang should be translated and be *C* highlighted
1757 expected_expr = (
1758 """<span class="cp">#include</span>"""
1759 """<span class="w"> </span>"""
1760 """<span class="cpf">&lt;STDIO.H&gt;</span>"""
1761 )
1762 assert_count(expected_expr, result, 1)
1763
1764 # literal block in list item should be translated
1765 expected_expr = (
1766 """<span class="no">LITERAL</span>"""
1767 """<span class="o">-</span>"""
1768 """<span class="no">BLOCK</span>\n"""
1769 """<span class="no">IN</span>"""
1770 """<span class="w"> </span>"""
1771 """<span class="no">LIST</span>"""
1772 )
1773 assert_count(expected_expr, result, 1)
1774
1775 # doctest block should not be translated but be highlighted
1776 expected_expr = (
1777 """<span class="gp">&gt;&gt;&gt; </span>"""
1778 f"""<span class="kn">import</span>{sp}<span class="nn">sys</span> """
1779 """<span class="c1"># SYS IMPORTING</span>"""
1780 )
1781 assert_count(expected_expr, result, 1)
1782
1783 # 'noqa' comments should remain in literal blocks.
1784 assert_count('#noqa', result, 1)
1785
1786 # [raw.txt]
1787
1788 result = (app.outdir / 'raw.html').read_text(encoding='utf8')
1789
1790 # raw block should be translated
1791 expected_expr = """<iframe src="HTTPS://SPHINX-DOC.ORG"></iframe></section>"""
1792 assert_count(expected_expr, result, 1)
1793
1794 # [figure.txt]
1795
1796 result = (app.outdir / 'figure.html').read_text(encoding='utf8')
1797
1798 # alt and src for image block should be translated
1799 expected_expr = """<img alt="I18N -&gt; IMG" src="_images/img.png" />"""
1800 assert_count(expected_expr, result, 1)
1801
1802 # alt and src for figure block should be translated
1803 expected_expr = """<img alt="IMG -&gt; I18N" src="_images/i18n.png" />"""
1804 assert_count(expected_expr, result, 1)
1805
1806
1807 @pytest.mark.sphinx(
1808 'html',
1809 testroot='intl_substitution_definitions',
1810 confoverrides={
1811 'language': _CATALOG_LOCALE,
1812 'locale_dirs': ['.'],
1813 'gettext_compact': False,
1814 'gettext_additional_targets': [
1815 'index',
1816 'literal-block',
1817 'doctest-block',
1818 'raw',
1819 'image',
1820 ],
1821 },
1822 copy_test_root=True,
1823 )
1824 def test_additional_targets_should_be_translated_substitution_definitions(
1825 app: SphinxTestApp,
1826 ) -> None:
1827 app.build(force_all=True)
1828
1829 # [prolog_epilog_substitution.txt]
1830
1831 result = (app.outdir / 'prolog_epilog_substitution.html').read_text(encoding='utf8')
1832
1833 # alt and src for image block should be translated
1834 expected_expr = """<img alt="SUBST_PROLOG_2 TRANSLATED" src="_images/i18n.png" />"""
1835 assert_count(expected_expr, result, 1)
1836
1837 # alt and src for image block should be translated
1838 expected_expr = """<img alt="SUBST_EPILOG_2 TRANSLATED" src="_images/img.png" />"""
1839 assert_count(expected_expr, result, 1)
1840
1841
1842 @sphinx_intl
1843 @pytest.mark.sphinx('text', testroot='intl')
1844 @pytest.mark.test_params(shared_result='test_intl_basic')
1845 def test_text_references(app: SphinxTestApp) -> None:
1846 app.build(filenames=[app.srcdir / 'refs.txt'])
1847
1848 warnings = app.warning.getvalue().replace(os.sep, '/')
1849 warning_expr = 'refs.txt:\\d+: ERROR: Unknown target name:'
1850 assert_count(warning_expr, warnings, 0)
1851
1852
1853 @pytest.mark.sphinx(
1854 'text',
1855 testroot='intl_substitution_definitions',
1856 confoverrides={
1857 'language': _CATALOG_LOCALE,
1858 'locale_dirs': ['.'],
1859 'gettext_compact': False,
1860 },
1861 copy_test_root=True,
1862 )
1863 def test_text_prolog_epilog_substitution(app: SphinxTestApp) -> None:
1864 app.build()
1865
1866 result = (app.outdir / 'prolog_epilog_substitution.txt').read_text(encoding='utf8')
1867
1868 assert result == (
1869 """\
1870 1. I18N WITH PROLOGUE AND EPILOGUE SUBSTITUTIONS
1871 ************************************************
1872
1873 THIS IS CONTENT THAT CONTAINS prologue substitute text.
1874
1875 SUBSTITUTED IMAGE [image: SUBST_PROLOG_2 TRANSLATED][image] HERE.
1876
1877 THIS IS CONTENT THAT CONTAINS epilogue substitute text.
1878
1879 SUBSTITUTED IMAGE [image: SUBST_EPILOG_2 TRANSLATED][image] HERE.
1880 """
1881 )
1882
1883
1884 @pytest.mark.usefixtures('_http_teapot')
1885 @pytest.mark.sphinx(
1886 'dummy',
1887 testroot='images',
1888 srcdir='test_intl_images',
1889 confoverrides={'language': _CATALOG_LOCALE},
1890 )
1891 def test_image_glob_intl(app: SphinxTestApp) -> None:
1892 app.build()
1893
1894 # index.rst
1895 doctree = app.env.get_doctree('index')
1896 assert_node(
1897 extract_node(doctree, 0, 1),
1898 nodes.image,
1899 uri='rimg.xx.png',
1900 candidates={'*': 'rimg.xx.png'},
1901 )
1902
1903 assert isinstance(extract_node(doctree, 0, 2), nodes.figure)
1904 assert_node(
1905 extract_node(doctree, 0, 2, 0),
1906 nodes.image,
1907 uri='rimg.xx.png',
1908 candidates={'*': 'rimg.xx.png'},
1909 )
1910
1911 assert_node(
1912 extract_node(doctree, 0, 3),
1913 nodes.image,
1914 uri='img.*',
1915 candidates={
1916 'application/pdf': 'img.pdf',
1917 'image/gif': 'img.gif',
1918 'image/png': 'img.png',
1919 },
1920 )
1921
1922 assert isinstance(extract_node(doctree, 0, 4), nodes.figure)
1923 assert_node(
1924 extract_node(doctree, 0, 4, 0),
1925 nodes.image,
1926 uri='img.*',
1927 candidates={
1928 'application/pdf': 'img.pdf',
1929 'image/gif': 'img.gif',
1930 'image/png': 'img.png',
1931 },
1932 )
1933
1934 # subdir/index.rst
1935 doctree = app.env.get_doctree('subdir/index')
1936 assert_node(
1937 extract_node(doctree, 0, 1),
1938 nodes.image,
1939 uri='subdir/rimg.xx.png',
1940 candidates={'*': 'subdir/rimg.xx.png'},
1941 )
1942
1943 assert_node(
1944 extract_node(doctree, 0, 2),
1945 nodes.image,
1946 uri='subdir/svgimg.*',
1947 candidates={
1948 'application/pdf': 'subdir/svgimg.pdf',
1949 'image/svg+xml': 'subdir/svgimg.xx.svg',
1950 },
1951 )
1952
1953 assert isinstance(extract_node(doctree, 0, 3), nodes.figure)
1954 assert_node(
1955 extract_node(doctree, 0, 3, 0),
1956 nodes.image,
1957 uri='subdir/svgimg.*',
1958 candidates={
1959 'application/pdf': 'subdir/svgimg.pdf',
1960 'image/svg+xml': 'subdir/svgimg.xx.svg',
1961 },
1962 )
1963
1964
1965 @pytest.mark.usefixtures('_http_teapot')
1966 @pytest.mark.sphinx(
1967 'dummy',
1968 testroot='images',
1969 srcdir='test_intl_images',
1970 confoverrides={
1971 'language': _CATALOG_LOCALE,
1972 'figure_language_filename': '{root}{ext}.{language}',
1973 },
1974 )
1975 def test_image_glob_intl_using_figure_language_filename(app: SphinxTestApp) -> None:
1976 app.build()
1977
1978 # index.rst
1979 doctree = app.env.get_doctree('index')
1980 assert_node(
1981 extract_node(doctree, 0, 1),
1982 nodes.image,
1983 uri='rimg.png.xx',
1984 candidates={'*': 'rimg.png.xx'},
1985 )
1986
1987 assert isinstance(extract_node(doctree, 0, 2), nodes.figure)
1988 assert_node(
1989 extract_node(doctree, 0, 2, 0),
1990 nodes.image,
1991 uri='rimg.png.xx',
1992 candidates={'*': 'rimg.png.xx'},
1993 )
1994
1995 assert_node(
1996 extract_node(doctree, 0, 3),
1997 nodes.image,
1998 uri='img.*',
1999 candidates={
2000 'application/pdf': 'img.pdf',
2001 'image/gif': 'img.gif',
2002 'image/png': 'img.png',
2003 },
2004 )
2005
2006 assert isinstance(extract_node(doctree, 0, 4), nodes.figure)
2007 assert_node(
2008 extract_node(doctree, 0, 4, 0),
2009 nodes.image,
2010 uri='img.*',
2011 candidates={
2012 'application/pdf': 'img.pdf',
2013 'image/gif': 'img.gif',
2014 'image/png': 'img.png',
2015 },
2016 )
2017
2018 # subdir/index.rst
2019 doctree = app.env.get_doctree('subdir/index')
2020 assert_node(
2021 extract_node(doctree, 0, 1),
2022 nodes.image,
2023 uri='subdir/rimg.png',
2024 candidates={'*': 'subdir/rimg.png'},
2025 )
2026
2027 assert_node(
2028 extract_node(doctree, 0, 2),
2029 nodes.image,
2030 uri='subdir/svgimg.*',
2031 candidates={
2032 'application/pdf': 'subdir/svgimg.pdf',
2033 'image/svg+xml': 'subdir/svgimg.svg',
2034 },
2035 )
2036
2037 assert isinstance(extract_node(doctree, 0, 3), nodes.figure)
2038 assert_node(
2039 extract_node(doctree, 0, 3, 0),
2040 nodes.image,
2041 uri='subdir/svgimg.*',
2042 candidates={
2043 'application/pdf': 'subdir/svgimg.pdf',
2044 'image/svg+xml': 'subdir/svgimg.svg',
2045 },
2046 )
2047
2048
2049 def getwarning(warnings: StringIO) -> str:
2050 return strip_escape_sequences(warnings.getvalue().replace(os.sep, '/'))
2051
2052
2053 @pytest.mark.sphinx(
2054 'html',
2055 testroot='basic',
2056 srcdir='gettext_allow_fuzzy_translations',
2057 confoverrides={
2058 'language': 'de',
2059 'gettext_allow_fuzzy_translations': True,
2060 },
2061 )
2062 def test_gettext_allow_fuzzy_translations(app: SphinxTestApp) -> None:
2063 locale_dir = app.srcdir / 'locales' / 'de' / 'LC_MESSAGES'
2064 locale_dir.mkdir(parents=True, exist_ok=True)
2065 with (locale_dir / 'index.po').open('wb') as f:
2066 catalog = Catalog()
2067 catalog.add('features', 'FEATURES', flags=('fuzzy',))
2068 pofile.write_po(f, catalog)
2069
2070 app.build()
2071 content = (app.outdir / 'index.html').read_text(encoding='utf8')
2072 assert 'FEATURES' in content
2073
2074
2075 @pytest.mark.sphinx(
2076 'html',
2077 testroot='basic',
2078 srcdir='gettext_disallow_fuzzy_translations',
2079 confoverrides={
2080 'language': 'de',
2081 'gettext_allow_fuzzy_translations': False,
2082 },
2083 )
2084 def test_gettext_disallow_fuzzy_translations(app: SphinxTestApp) -> None:
2085 locale_dir = app.srcdir / 'locales' / 'de' / 'LC_MESSAGES'
2086 locale_dir.mkdir(parents=True, exist_ok=True)
2087 with (locale_dir / 'index.po').open('wb') as f:
2088 catalog = Catalog()
2089 catalog.add('features', 'FEATURES', flags=('fuzzy',))
2090 pofile.write_po(f, catalog)
2091
2092 app.build()
2093 content = (app.outdir / 'index.html').read_text(encoding='utf8')
2094 assert 'FEATURES' not in content
2095
2096
2097 @pytest.mark.sphinx(
2098 'html',
2099 testroot='basic',
2100 confoverrides={'language': 'de', 'html_sidebars': {'**': ['searchbox.html']}},
2101 copy_test_root=True,
2102 )
2103 def test_customize_system_message(
2104 make_app: Callable[..., SphinxTestApp], app_params: _app_params
2105 ) -> None:
2106 try:
2107 # clear translators cache
2108 locale.translators.clear()
2109
2110 # prepare message catalog (.po)
2111 locale_dir = app_params.kwargs['srcdir'] / 'locales' / 'de' / 'LC_MESSAGES'
2112 locale_dir.mkdir(parents=True, exist_ok=True)
2113 with (locale_dir / 'sphinx.po').open('wb') as f:
2114 catalog = Catalog()
2115 catalog.add('Quick search', 'QUICK SEARCH')
2116 pofile.write_po(f, catalog)
2117
2118 # construct application and convert po file to .mo
2119 args, kwargs = app_params
2120 app = make_app(*args, **kwargs)
2121 assert (locale_dir / 'sphinx.mo').exists()
2122 assert app.translator.gettext('Quick search') == 'QUICK SEARCH'
2123
2124 app.build()
2125 content = (app.outdir / 'index.html').read_text(encoding='utf8')
2126 assert 'QUICK SEARCH' in content
2127 finally:
2128 locale.translators.clear()
2129
2130
2131 @pytest.mark.sphinx(
2132 'html',
2133 testroot='intl',
2134 confoverrides={'today_fmt': '%Y-%m-%d'},
2135 )
2136 def test_customize_today_date_format(
2137 app: SphinxTestApp, monkeypatch: pytest.MonkeyPatch
2138 ) -> None:
2139 with monkeypatch.context() as m:
2140 m.setenv('SOURCE_DATE_EPOCH', '1439131307')
2141 app.build()
2142 content = (app.outdir / 'refs.html').read_text(encoding='utf8')
2143
2144 assert '2015-08-09' in content