Debian Codegraph @

tests/test_builders/test_build_gettext.py

raw
1 """Test the build process with gettext builder with the test root."""
2
3 from __future__ import annotations
4
5 import gettext
6 import re
7 import subprocess
8 from contextlib import chdir
9 from pathlib import Path
10 from subprocess import CalledProcessError
11 from typing import TYPE_CHECKING
12
13 import pytest
14
15 from sphinx.builders.gettext import Catalog, MsgOrigin
16 from sphinx.testing.util import SphinxTestApp
17
18 if TYPE_CHECKING:
19 from sphinx.testing.util import SphinxTestApp
20
21 _MSGID_PATTERN = re.compile(r'msgid "((?:\n|.)*?)"\nmsgstr', re.MULTILINE)
22
23
24 def get_msgids(pot: str) -> list[str]:
25 matches = _MSGID_PATTERN.findall(pot)
26 return [m.replace('"\n"', '') for m in matches[1:]]
27
28
29 def test_Catalog_duplicated_message() -> None:
30 catalog = Catalog()
31 catalog.add('hello', MsgOrigin('/path/to/filename', 1))
32 catalog.add('hello', MsgOrigin('/path/to/filename', 1))
33 catalog.add('hello', MsgOrigin('/path/to/filename', 2))
34 catalog.add('hello', MsgOrigin('/path/to/yetanother', 1))
35 catalog.add('world', MsgOrigin('/path/to/filename', 1))
36
37 assert len(list(catalog)) == 2
38
39 msg1, msg2 = list(catalog)
40 assert msg1.text == 'hello'
41 assert msg1.locations == [
42 ('/path/to/filename', 1),
43 ('/path/to/filename', 2),
44 ('/path/to/yetanother', 1),
45 ]
46 assert msg2.text == 'world'
47 assert msg2.locations == [('/path/to/filename', 1)]
48
49
50 @pytest.mark.sphinx(
51 'gettext',
52 testroot='root',
53 srcdir='root-gettext',
54 )
55 def test_build_gettext(app: SphinxTestApp) -> None:
56 # Generic build; should fail only when the builder is horribly broken.
57 app.build(force_all=True)
58
59 # Do messages end up in the correct location?
60 # top-level documents end up in a message catalog
61 assert (app.outdir / 'extapi.pot').is_file()
62 # directory items are grouped into sections
63 assert (app.outdir / 'subdir.pot').is_file()
64
65 # regression test for https://github.com/sphinx-doc/sphinx/issues/960
66 catalog = (app.outdir / 'markup.pot').read_text(encoding='utf8')
67 assert 'msgid "something, something else, something more"' in catalog
68
69
70 @pytest.mark.sphinx(
71 'gettext',
72 testroot='root',
73 srcdir='root-gettext',
74 )
75 def test_msgfmt(app: SphinxTestApp) -> None:
76 app.build(force_all=True)
77
78 (app.outdir / 'en' / 'LC_MESSAGES').mkdir(parents=True, exist_ok=True)
79 with chdir(app.outdir):
80 try:
81 args = [
82 'msginit',
83 '--no-translator',
84 '-i',
85 'markup.pot',
86 '--locale',
87 'en_US',
88 ]
89 subprocess.run(args, capture_output=True, check=True)
90 except OSError:
91 pytest.skip() # most likely msginit was not found
92 except CalledProcessError as exc:
93 print(exc.stdout)
94 print(exc.stderr)
95 msg = f'msginit exited with return code {exc.returncode}'
96 raise AssertionError(msg) from exc
97
98 assert (app.outdir / 'en_US.po').is_file(), 'msginit failed'
99 try:
100 args = [
101 'msgfmt',
102 'en_US.po',
103 '-o',
104 str(Path('en', 'LC_MESSAGES', 'test_root.mo')),
105 ]
106 subprocess.run(args, capture_output=True, check=True)
107 except OSError:
108 pytest.skip() # most likely msgfmt was not found
109 except CalledProcessError as exc:
110 print(exc.stdout)
111 print(exc.stderr)
112 msg = f'msgfmt exited with return code {exc.returncode}'
113 raise AssertionError(msg) from exc
114
115 mo = app.outdir / 'en' / 'LC_MESSAGES' / 'test_root.mo'
116 assert mo.is_file(), 'msgfmt failed'
117
118 _ = gettext.translation('test_root', app.outdir, languages=['en']).gettext
119 assert _('Testing various markup') == 'Testing various markup'
120
121
122 @pytest.mark.sphinx(
123 'gettext',
124 testroot='intl',
125 srcdir='gettext',
126 confoverrides={'gettext_compact': False},
127 )
128 def test_gettext_index_entries(app: SphinxTestApp) -> None:
129 # regression test for https://github.com/sphinx-doc/sphinx/issues/976
130 app.build(filenames=[app.srcdir / 'index_entries.txt'])
131
132 pot = (app.outdir / 'index_entries.pot').read_text(encoding='utf8')
133 msg_ids = get_msgids(pot)
134
135 assert msg_ids == [
136 'i18n with index entries',
137 'index target section',
138 'this is :index:`Newsletter` target paragraph.',
139 'various index entries',
140 "That's all.",
141 'Mailing List',
142 'Newsletter',
143 'Recipients List',
144 'First',
145 'Second',
146 'Third',
147 'Entry',
148 'See',
149 ]
150
151
152 @pytest.mark.sphinx(
153 'gettext',
154 testroot='intl',
155 srcdir='gettext',
156 confoverrides={'gettext_compact': False, 'gettext_additional_targets': []},
157 )
158 def test_gettext_disable_index_entries(app: SphinxTestApp) -> None:
159 # regression test for https://github.com/sphinx-doc/sphinx/issues/976
160 app.env._pickled_doctree_cache.clear() # clear cache
161 app.build(filenames=[app.srcdir / 'index_entries.txt'])
162
163 pot = (app.outdir / 'index_entries.pot').read_text(encoding='utf8')
164 msg_ids = get_msgids(pot)
165
166 assert msg_ids == [
167 'i18n with index entries',
168 'index target section',
169 'this is :index:`Newsletter` target paragraph.',
170 'various index entries',
171 "That's all.",
172 ]
173
174
175 @pytest.mark.sphinx(
176 'gettext',
177 testroot='intl',
178 srcdir='gettext',
179 )
180 def test_gettext_template(app: SphinxTestApp) -> None:
181 app.build(force_all=True)
182
183 assert (app.outdir / 'sphinx.pot').is_file()
184
185 result = (app.outdir / 'sphinx.pot').read_text(encoding='utf8')
186 assert 'Welcome' in result
187 assert 'Sphinx %(version)s' in result
188
189
190 @pytest.mark.sphinx('gettext', testroot='gettext-template')
191 def test_gettext_template_msgid_order_in_sphinxpot(app: SphinxTestApp) -> None:
192 app.build(force_all=True)
193 assert (app.outdir / 'sphinx.pot').is_file()
194
195 result = (app.outdir / 'sphinx.pot').read_text(encoding='utf8')
196 assert re.search(
197 (
198 'msgid "Template 1".*'
199 'msgid "This is Template 1\\.".*'
200 'msgid "Template 2".*'
201 'msgid "This is Template 2\\.".*'
202 ),
203 result,
204 flags=re.DOTALL,
205 )
206
207
208 @pytest.mark.sphinx('gettext', testroot='gettext-custom-output-template')
209 def test_gettext_custom_output_template(app: SphinxTestApp) -> None:
210 app.build(force_all=True)
211 assert (app.outdir / 'index.pot').is_file()
212
213 result = (app.outdir / 'index.pot').read_text(encoding='utf8')
214 assert 'EVEN MORE DESCRIPTIVE TITLE' in result
215
216
217 @pytest.mark.sphinx(
218 'gettext',
219 testroot='root',
220 srcdir='root-gettext',
221 confoverrides={'gettext_compact': 'documentation'},
222 )
223 def test_build_single_pot(app: SphinxTestApp) -> None:
224 app.build(force_all=True)
225
226 assert (app.outdir / 'documentation.pot').is_file()
227
228 result = (app.outdir / 'documentation.pot').read_text(encoding='utf8')
229 assert re.search(
230 (
231 'msgid "Todo".*'
232 'msgid "Like footnotes.".*'
233 'msgid "The minute.".*'
234 'msgid "Generated section".*'
235 ),
236 result,
237 flags=re.DOTALL,
238 )
239
240
241 @pytest.mark.sphinx(
242 'gettext',
243 testroot='intl_substitution_definitions',
244 srcdir='gettext-subst',
245 confoverrides={'gettext_compact': False, 'gettext_additional_targets': ['image']},
246 )
247 def test_gettext_prolog_epilog_substitution(app: SphinxTestApp) -> None:
248 app.build(force_all=True)
249
250 assert (app.outdir / 'prolog_epilog_substitution.pot').is_file()
251 pot = (app.outdir / 'prolog_epilog_substitution.pot').read_text(encoding='utf8')
252 msg_ids = get_msgids(pot)
253
254 assert msg_ids == [
255 'i18n with prologue and epilogue substitutions',
256 'This is content that contains |subst_prolog_1|.',
257 'Substituted image |subst_prolog_2| here.',
258 'subst_prolog_2',
259 '.. image:: /img.png',
260 'This is content that contains |subst_epilog_1|.',
261 'Substituted image |subst_epilog_2| here.',
262 'subst_epilog_2',
263 '.. image:: /i18n.png',
264 ]
265
266
267 @pytest.mark.sphinx(
268 'gettext',
269 testroot='intl_substitution_definitions',
270 srcdir='gettext-subst',
271 confoverrides={'gettext_compact': False, 'gettext_additional_targets': ['image']},
272 )
273 def test_gettext_prolog_epilog_substitution_excluded(app: SphinxTestApp) -> None:
274 # regression test for https://github.com/sphinx-doc/sphinx/issues/9428
275 app.build(force_all=True)
276
277 assert (app.outdir / 'prolog_epilog_substitution_excluded.pot').is_file()
278 pot = (app.outdir / 'prolog_epilog_substitution_excluded.pot').read_text(
279 encoding='utf8'
280 )
281 msg_ids = get_msgids(pot)
282
283 assert msg_ids == [
284 'i18n without prologue and epilogue substitutions',
285 'This is content that does not include prologue and epilogue substitutions.',
286 ]
287
288
289 @pytest.mark.sphinx(
290 'gettext',
291 testroot='root',
292 srcdir='gettext',
293 confoverrides={
294 'gettext_compact': False,
295 'gettext_additional_targets': ['literal-block', 'doctest-block'],
296 },
297 )
298 def test_gettext_literalblock_additional(app: SphinxTestApp) -> None:
299 app.build(force_all=True)
300
301 assert (app.outdir / 'literalblock.pot').is_file()
302 pot = (app.outdir / 'literalblock.pot').read_text(encoding='utf8')
303 msg_ids = get_msgids(pot)
304
305 assert msg_ids == [
306 'i18n with literal block',
307 'Correct literal block::',
308 'this is\\nliteral block',
309 'Missing literal block::',
310 "That's all.",
311 'included raw.txt',
312 '===\\nRaw\\n===\\n\\n.. raw:: html\\n\\n <iframe src=\\"https://sphinx-doc.org\\"></iframe>\\n\\n',
313 'code blocks',
314 "def main\\n 'result'\\nend",
315 '#include <stdlib.h>\\nint main(int argc, char** argv)\\n{\\n return 0;\\n}',
316 'example of C language',
317 '#include <stdio.h>\\nint main(int argc, char** argv)\\n{\\n return 0;\\n}',
318 'literal-block\\nin list',
319 'test_code_for_noqa()\\ncontinued()',
320 'doctest blocks',
321 '>>> import sys # sys importing\\n>>> def main(): # define main '
322 "function\\n... sys.stdout.write('hello') # call write method of "
323 "stdout object\\n>>>\\n>>> if __name__ == '__main__': # if run this py "
324 'file as python script\\n... main() # call main',
325 ]
326
327
328 @pytest.mark.sphinx('gettext', testroot='intl', srcdir='gettext')
329 def test_gettext_trailing_backslashes(app: SphinxTestApp) -> None:
330 app.build(force_all=True)
331
332 assert (app.outdir / 'backslashes.pot').is_file()
333 pot = (app.outdir / 'backslashes.pot').read_text(encoding='utf8')
334 msg_ids = get_msgids(pot)
335 assert msg_ids == [
336 'i18n with backslashes',
337 (
338 'line 1 line 2 line 3 '
339 # middle backslashes are escaped normally
340 'line 4a \\\\ and 4b '
341 # whitespaces after backslashes are dropped
342 'line with spaces after backslash '
343 'last line with spaces '
344 'and done 1'
345 ),
346 'a b c',
347 'last trailing \\\\ \\\\ is ignored',
348 'See [#]_',
349 'footnote with backslashes and done 2',
350 'directive with backslashes',
351 ]