PageRenderTime 58ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/tests/i18n/test_extraction.py

http://github.com/django/django
Python | 785 lines | 705 code | 48 blank | 32 comment | 38 complexity | bae613063fc8c222d9e6a7effcaba005 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
  1. import os
  2. import re
  3. import shutil
  4. import tempfile
  5. import time
  6. import warnings
  7. from io import StringIO
  8. from pathlib import Path
  9. from unittest import mock, skipIf, skipUnless
  10. from admin_scripts.tests import AdminScriptTestCase
  11. from django.core import management
  12. from django.core.management import execute_from_command_line
  13. from django.core.management.base import CommandError
  14. from django.core.management.commands.makemessages import (
  15. Command as MakeMessagesCommand, write_pot_file,
  16. )
  17. from django.core.management.utils import find_command
  18. from django.test import SimpleTestCase, override_settings
  19. from django.test.utils import captured_stderr, captured_stdout
  20. from django.utils._os import symlinks_supported
  21. from django.utils.translation import TranslatorCommentWarning
  22. from .utils import POFileAssertionMixin, RunInTmpDirMixin, copytree
  23. LOCALE = 'de'
  24. has_xgettext = find_command('xgettext')
  25. gettext_version = MakeMessagesCommand().gettext_version if has_xgettext else None
  26. requires_gettext_019 = skipIf(has_xgettext and gettext_version < (0, 19), 'gettext 0.19 required')
  27. @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
  28. class ExtractorTests(POFileAssertionMixin, RunInTmpDirMixin, SimpleTestCase):
  29. work_subdir = 'commands'
  30. PO_FILE = 'locale/%s/LC_MESSAGES/django.po' % LOCALE
  31. def _run_makemessages(self, **options):
  32. out = StringIO()
  33. management.call_command('makemessages', locale=[LOCALE], verbosity=2, stdout=out, **options)
  34. output = out.getvalue()
  35. self.assertTrue(os.path.exists(self.PO_FILE))
  36. with open(self.PO_FILE) as fp:
  37. po_contents = fp.read()
  38. return output, po_contents
  39. def assertMsgIdPlural(self, msgid, haystack, use_quotes=True):
  40. return self._assertPoKeyword('msgid_plural', msgid, haystack, use_quotes=use_quotes)
  41. def assertMsgStr(self, msgstr, haystack, use_quotes=True):
  42. return self._assertPoKeyword('msgstr', msgstr, haystack, use_quotes=use_quotes)
  43. def assertNotMsgId(self, msgid, s, use_quotes=True):
  44. if use_quotes:
  45. msgid = '"%s"' % msgid
  46. msgid = re.escape(msgid)
  47. return self.assertTrue(not re.search('^msgid %s' % msgid, s, re.MULTILINE))
  48. def _assertPoLocComment(self, assert_presence, po_filename, line_number, *comment_parts):
  49. with open(po_filename) as fp:
  50. po_contents = fp.read()
  51. if os.name == 'nt':
  52. # #: .\path\to\file.html:123
  53. cwd_prefix = '%s%s' % (os.curdir, os.sep)
  54. else:
  55. # #: path/to/file.html:123
  56. cwd_prefix = ''
  57. path = os.path.join(cwd_prefix, *comment_parts)
  58. parts = [path]
  59. if isinstance(line_number, str):
  60. line_number = self._get_token_line_number(path, line_number)
  61. if line_number is not None:
  62. parts.append(':%d' % line_number)
  63. needle = ''.join(parts)
  64. pattern = re.compile(r'^\#\:.*' + re.escape(needle), re.MULTILINE)
  65. if assert_presence:
  66. return self.assertRegex(po_contents, pattern, '"%s" not found in final .po file.' % needle)
  67. else:
  68. return self.assertNotRegex(po_contents, pattern, '"%s" shouldn\'t be in final .po file.' % needle)
  69. def _get_token_line_number(self, path, token):
  70. with open(path) as f:
  71. for line, content in enumerate(f, 1):
  72. if token in content:
  73. return line
  74. self.fail("The token '%s' could not be found in %s, please check the test config" % (token, path))
  75. def assertLocationCommentPresent(self, po_filename, line_number, *comment_parts):
  76. r"""
  77. self.assertLocationCommentPresent('django.po', 42, 'dirA', 'dirB', 'foo.py')
  78. verifies that the django.po file has a gettext-style location comment of the form
  79. `#: dirA/dirB/foo.py:42`
  80. (or `#: .\dirA\dirB\foo.py:42` on Windows)
  81. None can be passed for the line_number argument to skip checking of
  82. the :42 suffix part.
  83. A string token can also be passed as line_number, in which case it
  84. will be searched in the template, and its line number will be used.
  85. A msgid is a suitable candidate.
  86. """
  87. return self._assertPoLocComment(True, po_filename, line_number, *comment_parts)
  88. def assertLocationCommentNotPresent(self, po_filename, line_number, *comment_parts):
  89. """Check the opposite of assertLocationComment()"""
  90. return self._assertPoLocComment(False, po_filename, line_number, *comment_parts)
  91. def assertRecentlyModified(self, path):
  92. """
  93. Assert that file was recently modified (modification time was less than 10 seconds ago).
  94. """
  95. delta = time.time() - os.stat(path).st_mtime
  96. self.assertLess(delta, 10, "%s was recently modified" % path)
  97. def assertNotRecentlyModified(self, path):
  98. """
  99. Assert that file was not recently modified (modification time was more than 10 seconds ago).
  100. """
  101. delta = time.time() - os.stat(path).st_mtime
  102. self.assertGreater(delta, 10, "%s wasn't recently modified" % path)
  103. class BasicExtractorTests(ExtractorTests):
  104. @override_settings(USE_I18N=False)
  105. def test_use_i18n_false(self):
  106. """
  107. makemessages also runs successfully when USE_I18N is False.
  108. """
  109. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  110. self.assertTrue(os.path.exists(self.PO_FILE))
  111. with open(self.PO_FILE, encoding='utf-8') as fp:
  112. po_contents = fp.read()
  113. # Check two random strings
  114. self.assertIn('#. Translators: One-line translator comment #1', po_contents)
  115. self.assertIn('msgctxt "Special trans context #1"', po_contents)
  116. def test_no_option(self):
  117. # One of either the --locale, --exclude, or --all options is required.
  118. msg = "Type 'manage.py help makemessages' for usage information."
  119. with mock.patch(
  120. 'django.core.management.commands.makemessages.sys.argv',
  121. ['manage.py', 'makemessages'],
  122. ):
  123. with self.assertRaisesRegex(CommandError, msg):
  124. management.call_command('makemessages')
  125. def test_comments_extractor(self):
  126. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  127. self.assertTrue(os.path.exists(self.PO_FILE))
  128. with open(self.PO_FILE, encoding='utf-8') as fp:
  129. po_contents = fp.read()
  130. self.assertNotIn('This comment should not be extracted', po_contents)
  131. # Comments in templates
  132. self.assertIn('#. Translators: This comment should be extracted', po_contents)
  133. self.assertIn(
  134. "#. Translators: Django comment block for translators\n#. "
  135. "string's meaning unveiled",
  136. po_contents
  137. )
  138. self.assertIn('#. Translators: One-line translator comment #1', po_contents)
  139. self.assertIn('#. Translators: Two-line translator comment #1\n#. continued here.', po_contents)
  140. self.assertIn('#. Translators: One-line translator comment #2', po_contents)
  141. self.assertIn('#. Translators: Two-line translator comment #2\n#. continued here.', po_contents)
  142. self.assertIn('#. Translators: One-line translator comment #3', po_contents)
  143. self.assertIn('#. Translators: Two-line translator comment #3\n#. continued here.', po_contents)
  144. self.assertIn('#. Translators: One-line translator comment #4', po_contents)
  145. self.assertIn('#. Translators: Two-line translator comment #4\n#. continued here.', po_contents)
  146. self.assertIn(
  147. '#. Translators: One-line translator comment #5 -- with '
  148. 'non ASCII characters: áéíóúö',
  149. po_contents
  150. )
  151. self.assertIn(
  152. '#. Translators: Two-line translator comment #5 -- with '
  153. 'non ASCII characters: áéíóúö\n#. continued here.',
  154. po_contents
  155. )
  156. def test_special_char_extracted(self):
  157. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  158. self.assertTrue(os.path.exists(self.PO_FILE))
  159. with open(self.PO_FILE, encoding='utf-8') as fp:
  160. po_contents = fp.read()
  161. self.assertMsgId("Non-breaking space\u00a0:", po_contents)
  162. def test_blocktranslate_trimmed(self):
  163. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  164. self.assertTrue(os.path.exists(self.PO_FILE))
  165. with open(self.PO_FILE) as fp:
  166. po_contents = fp.read()
  167. # should not be trimmed
  168. self.assertNotMsgId('Text with a few line breaks.', po_contents)
  169. # should be trimmed
  170. self.assertMsgId("Again some text with a few line breaks, this time should be trimmed.", po_contents)
  171. # #21406 -- Should adjust for eaten line numbers
  172. self.assertMsgId("Get my line number", po_contents)
  173. self.assertLocationCommentPresent(self.PO_FILE, 'Get my line number', 'templates', 'test.html')
  174. def test_extraction_error(self):
  175. msg = (
  176. 'Translation blocks must not include other block tags: blocktranslate '
  177. '(file %s, line 3)' % os.path.join('templates', 'template_with_error.tpl')
  178. )
  179. with self.assertRaisesMessage(SyntaxError, msg):
  180. management.call_command('makemessages', locale=[LOCALE], extensions=['tpl'], verbosity=0)
  181. # The temporary file was cleaned up
  182. self.assertFalse(os.path.exists('./templates/template_with_error.tpl.py'))
  183. def test_unicode_decode_error(self):
  184. shutil.copyfile('./not_utf8.sample', './not_utf8.txt')
  185. out = StringIO()
  186. management.call_command('makemessages', locale=[LOCALE], stdout=out)
  187. self.assertIn("UnicodeDecodeError: skipped file not_utf8.txt in .", out.getvalue())
  188. def test_unicode_file_name(self):
  189. open(os.path.join(self.test_dir, 'vidéo.txt'), 'a').close()
  190. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  191. def test_extraction_warning(self):
  192. """test xgettext warning about multiple bare interpolation placeholders"""
  193. shutil.copyfile('./code.sample', './code_sample.py')
  194. out = StringIO()
  195. management.call_command('makemessages', locale=[LOCALE], stdout=out)
  196. self.assertIn("code_sample.py:4", out.getvalue())
  197. def test_template_message_context_extractor(self):
  198. """
  199. Message contexts are correctly extracted for the {% translate %} and
  200. {% blocktranslate %} template tags (#14806).
  201. """
  202. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  203. self.assertTrue(os.path.exists(self.PO_FILE))
  204. with open(self.PO_FILE) as fp:
  205. po_contents = fp.read()
  206. # {% translate %}
  207. self.assertIn('msgctxt "Special trans context #1"', po_contents)
  208. self.assertMsgId("Translatable literal #7a", po_contents)
  209. self.assertIn('msgctxt "Special trans context #2"', po_contents)
  210. self.assertMsgId("Translatable literal #7b", po_contents)
  211. self.assertIn('msgctxt "Special trans context #3"', po_contents)
  212. self.assertMsgId("Translatable literal #7c", po_contents)
  213. # {% translate %} with a filter
  214. for minor_part in 'abcdefgh': # Iterate from #7.1a to #7.1h template markers
  215. self.assertIn('msgctxt "context #7.1{}"'.format(minor_part), po_contents)
  216. self.assertMsgId('Translatable literal #7.1{}'.format(minor_part), po_contents)
  217. # {% blocktranslate %}
  218. self.assertIn('msgctxt "Special blocktranslate context #1"', po_contents)
  219. self.assertMsgId("Translatable literal #8a", po_contents)
  220. self.assertIn('msgctxt "Special blocktranslate context #2"', po_contents)
  221. self.assertMsgId("Translatable literal #8b-singular", po_contents)
  222. self.assertIn("Translatable literal #8b-plural", po_contents)
  223. self.assertIn('msgctxt "Special blocktranslate context #3"', po_contents)
  224. self.assertMsgId("Translatable literal #8c-singular", po_contents)
  225. self.assertIn("Translatable literal #8c-plural", po_contents)
  226. self.assertIn('msgctxt "Special blocktranslate context #4"', po_contents)
  227. self.assertMsgId("Translatable literal #8d %(a)s", po_contents)
  228. # {% trans %} and {% blocktrans %}
  229. self.assertMsgId('trans text', po_contents)
  230. self.assertMsgId('blocktrans text', po_contents)
  231. def test_context_in_single_quotes(self):
  232. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  233. self.assertTrue(os.path.exists(self.PO_FILE))
  234. with open(self.PO_FILE) as fp:
  235. po_contents = fp.read()
  236. # {% translate %}
  237. self.assertIn('msgctxt "Context wrapped in double quotes"', po_contents)
  238. self.assertIn('msgctxt "Context wrapped in single quotes"', po_contents)
  239. # {% blocktranslate %}
  240. self.assertIn('msgctxt "Special blocktranslate context wrapped in double quotes"', po_contents)
  241. self.assertIn('msgctxt "Special blocktranslate context wrapped in single quotes"', po_contents)
  242. def test_template_comments(self):
  243. """Template comment tags on the same line of other constructs (#19552)"""
  244. # Test detection/end user reporting of old, incorrect templates
  245. # translator comments syntax
  246. with warnings.catch_warnings(record=True) as ws:
  247. warnings.simplefilter('always')
  248. management.call_command('makemessages', locale=[LOCALE], extensions=['thtml'], verbosity=0)
  249. self.assertEqual(len(ws), 3)
  250. for w in ws:
  251. self.assertTrue(issubclass(w.category, TranslatorCommentWarning))
  252. self.assertRegex(
  253. str(ws[0].message),
  254. r"The translator-targeted comment 'Translators: ignored i18n "
  255. r"comment #1' \(file templates[/\\]comments.thtml, line 4\) "
  256. r"was ignored, because it wasn't the last item on the line\."
  257. )
  258. self.assertRegex(
  259. str(ws[1].message),
  260. r"The translator-targeted comment 'Translators: ignored i18n "
  261. r"comment #3' \(file templates[/\\]comments.thtml, line 6\) "
  262. r"was ignored, because it wasn't the last item on the line\."
  263. )
  264. self.assertRegex(
  265. str(ws[2].message),
  266. r"The translator-targeted comment 'Translators: ignored i18n "
  267. r"comment #4' \(file templates[/\\]comments.thtml, line 8\) "
  268. r"was ignored, because it wasn't the last item on the line\."
  269. )
  270. # Now test .po file contents
  271. self.assertTrue(os.path.exists(self.PO_FILE))
  272. with open(self.PO_FILE) as fp:
  273. po_contents = fp.read()
  274. self.assertMsgId('Translatable literal #9a', po_contents)
  275. self.assertNotIn('ignored comment #1', po_contents)
  276. self.assertNotIn('Translators: ignored i18n comment #1', po_contents)
  277. self.assertMsgId("Translatable literal #9b", po_contents)
  278. self.assertNotIn('ignored i18n comment #2', po_contents)
  279. self.assertNotIn('ignored comment #2', po_contents)
  280. self.assertMsgId('Translatable literal #9c', po_contents)
  281. self.assertNotIn('ignored comment #3', po_contents)
  282. self.assertNotIn('ignored i18n comment #3', po_contents)
  283. self.assertMsgId('Translatable literal #9d', po_contents)
  284. self.assertNotIn('ignored comment #4', po_contents)
  285. self.assertMsgId('Translatable literal #9e', po_contents)
  286. self.assertNotIn('ignored comment #5', po_contents)
  287. self.assertNotIn('ignored i18n comment #4', po_contents)
  288. self.assertMsgId('Translatable literal #9f', po_contents)
  289. self.assertIn('#. Translators: valid i18n comment #5', po_contents)
  290. self.assertMsgId('Translatable literal #9g', po_contents)
  291. self.assertIn('#. Translators: valid i18n comment #6', po_contents)
  292. self.assertMsgId('Translatable literal #9h', po_contents)
  293. self.assertIn('#. Translators: valid i18n comment #7', po_contents)
  294. self.assertMsgId('Translatable literal #9i', po_contents)
  295. self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #8')
  296. self.assertRegex(po_contents, r'#\..+Translators: valid i18n comment #9')
  297. self.assertMsgId("Translatable literal #9j", po_contents)
  298. def test_makemessages_find_files(self):
  299. """
  300. find_files only discover files having the proper extensions.
  301. """
  302. cmd = MakeMessagesCommand()
  303. cmd.ignore_patterns = ['CVS', '.*', '*~', '*.pyc']
  304. cmd.symlinks = False
  305. cmd.domain = 'django'
  306. cmd.extensions = ['html', 'txt', 'py']
  307. cmd.verbosity = 0
  308. cmd.locale_paths = []
  309. cmd.default_locale_path = os.path.join(self.test_dir, 'locale')
  310. found_files = cmd.find_files(self.test_dir)
  311. found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
  312. self.assertEqual(found_exts.difference({'.py', '.html', '.txt'}), set())
  313. cmd.extensions = ['js']
  314. cmd.domain = 'djangojs'
  315. found_files = cmd.find_files(self.test_dir)
  316. found_exts = {os.path.splitext(tfile.file)[1] for tfile in found_files}
  317. self.assertEqual(found_exts.difference({'.js'}), set())
  318. @mock.patch('django.core.management.commands.makemessages.popen_wrapper')
  319. def test_makemessages_gettext_version(self, mocked_popen_wrapper):
  320. # "Normal" output:
  321. mocked_popen_wrapper.return_value = (
  322. "xgettext (GNU gettext-tools) 0.18.1\n"
  323. "Copyright (C) 1995-1998, 2000-2010 Free Software Foundation, Inc.\n"
  324. "License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>\n"
  325. "This is free software: you are free to change and redistribute it.\n"
  326. "There is NO WARRANTY, to the extent permitted by law.\n"
  327. "Written by Ulrich Drepper.\n", '', 0)
  328. cmd = MakeMessagesCommand()
  329. self.assertEqual(cmd.gettext_version, (0, 18, 1))
  330. # Version number with only 2 parts (#23788)
  331. mocked_popen_wrapper.return_value = (
  332. "xgettext (GNU gettext-tools) 0.17\n", '', 0)
  333. cmd = MakeMessagesCommand()
  334. self.assertEqual(cmd.gettext_version, (0, 17))
  335. # Bad version output
  336. mocked_popen_wrapper.return_value = (
  337. "any other return value\n", '', 0)
  338. cmd = MakeMessagesCommand()
  339. with self.assertRaisesMessage(CommandError, "Unable to get gettext version. Is it installed?"):
  340. cmd.gettext_version
  341. def test_po_file_encoding_when_updating(self):
  342. """
  343. Update of PO file doesn't corrupt it with non-UTF-8 encoding on Windows
  344. (#23271).
  345. """
  346. BR_PO_BASE = 'locale/pt_BR/LC_MESSAGES/django'
  347. shutil.copyfile(BR_PO_BASE + '.pristine', BR_PO_BASE + '.po')
  348. management.call_command('makemessages', locale=['pt_BR'], verbosity=0)
  349. self.assertTrue(os.path.exists(BR_PO_BASE + '.po'))
  350. with open(BR_PO_BASE + '.po', encoding='utf-8') as fp:
  351. po_contents = fp.read()
  352. self.assertMsgStr("Größe", po_contents)
  353. def test_pot_charset_header_is_utf8(self):
  354. """Content-Type: ... charset=CHARSET is replaced with charset=UTF-8"""
  355. msgs = (
  356. '# SOME DESCRIPTIVE TITLE.\n'
  357. '# (some lines truncated as they are not relevant)\n'
  358. '"Content-Type: text/plain; charset=CHARSET\\n"\n'
  359. '"Content-Transfer-Encoding: 8bit\\n"\n'
  360. '\n'
  361. '#: somefile.py:8\n'
  362. 'msgid "mañana; charset=CHARSET"\n'
  363. 'msgstr ""\n'
  364. )
  365. with tempfile.NamedTemporaryFile() as pot_file:
  366. pot_filename = pot_file.name
  367. write_pot_file(pot_filename, msgs)
  368. with open(pot_filename, encoding='utf-8') as fp:
  369. pot_contents = fp.read()
  370. self.assertIn('Content-Type: text/plain; charset=UTF-8', pot_contents)
  371. self.assertIn('mañana; charset=CHARSET', pot_contents)
  372. class JavascriptExtractorTests(ExtractorTests):
  373. PO_FILE = 'locale/%s/LC_MESSAGES/djangojs.po' % LOCALE
  374. def test_javascript_literals(self):
  375. _, po_contents = self._run_makemessages(domain='djangojs')
  376. self.assertMsgId('This literal should be included.', po_contents)
  377. self.assertMsgId('gettext_noop should, too.', po_contents)
  378. self.assertMsgId('This one as well.', po_contents)
  379. self.assertMsgId(r'He said, \"hello\".', po_contents)
  380. self.assertMsgId("okkkk", po_contents)
  381. self.assertMsgId("TEXT", po_contents)
  382. self.assertMsgId("It's at http://example.com", po_contents)
  383. self.assertMsgId("String", po_contents)
  384. self.assertMsgId("/* but this one will be too */ 'cause there is no way of telling...", po_contents)
  385. self.assertMsgId("foo", po_contents)
  386. self.assertMsgId("bar", po_contents)
  387. self.assertMsgId("baz", po_contents)
  388. self.assertMsgId("quz", po_contents)
  389. self.assertMsgId("foobar", po_contents)
  390. def test_media_static_dirs_ignored(self):
  391. """
  392. Regression test for #23583.
  393. """
  394. with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
  395. MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
  396. _, po_contents = self._run_makemessages(domain='djangojs')
  397. self.assertMsgId("Static content inside app should be included.", po_contents)
  398. self.assertNotMsgId("Content from STATIC_ROOT should not be included", po_contents)
  399. @override_settings(STATIC_ROOT=None, MEDIA_ROOT='')
  400. def test_default_root_settings(self):
  401. """
  402. Regression test for #23717.
  403. """
  404. _, po_contents = self._run_makemessages(domain='djangojs')
  405. self.assertMsgId("Static content inside app should be included.", po_contents)
  406. class IgnoredExtractorTests(ExtractorTests):
  407. def test_ignore_directory(self):
  408. out, po_contents = self._run_makemessages(ignore_patterns=[
  409. os.path.join('ignore_dir', '*'),
  410. ])
  411. self.assertIn("ignoring directory ignore_dir", out)
  412. self.assertMsgId('This literal should be included.', po_contents)
  413. self.assertNotMsgId('This should be ignored.', po_contents)
  414. def test_ignore_subdirectory(self):
  415. out, po_contents = self._run_makemessages(ignore_patterns=[
  416. 'templates/*/ignore.html',
  417. 'templates/subdir/*',
  418. ])
  419. self.assertIn("ignoring directory subdir", out)
  420. self.assertNotMsgId('This subdir should be ignored too.', po_contents)
  421. def test_ignore_file_patterns(self):
  422. out, po_contents = self._run_makemessages(ignore_patterns=[
  423. 'xxx_*',
  424. ])
  425. self.assertIn("ignoring file xxx_ignored.html", out)
  426. self.assertNotMsgId('This should be ignored too.', po_contents)
  427. def test_media_static_dirs_ignored(self):
  428. with override_settings(STATIC_ROOT=os.path.join(self.test_dir, 'static/'),
  429. MEDIA_ROOT=os.path.join(self.test_dir, 'media_root/')):
  430. out, _ = self._run_makemessages()
  431. self.assertIn("ignoring directory static", out)
  432. self.assertIn("ignoring directory media_root", out)
  433. class SymlinkExtractorTests(ExtractorTests):
  434. def setUp(self):
  435. super().setUp()
  436. self.symlinked_dir = os.path.join(self.test_dir, 'templates_symlinked')
  437. def test_symlink(self):
  438. if symlinks_supported():
  439. os.symlink(os.path.join(self.test_dir, 'templates'), self.symlinked_dir)
  440. else:
  441. self.skipTest("os.symlink() not available on this OS + Python version combination.")
  442. management.call_command('makemessages', locale=[LOCALE], verbosity=0, symlinks=True)
  443. self.assertTrue(os.path.exists(self.PO_FILE))
  444. with open(self.PO_FILE) as fp:
  445. po_contents = fp.read()
  446. self.assertMsgId('This literal should be included.', po_contents)
  447. self.assertLocationCommentPresent(self.PO_FILE, None, 'templates_symlinked', 'test.html')
  448. class CopyPluralFormsExtractorTests(ExtractorTests):
  449. PO_FILE_ES = 'locale/es/LC_MESSAGES/django.po'
  450. def test_copy_plural_forms(self):
  451. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  452. self.assertTrue(os.path.exists(self.PO_FILE))
  453. with open(self.PO_FILE) as fp:
  454. po_contents = fp.read()
  455. self.assertIn('Plural-Forms: nplurals=2; plural=(n != 1)', po_contents)
  456. def test_override_plural_forms(self):
  457. """Ticket #20311."""
  458. management.call_command('makemessages', locale=['es'], extensions=['djtpl'], verbosity=0)
  459. self.assertTrue(os.path.exists(self.PO_FILE_ES))
  460. with open(self.PO_FILE_ES, encoding='utf-8') as fp:
  461. po_contents = fp.read()
  462. found = re.findall(r'^(?P<value>"Plural-Forms.+?\\n")\s*$', po_contents, re.MULTILINE | re.DOTALL)
  463. self.assertEqual(1, len(found))
  464. def test_translate_and_plural_blocktranslate_collision(self):
  465. """
  466. Ensures a correct workaround for the gettext bug when handling a literal
  467. found inside a {% translate %} tag and also in another file inside a
  468. {% blocktranslate %} with a plural (#17375).
  469. """
  470. management.call_command('makemessages', locale=[LOCALE], extensions=['html', 'djtpl'], verbosity=0)
  471. self.assertTrue(os.path.exists(self.PO_FILE))
  472. with open(self.PO_FILE) as fp:
  473. po_contents = fp.read()
  474. self.assertNotIn("#-#-#-#-# django.pot (PACKAGE VERSION) #-#-#-#-#\\n", po_contents)
  475. self.assertMsgId('First `translate`, then `blocktranslate` with a plural', po_contents)
  476. self.assertMsgIdPlural('Plural for a `translate` and `blocktranslate` collision case', po_contents)
  477. class NoWrapExtractorTests(ExtractorTests):
  478. def test_no_wrap_enabled(self):
  479. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=True)
  480. self.assertTrue(os.path.exists(self.PO_FILE))
  481. with open(self.PO_FILE) as fp:
  482. po_contents = fp.read()
  483. self.assertMsgId(
  484. 'This literal should also be included wrapped or not wrapped '
  485. 'depending on the use of the --no-wrap option.',
  486. po_contents
  487. )
  488. def test_no_wrap_disabled(self):
  489. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_wrap=False)
  490. self.assertTrue(os.path.exists(self.PO_FILE))
  491. with open(self.PO_FILE) as fp:
  492. po_contents = fp.read()
  493. self.assertMsgId(
  494. '""\n"This literal should also be included wrapped or not '
  495. 'wrapped depending on the "\n"use of the --no-wrap option."',
  496. po_contents,
  497. use_quotes=False
  498. )
  499. class LocationCommentsTests(ExtractorTests):
  500. def test_no_location_enabled(self):
  501. """Behavior is correct if --no-location switch is specified. See #16903."""
  502. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=True)
  503. self.assertTrue(os.path.exists(self.PO_FILE))
  504. self.assertLocationCommentNotPresent(self.PO_FILE, None, 'test.html')
  505. def test_no_location_disabled(self):
  506. """Behavior is correct if --no-location switch isn't specified."""
  507. management.call_command('makemessages', locale=[LOCALE], verbosity=0, no_location=False)
  508. self.assertTrue(os.path.exists(self.PO_FILE))
  509. # #16903 -- Standard comment with source file relative path should be present
  510. self.assertLocationCommentPresent(self.PO_FILE, 'Translatable literal #6b', 'templates', 'test.html')
  511. def test_location_comments_for_templatized_files(self):
  512. """
  513. Ensure no leaky paths in comments, e.g. #: path\to\file.html.py:123
  514. Refs #21209/#26341.
  515. """
  516. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  517. self.assertTrue(os.path.exists(self.PO_FILE))
  518. with open(self.PO_FILE) as fp:
  519. po_contents = fp.read()
  520. self.assertMsgId('#: templates/test.html.py', po_contents)
  521. self.assertLocationCommentNotPresent(self.PO_FILE, None, '.html.py')
  522. self.assertLocationCommentPresent(self.PO_FILE, 5, 'templates', 'test.html')
  523. @requires_gettext_019
  524. def test_add_location_full(self):
  525. """makemessages --add-location=full"""
  526. management.call_command('makemessages', locale=[LOCALE], verbosity=0, add_location='full')
  527. self.assertTrue(os.path.exists(self.PO_FILE))
  528. # Comment with source file relative path and line number is present.
  529. self.assertLocationCommentPresent(self.PO_FILE, 'Translatable literal #6b', 'templates', 'test.html')
  530. @requires_gettext_019
  531. def test_add_location_file(self):
  532. """makemessages --add-location=file"""
  533. management.call_command('makemessages', locale=[LOCALE], verbosity=0, add_location='file')
  534. self.assertTrue(os.path.exists(self.PO_FILE))
  535. # Comment with source file relative path is present.
  536. self.assertLocationCommentPresent(self.PO_FILE, None, 'templates', 'test.html')
  537. # But it should not contain the line number.
  538. self.assertLocationCommentNotPresent(self.PO_FILE, 'Translatable literal #6b', 'templates', 'test.html')
  539. @requires_gettext_019
  540. def test_add_location_never(self):
  541. """makemessages --add-location=never"""
  542. management.call_command('makemessages', locale=[LOCALE], verbosity=0, add_location='never')
  543. self.assertTrue(os.path.exists(self.PO_FILE))
  544. self.assertLocationCommentNotPresent(self.PO_FILE, None, 'test.html')
  545. @mock.patch('django.core.management.commands.makemessages.Command.gettext_version', new=(0, 18, 99))
  546. def test_add_location_gettext_version_check(self):
  547. """
  548. CommandError is raised when using makemessages --add-location with
  549. gettext < 0.19.
  550. """
  551. msg = "The --add-location option requires gettext 0.19 or later. You have 0.18.99."
  552. with self.assertRaisesMessage(CommandError, msg):
  553. management.call_command('makemessages', locale=[LOCALE], verbosity=0, add_location='full')
  554. class KeepPotFileExtractorTests(ExtractorTests):
  555. POT_FILE = 'locale/django.pot'
  556. def test_keep_pot_disabled_by_default(self):
  557. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  558. self.assertFalse(os.path.exists(self.POT_FILE))
  559. def test_keep_pot_explicitly_disabled(self):
  560. management.call_command('makemessages', locale=[LOCALE], verbosity=0, keep_pot=False)
  561. self.assertFalse(os.path.exists(self.POT_FILE))
  562. def test_keep_pot_enabled(self):
  563. management.call_command('makemessages', locale=[LOCALE], verbosity=0, keep_pot=True)
  564. self.assertTrue(os.path.exists(self.POT_FILE))
  565. class MultipleLocaleExtractionTests(ExtractorTests):
  566. PO_FILE_PT = 'locale/pt/LC_MESSAGES/django.po'
  567. PO_FILE_DE = 'locale/de/LC_MESSAGES/django.po'
  568. PO_FILE_KO = 'locale/ko/LC_MESSAGES/django.po'
  569. LOCALES = ['pt', 'de', 'ch']
  570. def test_multiple_locales(self):
  571. management.call_command('makemessages', locale=['pt', 'de'], verbosity=0)
  572. self.assertTrue(os.path.exists(self.PO_FILE_PT))
  573. self.assertTrue(os.path.exists(self.PO_FILE_DE))
  574. def test_all_locales(self):
  575. """
  576. When the `locale` flag is absent, all dirs from the parent locale dir
  577. are considered as language directories, except if the directory doesn't
  578. start with two letters (which excludes __pycache__, .gitignore, etc.).
  579. """
  580. os.mkdir(os.path.join('locale', '_do_not_pick'))
  581. # Excluding locales that do not compile
  582. management.call_command('makemessages', exclude=['ja', 'es_AR'], verbosity=0)
  583. self.assertTrue(os.path.exists(self.PO_FILE_KO))
  584. self.assertFalse(os.path.exists('locale/_do_not_pick/LC_MESSAGES/django.po'))
  585. class ExcludedLocaleExtractionTests(ExtractorTests):
  586. work_subdir = 'exclude'
  587. LOCALES = ['en', 'fr', 'it']
  588. PO_FILE = 'locale/%s/LC_MESSAGES/django.po'
  589. def _set_times_for_all_po_files(self):
  590. """
  591. Set access and modification times to the Unix epoch time for all the .po files.
  592. """
  593. for locale in self.LOCALES:
  594. os.utime(self.PO_FILE % locale, (0, 0))
  595. def setUp(self):
  596. super().setUp()
  597. copytree('canned_locale', 'locale')
  598. self._set_times_for_all_po_files()
  599. def test_command_help(self):
  600. with captured_stdout(), captured_stderr():
  601. # `call_command` bypasses the parser; by calling
  602. # `execute_from_command_line` with the help subcommand we
  603. # ensure that there are no issues with the parser itself.
  604. execute_from_command_line(['django-admin', 'help', 'makemessages'])
  605. def test_one_locale_excluded(self):
  606. management.call_command('makemessages', exclude=['it'], verbosity=0)
  607. self.assertRecentlyModified(self.PO_FILE % 'en')
  608. self.assertRecentlyModified(self.PO_FILE % 'fr')
  609. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  610. def test_multiple_locales_excluded(self):
  611. management.call_command('makemessages', exclude=['it', 'fr'], verbosity=0)
  612. self.assertRecentlyModified(self.PO_FILE % 'en')
  613. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  614. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  615. def test_one_locale_excluded_with_locale(self):
  616. management.call_command('makemessages', locale=['en', 'fr'], exclude=['fr'], verbosity=0)
  617. self.assertRecentlyModified(self.PO_FILE % 'en')
  618. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  619. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  620. def test_multiple_locales_excluded_with_locale(self):
  621. management.call_command('makemessages', locale=['en', 'fr', 'it'], exclude=['fr', 'it'], verbosity=0)
  622. self.assertRecentlyModified(self.PO_FILE % 'en')
  623. self.assertNotRecentlyModified(self.PO_FILE % 'fr')
  624. self.assertNotRecentlyModified(self.PO_FILE % 'it')
  625. class CustomLayoutExtractionTests(ExtractorTests):
  626. work_subdir = 'project_dir'
  627. def test_no_locale_raises(self):
  628. msg = "Unable to find a locale path to store translations for file"
  629. with self.assertRaisesMessage(management.CommandError, msg):
  630. management.call_command('makemessages', locale=LOCALE, verbosity=0)
  631. def test_project_locale_paths(self):
  632. self._test_project_locale_paths(os.path.join(self.test_dir, 'project_locale'))
  633. def test_project_locale_paths_pathlib(self):
  634. self._test_project_locale_paths(Path(self.test_dir) / 'project_locale')
  635. def _test_project_locale_paths(self, locale_path):
  636. """
  637. * translations for an app containing a locale folder are stored in that folder
  638. * translations outside of that app are in LOCALE_PATHS[0]
  639. """
  640. with override_settings(LOCALE_PATHS=[locale_path]):
  641. management.call_command('makemessages', locale=[LOCALE], verbosity=0)
  642. project_de_locale = os.path.join(
  643. self.test_dir, 'project_locale', 'de', 'LC_MESSAGES', 'django.po')
  644. app_de_locale = os.path.join(
  645. self.test_dir, 'app_with_locale', 'locale', 'de', 'LC_MESSAGES', 'django.po')
  646. self.assertTrue(os.path.exists(project_de_locale))
  647. self.assertTrue(os.path.exists(app_de_locale))
  648. with open(project_de_locale) as fp:
  649. po_contents = fp.read()
  650. self.assertMsgId('This app has no locale directory', po_contents)
  651. self.assertMsgId('This is a project-level string', po_contents)
  652. with open(app_de_locale) as fp:
  653. po_contents = fp.read()
  654. self.assertMsgId('This app has a locale directory', po_contents)
  655. @skipUnless(has_xgettext, 'xgettext is mandatory for extraction tests')
  656. class NoSettingsExtractionTests(AdminScriptTestCase):
  657. def test_makemessages_no_settings(self):
  658. out, err = self.run_django_admin(['makemessages', '-l', 'en', '-v', '0'])
  659. self.assertNoOutput(err)
  660. self.assertNoOutput(out)