Debian Codegraph @

tests/messages/frontend/test_frontend.py

raw
1 #
2 # Copyright (C) 2007-2011 Edgewall Software, 2013-2025 the Babel team
3 # All rights reserved.
4 #
5 # This software is licensed as described in the file LICENSE, which
6 # you should have received as part of this distribution. The terms
7 # are also available at https://github.com/python-babel/babel/blob/master/LICENSE.
8 #
9 # This software consists of voluntary contributions made by many
10 # individuals. For the exact contribution history, see the revision
11 # history and logs, available at https://github.com/python-babel/babel/commits/master/.
12
13 from __future__ import annotations
14
15 import re
16 import shlex
17 from functools import partial
18 from io import BytesIO, StringIO
19
20 import pytest
21
22 from babel.messages import Catalog, extract, frontend
23 from babel.messages.frontend import (
24 CommandLineInterface,
25 ExtractMessages,
26 UpdateCatalog,
27 )
28 from babel.messages.pofile import write_po
29 from tests.messages.consts import project_dir
30 from tests.messages.utils import CUSTOM_EXTRACTOR_COOKIE
31
32 mapping_cfg = """
33 [extractors]
34 custom = tests.messages.utils:custom_extractor
35
36 # Special extractor for a given Python file
37 [custom: special.py]
38 treat = delicious
39
40 # Python source files
41 [python: **.py]
42
43 # Genshi templates
44 [genshi: **/templates/**.html]
45 include_attrs =
46
47 [genshi: **/templates/**.txt]
48 template_class = genshi.template:TextTemplate
49 encoding = latin-1
50
51 # Some custom extractor
52 [custom: **/custom/*.*]
53 """
54
55 mapping_toml = """
56 [extractors]
57 custom = "tests.messages.utils:custom_extractor"
58
59 # Special extractor for a given Python file
60 [[mappings]]
61 method = "custom"
62 pattern = "special.py"
63 treat = "delightful"
64
65 # Python source files
66 [[mappings]]
67 method = "python"
68 pattern = "**.py"
69
70 # Genshi templates
71 [[mappings]]
72 method = "genshi"
73 pattern = "**/templates/**.html"
74 include_attrs = ""
75
76 [[mappings]]
77 method = "genshi"
78 pattern = "**/templates/**.txt"
79 template_class = "genshi.template:TextTemplate"
80 encoding = "latin-1"
81
82 # Some custom extractor
83 [[mappings]]
84 method = "custom"
85 pattern = "**/custom/*.*"
86 """
87
88
89 @pytest.mark.parametrize(
90 ("data", "parser", "preprocess", "is_toml"),
91 [
92 (
93 mapping_cfg,
94 frontend.parse_mapping_cfg,
95 None,
96 False,
97 ),
98 (
99 mapping_toml,
100 frontend._parse_mapping_toml,
101 None,
102 True,
103 ),
104 (
105 mapping_toml,
106 partial(frontend._parse_mapping_toml, style="pyproject.toml"),
107 lambda s: re.sub(r"^(\[+)", r"\1tool.babel.", s, flags=re.MULTILINE),
108 True,
109 ),
110 ],
111 ids=("cfg", "toml", "pyproject-toml"),
112 )
113 def test_parse_mapping(data: str, parser, preprocess, is_toml):
114 if preprocess:
115 data = preprocess(data)
116 if is_toml:
117 buf = BytesIO(data.encode())
118 else:
119 buf = StringIO(data)
120
121 method_map, options_map = parser(buf)
122 assert len(method_map) == 5
123
124 assert method_map[1] == ('**.py', 'python')
125 assert options_map['**.py'] == {}
126 assert method_map[2] == ('**/templates/**.html', 'genshi')
127 assert options_map['**/templates/**.html']['include_attrs'] == ''
128 assert method_map[3] == ('**/templates/**.txt', 'genshi')
129 assert (options_map['**/templates/**.txt']['template_class']
130 == 'genshi.template:TextTemplate')
131 assert options_map['**/templates/**.txt']['encoding'] == 'latin-1'
132 assert method_map[4] == ('**/custom/*.*', 'tests.messages.utils:custom_extractor')
133 assert options_map['**/custom/*.*'] == {}
134
135
136 def test_parse_keywords():
137 kw = frontend.parse_keywords(['_', 'dgettext:2', 'dngettext:2,3', 'pgettext:1c,2'])
138 assert kw == {
139 '_': None,
140 'dgettext': (2,),
141 'dngettext': (2, 3),
142 'pgettext': ((1, 'c'), 2),
143 }
144
145
146 def test_parse_keywords_with_t():
147 kw = frontend.parse_keywords(['_:1', '_:2,2t', '_:2c,3,3t'])
148
149 assert kw == {
150 '_': {
151 None: (1,),
152 2: (2,),
153 3: ((2, 'c'), 3),
154 },
155 }
156
157
158 def test_extract_messages_with_t():
159 content = rb"""
160 _("1 arg, arg 1")
161 _("2 args, arg 1", "2 args, arg 2")
162 _("3 args, arg 1", "3 args, arg 2", "3 args, arg 3")
163 _("4 args, arg 1", "4 args, arg 2", "4 args, arg 3", "4 args, arg 4")
164 """
165 kw = frontend.parse_keywords(['_:1', '_:2,2t', '_:2c,3,3t'])
166 result = list(extract.extract("python", BytesIO(content), kw))
167 expected = [(2, '1 arg, arg 1', [], None),
168 (3, '2 args, arg 1', [], None),
169 (3, '2 args, arg 2', [], None),
170 (4, '3 args, arg 1', [], None),
171 (4, '3 args, arg 3', [], '3 args, arg 2'),
172 (5, '4 args, arg 1', [], None)]
173 assert result == expected
174
175
176 def configure_cli_command(cmdline: str | list[str]):
177 """
178 Helper to configure a command class, but not run it just yet.
179
180 :param cmdline: The command line (sans the executable name)
181 :return: Command instance
182 """
183 args = shlex.split(cmdline) if isinstance(cmdline, str) else list(cmdline)
184 cli = CommandLineInterface()
185 cmdinst = cli._configure_command(cmdname=args[0], argv=args[1:])
186 return cmdinst
187
188
189 @pytest.mark.parametrize("split", (False, True))
190 @pytest.mark.parametrize("arg_name", ("-k", "--keyword", "--keywords"))
191 def test_extract_keyword_args_384(split, arg_name):
192 # This is a regression test for https://github.com/python-babel/babel/issues/384
193 # and it also tests that the rest of the forgotten aliases/shorthands implied by
194 # https://github.com/python-babel/babel/issues/390 are re-remembered (or rather
195 # that the mechanism for remembering them again works).
196
197 kwarg_specs = [
198 "gettext_noop",
199 "gettext_lazy",
200 "ngettext_lazy:1,2",
201 "ugettext_noop",
202 "ugettext_lazy",
203 "ungettext_lazy:1,2",
204 "pgettext_lazy:1c,2",
205 "npgettext_lazy:1c,2,3",
206 ]
207
208 if split: # Generate a command line with multiple -ks
209 kwarg_text = " ".join(f"{arg_name} {kwarg_spec}" for kwarg_spec in kwarg_specs)
210 else: # Generate a single space-separated -k
211 specs = ' '.join(kwarg_specs)
212 kwarg_text = f'{arg_name} "{specs}"'
213
214 # (Both of those invocation styles should be equivalent, so there is no parametrization from here on out)
215
216 cmdinst = configure_cli_command(
217 f"extract -F babel-django.cfg --add-comments Translators: -o django232.pot {kwarg_text} .",
218 )
219 assert isinstance(cmdinst, ExtractMessages)
220 assert set(cmdinst.keywords.keys()) == {'_', 'dgettext', 'dngettext',
221 'dnpgettext', 'dpgettext',
222 'gettext', 'gettext_lazy',
223 'gettext_noop', 'N_', 'ngettext',
224 'ngettext_lazy', 'npgettext',
225 'npgettext_lazy', 'pgettext',
226 'pgettext_lazy', 'ugettext',
227 'ugettext_lazy', 'ugettext_noop',
228 'ungettext', 'ungettext_lazy'}
229
230
231 def test_update_catalog_boolean_args():
232 cmdinst = configure_cli_command(
233 "update --init-missing --no-wrap -N --ignore-obsolete --previous -i foo -o foo -l en")
234 assert isinstance(cmdinst, UpdateCatalog)
235 assert cmdinst.init_missing is True
236 assert cmdinst.no_wrap is True
237 assert cmdinst.no_fuzzy_matching is True
238 assert cmdinst.ignore_obsolete is True
239 assert cmdinst.previous is False # Mutually exclusive with no_fuzzy_matching
240
241
242 def test_compile_catalog_dir(tmp_path):
243 """
244 Test that `compile` can compile all locales in a directory.
245 """
246 locales = ("fi_FI", "sv_SE")
247 for locale in locales:
248 l_dir = tmp_path / locale / "LC_MESSAGES"
249 l_dir.mkdir(parents=True)
250 po_file = l_dir / 'messages.po'
251 po_file.write_text('msgid "foo"\nmsgstr "bar"\n')
252 cmdinst = configure_cli_command([ # fmt: skip
253 'compile',
254 '--statistics',
255 '--use-fuzzy',
256 '-d', str(tmp_path),
257 ])
258 assert not cmdinst.run()
259 for locale in locales:
260 assert (tmp_path / locale / "LC_MESSAGES" / "messages.mo").exists()
261
262
263 def test_compile_catalog_explicit(tmp_path):
264 """
265 Test that `compile` can explicitly compile a single catalog.
266 """
267 po_file = tmp_path / 'temp.po'
268 po_file.write_text('msgid "foo"\nmsgstr "bar"\n')
269 mo_file = tmp_path / 'temp.mo'
270 cmdinst = configure_cli_command([ # fmt: skip
271 'compile',
272 '--statistics',
273 '--use-fuzzy',
274 '-i', str(po_file),
275 '-o', str(mo_file),
276 '-l', 'fi_FI',
277 ])
278 assert not cmdinst.run()
279 assert mo_file.exists()
280
281
282 @pytest.mark.parametrize("explicit_locale", (None, 'fi_FI'), ids=("implicit", "explicit"))
283 def test_update_dir(tmp_path, explicit_locale: bool):
284 """
285 Test that `update` can deal with directories too.
286 """
287 template = Catalog()
288 template.add("1")
289 template.add("2")
290 template.add("3")
291 tmpl_file = tmp_path / 'temp-template.pot'
292 with tmpl_file.open("wb") as outfp:
293 write_po(outfp, template)
294 locales = ("fi_FI", "sv_SE")
295 for locale in locales:
296 l_dir = tmp_path / locale / "LC_MESSAGES"
297 l_dir.mkdir(parents=True)
298 po_file = l_dir / 'messages.po'
299 po_file.touch()
300 cmdinst = configure_cli_command([ # fmt: skip
301 'update',
302 '-i', str(tmpl_file),
303 '-d', str(tmp_path),
304 *(['-l', explicit_locale] if explicit_locale else []),
305 ])
306 assert not cmdinst.run()
307 for locale in locales:
308 if explicit_locale and locale != explicit_locale:
309 continue
310 assert (tmp_path / locale / "LC_MESSAGES" / "messages.po").stat().st_size > 0
311
312
313 def test_extract_cli_knows_dash_s():
314 # This is a regression test for https://github.com/python-babel/babel/issues/390
315 cmdinst = configure_cli_command("extract -s -o foo babel")
316 assert isinstance(cmdinst, ExtractMessages)
317 assert cmdinst.strip_comments
318
319
320 def test_extract_cli_knows_dash_dash_last_dash_translator():
321 cmdinst = configure_cli_command('extract --last-translator "FULL NAME EMAIL@ADDRESS" -o foo babel')
322 assert isinstance(cmdinst, ExtractMessages)
323 assert cmdinst.last_translator == "FULL NAME EMAIL@ADDRESS"
324
325
326 def test_extract_add_location():
327 cmdinst = configure_cli_command("extract -o foo babel --add-location full")
328 assert isinstance(cmdinst, ExtractMessages)
329 assert cmdinst.add_location == 'full'
330 assert not cmdinst.no_location
331 assert cmdinst.include_lineno
332
333 cmdinst = configure_cli_command("extract -o foo babel --add-location file")
334 assert isinstance(cmdinst, ExtractMessages)
335 assert cmdinst.add_location == 'file'
336 assert not cmdinst.no_location
337 assert not cmdinst.include_lineno
338
339 cmdinst = configure_cli_command("extract -o foo babel --add-location never")
340 assert isinstance(cmdinst, ExtractMessages)
341 assert cmdinst.add_location == 'never'
342 assert cmdinst.no_location
343
344
345 def test_extract_error_code(monkeypatch, capsys):
346 monkeypatch.chdir(project_dir)
347 cmdinst = configure_cli_command("compile --domain=messages --directory i18n --locale fi_BUGGY")
348 assert cmdinst.run() == 1
349 out, err = capsys.readouterr()
350 if err:
351 assert "unknown named placeholder 'merkki'" in err
352
353
354 @pytest.mark.parametrize("with_underscore_ignore", (False, True))
355 def test_extract_ignore_dirs(monkeypatch, capsys, tmp_path, with_underscore_ignore):
356 pot_file = tmp_path / 'temp.pot'
357 monkeypatch.chdir(project_dir)
358 cmd = f"extract . -o '{pot_file}' --ignore-dirs '*ignored* .*' "
359 if with_underscore_ignore:
360 # This also tests that multiple arguments are supported.
361 cmd += "--ignore-dirs '_*'"
362 cmdinst = configure_cli_command(cmd)
363 assert isinstance(cmdinst, ExtractMessages)
364 assert cmdinst.directory_filter
365 cmdinst.run()
366 pot_content = pot_file.read_text()
367
368 # The `ignored` directory is now actually ignored:
369 assert 'this_wont_normally_be_here' not in pot_content
370
371 # Since we manually set a filter, the otherwise `_hidden` directory is walked into,
372 # unless we opt in to ignore it again
373 assert ('ssshhh....' in pot_content) != with_underscore_ignore
374 assert ('_hidden_by_default' in pot_content) != with_underscore_ignore
375
376
377 def test_extract_header_comment(monkeypatch, tmp_path):
378 pot_file = tmp_path / 'temp.pot'
379 monkeypatch.chdir(project_dir)
380 cmdinst = configure_cli_command(f"extract . -o '{pot_file}' --header-comment 'Boing' ")
381 cmdinst.run()
382 pot_content = pot_file.read_text()
383 assert 'Boing' in pot_content
384
385
386 @pytest.mark.parametrize("mapping_format", ("toml", "cfg"))
387 def test_pr_1121(tmp_path, monkeypatch, caplog, mapping_format):
388 """
389 Test that extraction uses the first matching method and options,
390 instead of the first matching method and last matching options.
391
392 Without the fix in PR #1121, this test would fail,
393 since the `custom_extractor` isn't passed a delicious treat via
394 the configuration.
395 """
396 if mapping_format == "cfg":
397 mapping_file = (tmp_path / "mapping.cfg")
398 mapping_file.write_text(mapping_cfg)
399 else:
400 mapping_file = (tmp_path / "mapping.toml")
401 mapping_file.write_text(mapping_toml)
402 (tmp_path / "special.py").write_text("# this file is special")
403 pot_path = (tmp_path / "output.pot")
404 monkeypatch.chdir(tmp_path)
405 cmdinst = configure_cli_command(f"extract . -o {shlex.quote(str(pot_path))} --mapping {shlex.quote(mapping_file.name)}")
406 assert isinstance(cmdinst, ExtractMessages)
407 cmdinst.run()
408 # If the custom extractor didn't run, we wouldn't see the cookie in there.
409 assert CUSTOM_EXTRACTOR_COOKIE in pot_path.read_text()