Debian Codegraph @

Lib/test/test_tools/test_i18n.py

raw
1 """Tests to cover the Tools/i18n package"""
2
3 import os
4 import re
5 import sys
6 import unittest
7 from textwrap import dedent
8 from pathlib import Path
9
10 from test.support.script_helper import assert_python_ok
11 from test.test_tools import skip_if_missing, toolsdir
12 from test.support.os_helper import temp_cwd, temp_dir
13
14
15 skip_if_missing()
16
17 DATA_DIR = Path(__file__).resolve().parent / 'i18n_data'
18
19
20 def normalize_POT_file(pot):
21 """Normalize the POT creation timestamp, charset and
22 file locations to make the POT file easier to compare.
23
24 """
25 # Normalize the creation date.
26 date_pattern = re.compile(r'"POT-Creation-Date: .+?\\n"')
27 header = r'"POT-Creation-Date: 2000-01-01 00:00+0000\\n"'
28 pot = re.sub(date_pattern, header, pot)
29
30 # Normalize charset to UTF-8 (currently there's no way to specify the output charset).
31 charset_pattern = re.compile(r'"Content-Type: text/plain; charset=.+?\\n"')
32 charset = r'"Content-Type: text/plain; charset=UTF-8\\n"'
33 pot = re.sub(charset_pattern, charset, pot)
34
35 # Normalize file location path separators in case this test is
36 # running on Windows (which uses '\').
37 fileloc_pattern = re.compile(r'#:.+')
38
39 def replace(match):
40 return match[0].replace(os.sep, "/")
41 pot = re.sub(fileloc_pattern, replace, pot)
42 return pot
43
44
45 class Test_pygettext(unittest.TestCase):
46 """Tests for the pygettext.py tool"""
47
48 script = Path(toolsdir, 'i18n', 'pygettext.py')
49
50 def get_header(self, data):
51 """ utility: return the header of a .po file as a dictionary """
52 headers = {}
53 for line in data.split('\n'):
54 if not line or line.startswith(('#', 'msgid', 'msgstr')):
55 continue
56 line = line.strip('"')
57 key, val = line.split(':', 1)
58 headers[key] = val.strip()
59 return headers
60
61 def get_msgids(self, data):
62 """ utility: return all msgids in .po file as a list of strings """
63 msgids = []
64 reading_msgid = False
65 cur_msgid = []
66 for line in data.split('\n'):
67 if reading_msgid:
68 if line.startswith('"'):
69 cur_msgid.append(line.strip('"'))
70 else:
71 msgids.append('\n'.join(cur_msgid))
72 cur_msgid = []
73 reading_msgid = False
74 continue
75 if line.startswith('msgid '):
76 line = line[len('msgid '):]
77 cur_msgid.append(line.strip('"'))
78 reading_msgid = True
79 else:
80 if reading_msgid:
81 msgids.append('\n'.join(cur_msgid))
82
83 return msgids
84
85 def assert_POT_equal(self, expected, actual):
86 """Check if two POT files are equal"""
87 self.maxDiff = None
88 self.assertEqual(normalize_POT_file(expected), normalize_POT_file(actual))
89
90 def extract_from_str(self, module_content, *, args=(), strict=True):
91 """Return all msgids extracted from module_content."""
92 filename = 'test.py'
93 with temp_cwd(None):
94 with open(filename, 'w', encoding='utf-8') as fp:
95 fp.write(module_content)
96 res = assert_python_ok('-Xutf8', self.script, *args, filename)
97 if strict:
98 self.assertEqual(res.err, b'')
99 with open('messages.pot', encoding='utf-8') as fp:
100 data = fp.read()
101 return self.get_msgids(data)
102
103 def extract_docstrings_from_str(self, module_content):
104 """Return all docstrings extracted from module_content."""
105 return self.extract_from_str(module_content, args=('--docstrings',), strict=False)
106
107 def test_header(self):
108 """Make sure the required fields are in the header, according to:
109 http://www.gnu.org/software/gettext/manual/gettext.html#Header-Entry
110 """
111 with temp_cwd(None) as cwd:
112 assert_python_ok('-Xutf8', self.script)
113 with open('messages.pot', encoding='utf-8') as fp:
114 data = fp.read()
115 header = self.get_header(data)
116
117 self.assertIn("Project-Id-Version", header)
118 self.assertIn("POT-Creation-Date", header)
119 self.assertIn("PO-Revision-Date", header)
120 self.assertIn("Last-Translator", header)
121 self.assertIn("Language-Team", header)
122 self.assertIn("MIME-Version", header)
123 self.assertIn("Content-Type", header)
124 self.assertIn("Content-Transfer-Encoding", header)
125 self.assertIn("Generated-By", header)
126
127 # not clear if these should be required in POT (template) files
128 #self.assertIn("Report-Msgid-Bugs-To", header)
129 #self.assertIn("Language", header)
130
131 #"Plural-Forms" is optional
132
133 @unittest.skipIf(sys.platform.startswith('aix'),
134 'bpo-29972: broken test on AIX')
135 def test_POT_Creation_Date(self):
136 """ Match the date format from xgettext for POT-Creation-Date """
137 from datetime import datetime
138 with temp_cwd(None) as cwd:
139 assert_python_ok('-Xutf8', self.script)
140 with open('messages.pot', encoding='utf-8') as fp:
141 data = fp.read()
142 header = self.get_header(data)
143 creationDate = header['POT-Creation-Date']
144
145 # peel off the escaped newline at the end of string
146 if creationDate.endswith('\\n'):
147 creationDate = creationDate[:-len('\\n')]
148
149 # This will raise if the date format does not exactly match.
150 datetime.strptime(creationDate, '%Y-%m-%d %H:%M%z')
151
152 def test_output_option(self):
153 for opt in ('-o', '--output='):
154 with temp_cwd():
155 assert_python_ok(self.script, f'{opt}test')
156 self.assertTrue(os.path.exists('test'))
157 res = assert_python_ok(self.script, f'{opt}-')
158 self.assertIn(b'Project-Id-Version: PACKAGE VERSION', res.out)
159
160 def test_funcdocstring(self):
161 for doc in ('"""doc"""', "r'''doc'''", "R'doc'", 'u"doc"'):
162 with self.subTest(doc):
163 msgids = self.extract_docstrings_from_str(dedent('''\
164 def foo(bar):
165 %s
166 ''' % doc))
167 self.assertIn('doc', msgids)
168
169 def test_funcdocstring_bytes(self):
170 msgids = self.extract_docstrings_from_str(dedent('''\
171 def foo(bar):
172 b"""doc"""
173 '''))
174 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
175
176 def test_funcdocstring_fstring(self):
177 msgids = self.extract_docstrings_from_str(dedent('''\
178 def foo(bar):
179 f"""doc"""
180 '''))
181 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
182
183 def test_classdocstring(self):
184 for doc in ('"""doc"""', "r'''doc'''", "R'doc'", 'u"doc"'):
185 with self.subTest(doc):
186 msgids = self.extract_docstrings_from_str(dedent('''\
187 class C:
188 %s
189 ''' % doc))
190 self.assertIn('doc', msgids)
191
192 def test_classdocstring_bytes(self):
193 msgids = self.extract_docstrings_from_str(dedent('''\
194 class C:
195 b"""doc"""
196 '''))
197 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
198
199 def test_classdocstring_fstring(self):
200 msgids = self.extract_docstrings_from_str(dedent('''\
201 class C:
202 f"""doc"""
203 '''))
204 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
205
206 def test_moduledocstring(self):
207 for doc in ('"""doc"""', "r'''doc'''", "R'doc'", 'u"doc"'):
208 with self.subTest(doc):
209 msgids = self.extract_docstrings_from_str(dedent('''\
210 %s
211 ''' % doc))
212 self.assertIn('doc', msgids)
213
214 def test_moduledocstring_bytes(self):
215 msgids = self.extract_docstrings_from_str(dedent('''\
216 b"""doc"""
217 '''))
218 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
219
220 def test_moduledocstring_fstring(self):
221 msgids = self.extract_docstrings_from_str(dedent('''\
222 f"""doc"""
223 '''))
224 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
225
226 def test_msgid(self):
227 msgids = self.extract_docstrings_from_str(
228 '''_("""doc""" r'str' u"ing")''')
229 self.assertIn('docstring', msgids)
230
231 def test_msgid_bytes(self):
232 msgids = self.extract_docstrings_from_str('_(b"""doc""")')
233 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
234
235 def test_msgid_fstring(self):
236 msgids = self.extract_docstrings_from_str('_(f"""doc""")')
237 self.assertFalse([msgid for msgid in msgids if 'doc' in msgid])
238
239 def test_funcdocstring_annotated_args(self):
240 """ Test docstrings for functions with annotated args """
241 msgids = self.extract_docstrings_from_str(dedent('''\
242 def foo(bar: str):
243 """doc"""
244 '''))
245 self.assertIn('doc', msgids)
246
247 def test_funcdocstring_annotated_return(self):
248 """ Test docstrings for functions with annotated return type """
249 msgids = self.extract_docstrings_from_str(dedent('''\
250 def foo(bar) -> str:
251 """doc"""
252 '''))
253 self.assertIn('doc', msgids)
254
255 def test_funcdocstring_defvalue_args(self):
256 """ Test docstring for functions with default arg values """
257 msgids = self.extract_docstrings_from_str(dedent('''\
258 def foo(bar=()):
259 """doc"""
260 '''))
261 self.assertIn('doc', msgids)
262
263 def test_funcdocstring_multiple_funcs(self):
264 """ Test docstring extraction for multiple functions combining
265 annotated args, annotated return types and default arg values
266 """
267 msgids = self.extract_docstrings_from_str(dedent('''\
268 def foo1(bar: tuple=()) -> str:
269 """doc1"""
270
271 def foo2(bar: List[1:2]) -> (lambda x: x):
272 """doc2"""
273
274 def foo3(bar: 'func'=lambda x: x) -> {1: 2}:
275 """doc3"""
276 '''))
277 self.assertIn('doc1', msgids)
278 self.assertIn('doc2', msgids)
279 self.assertIn('doc3', msgids)
280
281 def test_classdocstring_early_colon(self):
282 """ Test docstring extraction for a class with colons occurring within
283 the parentheses.
284 """
285 msgids = self.extract_docstrings_from_str(dedent('''\
286 class D(L[1:2], F({1: 2}), metaclass=M(lambda x: x)):
287 """doc"""
288 '''))
289 self.assertIn('doc', msgids)
290
291 def test_calls_in_fstrings(self):
292 msgids = self.extract_docstrings_from_str(dedent('''\
293 f"{_('foo bar')}"
294 '''))
295 self.assertIn('foo bar', msgids)
296
297 def test_calls_in_fstrings_raw(self):
298 msgids = self.extract_docstrings_from_str(dedent('''\
299 rf"{_('foo bar')}"
300 '''))
301 self.assertIn('foo bar', msgids)
302
303 def test_calls_in_fstrings_nested(self):
304 msgids = self.extract_docstrings_from_str(dedent('''\
305 f"""{f'{_("foo bar")}'}"""
306 '''))
307 self.assertIn('foo bar', msgids)
308
309 def test_calls_in_fstrings_attribute(self):
310 msgids = self.extract_docstrings_from_str(dedent('''\
311 f"{obj._('foo bar')}"
312 '''))
313 self.assertIn('foo bar', msgids)
314
315 def test_calls_in_fstrings_with_call_on_call(self):
316 msgids = self.extract_docstrings_from_str(dedent('''\
317 f"{type(str)('foo bar')}"
318 '''))
319 self.assertNotIn('foo bar', msgids)
320
321 def test_calls_in_fstrings_with_format(self):
322 msgids = self.extract_docstrings_from_str(dedent('''\
323 f"{_('foo {bar}').format(bar='baz')}"
324 '''))
325 self.assertIn('foo {bar}', msgids)
326
327 def test_calls_in_fstrings_with_wrong_input_1(self):
328 msgids = self.extract_docstrings_from_str(dedent('''\
329 f"{_(f'foo {bar}')}"
330 '''))
331 self.assertFalse([msgid for msgid in msgids if 'foo {bar}' in msgid])
332
333 def test_calls_in_fstrings_with_wrong_input_2(self):
334 msgids = self.extract_docstrings_from_str(dedent('''\
335 f"{_(1)}"
336 '''))
337 self.assertNotIn(1, msgids)
338
339 def test_calls_in_fstring_with_multiple_args(self):
340 msgids = self.extract_docstrings_from_str(dedent('''\
341 f"{_('foo', 'bar')}"
342 '''))
343 self.assertNotIn('foo', msgids)
344 self.assertNotIn('bar', msgids)
345
346 def test_calls_in_fstring_with_keyword_args(self):
347 msgids = self.extract_docstrings_from_str(dedent('''\
348 f"{_('foo', bar='baz')}"
349 '''))
350 self.assertNotIn('foo', msgids)
351 self.assertNotIn('bar', msgids)
352 self.assertNotIn('baz', msgids)
353
354 def test_calls_in_fstring_with_partially_wrong_expression(self):
355 msgids = self.extract_docstrings_from_str(dedent('''\
356 f"{_(f'foo') + _('bar')}"
357 '''))
358 self.assertNotIn('foo', msgids)
359 self.assertIn('bar', msgids)
360
361 def test_function_and_class_names(self):
362 """Test that function and class names are not mistakenly extracted."""
363 msgids = self.extract_from_str(dedent('''\
364 def _(x):
365 pass
366
367 def _(x="foo"):
368 pass
369
370 async def _(x):
371 pass
372
373 class _(object):
374 pass
375 '''))
376 self.assertEqual(msgids, [''])
377
378 def test_pygettext_output(self):
379 """Test that the pygettext output exactly matches snapshots."""
380 for input_file, output_file, output in extract_from_snapshots():
381 with self.subTest(input_file=input_file):
382 expected = output_file.read_text(encoding='utf-8')
383 self.assert_POT_equal(expected, output)
384
385 def test_files_list(self):
386 """Make sure the directories are inspected for source files
387 bpo-31920
388 """
389 text1 = 'Text to translate1'
390 text2 = 'Text to translate2'
391 text3 = 'Text to ignore'
392 with temp_cwd(None), temp_dir(None) as sdir:
393 pymod = Path(sdir, 'pypkg', 'pymod.py')
394 pymod.parent.mkdir()
395 pymod.write_text(f'_({text1!r})', encoding='utf-8')
396
397 pymod2 = Path(sdir, 'pkg.py', 'pymod2.py')
398 pymod2.parent.mkdir()
399 pymod2.write_text(f'_({text2!r})', encoding='utf-8')
400
401 pymod3 = Path(sdir, 'CVS', 'pymod3.py')
402 pymod3.parent.mkdir()
403 pymod3.write_text(f'_({text3!r})', encoding='utf-8')
404
405 assert_python_ok('-Xutf8', self.script, sdir)
406 data = Path('messages.pot').read_text(encoding='utf-8')
407 self.assertIn(f'msgid "{text1}"', data)
408 self.assertIn(f'msgid "{text2}"', data)
409 self.assertNotIn(text3, data)
410
411
412 def extract_from_snapshots():
413 snapshots = {
414 'messages.py': ('--docstrings',),
415 'fileloc.py': ('--docstrings',),
416 'docstrings.py': ('--docstrings',),
417 # == Test character escaping
418 # Escape ascii and unicode:
419 'escapes.py': ('--escape',),
420 # Escape only ascii and let unicode pass through:
421 ('escapes.py', 'ascii-escapes.pot'): (),
422 }
423
424 for filename, args in snapshots.items():
425 if isinstance(filename, tuple):
426 filename, output_file = filename
427 output_file = DATA_DIR / output_file
428 input_file = DATA_DIR / filename
429 else:
430 input_file = DATA_DIR / filename
431 output_file = input_file.with_suffix('.pot')
432 contents = input_file.read_bytes()
433 with temp_cwd(None):
434 Path(input_file.name).write_bytes(contents)
435 assert_python_ok('-Xutf8', Test_pygettext.script, *args,
436 input_file.name)
437 yield (input_file, output_file,
438 Path('messages.pot').read_text(encoding='utf-8'))
439
440
441 def update_POT_snapshots():
442 for _, output_file, output in extract_from_snapshots():
443 output = normalize_POT_file(output)
444 output_file.write_text(output, encoding='utf-8')
445
446
447 if __name__ == '__main__':
448 # To regenerate POT files
449 if len(sys.argv) > 1 and sys.argv[1] == '--snapshot-update':
450 update_POT_snapshots()
451 sys.exit(0)
452 unittest.main()