Debian Codegraph @

tests/messages/test_extract_python.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 import codecs
14 from io import BytesIO
15
16 import pytest
17
18 from babel.messages import extract
19
20
21 def test_nested_calls():
22 buf = BytesIO(b"""\
23 msg1 = _(i18n_arg.replace(r'\"', '"'))
24 msg2 = ungettext(i18n_arg.replace(r'\"', '"'), multi_arg.replace(r'\"', '"'), 2)
25 msg3 = ungettext("Babel", multi_arg.replace(r'\"', '"'), 2)
26 msg4 = ungettext(i18n_arg.replace(r'\"', '"'), "Babels", 2)
27 msg5 = ungettext('bunny', 'bunnies', random.randint(1, 2))
28 msg6 = ungettext(arg0, 'bunnies', random.randint(1, 2))
29 msg7 = _(hello.there)
30 msg8 = gettext('Rabbit')
31 msg9 = dgettext('wiki', model.addPage())
32 msg10 = dngettext(getDomain(), 'Page', 'Pages', 3)
33 msg11 = ngettext(
34 "bunny",
35 "bunnies",
36 len(bunnies)
37 )
38 """)
39 messages = list(extract.extract_python(buf,
40 extract.DEFAULT_KEYWORDS.keys(),
41 [], {}))
42 assert messages == [
43 (1, '_', None, []),
44 (2, 'ungettext', (None, None, None), []),
45 (3, 'ungettext', ('Babel', None, None), []),
46 (4, 'ungettext', (None, 'Babels', None), []),
47 (5, 'ungettext', ('bunny', 'bunnies', None), []),
48 (6, 'ungettext', (None, 'bunnies', None), []),
49 (7, '_', None, []),
50 (8, 'gettext', 'Rabbit', []),
51 (9, 'dgettext', ('wiki', None), []),
52 (10, 'dngettext', (None, 'Page', 'Pages', None), []),
53 (12, 'ngettext', ('bunny', 'bunnies', None), []),
54 ]
55
56
57 def test_extract_default_encoding_ascii():
58 buf = BytesIO(b'_("a")')
59 messages = list(extract.extract_python(
60 buf, list(extract.DEFAULT_KEYWORDS), [], {},
61 ))
62 # Should work great in both py2 and py3
63 assert messages == [(1, '_', 'a', [])]
64
65
66 def test_extract_default_encoding_utf8():
67 buf = BytesIO('_("☃")'.encode('UTF-8'))
68 messages = list(extract.extract_python(
69 buf, list(extract.DEFAULT_KEYWORDS), [], {},
70 ))
71 assert messages == [(1, '_', '☃', [])]
72
73
74 def test_nested_comments():
75 buf = BytesIO(b"""\
76 msg = ngettext('pylon', # TRANSLATORS: shouldn't be
77 'pylons', # TRANSLATORS: seeing this
78 count)
79 """)
80 messages = list(extract.extract_python(buf, ('ngettext',),
81 ['TRANSLATORS:'], {}))
82 assert messages == [(1, 'ngettext', ('pylon', 'pylons', None), [])]
83
84
85 def test_comments_with_calls_that_spawn_multiple_lines():
86 buf = BytesIO(b"""\
87 # NOTE: This Comment SHOULD Be Extracted
88 add_notice(req, ngettext("Catalog deleted.",
89 "Catalogs deleted.", len(selected)))
90
91 # NOTE: This Comment SHOULD Be Extracted
92 add_notice(req, _("Locale deleted."))
93
94
95 # NOTE: This Comment SHOULD Be Extracted
96 add_notice(req, ngettext("Foo deleted.", "Foos deleted.", len(selected)))
97
98 # NOTE: This Comment SHOULD Be Extracted
99 # NOTE: And This One Too
100 add_notice(req, ngettext("Bar deleted.",
101 "Bars deleted.", len(selected)))
102 """)
103 messages = list(extract.extract_python(buf, ('ngettext', '_'), ['NOTE:'],
104
105 {'strip_comment_tags': False}))
106 assert messages[0] == (2, 'ngettext', ('Catalog deleted.', 'Catalogs deleted.', None), ['NOTE: This Comment SHOULD Be Extracted'])
107 assert messages[1] == (6, '_', 'Locale deleted.', ['NOTE: This Comment SHOULD Be Extracted'])
108 assert messages[2] == (10, 'ngettext', ('Foo deleted.', 'Foos deleted.', None), ['NOTE: This Comment SHOULD Be Extracted'])
109 assert messages[3] == (14, 'ngettext', ('Bar deleted.', 'Bars deleted.', None), ['NOTE: This Comment SHOULD Be Extracted', 'NOTE: And This One Too'])
110
111
112 def test_declarations():
113 buf = BytesIO(b"""\
114 class gettext(object):
115 pass
116 def render_body(context,x,y=_('Page arg 1'),z=_('Page arg 2'),**pageargs):
117 pass
118 def ngettext(y='arg 1',z='arg 2',**pageargs):
119 pass
120 class Meta:
121 verbose_name = _('log entry')
122 """)
123 messages = list(extract.extract_python(buf,
124 extract.DEFAULT_KEYWORDS.keys(),
125 [], {}))
126 assert messages == [
127 (3, '_', 'Page arg 1', []),
128 (3, '_', 'Page arg 2', []),
129 (8, '_', 'log entry', []),
130 ]
131
132
133 def test_multiline():
134 buf = BytesIO(b"""\
135 msg1 = ngettext('pylon',
136 'pylons', count)
137 msg2 = ngettext('elvis',
138 'elvises',
139 count)
140 """)
141 messages = list(extract.extract_python(buf, ('ngettext',), [], {}))
142 assert messages == [
143 (1, 'ngettext', ('pylon', 'pylons', None), []),
144 (3, 'ngettext', ('elvis', 'elvises', None), []),
145 ]
146
147
148 def test_dpgettext():
149 buf = BytesIO(b"""\
150 msg1 = dpgettext('dev', 'Strings',
151 'pylon')
152 msg2 = dpgettext('dev', 'Strings', 'elvis')
153 """)
154 messages = list(extract.extract_python(buf, ('dpgettext',), [], {}))
155 assert messages == [
156 (1, 'dpgettext', ('dev', 'Strings', 'pylon'), []),
157 (3, 'dpgettext', ('dev', 'Strings', 'elvis'), []),
158 ]
159 buf = BytesIO(b"""\
160 msg = dpgettext('dev', 'Strings', 'pylon', # TRANSLATORS: shouldn't be
161 ) # TRANSLATORS: seeing this
162 """)
163 messages = list(extract.extract_python(buf, ('dpgettext',),['TRANSLATORS:'], {}))
164 assert messages == [
165 (1, 'dpgettext', ('dev', 'Strings', 'pylon', None), []),
166 ]
167
168
169 def test_npgettext():
170 buf = BytesIO(b"""\
171 msg1 = npgettext('Strings','pylon',
172 'pylons', count)
173 msg2 = npgettext('Strings','elvis',
174 'elvises',
175 count)
176 """)
177 messages = list(extract.extract_python(buf, ('npgettext',), [], {}))
178 assert messages == [
179 (1, 'npgettext', ('Strings', 'pylon', 'pylons', None), []),
180 (3, 'npgettext', ('Strings', 'elvis', 'elvises', None), []),
181 ]
182 buf = BytesIO(b"""\
183 msg = npgettext('Strings', 'pylon', # TRANSLATORS: shouldn't be
184 'pylons', # TRANSLATORS: seeing this
185 count)
186 """)
187 messages = list(extract.extract_python(buf, ('npgettext',),
188 ['TRANSLATORS:'], {}))
189 assert messages == [
190 (1, 'npgettext', ('Strings', 'pylon', 'pylons', None), []),
191 ]
192
193
194 def test_dnpgettext():
195 buf = BytesIO(b"""\
196 msg1 = dnpgettext('dev', 'Strings','pylon',
197 'pylons', count)
198 msg2 = dnpgettext('dev', 'Strings','elvis',
199 'elvises',
200 count)
201 """)
202 messages = list(extract.extract_python(buf, ('dnpgettext',), [], {}))
203 assert messages == [
204 (1, 'dnpgettext', ('dev', 'Strings', 'pylon', 'pylons', None), []),
205 (3, 'dnpgettext', ('dev', 'Strings', 'elvis', 'elvises', None), []),
206 ]
207 buf = BytesIO(b"""\
208 msg = dnpgettext('dev', 'Strings', 'pylon', # TRANSLATORS: shouldn't be
209 'pylons', # TRANSLATORS: seeing this
210 count)
211 """)
212 messages = list(extract.extract_python(buf, ('dnpgettext',),['TRANSLATORS:'], {}))
213 assert messages == [
214 (1, 'dnpgettext', ('dev', 'Strings', 'pylon', 'pylons', None), []),
215 ]
216
217
218 def test_triple_quoted_strings():
219 buf = BytesIO(b"""\
220 msg1 = _('''pylons''')
221 msg2 = ngettext(r'''elvis''', \"\"\"elvises\"\"\", count)
222 msg2 = ngettext(\"\"\"elvis\"\"\", 'elvises', count)
223 """)
224 messages = list(extract.extract_python(buf,
225 extract.DEFAULT_KEYWORDS.keys(),
226 [], {}))
227 assert messages == [
228 (1, '_', 'pylons', []),
229 (2, 'ngettext', ('elvis', 'elvises', None), []),
230 (3, 'ngettext', ('elvis', 'elvises', None), []),
231 ]
232
233
234 def test_multiline_strings():
235 buf = BytesIO(b"""\
236 _('''This module provides internationalization and localization
237 support for your Python programs by providing an interface to the GNU
238 gettext message catalog library.''')
239 """)
240 messages = list(extract.extract_python(buf,
241 extract.DEFAULT_KEYWORDS.keys(),
242 [], {}))
243 assert messages == [
244 (1, '_',
245 'This module provides internationalization and localization\n'
246 'support for your Python programs by providing an interface to '
247 'the GNU\ngettext message catalog library.', []),
248 ]
249
250
251 def test_concatenated_strings():
252 buf = BytesIO(b"""\
253 foobar = _('foo' 'bar')
254 """)
255 messages = list(extract.extract_python(buf,
256 extract.DEFAULT_KEYWORDS.keys(),
257 [], {}))
258 assert messages[0][2] == 'foobar'
259
260
261 def test_unicode_string_arg():
262 buf = BytesIO(b"msg = _('Foo Bar')")
263 messages = list(extract.extract_python(buf, ('_',), [], {}))
264 assert messages[0][2] == 'Foo Bar'
265
266
267 def test_comment_tag():
268 buf = BytesIO(b"""
269 # NOTE: A translation comment
270 msg = _('Foo Bar')
271 """)
272 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
273 assert messages[0][2] == 'Foo Bar'
274 assert messages[0][3] == ['NOTE: A translation comment']
275
276
277 def test_comment_tag_multiline():
278 buf = BytesIO(b"""
279 # NOTE: A translation comment
280 # with a second line
281 msg = _('Foo Bar')
282 """)
283 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
284 assert messages[0][2] == 'Foo Bar'
285 assert messages[0][3] == ['NOTE: A translation comment', 'with a second line']
286
287
288 def test_translator_comments_with_previous_non_translator_comments():
289 buf = BytesIO(b"""
290 # This shouldn't be in the output
291 # because it didn't start with a comment tag
292 # NOTE: A translation comment
293 # with a second line
294 msg = _('Foo Bar')
295 """)
296 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
297 assert messages[0][2] == 'Foo Bar'
298 assert messages[0][3] == ['NOTE: A translation comment', 'with a second line']
299
300
301 def test_comment_tags_not_on_start_of_comment():
302 buf = BytesIO(b"""
303 # This shouldn't be in the output
304 # because it didn't start with a comment tag
305 # do NOTE: this will not be a translation comment
306 # NOTE: This one will be
307 msg = _('Foo Bar')
308 """)
309 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
310 assert messages[0][2] == 'Foo Bar'
311 assert messages[0][3] == ['NOTE: This one will be']
312
313
314 def test_multiple_comment_tags():
315 buf = BytesIO(b"""
316 # NOTE1: A translation comment for tag1
317 # with a second line
318 msg = _('Foo Bar1')
319
320 # NOTE2: A translation comment for tag2
321 msg = _('Foo Bar2')
322 """)
323 messages = list(extract.extract_python(buf, ('_',),
324 ['NOTE1:', 'NOTE2:'], {}))
325 assert messages[0][2] == 'Foo Bar1'
326 assert messages[0][3] == ['NOTE1: A translation comment for tag1', 'with a second line']
327 assert messages[1][2] == 'Foo Bar2'
328 assert messages[1][3] == ['NOTE2: A translation comment for tag2']
329
330
331 def test_two_succeeding_comments():
332 buf = BytesIO(b"""
333 # NOTE: one
334 # NOTE: two
335 msg = _('Foo Bar')
336 """)
337 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
338 assert messages[0][2] == 'Foo Bar'
339 assert messages[0][3] == ['NOTE: one', 'NOTE: two']
340
341
342 def test_invalid_translator_comments():
343 buf = BytesIO(b"""
344 # NOTE: this shouldn't apply to any messages
345 hello = 'there'
346
347 msg = _('Foo Bar')
348 """)
349 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
350 assert messages[0][2] == 'Foo Bar'
351 assert messages[0][3] == []
352
353
354 def test_invalid_translator_comments2():
355 buf = BytesIO(b"""
356 # NOTE: Hi!
357 hithere = _('Hi there!')
358
359 # NOTE: you should not be seeing this in the .po
360 rows = [[v for v in range(0,10)] for row in range(0,10)]
361
362 # this (NOTE:) should not show up either
363 hello = _('Hello')
364 """)
365 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
366 assert messages[0][2] == 'Hi there!'
367 assert messages[0][3] == ['NOTE: Hi!']
368 assert messages[1][2] == 'Hello'
369 assert messages[1][3] == []
370
371
372 def test_invalid_translator_comments3():
373 buf = BytesIO(b"""
374 # NOTE: Hi,
375
376 # there!
377 hithere = _('Hi there!')
378 """)
379 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
380 assert messages[0][2] == 'Hi there!'
381 assert messages[0][3] == []
382
383
384 def test_comment_tag_with_leading_space():
385 buf = BytesIO(b"""
386 #: A translation comment
387 #: with leading spaces
388 msg = _('Foo Bar')
389 """)
390 messages = list(extract.extract_python(buf, ('_',), [':'], {}))
391 assert messages[0][2] == 'Foo Bar'
392 assert messages[0][3] == [': A translation comment', ': with leading spaces']
393
394
395 def test_different_signatures():
396 buf = BytesIO(b"""
397 foo = _('foo', 'bar')
398 n = ngettext('hello', 'there', n=3)
399 n = ngettext(n=3, 'hello', 'there')
400 n = ngettext(n=3, *messages)
401 n = ngettext()
402 n = ngettext('foo')
403 """)
404 messages = list(extract.extract_python(buf, ('_', 'ngettext'), [], {}))
405 assert messages[0][2] == ('foo', 'bar')
406 assert messages[1][2] == ('hello', 'there', None)
407 assert messages[2][2] == (None, 'hello', 'there')
408 assert messages[3][2] == (None, None)
409 assert messages[4][2] is None
410 assert messages[5][2] == 'foo'
411
412
413 def test_utf8_message():
414 buf = BytesIO("""
415 # NOTE: hello
416 msg = _('Bonjour à tous')
417 """.encode('utf-8'))
418 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'],
419 {'encoding': 'utf-8'}))
420 assert messages[0][2] == 'Bonjour à tous'
421 assert messages[0][3] == ['NOTE: hello']
422
423
424 def test_utf8_message_with_magic_comment():
425 buf = BytesIO("""# -*- coding: utf-8 -*-
426 # NOTE: hello
427 msg = _('Bonjour à tous')
428 """.encode('utf-8'))
429 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
430 assert messages[0][2] == 'Bonjour à tous'
431 assert messages[0][3] == ['NOTE: hello']
432
433
434 def test_utf8_message_with_utf8_bom():
435 buf = BytesIO(codecs.BOM_UTF8 + """
436 # NOTE: hello
437 msg = _('Bonjour à tous')
438 """.encode('utf-8'))
439 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
440 assert messages[0][2] == 'Bonjour à tous'
441 assert messages[0][3] == ['NOTE: hello']
442
443
444 def test_utf8_message_with_utf8_bom_and_magic_comment():
445 buf = BytesIO(codecs.BOM_UTF8 + """# -*- coding: utf-8 -*-
446 # NOTE: hello
447 msg = _('Bonjour à tous')
448 """.encode('utf-8'))
449 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
450 assert messages[0][2] == 'Bonjour à tous'
451 assert messages[0][3] == ['NOTE: hello']
452
453
454 def test_utf8_bom_with_latin_magic_comment_fails():
455 buf = BytesIO(codecs.BOM_UTF8 + """# -*- coding: latin-1 -*-
456 # NOTE: hello
457 msg = _('Bonjour à tous')
458 """.encode('utf-8'))
459 with pytest.raises(SyntaxError):
460 list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
461
462
463 def test_utf8_raw_strings_match_unicode_strings():
464 buf = BytesIO(codecs.BOM_UTF8 + """
465 msg = _('Bonjour à tous')
466 msgu = _('Bonjour à tous')
467 """.encode('utf-8'))
468 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
469 assert messages[0][2] == 'Bonjour à tous'
470 assert messages[0][2] == messages[1][2]
471
472
473 def test_extract_strip_comment_tags():
474 buf = BytesIO(b"""\
475 #: This is a comment with a very simple
476 #: prefix specified
477 _('Servus')
478
479 # NOTE: This is a multiline comment with
480 # a prefix too
481 _('Babatschi')""")
482 messages = list(extract.extract('python', buf, comment_tags=['NOTE:', ':'],
483 strip_comment_tags=True))
484 assert messages[0][1] == 'Servus'
485 assert messages[0][2] == ['This is a comment with a very simple', 'prefix specified']
486 assert messages[1][1] == 'Babatschi'
487 assert messages[1][2] == ['This is a multiline comment with', 'a prefix too']
488
489
490 def test_nested_messages():
491 buf = BytesIO(b"""
492 # NOTE: First
493 _('Hello, {name}!', name=_('Foo Bar'))
494
495 # NOTE: Second
496 _('Hello, {name1} and {name2}!', name1=_('Heungsub'),
497 name2=_('Armin'))
498
499 # NOTE: Third
500 _('Hello, {0} and {1}!', _('Heungsub'),
501 _('Armin'))
502 """)
503 messages = list(extract.extract_python(buf, ('_',), ['NOTE:'], {}))
504 assert messages[0][2] == ('Hello, {name}!', None)
505 assert messages[0][3] == ['NOTE: First']
506 assert messages[1][2] == 'Foo Bar'
507 assert messages[1][3] == []
508 assert messages[2][2] == ('Hello, {name1} and {name2}!', None)
509 assert messages[2][3] == ['NOTE: Second']
510 assert messages[3][2] == 'Heungsub'
511 assert messages[3][3] == []
512 assert messages[4][2] == 'Armin'
513 assert messages[4][3] == []
514 assert messages[5][2] == ('Hello, {0} and {1}!', None)
515 assert messages[5][3] == ['NOTE: Third']
516 assert messages[6][2] == 'Heungsub'
517 assert messages[6][3] == []
518 assert messages[7][2] == 'Armin'
519 assert messages[7][3] == []