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